diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 27569cfcb31bb..b07b790803d7c 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -63,7 +63,9 @@ jobs: path: ../build-cache key: ${{ runner.os }}-sccache-v5-5.3 - name: Build macOS installable archive - run: ./utils/webassembly/ci.sh + run: | + sudo xcode-select --switch /Applications/Xcode_12_beta.app/Contents/Developer/ + ./utils/webassembly/ci.sh - name: Upload macOS installable archive uses: actions/upload-artifact@v1 with: diff --git a/README.md b/README.md index ab09f3ab9c01a..144cb80c7d893 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ Please make sure you use Python 2.x. Python 3.x is not supported currently. #### macOS -To build for macOS, you need [Xcode 11.4](https://developer.apple.com/xcode/resources/). +To build for macOS, you need [Xcode 12 beta](https://developer.apple.com/xcode/resources/). The required version of Xcode changes frequently, and is often a beta release. Check this document or the host information on for the current required version. diff --git a/benchmark/cmake/modules/AddSwiftBenchmarkSuite.cmake b/benchmark/cmake/modules/AddSwiftBenchmarkSuite.cmake index 76e439bd7eb57..05a9e75ddc7f2 100644 --- a/benchmark/cmake/modules/AddSwiftBenchmarkSuite.cmake +++ b/benchmark/cmake/modules/AddSwiftBenchmarkSuite.cmake @@ -660,8 +660,11 @@ function (swift_benchmark_compile_archopts) "-m${triple_platform}-version-min=${ver}" "-lobjc" "-L${SWIFT_LIBRARY_PATH}/${BENCH_COMPILE_ARCHOPTS_PLATFORM}" + "-L${sdk}/usr/lib/swift" "-Xlinker" "-rpath" "-Xlinker" "${SWIFT_LINK_RPATH}" + "-Xlinker" "-rpath" + "-Xlinker" "/usr/lib/swift" ${bench_library_objects} ${bench_driver_objects} ${ld64_add_ast_path_opts} diff --git a/include/swift/IDE/ConformingMethodList.h b/include/swift/IDE/ConformingMethodList.h index 1dbe1c3770972..d755f080798ae 100644 --- a/include/swift/IDE/ConformingMethodList.h +++ b/include/swift/IDE/ConformingMethodList.h @@ -42,6 +42,7 @@ class ConformingMethodListConsumer { public: virtual ~ConformingMethodListConsumer() {} virtual void handleResult(const ConformingMethodListResult &result) = 0; + virtual void setReusingASTContext(bool flag) = 0; }; /// Printing consumer @@ -53,6 +54,7 @@ class PrintingConformingMethodListConsumer PrintingConformingMethodListConsumer(llvm::raw_ostream &OS) : OS(OS) {} void handleResult(const ConformingMethodListResult &result) override; + void setReusingASTContext(bool flag) override {} }; /// Create a factory for code completion callbacks. diff --git a/include/swift/IDE/TypeContextInfo.h b/include/swift/IDE/TypeContextInfo.h index 2bb8c95053710..ed12906edf303 100644 --- a/include/swift/IDE/TypeContextInfo.h +++ b/include/swift/IDE/TypeContextInfo.h @@ -38,6 +38,7 @@ class TypeContextInfoConsumer { public: virtual ~TypeContextInfoConsumer() {} virtual void handleResults(ArrayRef) = 0; + virtual void setReusingASTContext(bool flag) = 0; }; /// Printing consumer @@ -48,6 +49,7 @@ class PrintingTypeContextInfoConsumer : public TypeContextInfoConsumer { PrintingTypeContextInfoConsumer(llvm::raw_ostream &OS) : OS(OS) {} void handleResults(ArrayRef) override; + void setReusingASTContext(bool flag) override {} }; /// Create a factory for code completion callbacks. diff --git a/lib/AST/Attr.cpp b/lib/AST/Attr.cpp index cf90377151b74..94e21936b4e9f 100644 --- a/lib/AST/Attr.cpp +++ b/lib/AST/Attr.cpp @@ -749,8 +749,11 @@ bool DeclAttribute::printImpl(ASTPrinter &Printer, const PrintOptions &Options, if (auto *VD = dyn_cast(D)) { if (auto *BD = VD->getOverriddenDecl()) { if (!BD->hasClangNode() && - VD->isEffectiveLinkageMoreVisibleThan(BD)) + !BD->getFormalAccessScope(VD->getDeclContext(), + /*treatUsableFromInlineAsPublic*/ true) + .isPublic()) { return false; + } } } break; diff --git a/lib/Demangling/Demangler.cpp b/lib/Demangling/Demangler.cpp index c88a98d2a8a31..9caa70dfbf331 100644 --- a/lib/Demangling/Demangler.cpp +++ b/lib/Demangling/Demangler.cpp @@ -2007,6 +2007,8 @@ NodePointer Demangler::demangleArchetype() { if (!demangleBoundGenerics(boundGenericArgs, retroactiveConformances)) return nullptr; auto Name = popNode(); + if (!Name) + return nullptr; auto opaque = createWithChildren(Node::Kind::OpaqueType, Name, createNode(Node::Kind::Index, index)); auto boundGenerics = createNode(Node::Kind::TypeList); diff --git a/lib/IDE/CodeCompletion.cpp b/lib/IDE/CodeCompletion.cpp index 89dc873b2ed2f..1e99701ee94c6 100644 --- a/lib/IDE/CodeCompletion.cpp +++ b/lib/IDE/CodeCompletion.cpp @@ -6158,15 +6158,29 @@ void CodeCompletionCallbacksImpl::doneParsing() { if (IsAtStartOfLine) { // foo() {} // - // Global completion. + auto &Sink = CompletionContext.getResultSink(); - addDeclKeywords(Sink); - addStmtKeywords(Sink, MaybeFuncBody); - addSuperKeyword(Sink); - addLetVarKeywords(Sink); - addExprKeywords(Sink); - addAnyTypeKeyword(Sink, CurDeclContext->getASTContext().TheAnyType); - DoPostfixExprBeginning(); + if (isa(CurDeclContext)) + CurDeclContext = CurDeclContext->getParent(); + + if (CurDeclContext->isTypeContext()) { + // Override completion (CompletionKind::NominalMemberBeginning). + addDeclKeywords(Sink); + addLetVarKeywords(Sink); + SmallVector ParsedKeywords; + CompletionOverrideLookup OverrideLookup(Sink, Context, CurDeclContext, + ParsedKeywords, SourceLoc()); + OverrideLookup.getOverrideCompletions(SourceLoc()); + } else { + // Global completion (CompletionKind::PostfixExprBeginning). + addDeclKeywords(Sink); + addStmtKeywords(Sink, MaybeFuncBody); + addSuperKeyword(Sink); + addLetVarKeywords(Sink); + addExprKeywords(Sink); + addAnyTypeKeyword(Sink, Context.TheAnyType); + DoPostfixExprBeginning(); + } } else { // foo() {} // Member completion. diff --git a/lib/IDE/Formatting.cpp b/lib/IDE/Formatting.cpp index 4c6be8f877833..e30ae5590bf5a 100644 --- a/lib/IDE/Formatting.cpp +++ b/lib/IDE/Formatting.cpp @@ -1906,6 +1906,11 @@ class FormatWalker : public ASTWalker { return Aligner.getContextAndSetAlignment(CtxOverride); } + // There are no parens at this point, so if there are no parameters either, + // this shouldn't be a context (it's an implicit parameter list). + if (!PL->size()) + return None; + ListAligner Aligner(SM, TargetLocation, ContextLoc, Range.Start); for (auto *PD: *PL) Aligner.updateAlignment(PD->getSourceRange(), PD); @@ -2336,8 +2341,17 @@ class FormatWalker : public ASTWalker { return None; ListAligner Aligner(SM, TargetLocation, L, L, R, true); - for (auto *Elem: AE->getElements()) - Aligner.updateAlignment(Elem->getStartLoc(), Elem->getEndLoc(), Elem); + for (auto *Elem: AE->getElements()) { + SourceRange ElemRange = Elem->getSourceRange(); + Aligner.updateAlignment(ElemRange, Elem); + if (isTargetContext(ElemRange)) { + Aligner.setAlignmentIfNeeded(CtxOverride); + return IndentContext { + ElemRange.Start, + !OutdentChecker::hasOutdent(SM, ElemRange, Elem) + }; + } + } return Aligner.getContextAndSetAlignment(CtxOverride); } diff --git a/lib/Parse/ParseExpr.cpp b/lib/Parse/ParseExpr.cpp index 02775bfd558b8..cc4ef2471061b 100644 --- a/lib/Parse/ParseExpr.cpp +++ b/lib/Parse/ParseExpr.cpp @@ -3228,7 +3228,7 @@ Parser::parseTrailingClosures(bool isExprBasic, SourceRange calleeRange, if (CodeCompletion) CodeCompletion->completeLabeledTrailingClosure(CCExpr, Tok.isAtStartOfLine()); consumeToken(tok::code_complete); - result.hasCodeCompletion(); + result.setHasCodeCompletion(); closures.push_back({Identifier(), SourceLoc(), CCExpr}); continue; } diff --git a/lib/SILOptimizer/Transforms/CopyForwarding.cpp b/lib/SILOptimizer/Transforms/CopyForwarding.cpp index 8d6a43a200bb0..f8f0af4665d40 100644 --- a/lib/SILOptimizer/Transforms/CopyForwarding.cpp +++ b/lib/SILOptimizer/Transforms/CopyForwarding.cpp @@ -322,6 +322,9 @@ namespace { /// This returns false and sets Oper to a valid operand if the instruction is a /// projection of the value at the given address. The assumption is that we /// cannot deinitialize memory via projections. +/// +/// This returns true with Oper == nullptr for trivial stores (without a proper +/// deinit). class AnalyzeForwardUse : public SILInstructionVisitor { public: @@ -352,7 +355,10 @@ class AnalyzeForwardUse return true; } bool visitStoreInst(StoreInst *Store) { - llvm_unreachable("illegal reinitialization or store of an address"); + // Trivial values may be stored prior to the next deinit. A store is an + // implicit "deinit" with no operand to replace. + assert(Store->getOperand(0)->getType().isTrivial(*Store->getFunction())); + return true; } bool visitDestroyAddrInst(DestroyAddrInst *UserInst) { Oper = &UserInst->getOperandRef(); @@ -1011,15 +1017,17 @@ bool CopyForwarding::forwardPropagateCopy() { continue; AnalyzeForwardUse AnalyzeUse(CopyDest); - bool seenDeinit = AnalyzeUse.visit(UserInst); - // If this use cannot be analyzed, then abort. + bool seenDeinitOrStore = AnalyzeUse.visit(UserInst); + if (AnalyzeUse.Oper) + ValueUses.push_back(AnalyzeUse.Oper); + + // If this is a deinit or store, we're done searching. + if (seenDeinitOrStore) + break; + + // If this non-deinit instruction wasn't fully analyzed, bail-out. if (!AnalyzeUse.Oper) return false; - // Otherwise record the operand. - ValueUses.push_back(AnalyzeUse.Oper); - // If this is a deinit, we're done searching. - if (seenDeinit) - break; } if (SI == SE) return false; diff --git a/lib/Sema/BuilderTransform.cpp b/lib/Sema/BuilderTransform.cpp index 8044cbd09730f..aeffe2b5766c0 100644 --- a/lib/Sema/BuilderTransform.cpp +++ b/lib/Sema/BuilderTransform.cpp @@ -283,8 +283,10 @@ class BuilderClosureVisitor auto target = SolutionApplicationTarget::forInitialization( patternBinding->getInit(index), dc, patternType, pattern, /*bindPatternVarsOneWay=*/true); - if (cs->generateConstraints(target, FreeTypeVariableBinding::Disallow)) + if (cs->generateConstraints(target, FreeTypeVariableBinding::Disallow)) { + hadError = true; continue; + } // Keep track of this binding entry. applied.patternBindingEntries.insert({{patternBinding, index}, target}); @@ -1223,6 +1225,65 @@ BraceStmt *swift::applyFunctionBuilderTransform( captured.first, captured.second))); } +/// Produce any additional syntactic diagnostics for the body of a +static void performAddOnDiagnostics(BraceStmt *stmt, DeclContext *dc) { + class AddOnDiagnosticWalker : public ASTWalker { + SmallVector dcStack; + + public: + AddOnDiagnosticWalker(DeclContext *dc) { + dcStack.push_back(dc); + } + + std::pair walkToExprPre(Expr *expr) override { + performSyntacticExprDiagnostics( + expr, dcStack.back(), /*isExprStmt=*/false); + + if (auto closure = dyn_cast(expr)) { + if (!closure->hasSingleExpressionBody() && + !closure->hasAppliedFunctionBuilder()) { + dcStack.push_back(closure); + return { true, expr }; + } + } + + return { false, expr }; + } + + Expr *walkToExprPost(Expr *expr) override { + if (auto closure = dyn_cast(expr)) { + if (!closure->hasSingleExpressionBody() && + !closure->hasAppliedFunctionBuilder()) { + assert(dcStack.back() == closure); + dcStack.pop_back(); + } + } + + return expr; + } + + std::pair walkToStmtPre(Stmt *stmt) override { + performStmtDiagnostics(dcStack.back()->getASTContext(), stmt); + return { true, stmt }; + } + + std::pair walkToPatternPre(Pattern *pattern) override { + return { false, pattern }; + } + + bool walkToTypeLocPre(TypeLoc &typeLoc) override { return false; } + + bool walkToTypeReprPre(TypeRepr *typeRepr) override { return false; } + + bool walkToParameterListPre(ParameterList *params) override { + return false; + } + }; + + AddOnDiagnosticWalker walker(dc); + stmt->walk(walker); +} + Optional TypeChecker::applyFunctionBuilderBodyTransform( FuncDecl *func, Type builderType) { // Pre-check the body: pre-check any expressions in it and look @@ -1363,6 +1424,7 @@ Optional TypeChecker::applyFunctionBuilderBodyTransform( if (auto result = cs.applySolution( solutions.front(), SolutionApplicationTarget(func))) { + performAddOnDiagnostics(result->getFunctionBody(), func); return result->getFunctionBody(); } diff --git a/lib/Sema/CSGen.cpp b/lib/Sema/CSGen.cpp index 4519e73598dc3..a1b6f903cc8b1 100644 --- a/lib/Sema/CSGen.cpp +++ b/lib/Sema/CSGen.cpp @@ -1180,18 +1180,24 @@ namespace { TVO_CanBindToLValue | TVO_CanBindToNoEscape); - // Defaults to the type of the base expression if we have a base - // expression. - // FIXME: This is just to keep the old behavior where `foo(base.)` - // the argument is type checked to the type of the 'base'. Ideally, code - // completion expression should be defauled to 'UnresolvedType' - // regardless of the existence of the base expression. But the constraint - // system is simply not ready for that. if (auto base = E->getBase()) { + // Defaults to the type of the base expression if we have a base + // expression. + // FIXME: This is just to keep the old behavior where `foo(base.)` + // the argument is type checked to the type of the 'base'. Ideally, code + // completion expression should be defauled to 'UnresolvedType' + // regardless of the existence of the base expression. But the + // constraint system is simply not ready for that. CS.addConstraint(ConstraintKind::Defaultable, ty, CS.getType(base), locator); + + // Apply a viable solution even if it's ambiguous. + // FIXME: Remove this. This is a hack for code completion which only + // see solution applied AST. In future, code completion collects all + // viable solutions so we need to apply any solution at all. + CS.Options |= ConstraintSystemFlags::ForceApplyViableSolution; } - + return ty; } @@ -2321,12 +2327,18 @@ namespace { return setType(ParenType::get(CS.getASTContext(), underlyingType)); } - case PatternKind::Var: + case PatternKind::Var: { + auto *subPattern = cast(pattern)->getSubPattern(); + auto type = getTypeForPattern(subPattern, locator, externalPatternType, + bindPatternVarsOneWay); + + if (!type) + return Type(); + // Var doesn't affect the type. - return setType( - getTypeForPattern( - cast(pattern)->getSubPattern(), locator, - externalPatternType, bindPatternVarsOneWay)); + return setType(type); + } + case PatternKind::Any: { return setType( CS.createTypeVariable(CS.getConstraintLocator(locator), @@ -4235,7 +4247,9 @@ static bool generateInitPatternConstraints( pattern, locator, target.shouldBindPatternVarsOneWay(), target.getInitializationPatternBindingDecl(), target.getInitializationPatternBindingIndex()); - assert(patternType && "All patterns have a type"); + + if (!patternType) + return true; if (auto wrappedVar = target.getInitializationWrappedVar()) { // Add an equal constraint between the pattern type and the diff --git a/lib/Sema/CSRanking.cpp b/lib/Sema/CSRanking.cpp index c4874a0676f94..131bd402371b3 100644 --- a/lib/Sema/CSRanking.cpp +++ b/lib/Sema/CSRanking.cpp @@ -1335,6 +1335,12 @@ ConstraintSystem::findBestSolution(SmallVectorImpl &viable, return bestIdx; } + // FIXME: Terrible hack for code completion. But applying a solution is better + // than just failing. + if (Options.contains(ConstraintSystemFlags::ForceApplyViableSolution)) { + return bestIdx; + } + // If there is not a single "better" than others // solution, which probably means that solutions // were incomparable, let's just keep the original diff --git a/lib/Sema/ConstraintSystem.h b/lib/Sema/ConstraintSystem.h index c30c0a1f210a5..52506d3fb9461 100644 --- a/lib/Sema/ConstraintSystem.h +++ b/lib/Sema/ConstraintSystem.h @@ -1074,6 +1074,11 @@ enum class ConstraintSystemFlags { /// If set, constraint system always reuses type of pre-typechecked /// expression, and doesn't dig into its subexpressions. ReusePrecheckedType = 0x08, + + /// FIME: Temporary hack. + /// Force apply a viable solution even if they are ambiguous, so that the + /// client get a solution. + ForceApplyViableSolution = 0x10, }; /// Options that affect the constraint system as a whole. diff --git a/lib/Sema/TypeCheckAccess.cpp b/lib/Sema/TypeCheckAccess.cpp index 130b1cb2a9812..4bf6bdbdc3c87 100644 --- a/lib/Sema/TypeCheckAccess.cpp +++ b/lib/Sema/TypeCheckAccess.cpp @@ -1483,14 +1483,11 @@ class UsableFromInlineChecker : public AccessControlCheckerBase, } }; -// Diagnose public APIs exposing types that are either imported as -// implementation-only or declared as SPI. class ExportabilityChecker : public DeclVisitor { class Diagnoser; void checkTypeImpl( Type type, const TypeRepr *typeRepr, const SourceFile &SF, - const Decl *context, const Diagnoser &diagnoser) { // Don't bother checking errors. if (type && type->hasError()) @@ -1503,15 +1500,14 @@ class ExportabilityChecker : public DeclVisitor { if (typeRepr) { const_cast(typeRepr)->walk(TypeReprIdentFinder( [&](const ComponentIdentTypeRepr *component) { - TypeDecl *typeDecl = component->getBoundDecl(); - ModuleDecl *M = typeDecl->getModuleContext(); - bool isImplementationOnly = SF.isImportedImplementationOnly(M); - if (isImplementationOnly || - (SF.isImportedAsSPI(typeDecl) && !context->isSPI())) { - diagnoser.diagnoseType(typeDecl, component, isImplementationOnly); - foundAnyIssues = true; - } - + ModuleDecl *M = component->getBoundDecl()->getModuleContext(); + if (!SF.isImportedImplementationOnly(M) && + !SF.isImportedAsSPI(component->getBoundDecl())) + return true; + + diagnoser.diagnoseType(component->getBoundDecl(), component, + SF.isImportedImplementationOnly(M)); + foundAnyIssues = true; // We still continue even in the diagnostic case to report multiple // violations. return true; @@ -1529,19 +1525,19 @@ class ExportabilityChecker : public DeclVisitor { class ProblematicTypeFinder : public TypeDeclFinder { const SourceFile &SF; - const Decl *context; const Diagnoser &diagnoser; public: - ProblematicTypeFinder(const SourceFile &SF, const Decl *context, const Diagnoser &diagnoser) - : SF(SF), context(context), diagnoser(diagnoser) {} + ProblematicTypeFinder(const SourceFile &SF, const Diagnoser &diagnoser) + : SF(SF), diagnoser(diagnoser) {} void visitTypeDecl(const TypeDecl *typeDecl) { ModuleDecl *M = typeDecl->getModuleContext(); - bool isImplementationOnly = SF.isImportedImplementationOnly(M); - if (isImplementationOnly || - (SF.isImportedAsSPI(typeDecl) && !context->isSPI())) - diagnoser.diagnoseType(typeDecl, /*typeRepr*/nullptr, - isImplementationOnly); + if (!SF.isImportedImplementationOnly(M) && + !SF.isImportedAsSPI(typeDecl)) + return; + + diagnoser.diagnoseType(typeDecl, /*typeRepr*/nullptr, + SF.isImportedImplementationOnly(M)); } void visitSubstitutionMap(SubstitutionMap subs) { @@ -1601,7 +1597,7 @@ class ExportabilityChecker : public DeclVisitor { } }; - type.walk(ProblematicTypeFinder(SF, context, diagnoser)); + type.walk(ProblematicTypeFinder(SF, diagnoser)); } void checkType( @@ -1609,7 +1605,7 @@ class ExportabilityChecker : public DeclVisitor { const Diagnoser &diagnoser) { auto *SF = context->getDeclContext()->getParentSourceFile(); assert(SF && "checking a non-source declaration?"); - return checkTypeImpl(type, typeRepr, *SF, context, diagnoser); + return checkTypeImpl(type, typeRepr, *SF, diagnoser); } void checkType( @@ -1706,7 +1702,7 @@ class ExportabilityChecker : public DeclVisitor { AccessScope accessScope = VD->getFormalAccessScope(nullptr, /*treatUsableFromInlineAsPublic*/true); - if (accessScope.isPublic()) + if (accessScope.isPublic() && !accessScope.isSPI()) return false; // Is this a stored property in a non-resilient struct or class? diff --git a/lib/Sema/TypeCheckDecl.cpp b/lib/Sema/TypeCheckDecl.cpp index f1620fb6882b1..9c584f7dece61 100644 --- a/lib/Sema/TypeCheckDecl.cpp +++ b/lib/Sema/TypeCheckDecl.cpp @@ -1152,6 +1152,10 @@ bool SimpleDidSetRequest::evaluate(Evaluator &evaluator, return false; } + // Always assume non-simple 'didSet' in code completion mode. + if (decl->getASTContext().SourceMgr.hasCodeCompletionBuffer()) + return false; + // didSet must have a single parameter. if (decl->getParameters()->size() != 1) { return false; diff --git a/stdlib/cmake/modules/AddSwiftStdlib.cmake b/stdlib/cmake/modules/AddSwiftStdlib.cmake index 53ec587be0873..0a2e3b53f5bed 100644 --- a/stdlib/cmake/modules/AddSwiftStdlib.cmake +++ b/stdlib/cmake/modules/AddSwiftStdlib.cmake @@ -1105,6 +1105,8 @@ function(_add_swift_target_library_single target name) list(APPEND library_search_directories "$ENV{SDKROOT}/usr/lib/swift") endif() + list(APPEND library_search_directories "${SWIFT_SDK_${sdk}_ARCH_${arch}_PATH}/usr/lib/swift") + # Add variant-specific flags. if(SWIFTLIB_SINGLE_TARGET_LIBRARY) set(build_type "${SWIFT_STDLIB_BUILD_TYPE}") diff --git a/stdlib/public/Darwin/ARKit/ARKit.swift b/stdlib/public/Darwin/ARKit/ARKit.swift deleted file mode 100644 index 6fe12d52a7a8c..0000000000000 --- a/stdlib/public/Darwin/ARKit/ARKit.swift +++ /dev/null @@ -1,249 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import ARKit - -@available(iOS, introduced: 11.0) -extension ARCamera { - /** - A value describing the camera's tracking state. - */ - @frozen - public enum TrackingState { - public enum Reason { - /** Tracking is limited due to initialization in progress. */ - case initializing - - /** Tracking is limited due to a excessive motion of the camera. */ - case excessiveMotion - - /** Tracking is limited due to a lack of features visible to the camera. */ - case insufficientFeatures - - /** Tracking is limited due to a relocalization in progress. */ - @available(iOS, introduced: 11.3) - case relocalizing - } - - /** Tracking is not available. */ - case notAvailable - - /** Tracking is limited. See tracking reason for details. */ - case limited(Reason) - - /** Tracking is normal. */ - case normal - } - - /** - The tracking state of the camera. - */ - public var trackingState: TrackingState { - switch __trackingState { - case .notAvailable: return .notAvailable - case .normal: return .normal - case .limited: - let reason: TrackingState.Reason - - if #available(iOS 11.3, *) { - switch __trackingStateReason { - case .initializing: reason = .initializing - case .relocalizing: reason = .relocalizing - case .excessiveMotion: reason = .excessiveMotion - default: reason = .insufficientFeatures - } - } - else { - switch __trackingStateReason { - case .initializing: reason = .initializing - case .excessiveMotion: reason = .excessiveMotion - default: reason = .insufficientFeatures - } - } - - return .limited(reason) - } - } - - @available(iOS, introduced: 12.0) - @nonobjc - public func unprojectPoint( - _ point: CGPoint, - ontoPlane planeTransform: simd_float4x4, - orientation: UIInterfaceOrientation, - viewportSize: CGSize - ) -> simd_float3? { - let result = __unprojectPoint( - point, - ontoPlaneWithTransform: planeTransform, - orientation: orientation, - viewportSize: viewportSize) - if result.x.isNaN || result.y.isNaN || result.z.isNaN { - return nil - } - - return result - } -} - -@available(iOS, introduced: 12.0) -extension ARSCNView { - @nonobjc public func unprojectPoint( - _ point: CGPoint, ontoPlane planeTransform: simd_float4x4 - ) -> simd_float3? { - let result = __unprojectPoint( - point, ontoPlaneWithTransform: planeTransform) - if result.x.isNaN || result.y.isNaN || result.z.isNaN { - return nil - } - - return result - } -} - -@available(iOS, introduced: 11.0) -extension ARPointCloud { - /** - The 3D points comprising the point cloud. - */ - @nonobjc public var points: [vector_float3] { - let buffer = UnsafeBufferPointer(start: __points, count: Int(__count)) - return Array(buffer) - } - - /** - The 3D point identifiers comprising the point cloud. - */ - @nonobjc public var identifiers: [UInt64] { - let buffer = UnsafeBufferPointer(start: __identifiers, count: Int(__count)) - return Array(buffer) - } -} - -@available(iOS, introduced: 11.0) -extension ARFaceGeometry { - /** - The mesh vertices of the geometry. - */ - @nonobjc public var vertices: [vector_float3] { - let buffer = UnsafeBufferPointer(start: __vertices, count: Int(__vertexCount)) - return Array(buffer) - } - - /** - The texture coordinates of the geometry. - */ - @nonobjc public var textureCoordinates: [vector_float2] { - let buffer = UnsafeBufferPointer(start: __textureCoordinates, count: Int(__textureCoordinateCount)) - return Array(buffer) - } - - /** - The triangle indices of the geometry. - */ - @nonobjc public var triangleIndices: [Int16] { - let buffer = UnsafeBufferPointer(start: __triangleIndices, count: Int(triangleCount * 3)) - return Array(buffer) - } -} - -@available(iOS, introduced: 11.3) -extension ARPlaneGeometry { - /** - The mesh vertices of the geometry. - */ - @nonobjc public var vertices: [vector_float3] { - let buffer = UnsafeBufferPointer(start: __vertices, count: Int(__vertexCount)) - return Array(buffer) - } - - /** - The texture coordinates of the geometry. - */ - @nonobjc public var textureCoordinates: [vector_float2] { - let buffer = UnsafeBufferPointer(start: __textureCoordinates, count: Int(__textureCoordinateCount)) - return Array(buffer) - } - - /** - The triangle indices of the geometry. - */ - @nonobjc public var triangleIndices: [Int16] { - let buffer = UnsafeBufferPointer(start: __triangleIndices, count: Int(triangleCount * 3)) - return Array(buffer) - } - - /** - The vertices of the geometry's outermost boundary. - */ - @nonobjc public var boundaryVertices: [vector_float3] { - let buffer = UnsafeBufferPointer(start: __boundaryVertices, count: Int(__boundaryVertexCount)) - return Array(buffer) - } -} - -@available(iOS, introduced: 12.0) -extension ARPlaneAnchor { - /** - A value describing the classification of a plane anchor. - */ - public enum Classification { - - public enum Status { - - /** Plane classification is currently unavailable. */ - case notAvailable - - /** ARKit has not yet determined the classification of this plane. */ - case undetermined - - /** ARKit is confident the plane is not any of the known classes. */ - case unknown - } - - /** The classification is not any of the known classes. */ - case none(Status) - - case wall - - case floor - - case ceiling - - case table - - case seat - } - - - /** - Classification of the plane. - */ - public var classification: ARPlaneAnchor.Classification { - switch __classification { - case .wall: return .wall - case .floor: return .floor - case .ceiling: return .ceiling - case .table: return .table - case .seat: return .seat - case .none: fallthrough - default: - switch __classificationStatus { - case .notAvailable: return .none(.notAvailable) - case .unknown: return .none(.unknown) - case .undetermined: fallthrough - case .known: fallthrough - default: return .none(.undetermined) - } - } - } -} diff --git a/stdlib/public/Darwin/ARKit/CMakeLists.txt b/stdlib/public/Darwin/ARKit/CMakeLists.txt deleted file mode 100644 index f8e3eeff16388..0000000000000 --- a/stdlib/public/Darwin/ARKit/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftARKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - ARKit.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS IOS IOS_SIMULATOR - SWIFT_MODULE_DEPENDS_IOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch GLKit SceneKit simd Foundation AVFoundation SpriteKit CoreMedia QuartzCore ModelIO CoreFoundation CoreAudio ObjectiveC # auto-updated - FRAMEWORK_DEPENDS_WEAK ARKit - SWIFT_MODULE_DEPENDS_FROM_SDK CoreMIDI - - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_ARKIT_IOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/AVFoundation/AVCaptureDevice.swift b/stdlib/public/Darwin/AVFoundation/AVCaptureDevice.swift deleted file mode 100644 index c7519a2fc3852..0000000000000 --- a/stdlib/public/Darwin/AVFoundation/AVCaptureDevice.swift +++ /dev/null @@ -1,37 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import AVFoundation // Clang module -import Foundation - - -#if os(iOS) - -@available(iOS, introduced: 10.0) -extension AVCaptureDevice.Format { - @available(swift, obsoleted: 4.0) - @available(iOS, introduced: 10.0) - @nonobjc - public var supportedColorSpaces: [NSNumber]! { - return __supportedColorSpaces - } - - @available(swift, introduced: 4.0) - @available(iOS, introduced: 10.0) - @nonobjc - public var supportedColorSpaces: [AVCaptureColorSpace] { - return __supportedColorSpaces.map { AVCaptureColorSpace(rawValue: $0.intValue)! } - } -} - -#endif - diff --git a/stdlib/public/Darwin/AVFoundation/AVCapturePhotoOutput.swift b/stdlib/public/Darwin/AVFoundation/AVCapturePhotoOutput.swift deleted file mode 100644 index 70cac62515eaf..0000000000000 --- a/stdlib/public/Darwin/AVFoundation/AVCapturePhotoOutput.swift +++ /dev/null @@ -1,81 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import AVFoundation // Clang module -import Foundation - - -#if os(iOS) - -@available(iOS, introduced: 10.0) -extension AVCapturePhotoOutput { - @available(swift, obsoleted: 4.0) - @available(iOS, introduced: 10.0) - @nonobjc - public var supportedFlashModes: [NSNumber] { - return __supportedFlashModes - } - - @available(swift, introduced: 4.0) - @available(iOS, introduced: 10.0) - @nonobjc - public var supportedFlashModes: [AVCaptureDevice.FlashMode] { - return __supportedFlashModes.map { AVCaptureDevice.FlashMode(rawValue: $0.intValue)! } - } - - @available(swift, obsoleted: 4.0) - @available(iOS, introduced: 10.0) - @nonobjc - public var availablePhotoPixelFormatTypes: [NSNumber] { - return __availablePhotoPixelFormatTypes - } - - @available(swift, introduced: 4.0) - @available(iOS, introduced: 10.0) - @nonobjc - public var availablePhotoPixelFormatTypes: [OSType] { - return __availablePhotoPixelFormatTypes.map { $0.uint32Value } as [OSType] - } - - @available(swift, obsoleted: 4.0) - @available(iOS, introduced: 10.0) - @nonobjc - public var availableRawPhotoPixelFormatTypes: [NSNumber] { - return __availableRawPhotoPixelFormatTypes - } - - @available(swift, introduced: 4.0) - @available(iOS, introduced: 10.0) - @nonobjc - public var availableRawPhotoPixelFormatTypes: [OSType] { - return __availableRawPhotoPixelFormatTypes.map { $0.uint32Value } as [OSType] - } -} - -@available(iOS, introduced: 10.0) -extension AVCapturePhotoSettings { - @available(swift, obsoleted: 4.0) - @available(iOS, introduced: 10.0) - @nonobjc - public var availablePreviewPhotoPixelFormatTypes: [NSNumber] { - return __availablePreviewPhotoPixelFormatTypes - } - - @available(swift, introduced: 4.0) - @available(iOS, introduced: 10.0) - @nonobjc - public var availablePreviewPhotoPixelFormatTypes: [OSType] { - return __availablePreviewPhotoPixelFormatTypes.map { $0.uint32Value } as [OSType] - } -} - -#endif diff --git a/stdlib/public/Darwin/AVFoundation/AVCaptureSynchronizedDataCollection.swift b/stdlib/public/Darwin/AVFoundation/AVCaptureSynchronizedDataCollection.swift deleted file mode 100644 index a17beb151790c..0000000000000 --- a/stdlib/public/Darwin/AVFoundation/AVCaptureSynchronizedDataCollection.swift +++ /dev/null @@ -1,38 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import AVFoundation // Clang module -import Foundation - - -#if os(iOS) -@available(iOS, introduced: 11.0) -extension AVCaptureSynchronizedDataCollection : Sequence { - public func makeIterator() -> Iterator { - return Iterator(self) - } - - public struct Iterator : IteratorProtocol { - internal var fastIterator: NSFastEnumerationIterator - - internal init(_ collection: AVCaptureSynchronizedDataCollection) { - self.fastIterator = NSFastEnumerationIterator(collection) - } - - public mutating func next() -> AVCaptureSynchronizedData? { - guard let nextAny = fastIterator.next() else { return nil } - return (nextAny as! AVCaptureSynchronizedData) - } - } -} - -#endif diff --git a/stdlib/public/Darwin/AVFoundation/AVCaptureVideoDataOutput.swift b/stdlib/public/Darwin/AVFoundation/AVCaptureVideoDataOutput.swift deleted file mode 100644 index 7cb9c4e06ed6d..0000000000000 --- a/stdlib/public/Darwin/AVFoundation/AVCaptureVideoDataOutput.swift +++ /dev/null @@ -1,37 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import AVFoundation // Clang module -import Foundation - - -#if os(macOS) || os(iOS) - -extension AVCaptureVideoDataOutput { - @available(swift, obsoleted: 4.0) - @available(macOS, introduced: 10.7) - @available(iOS, introduced: 5.0) - @nonobjc - public var availableVideoCVPixelFormatTypes: [Any]! { - return __availableVideoCVPixelFormatTypes - } - - @available(swift, introduced: 4.0) - @available(macOS, introduced: 10.7) - @available(iOS, introduced: 5.0) - @nonobjc - public var availableVideoPixelFormatTypes: [OSType] { - return __availableVideoCVPixelFormatTypes.map { $0.uint32Value } as [OSType] - } -} - -#endif diff --git a/stdlib/public/Darwin/AVFoundation/AVError.swift b/stdlib/public/Darwin/AVFoundation/AVError.swift deleted file mode 100644 index 3b6da62e01048..0000000000000 --- a/stdlib/public/Darwin/AVFoundation/AVError.swift +++ /dev/null @@ -1,103 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import AVFoundation // Clang module -import Foundation - - -extension AVError { - /// The device name. -#if os(tvOS) - @available(*, unavailable) - public var device: String? { return nil } -#else - @available(swift, obsoleted: 4.2, message: "Use `device: AVCaptureDevice?` instead") - public var device: String? { return nil } - - @available(swift, introduced: 4.2) - public var device: AVCaptureDevice? { - return userInfo[AVErrorDeviceKey] as? AVCaptureDevice - } -#endif - - /// The time. - public var time: CMTime? { - if let time = userInfo[AVErrorTimeKey] as? CMTime { - return time - } - else if let timeDictionary = userInfo[AVErrorTimeKey] { - return CMTimeMakeFromDictionary((timeDictionary as! CFDictionary)) - } - else { - return nil - } - } - - /// The file size. - public var fileSize: Int64? { - return userInfo[AVErrorFileSizeKey] as? Int64 - } - - /// The process ID number. - public var processID: Int? { - return userInfo[AVErrorPIDKey] as? Int - } - - /// Whether the recording successfully finished. - public var recordingSuccessfullyFinished: Bool? { - return userInfo[AVErrorRecordingSuccessfullyFinishedKey] as? Bool - } - - /// The media type. - @available(swift, obsoleted: 4.2) - public var mediaType: String? { - return userInfo[AVErrorMediaTypeKey] as? String - } - - /// The media type. - @available(swift, introduced: 4.2) - public var mediaType: AVMediaType? { - return userInfo[AVErrorMediaTypeKey] as? AVMediaType - } - - /// The media subtypes. - public var mediaSubtypes: [Int]? { - return userInfo[AVErrorMediaSubTypeKey] as? [Int] - } - - /// The presentation time stamp. - @available(swift, introduced: 4.2) - @available(macOS, introduced: 10.10) - @available(iOS, introduced: 8.0) - @available(tvOS, introduced: 9.0) - public var presentationTimeStamp: CMTime? { - return userInfo[AVErrorPresentationTimeStampKey] as? CMTime - } - - /// The persistent track ID. - @available(swift, introduced: 4.2) - @available(macOS, introduced: 10.10) - @available(iOS, introduced: 8.0) - @available(tvOS, introduced: 9.0) - public var persistentTrackID: CMPersistentTrackID? { - return userInfo[AVErrorPersistentTrackIDKey] as? CMPersistentTrackID - } - - /// The file type. - @available(swift, introduced: 4.2) - @available(macOS, introduced: 10.10) - @available(iOS, introduced: 8.0) - @available(tvOS, introduced: 9.0) - public var fileType: AVFileType? { - return userInfo[AVErrorFileTypeKey] as? AVFileType - } -} diff --git a/stdlib/public/Darwin/AVFoundation/AVMetadataObject.swift b/stdlib/public/Darwin/AVFoundation/AVMetadataObject.swift deleted file mode 100644 index d884fcdef848e..0000000000000 --- a/stdlib/public/Darwin/AVFoundation/AVMetadataObject.swift +++ /dev/null @@ -1,37 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import AVFoundation // Clang module -import Foundation -import CoreGraphics - - -#if os(iOS) - -extension AVMetadataMachineReadableCodeObject { - @available(swift, obsoleted: 4.0) - @available(iOS, introduced: 7.0) - @nonobjc - public var corners: [Any]! { - return __corners - } - - @available(swift, introduced: 4.0) - @available(iOS, introduced: 7.0) - @nonobjc - public var corners: [CGPoint] { - return __corners.map { CGPoint(dictionaryRepresentation: $0 as CFDictionary)! } - } -} - -#endif - diff --git a/stdlib/public/Darwin/AVFoundation/CMakeLists.txt b/stdlib/public/Darwin/AVFoundation/CMakeLists.txt deleted file mode 100644 index e77e6e3618d0b..0000000000000 --- a/stdlib/public/Darwin/AVFoundation/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftAVFoundation ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - AVCaptureDevice.swift - AVCapturePhotoOutput.swift - AVCaptureSynchronizedDataCollection.swift - AVCaptureVideoDataOutput.swift - AVError.swift - AVMetadataObject.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - GYB_SOURCES - NSValue.swift.gyb - - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" "-L${sdk}/usr/lib/swift/" - SWIFT_MODULE_DEPENDS_OSX Darwin CoreImage CoreGraphics Metal Dispatch IOKit simd Foundation CoreMedia QuartzCore XPC CoreFoundation CoreAudio ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics Metal Dispatch simd Foundation CoreMedia QuartzCore CoreFoundation CoreAudio ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreGraphics Metal Dispatch simd Foundation CoreMedia QuartzCore CoreFoundation CoreAudio ObjectiveC # auto-updated - FRAMEWORK_DEPENDS AVFoundation - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_AVFOUNDATION_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_AVFOUNDATION_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_AVFOUNDATION_TVOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/AVFoundation/NSValue.swift.gyb b/stdlib/public/Darwin/AVFoundation/NSValue.swift.gyb deleted file mode 100644 index f4004ca838f0c..0000000000000 --- a/stdlib/public/Darwin/AVFoundation/NSValue.swift.gyb +++ /dev/null @@ -1,29 +0,0 @@ -@_exported import AVFoundation // Clang module -import CoreMedia -import Foundation - -%{ -from gyb_foundation_support import \ - ObjectiveCBridgeableImplementationForNSValueWithCategoryMethods -}% - -// Bridge CoreMedia structs to NSValue. -// AVFoundation provides internal NSValue subclasses for these structures that -// are incompatible with the NSConcreteValue subclasses you get using -// -[NSValue valueWithBytes:objCType:]. - -${ ObjectiveCBridgeableImplementationForNSValueWithCategoryMethods( - Type="CMTime", - initializer="{ NSValue(time: $0) }", - getter="{ $0.timeValue }", -) } -${ ObjectiveCBridgeableImplementationForNSValueWithCategoryMethods( - Type="CMTimeRange", - initializer="{ NSValue(timeRange: $0) }", - getter="{ $0.timeRangeValue }", -) } -${ ObjectiveCBridgeableImplementationForNSValueWithCategoryMethods( - Type="CMTimeMapping", - initializer="{ NSValue(timeMapping: $0) }", - getter="{ $0.timeMappingValue }", -) } diff --git a/stdlib/public/Darwin/Accelerate/Accelerate.swift b/stdlib/public/Darwin/Accelerate/Accelerate.swift deleted file mode 100644 index 047420decd9bb..0000000000000 --- a/stdlib/public/Darwin/Accelerate/Accelerate.swift +++ /dev/null @@ -1,36 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -/// An enum that acts as a namespace for Swift overlays to vImage option sets and enums.. -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public enum vImage {} - -/// An enum that acts as a namespace for Swift overlays to vDSP based functions. -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public enum vDSP {} - -/// An enum that acts as a namespace for Swift overlays to vForce based functions. -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public enum vForce {} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - public struct VectorizableFloat { - public typealias Scalar = Float - } - - @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - public struct VectorizableDouble { - public typealias Scalar = Double - } -} diff --git a/stdlib/public/Darwin/Accelerate/AccelerateBuffer.swift b/stdlib/public/Darwin/Accelerate/AccelerateBuffer.swift deleted file mode 100644 index c1a68eec66f6e..0000000000000 --- a/stdlib/public/Darwin/Accelerate/AccelerateBuffer.swift +++ /dev/null @@ -1,86 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -/// An object composed of count elements that are stored contiguously in memory. -/// -/// In practice, most types conforming to this protocol will be Collections, -/// but they need not be--they need only have an Element type and count, and -/// provide the withUnsafeBufferPointer function. -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public protocol AccelerateBuffer { - /// The buffer's element type. - associatedtype Element - - /// The number of elements in the buffer. - var count: Int { get } - - /// Calls a closure with a pointer to the object's contiguous storage. - func withUnsafeBufferPointer( - _ body: (UnsafeBufferPointer) throws -> R - ) rethrows -> R -} - -/// A mutable object composed of count elements that are stored contiguously -/// in memory. -/// -/// In practice, most types conforming to this protocol will be -/// MutableCollections, but they need not be. -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public protocol AccelerateMutableBuffer: AccelerateBuffer { - /// Calls the given closure with a pointer to the object's mutable - /// contiguous storage. - mutating func withUnsafeMutableBufferPointer( - _ body: (inout UnsafeMutableBufferPointer) throws -> R - ) rethrows -> R -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public extension AccelerateBuffer where Self: Collection { - @inlinable - func withUnsafeBufferPointer( - _ body: (UnsafeBufferPointer) throws -> R - ) rethrows -> R { - return try withContiguousStorageIfAvailable(body)! - } -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension AccelerateMutableBuffer where Self: MutableCollection { - @inlinable - public mutating func withUnsafeMutableBufferPointer( - _ body: (inout UnsafeMutableBufferPointer) throws -> R - ) rethrows -> R { - return try withContiguousMutableStorageIfAvailable(body)! - } -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension Array: AccelerateMutableBuffer { } - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension ContiguousArray: AccelerateMutableBuffer { } - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension ArraySlice: AccelerateMutableBuffer { } - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension UnsafeBufferPointer: AccelerateBuffer { } - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension UnsafeMutableBufferPointer: AccelerateMutableBuffer { } - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension Slice: AccelerateBuffer where Base: AccelerateBuffer { } - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension Slice: AccelerateMutableBuffer -where Base: AccelerateMutableBuffer & MutableCollection { } diff --git a/stdlib/public/Darwin/Accelerate/BNNS.swift.gyb b/stdlib/public/Darwin/Accelerate/BNNS.swift.gyb deleted file mode 100644 index e64cbd73436f2..0000000000000 --- a/stdlib/public/Darwin/Accelerate/BNNS.swift.gyb +++ /dev/null @@ -1,303 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Accelerate -@_exported import Accelerate.vecLib.BNNS - -%{ -bnns2016 = [ - ('macOS','10.12'), ('iOS','10.0'), ('tvOS','10.0'), ('watchOS','3.0') -] - -bnns2017 = [ - ('macOS','10.13'), ('iOS','11.0'), ('tvOS','11.0'), ('watchOS','4.0') -] - -def relString(releases): - if not releases: - return '*' - return ', '.join([ - r[0] + ' ' + r[1] for r in releases - ] + ['*']) - -def available(releases): - return '@available(' + relString(releases) + ')' - -def renamed(name, rel=None): - return '\n'.join([ - available(rel), - '@available(*, deprecated, renamed: "' + name + '")' - ]) - -def newEnumValue(base, new, old, rel): - decl = ' public static var ' + new + ': ' + base + ' {\n' - impl = ' return __' + base + old + '\n }' - return ' ' + available(rel) + '\n' + decl + impl - -def oldEnumValue(base, new, old, oldRel): - return renamed(base + '.' + new, oldRel) + '\n' + \ - 'public var ' + base + old + ' = __' + base + old - -def renameEnumMembers(base, baseRel, names): - return available(baseRel) + \ - '\nextension ' + base + ' {\n' + \ - '\n'.join([newEnumValue(base, new, old, rel) for new, old, rel in names]) + '\n}\n' + \ - '\n'.join([oldEnumValue(base, new, old, rel) for new, old, rel in names if rel != bnns2017]) -}% - -${renameEnumMembers('BNNSDataType', bnns2016, [ - ('float16', 'Float16', bnns2016), - ('float', 'Float32', bnns2016), - ('int8', 'Int8', bnns2016), - ('int16', 'Int16', bnns2016), - ('int32', 'Int32', bnns2016), - ('uint8', 'UInt8', bnns2017), - ('uint16', 'UInt16', bnns2017), - ('uint32', 'UInt32', bnns2017), - ('indexed8','Indexed8',bnns2016), -])} - -${renameEnumMembers('BNNSPoolingFunction', bnns2016, [ - ('max', 'Max', bnns2016), - ('average', 'Average', bnns2016), -])} - -${renameEnumMembers('BNNSActivationFunction', bnns2016, [ - ('identity', 'Identity', bnns2016), - ('rectifiedLinear', 'RectifiedLinear', bnns2016), - ('leakyRectifiedLinear', 'LeakyRectifiedLinear', bnns2016), - ('sigmoid', 'Sigmoid', bnns2016), - ('tanh', 'Tanh', bnns2016), - ('scaledTanh', 'ScaledTanh', bnns2016), - ('abs', 'Abs', bnns2016), - ('linear', 'Linear', bnns2017), - ('clamp', 'Clamp', bnns2017), - ('integerLinearSaturate', 'IntegerLinearSaturate', bnns2017), - ('integerLinearSaturatePerChannel', 'IntegerLinearSaturatePerChannel', bnns2017), - ('softmax', 'Softmax', bnns2017), -])} - -${renameEnumMembers('BNNSFlags', bnns2016, [('useClientPointer', 'UseClientPtr', bnns2016)])} - -${available(bnns2016)} -extension BNNSImageStackDescriptor { - ${available(bnns2016)} - public init(width: Int, - height: Int, - channels: Int, - row_stride: Int, - image_stride: Int, - data_type: BNNSDataType) { - - precondition(data_type != .indexed8, - "Image stacks cannot use the indexed8 data type.") - - self.init(width: width, - height: height, - channels: channels, - row_stride: row_stride, - image_stride: image_stride, - data_type: data_type, - data_scale: 1, - data_bias: 0) - } -} - -${available(bnns2016)} -extension BNNSVectorDescriptor { - ${available(bnns2016)} - public init(size: Int, - data_type: BNNSDataType) { - - precondition(data_type != .indexed8, - "Vectors cannot use the indexed8 data type.") - - self.init(size: size, - data_type: data_type, - data_scale: 1, - data_bias: 0) - } -} - -${available(bnns2016)} -extension BNNSLayerData { - ${available(bnns2016)} - public init(data: UnsafeRawPointer?, - data_type: BNNSDataType, - data_scale: Float = 1, - data_bias: Float = 0) { - - precondition(data_type != .indexed8, - "This initializer cannot be used with the indexed8 data type; use BNNSLayerData.indexed8 instead.") - - self.init(data: data, - data_type: data_type, - data_scale: data_scale, - data_bias: data_bias, - data_table: nil) - } - - ${available(bnns2016)} - public static var zero: BNNSLayerData { - return BNNSLayerData() - } - - /// A BNNSLayerData object with the indexed8 data type. - ${available(bnns2016)} - public static func indexed8(data: UnsafePointer?, - data_table: UnsafePointer) - -> BNNSLayerData { - return BNNSLayerData(data: data, - data_type: .indexed8, - data_scale: 1, // unused - data_bias: 0, // unused - data_table: data_table) - } -} - -${available(bnns2016)} -extension BNNSActivation { - - ${available(bnns2016)} - public init(function: BNNSActivationFunction, - alpha: Float = .nan, - beta: Float = .nan) { - if #available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) { - precondition(function != .integerLinearSaturate, - "This initializer cannot be used with the integerLinearSaturate activation function; use BNNSActivation.integerLinearSaturate(scale:Int32, offset:Int32, shift:Int32) instead.") - precondition(function != .integerLinearSaturatePerChannel, - "This initializer cannot be used with the integerLinearSaturatePerChannel activation function; use BNNSActivation.integerLinearSaturatePerChannel(scale:UnsafePointer, offset:UnsafePointer, shift:UnsafePointer) instead.") - } - self.init(function: function, - alpha: alpha, - beta: beta, - iscale: 1, // unused - ioffset: 0, // unused - ishift: 0, // unused - iscale_per_channel: nil, // unused - ioffset_per_channel: nil, // unused - ishift_per_channel: nil) // unused - } - - /// A BNNSActivation object that uses the identity activation function. - ${available(bnns2016)} - public static var identity: BNNSActivation { - return BNNSActivation(function: .identity) - } - - /// A BNNSActivation object that uses the integerLinearSaturate - /// activation function. - ${available(bnns2017)} - public static func integerLinearSaturate( - scale: Int32 = 1, - offset: Int32 = 0, - shift: Int32 = 0) - -> BNNSActivation { - return BNNSActivation(function: .integerLinearSaturate, - alpha: .nan, // unused - beta: .nan, // unused - iscale: scale, - ioffset: offset, - ishift: shift, - iscale_per_channel: nil, // unused - ioffset_per_channel: nil,// unused - ishift_per_channel: nil) // unused - } - - /// A BNNSActivation object that uses the integerLinearSaturatePerChannel - /// activation function. - /// - /// `scale`, `offset`, and `shift` must each point to a buffer with count - /// equal to the number of channels on which this activation object operates. - ${available(bnns2017)} - public static func integerLinearSaturatePerChannel( - scale: UnsafePointer, - offset: UnsafePointer, - shift: UnsafePointer) - -> BNNSActivation { - return BNNSActivation(function: .integerLinearSaturatePerChannel, - alpha: .nan, // unused - beta: .nan, // unused - iscale: 1, // unused - ioffset: 0, // unused - ishift: 0, // unused - iscale_per_channel: scale, - ioffset_per_channel: offset, - ishift_per_channel: shift) - } -} - -${available(bnns2016)} -extension BNNSConvolutionLayerParameters { - ${available(bnns2016)} - public init(x_stride: Int, - y_stride: Int, - x_padding: Int, - y_padding: Int, - k_width: Int, - k_height: Int, - in_channels: Int, - out_channels: Int, - weights: BNNSLayerData) { - self.init(x_stride: x_stride, - y_stride: y_stride, - x_padding: x_padding, - y_padding: y_padding, - k_width: k_width, - k_height: k_height, - in_channels: in_channels, - out_channels: out_channels, - weights: weights, - bias: .zero, - activation: .identity) - } -} - -${available(bnns2016)} -extension BNNSPoolingLayerParameters { - ${available(bnns2016)} - public init(x_stride: Int, - y_stride: Int, - x_padding: Int, - y_padding: Int, - k_width: Int, - k_height: Int, - in_channels: Int, - out_channels: Int, - pooling_function: BNNSPoolingFunction) { - self.init(x_stride: x_stride, - y_stride: y_stride, - x_padding: x_padding, - y_padding: y_padding, - k_width: k_width, - k_height: k_height, - in_channels: in_channels, - out_channels: out_channels, - pooling_function: pooling_function, - bias: .zero, - activation: .identity) - } -} - -${available(bnns2016)} -extension BNNSFullyConnectedLayerParameters { - ${available(bnns2016)} - public init(in_size: Int, - out_size: Int, - weights: BNNSLayerData) { - self.init(in_size: in_size, - out_size: out_size, - weights: weights, - bias: .zero, - activation: .identity) - } -} diff --git a/stdlib/public/Darwin/Accelerate/CMakeLists.txt b/stdlib/public/Darwin/Accelerate/CMakeLists.txt deleted file mode 100644 index 6bb4e7329a496..0000000000000 --- a/stdlib/public/Darwin/Accelerate/CMakeLists.txt +++ /dev/null @@ -1,60 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftAccelerate ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - Accelerate.swift - vImage_Error.swift - vImage_Options.swift - vImage_Buffer.swift - vImage_CVImageFormat.swift - vImage_CGImageFormat.swift - vImage_Converter.swift - AccelerateBuffer.swift - Quadrature.swift - vDSP_Arithmetic.swift - vDSP_Biquad.swift - vDSP_ClippingLimitThreshold.swift - vDSP_ComplexConversion.swift - vDSP_ComplexOperations.swift - vDSP_Conversion.swift - vDSP_Convolution.swift - vDSP_DCT.swift - vDSP_DFT.swift - vDSP_DecibelConversion.swift - vDSP_FFT.swift - vDSP_FFT_DFT_Common.swift - vDSP_FIR.swift - vDSP_FillClearGenerate.swift - vDSP_Geometry.swift - vDSP_Integration.swift - vDSP_Interpolation.swift - vDSP_PolarRectangularConversion.swift - vDSP_PolynomialEvaluation.swift - vDSP_RecursiveFilters.swift - vDSP_Reduction.swift - vDSP_SingleVectorOperations.swift - vDSP_SlidingWindow.swift - vForce_Operations.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - GYB_SOURCES - BNNS.swift.gyb - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Metal Dispatch IOKit Foundation os XPC CoreFoundation ObjectiveC # auto-updated - os - SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics Dispatch Foundation Metal ObjectiveC os # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics Dispatch Foundation Metal ObjectiveC os # auto-updated - SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreGraphics Dispatch os CoreFoundation ObjectiveC # auto-updated - - FRAMEWORK_DEPENDS Accelerate - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_SIMD_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_SIMD_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_SIMD_TVOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_SIMD_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/Accelerate/Quadrature.swift b/stdlib/public/Darwin/Accelerate/Quadrature.swift deleted file mode 100644 index 3abccee329bb5..0000000000000 --- a/stdlib/public/Darwin/Accelerate/Quadrature.swift +++ /dev/null @@ -1,293 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -// MARK: Quadrature - -/// A structure that approximates the definite integral of a function over a finite interval. -/// -/// The following code is an example of using a `Quadrature` structure to calculate the -/// area under a curve defined by `y = sqrt(radius * radius - pow(x - radius, 2))`: -/// -/// -/// let quadrature = Quadrature(integrator: .qags(maxIntervals: 10), -/// absoluteTolerance: 1.0e-8, -/// relativeTolerance: 1.0e-2) -/// -/// let result = quadrature.integrate(over: 0.0 ... 25.0) { x in -/// let radius: Double = 12.5 -/// return sqrt(radius * radius - pow(x - radius, 2)) -/// } -/// -/// switch result { -/// case .success(let integralResult, let estimatedAbsoluteError): -/// print("quadrature success:", integralResult, -/// estimatedAbsoluteError) -/// case .failure(let error): -/// print("quadrature error:", error.errorDescription) -/// } -/// -/// Alternatively, you can integrate over a function that uses vectors for its -/// source and destination. For example: -/// -/// func vectorExp(x: UnsafeBufferPointer, -/// y: UnsafeMutableBufferPointer) { -/// let radius: Double = 12.5 -/// for i in 0 ..< x.count { -/// y[i] = sqrt(radius * radius - pow(x[i] - radius, 2)) -/// } -/// } -/// -/// let vRresult = quadrature.integrate(over: 0.0 ... diameter, -/// integrand: vectorExp) -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public struct Quadrature { - - private var integrateOptions = quadrature_integrate_options() - - /// Initializes and returns a quadrature instance. - /// - /// - Parameter integrator: An enumeration specifying the integration algorithm and relevant properties. - /// - Parameter absoluteTolerance: Requested absolute tolerance on the result. - /// - Parameter relativeTolerance: Requested relative tolerance on the result. - public init(integrator: Integrator, - absoluteTolerance: Double = 1.0e-8, - relativeTolerance: Double = 1.0e-2){ - - integrateOptions.abs_tolerance = absoluteTolerance - integrateOptions.rel_tolerance = relativeTolerance - - switch integrator { - case .qng: - integrateOptions.integrator = QUADRATURE_INTEGRATE_QNG - case .qag(let pointsPerInterval, let maxIntervals): - integrateOptions.integrator = QUADRATURE_INTEGRATE_QAG - integrateOptions.qag_points_per_interval = pointsPerInterval.points - integrateOptions.max_intervals = maxIntervals - case .qags(let maxIntervals): - integrateOptions.integrator = QUADRATURE_INTEGRATE_QAGS - integrateOptions.max_intervals = maxIntervals - } - } - - /// The quadrature instance's requested absolute tolerance on the result. - public var absoluteTolerance: Double { - set { - integrateOptions.abs_tolerance = newValue - } - get { - return integrateOptions.abs_tolerance - } - } - - /// The quadrature instance's requested relative tolerance on the result. - public var relativeTolerance: Double { - set { - integrateOptions.rel_tolerance = newValue - } - get { - return integrateOptions.rel_tolerance - } - } - - /// Performs the integration over the supplied function. - /// - /// - Parameter interval: The lower and upper bounds of the integration interval. - /// - Parameter integrand: The function to integrate. The input value is `x` that's within the interval over which the integrand is being integrated, and the output value is the corresponding value `y = integrand(x)` at those points. - public func integrate(over interval: ClosedRange, - integrand: (_ input: UnsafeBufferPointer, _ result: UnsafeMutableBufferPointer) -> ()) -> - Result<(integralResult: Double, estimatedAbsoluteError: Double), Error>{ - - var status = QUADRATURE_SUCCESS - var estimatedAbsoluteError: Double = 0 - var result: Double = 0 - - var callback: quadrature_integrate_function! - - withoutActuallyEscaping(integrand) {escapableIntegrand in - withUnsafePointer(to: escapableIntegrand) { - let integrandPointer = UnsafeMutableRawPointer(mutating: $0) - - callback = quadrature_integrate_function( - fun: { (arg: UnsafeMutableRawPointer?, - n: Int, - x: UnsafePointer, - y: UnsafeMutablePointer - ) in - - guard let integrand = arg?.load(as: ((UnsafeBufferPointer, UnsafeMutableBufferPointer) ->()).self) else { - return - } - - integrand(UnsafeBufferPointer(start: x, count: n), - UnsafeMutableBufferPointer(start: y, count: n)) - }, - fun_arg: integrandPointer) - - withUnsafePointer(to: self.integrateOptions) { options in - result = quadrature_integrate(&callback, - interval.lowerBound, - interval.upperBound, - options, - &status, - &estimatedAbsoluteError, - 0, - nil) - } - } - } - - if status == QUADRATURE_SUCCESS { - return .success((integralResult: result, - estimatedAbsoluteError: estimatedAbsoluteError)) - } else { - return .failure(Error(quadratureStatus: status)) - } - } - - /// Performs the integration over the supplied function. - /// - /// - Parameter interval: The lower and upper bounds of the integration interval. - /// - Parameter integrand: The function to integrate. The input value is `x` that's within the interval over which the integrand is being integrated, and the output value is the corresponding value `y = integrand(x)` at those points. - public func integrate(over interval: ClosedRange, - integrand: (Double) -> Double) -> - Result<(integralResult: Double, estimatedAbsoluteError: Double), Error> { - - var status = QUADRATURE_SUCCESS - var estimatedAbsoluteError: Double = 0 - var result: Double = 0 - - var callback: quadrature_integrate_function! - - withoutActuallyEscaping(integrand) {escapableIntegrand in - withUnsafePointer(to: escapableIntegrand) { - let integrandPointer = UnsafeMutableRawPointer(mutating: $0) - - callback = quadrature_integrate_function( - fun: { (arg: UnsafeMutableRawPointer?, - n: Int, - x: UnsafePointer, - y: UnsafeMutablePointer - ) in - - guard let integrand = arg?.load(as: ((Double) -> Double).self) else { - return - } - - (0 ..< n).forEach { i in - y[i] = integrand(x[i]) - } - }, - fun_arg: integrandPointer) - - withUnsafePointer(to: self.integrateOptions) { options in - result = quadrature_integrate(&callback, - interval.lowerBound, - interval.upperBound, - options, - &status, - &estimatedAbsoluteError, - 0, - nil) - } - } - } - - if status == QUADRATURE_SUCCESS { - return .success((integralResult: result, - estimatedAbsoluteError: estimatedAbsoluteError)) - } else { - return .failure(Error(quadratureStatus: status)) - } - } - - public enum Integrator { - /// Simple non-adaptive automatic integrator using Gauss-Kronrod-Patterson quadrature coefficients. - /// Evaluates 21, or 43, or 87 points in the interval until the requested accuracy is reached. - case qng - - /// Simple non-adaptive automatic integrator using Gauss-Kronrod-Patterson quadrature coefficients. - /// Evaluates 21, or 43, or 87 points in the interval until the requested accuracy is reached. - public static let nonAdaptive = Integrator.qng - - /// Simple globally adaptive integrator. - /// Allows selection of the number of Gauss-Kronrod points used in each subinterval, and the max number of subintervals. - case qag(pointsPerInterval: QAGPointsPerInterval, maxIntervals: Int) - - /// Simple globally adaptive integrator. - /// Allows selection of the number of Gauss-Kronrod points used in each subinterval, and the max number of subintervals. - public static func adaptive(pointsPerInterval: QAGPointsPerInterval, maxIntervals: Int) -> Integrator { - return Integrator.qag(pointsPerInterval: pointsPerInterval, maxIntervals: maxIntervals) - } - - /// Global adaptive quadrature based on 21-point or 15-point (if at least one bound is infinite) Gauss–Kronrod quadrature within each subinterval, with acceleration by Peter Wynn's epsilon algorithm. - /// If at least one of the interval bounds is infinite, this is equivalent to the QUADPACK QAGI routine. Otherwise, this is equivalent to the QUADPACK QAGS routine. - case qags(maxIntervals: Int) - - /// Global adaptive quadrature based on 21-point or 15-point (if at least one bound is infinite) Gauss–Kronrod quadrature within each subinterval, with acceleration by Peter Wynn's epsilon algorithm. - /// If at least one of the interval bounds is infinite, this is equivalent to the QUADPACK QAGI routine. Otherwise, this is equivalent to the QUADPACK QAGS routine. - public static func adaptiveWithSingularities(maxIntervals: Int) -> Integrator { - return Integrator.qags(maxIntervals: maxIntervals) - } - } - - public struct QAGPointsPerInterval { - public let points: Int - private init(points: Int) { self.points = points } - - public static let fifteen = QAGPointsPerInterval(points: 15) - public static let twentyOne = QAGPointsPerInterval(points: 21) - public static let thirtyOne = QAGPointsPerInterval(points: 31) - public static let fortyOne = QAGPointsPerInterval(points: 41) - public static let fiftyOne = QAGPointsPerInterval(points: 51) - public static let sixtyOne = QAGPointsPerInterval(points: 61) - } - - public enum Error: Swift.Error { - case generic - case invalidArgument - case `internal` - case integrateMaxEval - case badIntegrandBehaviour - - public init(quadratureStatus: quadrature_status) { - switch quadratureStatus { - case QUADRATURE_ERROR: - self = .generic - case QUADRATURE_INVALID_ARG_ERROR: - self = .invalidArgument - case QUADRATURE_INTERNAL_ERROR: - self = .internal - case QUADRATURE_INTEGRATE_MAX_EVAL_ERROR: - self = .integrateMaxEval - case QUADRATURE_INTEGRATE_BAD_BEHAVIOUR_ERROR: - self = .badIntegrandBehaviour - default: - self = .internal - } - } - - public var errorDescription: String { - switch self { - case .generic: - return "Generic error." - case .invalidArgument: - return "Invalid Argument." - case .internal: - return "This is a bug in the Quadrature code, please file a bug report." - case .integrateMaxEval: - return "The requested accuracy limit could not be reached with the allowed number of evals/subdivisions." - case .badIntegrandBehaviour: - return "Extremely bad integrand behaviour, or excessive roundoff error occurs at some points of the integration interval." - } - } - } -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_Arithmetic.swift b/stdlib/public/Darwin/Accelerate/vDSP_Arithmetic.swift deleted file mode 100644 index 2e0438616b8f0..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_Arithmetic.swift +++ /dev/null @@ -1,3206 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -// Vector-vector and vector-scalar arithmetic - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - // MARK: c[i] = a[i] + b vDSP_vsadd - - /// Returns the elementwise sum of `vector` and `scalar`, - /// single-precision. - /// - /// - Parameter scalar: the `b` in `c[i] = a[i] + b`. - /// - Parameter vector: the `a` in `c[i] = a[i] + b`. - /// - Returns: The `c` in `c[i] = a[i] + b`. - @inlinable - public static func add(_ scalar: Float, - _ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - add(scalar, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise sum of `vector` and `scalar`, - /// single-precision. - /// - /// - Parameter scalar: the `b` in `c[i] = a[i] + b`. - /// - Parameter vector: the `a` in `c[i] = a[i] + b`. - /// - Parameter result: The `c` in `c[i] = a[i] + b`. - @inlinable - public static func add(_ scalar: Float, - _ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vector.count == n) - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - withUnsafePointer(to: scalar) { s in - vDSP_vsadd(v.baseAddress!, 1, - s, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - /// Returns the elementwise sum of `vector` and `scalar`, - /// double-precision. - /// - /// - Parameter scalar: the `b` in `c[i] = a[i] + b`. - /// - Parameter vector: the `a` in `c[i] = a[i] + b`. - /// - Returns: The `c` in `c[i] = a[i] + b`. - @inlinable - public static func add(_ scalar: Double, - _ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - add(scalar, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise sum of `vector` and `scalar`, - /// double-precision. - /// - /// - Parameter scalar: the `b` in `c[i] = a[i] + b`. - /// - Parameter vector: the `a` in `c[i] = a[i] + b`. - /// - Parameter result: The `c` in `c[i] = a[i] + b`. - @inlinable - public static func add(_ scalar: Double, - _ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vector.count == n) - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - withUnsafePointer(to: scalar) { s in - vDSP_vsaddD(v.baseAddress!, 1, - s, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - // MARK: c[i] = a[i] + b[i] vDSP_vadd - - /// Returns the elementwise sum of `vectorA` and `vectorB`, - /// single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] + b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] + b[i]`. - /// - Returns: The `c` in `c[i] = a[i] + b[i]`. - @inlinable - public static func add(_ vectorA: T, - _ vectorB: U) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vectorA.count) { - buffer, initializedCount in - - add(vectorA, - vectorB, - result: &buffer) - - initializedCount = vectorA.count - } - - return result - } - - /// Populates `result` with the elementwise sum of `vectorA` and `vectorB`, - /// single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] + b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] + b[i]`. - /// - Parameter result: The `c` in `c[i] = a[i] + b[i]`. - @inlinable - public static func add(_ vectorA: T, - _ vectorB: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vectorA.count == n && vectorB.count == n) - - result.withUnsafeMutableBufferPointer { r in - vectorA.withUnsafeBufferPointer { a in - vectorB.withUnsafeBufferPointer { b in - vDSP_vadd(a.baseAddress!, 1, - b.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - /// Returns the elementwise sum of `vectorA` and `vectorB`, - /// double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] + b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] + b[i]`. - /// - Returns: The `c` in `c[i] = a[i] + b[i]`. - @inlinable - public static func add(_ vectorA: T, - _ vectorB: U) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vectorA.count) { - buffer, initializedCount in - - add(vectorA, - vectorB, - result: &buffer) - - initializedCount = vectorA.count - } - - return result - } - - /// Populates `result` with the elementwise sum of `vectorA` and `vectorB`, - /// double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] + b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] + b[i]`. - /// - Parameter result: The `c` in `c[i] = a[i] + b[i]`. - @inlinable - public static func add(_ vectorA: T, - _ vectorB: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vectorA.count == n && vectorB.count == n) - - result.withUnsafeMutableBufferPointer { r in - vectorA.withUnsafeBufferPointer { a in - vectorB.withUnsafeBufferPointer { b in - vDSP_vaddD(a.baseAddress!, 1, - b.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - // MARK: c[i] = a[i] - b[i] vDSP_vsub - - /// Returns the elementwise difference of `vectorA` and `vectorB`, - /// single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] - b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] - b[i]`. - /// - Returns: The `c` in `c[i] = a[i] - b[i]`. - @inlinable - public static func subtract(_ vectorA: U, - _ vectorB: T) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vectorA.count) { - buffer, initializedCount in - - subtract(vectorA, - vectorB, - result: &buffer) - - initializedCount = vectorA.count - } - - return result - } - - /// Populates `result` with the elementwise difference of `vectorA` and `vectorB`, - /// single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] - b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] - b[i]`. - /// - Parameter result: The `c` in `c[i] = a[i] - b[i]`. - @inlinable - public static func subtract(_ vectorA: U, - _ vectorB: T, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vectorA.count == n && vectorB.count == n) - - result.withUnsafeMutableBufferPointer { r in - vectorB.withUnsafeBufferPointer { b in - vectorA.withUnsafeBufferPointer { a in - vDSP_vsub(b.baseAddress!, 1, - a.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - /// Returns the elementwise difference of `vectorA` and `vectorB`, - /// double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] - b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] - b[i]`. - /// - Returns: The `c` in `c[i] = a[i] - b[i]`. - @inlinable - public static func subtract(_ vectorA: U, - _ vectorB: T) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vectorA.count) { - buffer, initializedCount in - - subtract(vectorA, - vectorB, - result: &buffer) - - initializedCount = vectorA.count - } - - return result - } - - /// Populates `result` with the elementwise difference of `vectorA` and `vectorB`, - /// double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] - b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] - b[i]`. - /// - Parameter result: The `c` in `c[i] = a[i] - b[i]`. - @inlinable - public static func subtract(_ vectorA: U, - _ vectorB: T, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vectorA.count == n && vectorB.count == n) - - result.withUnsafeMutableBufferPointer { r in - vectorB.withUnsafeBufferPointer { b in - vectorA.withUnsafeBufferPointer { a in - vDSP_vsubD(b.baseAddress!, 1, - a.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - // MARK: c[i] = a[i] * b vDSP_vsmul - - /// Returns the elementwise product of `vector` and `scalar - /// single-precision. - /// - /// - Parameter vector: the `a` in `c[i] = a[i] * b`. - /// - Parameter scalar: the `b` in `c[i] = a[i] * b`. - /// - Returns: The `c` in `c[i] = a[i] * b`. - @inlinable - public static func multiply(_ scalar: Float, - _ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - multiply(scalar, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise product of `vector` and `scalar - /// single-precision. - /// - /// - Parameter vector: the `a` in `c[i] = a[i] * b`. - /// - Parameter scalar: the `b` in `c[i] = a[i] * b`. - /// - Parameter result: The `c` in `c[i] = a[i] * b`. - @inlinable - public static func multiply(_ scalar: Float, - _ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vector.count == n) - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - withUnsafePointer(to: scalar) { s in - vDSP_vsmul(v.baseAddress!, 1, - s, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - /// Returns the elementwise product of `vector` and `scalar - /// double-precision. - /// - /// - Parameter vector: the `a` in `c[i] = a[i] * b`. - /// - Parameter scalar: the `b` in `c[i] = a[i] * b`. - /// - Returns: The `c` in `c[i] = a[i] * b`. - @inlinable - public static func multiply(_ scalar: Double, - _ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - multiply(scalar, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise product of `vector` and `scalar`, - /// double-precision. - /// - /// - Parameter vector: the `a` in `c[i] = a[i] * b`. - /// - Parameter scalar: the `b` in `c[i] = a[i] * b`. - /// - Parameter result: The `c` in `c[i] = a[i] * b`. - @inlinable - public static func multiply(_ scalar: Double, - _ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vector.count == n) - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - withUnsafePointer(to: scalar) { s in - vDSP_vsmulD(v.baseAddress!, 1, - s, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - // MARK: c[i] = a[i] * b[i] vDSP_vmul - - /// Returns the elementwise product of `vectorA` and `vectorB`, - /// single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] * b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] * b[i]`. - /// - Parameter result: The `c` in `c[i] = a[i] * b[i]`. - @inlinable - public static func multiply(_ vectorA: T, - _ vectorB: U) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vectorA.count) { - buffer, initializedCount in - - multiply(vectorA, - vectorB, - result: &buffer) - - initializedCount = vectorA.count - } - - return result - } - - /// Populates `result` with the elementwise product of `vectorA` and `vectorB`, - /// single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] * b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] * b[i]`. - /// - Parameter result: The `c` in `c[i] = a[i] * b[i]`. - @inlinable - public static func multiply(_ vectorA: T, - _ vectorB: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vectorA.count == n && vectorB.count == n) - result.withUnsafeMutableBufferPointer { r in - vectorA.withUnsafeBufferPointer { a in - vectorB.withUnsafeBufferPointer { b in - vDSP_vmul(a.baseAddress!, 1, - b.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - /// Returns the elementwise product of `vectorA` and `vectorB`, - /// double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] * b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] * b[i]`. - /// - Parameter result: The `c` in `c[i] = a[i] * b[i]`. - @inlinable - public static func multiply(_ vectorA: T, - _ vectorB: U) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vectorA.count) { - buffer, initializedCount in - - multiply(vectorA, - vectorB, - result: &buffer) - - initializedCount = vectorA.count - } - - return result - } - - /// Populates `result` with the elementwise product of `vectorA` and `vectorB`, - /// double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] * b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] * b[i]`. - /// - Parameter result: The `c` in `c[i] = a[i] * b[i]`. - @inlinable - public static func multiply(_ vectorA: T, - _ vectorB: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vectorA.count == n && vectorB.count == n) - result.withUnsafeMutableBufferPointer { r in - vectorA.withUnsafeBufferPointer { a in - vectorB.withUnsafeBufferPointer { b in - vDSP_vmulD(a.baseAddress!, 1, - b.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - // MARK: c[i] = a[i] / b vDSP_vsdiv - - /// Returns the elementwise division of `vector` by `scalar`, - /// single-precision. - /// - /// - Parameter vector: the `a` in `c[i] = a[i] / b`. - /// - Parameter scalar: the `b` in `c[i] = a[i] / b`. - /// - Returns: The `c` in `c[i] = a[i] / b` - @inlinable - public static func divide(_ vector: U, - _ scalar: Float) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - divide(vector, - scalar, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise division of `vector` by `scalar`, - /// single-precision. - /// - /// - Parameter vector: the `a` in `c[i] = a[i] / b`. - /// - Parameter scalar: the `b` in `c[i] = a[i] / b`. - /// - Parameter result: The `c` in `c[i] = a[i] / b` - @inlinable - public static func divide(_ vector: U, - _ scalar: Float, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vector.count == n) - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - withUnsafePointer(to: scalar) { s in - vDSP_vsdiv(v.baseAddress!, 1, - [scalar], - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - /// Returns the elementwise division of `vector` by `scalar`, - /// double-precision. - /// - /// - Parameter vector: the `a` in `c[i] = a[i] / b`. - /// - Parameter scalar: the `b` in `c[i] = a[i] / b`. - /// - Returns: The `c` in `c[i] = a[i] / b` - @inlinable - public static func divide(_ vector: U, - _ scalar: Double) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - divide(vector, - scalar, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise division of `vector` by `scalar`, - /// double-precision. - /// - /// - Parameter vector: the `a` in `c[i] = a[i] / b`. - /// - Parameter scalar: the `b` in `c[i] = a[i] / b`. - /// - Parameter result: The `c` in `c[i] = a[i] / b` - @inlinable - public static func divide(_ vector: U, - _ scalar: Double, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vector.count == n) - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - withUnsafePointer(to: scalar) { s in - vDSP_vsdivD(v.baseAddress!, 1, - s, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - // MARK: c[i] = a / b[i] vDSP_svdiv - - /// Returns the elementwise division of `scalar` by `vector`, - /// single-precision. - /// - /// - Parameter scalar: the `a` in `c[i] = a / b[i]`. - /// - Parameter vector: the `b` in `c[i] = a / b[i]`. - /// - Returns: The `c` in `c[i] = a / b[i]`. - @inlinable - public static func divide(_ scalar: Float, - _ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - divide(scalar, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise division of `scalar` by `vector`, - /// single-precision. - /// - /// - Parameter scalar: the `a` in `c[i] = a / b[i]`. - /// - Parameter vector: the `b` in `c[i] = a / b[i]`. - /// - Parameter result: The `c` in `c[i] = a / b[i]`. - @inlinable - public static func divide(_ scalar: Float, - _ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vector.count == n) - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - withUnsafePointer(to: scalar) { s in - vDSP_svdiv(s, - v.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - /// Returns the elementwise division of `scalar` by `vector`, - /// double-precision. - /// - /// - Parameter scalar: the `a` in `c[i] = a / b[i]`. - /// - Parameter vector: the `b` in `c[i] = a / b[i]`. - /// - Returns: The `c` in `c[i] = a / b[i]`. - @inlinable - public static func divide(_ scalar: Double, - _ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - divide(scalar, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise division of `scalar` by `vector`, - /// double-precision. - /// - /// - Parameter scalar: the `a` in `c[i] = a / b[i]`. - /// - Parameter vector: the `b` in `c[i] = a / b[i]`. - /// - Parameter result: The `c` in `c[i] = a / b[i]`. - @inlinable - public static func divide(_ scalar: Double, - _ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vector.count == n) - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - withUnsafePointer(to: scalar) { s in - vDSP_svdivD(s, - v.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - // MARK: c[i] = a[i] / b[i] vDSP_vdiv - - /// Returns the elementwise division of `vectorA` by `vectorB`, - /// single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] / b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] / b[i]`. - /// - Returns: The `c` in `c[i] = a[i] / b[i]`. - @inlinable - public static func divide(_ vectorA: T, - _ vectorB: U) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vectorA.count) { - buffer, initializedCount in - - divide(vectorA, - vectorB, - result: &buffer) - - initializedCount = vectorA.count - } - - return result - } - - /// Populates `result` with the elementwise division of `vectorA` by `vectorB`, - /// single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] / b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] / b[i]`. - /// - Parameter result: The `c` in `c[i] = a[i] / b[i]`. - @inlinable - public static func divide(_ vectorA: T, - _ vectorB: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vectorA.count == n && vectorB.count == n) - result.withUnsafeMutableBufferPointer { r in - vectorA.withUnsafeBufferPointer { a in - vectorB.withUnsafeBufferPointer { b in - vDSP_vdiv(b.baseAddress!, 1, - a.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - /// Returns the elementwise division of `vectorA` by `vectorB`, - /// double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] / b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] / b[i]`. - /// - Returns: The `c` in `c[i] = a[i] / b[i]`. - @inlinable - public static func divide(_ vectorA: T, - _ vectorB: U) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vectorA.count) { - buffer, initializedCount in - - divide(vectorA, - vectorB, - result: &buffer) - - initializedCount = vectorA.count - } - - return result - } - - /// Populates `result` with the elementwise division of `vectorA` by `vectorB`, - /// double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] / b[i]`. - /// - Parameter vectorB: the `b` in `c[i] = a[i] / b[i]`. - /// - Parameter result: The `c` in `c[i] = a[i] / b[i]`. - @inlinable - public static func divide(_ vectorA: T, - _ vectorB: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vectorA.count == n && vectorB.count == n) - result.withUnsafeMutableBufferPointer { r in - vectorA.withUnsafeBufferPointer { a in - vectorB.withUnsafeBufferPointer { b in - vDSP_vdivD(b.baseAddress!, 1, - a.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - - // MARK: o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i] vDSP_vaddsub - - /// Calculates elementwise sum and difference of `vectorA` and `vectorB`, - /// single-precision. - /// - /// - Parameter vectorA: the `i1` in `o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. - /// - Parameter vectorB: the `i0` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. - /// - Parameter addResult: The `o0` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. - /// - Parameter subtractResult: The `o1` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. - @inlinable - public static func addSubtract(_ vectorA: S, - _ vectorB: T, - addResult: inout U, - subtractResult: inout V) - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateMutableBuffer, - V: AccelerateMutableBuffer, - S.Element == Float, T.Element == Float, - U.Element == Float, V.Element == Float { - - let n = addResult.count - precondition(vectorA.count == n && - vectorB.count == n && - subtractResult.count == n) - - addResult.withUnsafeMutableBufferPointer { o0 in - subtractResult.withUnsafeMutableBufferPointer { o1 in - vectorA.withUnsafeBufferPointer { i1 in - vectorB.withUnsafeBufferPointer { i0 in - vDSP_vaddsub(i0.baseAddress!, 1, - i1.baseAddress!, 1, - o0.baseAddress!, 1, - o1.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - /// Calculates elementwise sum and difference of `vectorA` and `vectorB`, - /// double-precision. - /// - /// - Parameter vectorA: the `i1` in `o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. - /// - Parameter vectorB: the `i0` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. - /// - Parameter addResult: The `o0` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. - /// - Parameter subtractResult: The `o1` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. - @inlinable - public static func addSubtract(_ vectorA: S, - _ vectorB: T, - addResult: inout U, - subtractResult: inout V) - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateMutableBuffer, - V: AccelerateMutableBuffer, - S.Element == Double, T.Element == Double, - U.Element == Double, V.Element == Double { - - let n = addResult.count - precondition(vectorA.count == n && - vectorB.count == n && - subtractResult.count == n) - - addResult.withUnsafeMutableBufferPointer { o0 in - subtractResult.withUnsafeMutableBufferPointer { o1 in - vectorA.withUnsafeBufferPointer { i1 in - vectorB.withUnsafeBufferPointer { i0 in - vDSP_vaddsubD(i0.baseAddress!, 1, - i1.baseAddress!, 1, - o0.baseAddress!, 1, - o1.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - // MARK: d[i] = (a[i] + b[i]) * c vDSP_vasm - - /// Returns the elementwise product of the sum of the vectors in `addition` and `scalar`, - /// single-precision. - /// - /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c`. - /// - Parameter scalar: the `c` in `d[i] = `(a[i] + b[i]) * c`. - /// - Returns: The `d` in `d[i] = `(a[i] + b[i]) * c`. - @inlinable - public static func multiply(addition: (a: T, b: U), - _ scalar: Float) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: addition.a.count) { - buffer, initializedCount in - - multiply(addition: addition, - scalar, - result: &buffer) - - initializedCount = addition.a.count - } - - return result - } - - /// Populates `result` with the elementwise product of the sum of the vectors in `addition` and `scalar`, - /// single-precision. - /// - /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c`. - /// - Parameter scalar: the `c` in `d[i] = `(a[i] + b[i]) * c`. - /// - Parameter result: The `d` in `d[i] = `(a[i] + b[i]) * c`. - @inlinable - public static func multiply(addition: (a: T, b: U), - _ scalar: Float, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - let n = result.count - precondition(addition.a.count == n && - addition.b.count == n) - - result.withUnsafeMutableBufferPointer { r in - addition.a.withUnsafeBufferPointer { a in - addition.b.withUnsafeBufferPointer { b in - withUnsafePointer(to: scalar) { s in - vDSP_vasm(a.baseAddress!, 1, - b.baseAddress!, 1, - s, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - /// Returns the elementwise product of the sum of the vectors in `addition` and `scalar`, - /// double-precision. - /// - /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c`. - /// - Parameter scalar: the `c` in `d[i] = `(a[i] + b[i]) * c`. - /// - Returns: The `d` in `d[i] = `(a[i] + b[i]) * c`. - @inlinable - public static func multiply(addition: (a: T, b: U), - _ scalar: Double) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: addition.a.count) { - buffer, initializedCount in - - multiply(addition: addition, - scalar, - result: &buffer) - - initializedCount = addition.a.count - } - - return result - } - - /// Populates `result` with the elementwise product of the sum of the vectors in `addition` and `scalar`, - /// double-precision. - /// - /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c`. - /// - Parameter scalar: the `c` in `d[i] = `(a[i] + b[i]) * c`. - /// - Parameter result: The `d` in `d[i] = `(a[i] + b[i]) * c`. - @inlinable - public static func multiply(addition: (a: T, b: U), - _ scalar: Double, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - let n = result.count - precondition(addition.a.count == n && - addition.b.count == n) - - result.withUnsafeMutableBufferPointer { r in - addition.a.withUnsafeBufferPointer { a in - addition.b.withUnsafeBufferPointer { b in - withUnsafePointer(to: scalar) { s in - vDSP_vasmD(a.baseAddress!, 1, - b.baseAddress!, 1, - s, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - // MARK: d[i] = (a[i] + b[i]) * c[i] vDSP_vam - - /// Returns the elementwise product of the sum of the vectors in `addition` and `vector`, - /// single-precision. - /// - /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] + b[i]) * c[i]`. - /// - Returns: The `d` in `d[i] = (a[i] + b[i]) * c[i]`. - @inlinable - public static func multiply(addition: (a: S, b: T), - _ vector: U) -> [Float] - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - S.Element == Float, T.Element == Float, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - multiply(addition: addition, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise product of the sum of the vectors in `addition` and `vector`, - /// single-precision. - /// - /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] + b[i]) * c[i]`. - /// - Parameter result: The `d` in `d[i] = (a[i] + b[i]) * c[i]`. - @inlinable - public static func multiply(addition: (a: S, b: T), - _ vector: U, - result: inout V) - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - S.Element == Float, T.Element == Float, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(addition.a.count == n && - addition.b.count == n) - - result.withUnsafeMutableBufferPointer { r in - addition.a.withUnsafeBufferPointer { a in - addition.b.withUnsafeBufferPointer { b in - vector.withUnsafeBufferPointer { c in - vDSP_vam(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - /// Returns the elementwise product of the sum of the vectors in `addition` and `vector`, - /// double-precision. - /// - /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] + b[i]) * c[i]`. - /// - Returns: The `d` in `d[i] = (a[i] + b[i]) * c[i]`. - @inlinable - public static func multiply(addition: (a: S, b: T), - _ vector: U) -> [Double] - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - S.Element == Double, T.Element == Double, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - multiply(addition: addition, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise product of the sum of the vectors in `addition` and `vector`, - /// double-precision. - /// - /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] + b[i]) * c[i]`. - /// - Parameter result: The `d` in `d[i] = (a[i] + b[i]) * c[i]`. - @inlinable - public static func multiply(addition: (a: S, b: T), - _ vector: U, - result: inout V) - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - S.Element == Double, T.Element == Double, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(addition.a.count == n && - addition.b.count == n) - - result.withUnsafeMutableBufferPointer { r in - addition.a.withUnsafeBufferPointer { a in - addition.b.withUnsafeBufferPointer { b in - vector.withUnsafeBufferPointer { c in - vDSP_vamD(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - // MARK: d[i] = (a[i] - b[i]) * c vDSP_vsbsm - - /// Returns the elementwise product of the difference of the vectors in `subtraction` and `scalar`, - /// single-precision. - /// - /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c`. - /// - Parameter scalar: the `c` in `d[i] = `(a[i] - b[i]) * c`. - /// - Returns: The `d` in `d[i] = `(a[i] - b[i]) * c`. - @inlinable - public static func multiply(subtraction: (a: T, b: U), - _ scalar: Float) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: subtraction.a.count) { - buffer, initializedCount in - - multiply(subtraction: subtraction, - scalar, - result: &buffer) - - initializedCount = subtraction.a.count - } - - return result - } - - /// Populates `result` with the elementwise product of the difference of the vectors in `subtraction` and `scalar`, - /// single-precision. - /// - /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c`. - /// - Parameter scalar: the `c` in `d[i] = `(a[i] - b[i]) * c`. - /// - Parameter result: The `d` in `d[i] = `(a[i] - b[i]) * c`. - @inlinable - public static func multiply(subtraction: (a: T, b: U), - _ scalar: Float, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - let n = result.count - precondition(subtraction.a.count == n && - subtraction.b.count == n) - - result.withUnsafeMutableBufferPointer { r in - subtraction.a.withUnsafeBufferPointer { a in - subtraction.b.withUnsafeBufferPointer { b in - withUnsafePointer(to: scalar) { s in - vDSP_vsbsm(a.baseAddress!, 1, - b.baseAddress!, 1, - s, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - /// Returns the elementwise product of the difference of the vectors in `subtraction` and `scalar`, - /// double-precision. - /// - /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c`. - /// - Parameter scalar: the `c` in `d[i] = `(a[i] - b[i]) * c`. - /// - Returns: The `d` in `d[i] = `(a[i] - b[i]) * c`. - @inlinable - public static func multiply(subtraction: (a: T, b: U), - _ scalar: Double) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: subtraction.a.count) { - buffer, initializedCount in - - multiply(subtraction: subtraction, - scalar, - result: &buffer) - - initializedCount = subtraction.a.count - } - - return result - } - - /// Populates `result` with the elementwise product of the difference of the vectors in `subtraction` and `scalar`, - /// double-precision. - /// - /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c`. - /// - Parameter scalar: the `c` in `d[i] = `(a[i] - b[i]) * c`. - /// - Parameter result: The `d` in `d[i] = `(a[i] - b[i]) * c`. - @inlinable - public static func multiply(subtraction: (a: T, b: U), - _ scalar: Double, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - let n = result.count - precondition(subtraction.a.count == n && - subtraction.b.count == n) - - result.withUnsafeMutableBufferPointer { r in - subtraction.a.withUnsafeBufferPointer { a in - subtraction.b.withUnsafeBufferPointer { b in - withUnsafePointer(to: scalar) { s in - vDSP_vsbsmD(a.baseAddress!, 1, - b.baseAddress!, 1, - s, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - // MARK: d[i] = (a[i] - b[i]) * c[i] vDSP_vsbm - - /// Returns the elementwise product of the difference of the vectors in `subtraction` and `vector`, - /// single-precision. - /// - /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c[i]`. - /// - Parameter vector: the `c` in `d[i] = `(a[i] - b[i]) * c[i]`. - /// - Returns: The `d` in `d[i] = `(a[i] - b[i]) * c[i]`. - @inlinable - public static func multiply(subtraction: (a: S, b: T), - _ vector: U) -> [Float] - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - S.Element == Float, T.Element == Float, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - multiply(subtraction: subtraction, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise product of the difference of the vectors in `subtraction` and `vector`, - /// single-precision. - /// - /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c[i]`. - /// - Parameter vector: the `c` in `d[i] = `(a[i] - b[i]) * c[i]`. - /// - Parameter result: The `d` in `d[i] = `(a[i] - b[i]) * c[i]`. - @inlinable - public static func multiply(subtraction: (a: S, b: T), - _ vector: U, - result: inout V) - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - S.Element == Float, T.Element == Float, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(subtraction.a.count == n && - subtraction.b.count == n) - - result.withUnsafeMutableBufferPointer { r in - subtraction.a.withUnsafeBufferPointer { a in - subtraction.b.withUnsafeBufferPointer { b in - vector.withUnsafeBufferPointer { c in - vDSP_vsbm(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - /// Returns the elementwise product of the difference of the vectors in `subtraction` and `vector`, - /// double-precision. - /// - /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c[i]`. - /// - Parameter vector: the `c` in `d[i] = `(a[i] - b[i]) * c[i]`. - /// - Returns: The `d` in `d[i] = `(a[i] - b[i]) * c[i]`. - @inlinable - public static func multiply(subtraction: (a: S, b: T), - _ vector: U) -> [Double] - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - S.Element == Double, T.Element == Double, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - multiply(subtraction: subtraction, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise product of the difference of the vectors in `subtraction` and `vector`, - /// double-precision. - /// - /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c[i]`. - /// - Parameter vector: the `c` in `d[i] = `(a[i] - b[i]) * c[i]`. - /// - Parameter result: The `d` in `d[i] = `(a[i] - b[i]) * c[i]`. - @inlinable - public static func multiply(subtraction: (a: S, b: T), - _ vector: U, - result: inout V) - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - S.Element == Double, T.Element == Double, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(subtraction.a.count == n && - subtraction.b.count == n) - - result.withUnsafeMutableBufferPointer { r in - subtraction.a.withUnsafeBufferPointer { a in - subtraction.b.withUnsafeBufferPointer { b in - vector.withUnsafeBufferPointer { c in - vDSP_vsbmD(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - // MARK: d[i] = a[i]*b[i] + c; vDSP_vmsa - - /// Returns the elementwise sum of `scalar` - /// and the product of the two vectors in `multiplication`, - /// single-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = a[i]*b[i] + c`. - /// - Parameter scalar: the `c` in `d[i] = a[i]*b[i] + c`. - /// - Returns: the `d` in `d[i] = a[i]*b[i] + c`. - @inlinable - public static func add(multiplication: (a: T, b: U), - _ scalar: Float) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: multiplication.a.count) { - buffer, initializedCount in - - add(multiplication: multiplication, - scalar, - result: &buffer) - - initializedCount = multiplication.a.count - } - - return result - } - - /// Populates `result` with the elementwise sum of `scalar` - /// and the product of the two vectors in `multiplication`, - /// single-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = a[i]*b[i] + c`. - /// - Parameter scalar: the `c` in `d[i] = a[i]*b[i] + c`. - /// - Parameter result: the `d` in `d[i] = a[i]*b[i] + c`. - @inlinable - public static func add(multiplication: (a: T, b: U), - _ scalar: Float, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - let n = result.count - precondition(multiplication.a.count == n && - multiplication.b.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplication.a.withUnsafeBufferPointer { a in - multiplication.b.withUnsafeBufferPointer { b in - withUnsafePointer(to: scalar) { s in - vDSP_vmsa(a.baseAddress!, 1, - b.baseAddress!, 1, - s, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - /// Returns the elementwise sum of `scalar` - /// and the product of the two vectors in `multiplication`, - /// double-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = a[i]*b[i] + c`. - /// - Parameter scalar: the `c` in `d[i] = a[i]*b[i] + c`. - /// - Returns: the `d` in `d[i] = a[i]*b[i] + c`. - @inlinable - public static func add(multiplication: (a: T, b: U), - _ scalar: Double) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: multiplication.a.count) { - buffer, initializedCount in - - add(multiplication: multiplication, - scalar, - result: &buffer) - - initializedCount = multiplication.a.count - } - - return result - } - - /// Populates `result` with the elementwise sum of `scalar` - /// and the product of the two vectors in `multiplication`, - /// double-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = a[i]*b[i] + c`. - /// - Parameter scalar: the `c` in `d[i] = a[i]*b[i] + c`. - /// - Parameter result: the `d` in `d[i] = a[i]*b[i] + c`. - @inlinable - public static func add(multiplication: (a: T, b: U), - _ scalar: Double, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - let n = result.count - precondition(multiplication.a.count == n && - multiplication.b.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplication.a.withUnsafeBufferPointer { a in - multiplication.b.withUnsafeBufferPointer { b in - withUnsafePointer(to: scalar) { s in - vDSP_vmsaD(a.baseAddress!, 1, - b.baseAddress!, 1, - s, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - // MARK: d[i] = (a[i] * b) + c[i] vDSP_vsma - - /// Returns the elementwise sum of `vector` - /// and the product of the vector and scalar in `multiplication`, - /// single-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b) + c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] * b) + c[i]`. - /// - Returns: the `d` in `d[i] = (a[i] * b) + c[i]`. - @inlinable - public static func add(multiplication: (a: T, b: Float), - _ vector: U) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - add(multiplication: multiplication, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise sum of `vector` - /// and the product of the vector and scalar in `multiplication`, - /// single-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b) + c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] * b) + c[i]`. - /// - Parameter result: the `d` in `d[i] = (a[i] * b) + c[i]`. - @inlinable - public static func add(multiplication: (a: T, b: Float), - _ vector: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - let n = result.count - precondition(multiplication.a.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplication.a.withUnsafeBufferPointer { a in - vector.withUnsafeBufferPointer { c in - withUnsafePointer(to: multiplication.b) { b in - vDSP_vsma(a.baseAddress!, 1, - b, - c.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - /// Returns the elementwise sum of `vector` - /// and the product of the vector and scalar in `multiplication`, - /// double-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b) + c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] * b) + c[i]`. - /// - Returns: the `d` in `d[i] = (a[i] * b) + c[i]`. - @inlinable - public static func add(multiplication: (a: T, b: Double), - _ vector: U) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - add(multiplication: multiplication, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise sum of `vector` - /// and the product of the vector and scalar in `multiplication`, - /// double-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b) + c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] * b) + c[i]`. - /// - Parameter result: the `d` in `d[i] = (a[i] * b) + c[i]`. - @inlinable - public static func add(multiplication: (a: T, b: Double), - _ vector: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - let n = result.count - precondition(multiplication.a.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplication.a.withUnsafeBufferPointer { a in - vector.withUnsafeBufferPointer { c in - withUnsafePointer(to: multiplication.b) { b in - vDSP_vsmaD(a.baseAddress!, 1, - b, - c.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - // MARK: d[i] = (a[i] * b[i]) + c[i] vDSP_vma - - /// Returns the elementwise sum of `vector` - /// and the product of the two vectors in `multiplication`, - /// single-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) + c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) + c[i]`. - /// - Returns: the `d` in `d[i] = (a[i] * b[i]) + c[i]`. - @inlinable - public static func add(multiplication: (a: S, b: T), - _ vector: U) -> [Float] - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - S.Element == Float, T.Element == Float, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - add(multiplication: multiplication, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise sum of `vector` - /// and the product of the two vectors in `multiplication`, - /// single-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) + c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) + c[i]`. - /// - Parameter result: the `d` in `d[i] = (a[i] * b[i]) + c[i]`. - @inlinable - public static func add(multiplication: (a: S, b: T), - _ vector: U, - result: inout V) - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - S.Element == Float, T.Element == Float, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(multiplication.a.count == n && - multiplication.b.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplication.a.withUnsafeBufferPointer { a in - multiplication.b.withUnsafeBufferPointer { b in - vector.withUnsafeBufferPointer { c in - vDSP_vma(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - /// Returns the elementwise sum of `vector` - /// and the product of the two vectors in `multiplication`, - /// double-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) + c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) + c[i]`. - /// - Returns: the `d` in `d[i] = (a[i] * b[i]) + c[i]`. - @inlinable - public static func add(multiplication: (a: S, b: T), - _ vector: U) -> [Double] - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - S.Element == Double, T.Element == Double, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - add(multiplication: multiplication, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise sum of `vector` - /// and the product of the two vectors in `multiplication`, - /// double-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) + c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) + c[i]`. - /// - Parameter result: the `d` in `d[i] = (a[i] * b[i]) + c[i]`. - @inlinable - public static func add(multiplication: (a: S, b: T), - _ vector: U, - result: inout V) - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - S.Element == Double, T.Element == Double, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(multiplication.a.count == n && - multiplication.b.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplication.a.withUnsafeBufferPointer { a in - multiplication.b.withUnsafeBufferPointer { b in - vector.withUnsafeBufferPointer { c in - vDSP_vmaD(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - // MARK: d[i] = (a[i] * b[i]) - c[i] vDSP_vmsb - - /// Returns the elementwise difference of `vector` - /// and the product of the two vectors in `multiplication`, - /// single-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) - c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) - c[i]`. - /// - Returns: the `d` in `d[i] = (a[i] * b[i]) - c[i]`. - @inlinable - public static func subtract(multiplication: (a: T, b: U), - _ vector: S) -> [Float] - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - S.Element == Float, T.Element == Float, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - subtract(multiplication: multiplication, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise difference of `vector` - /// and the product of the two vectors in `multiplication`, - /// single-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) - c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) - c[i]`. - /// - Parameter result: the `d` in `d[i] = (a[i] * b[i]) - c[i]`. - @inlinable - public static func subtract(multiplication: (a: T, b: U), - _ vector: S, - result: inout V) - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - S.Element == Float, T.Element == Float, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(multiplication.a.count == n && - multiplication.b.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplication.a.withUnsafeBufferPointer { a in - multiplication.b.withUnsafeBufferPointer { b in - vector.withUnsafeBufferPointer { c in - vDSP_vmsb(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - /// Returns the elementwise difference of `vector` - /// and the product of the two vectors in `multiplication`, - /// double-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) - c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) - c[i]`. - /// - Returns: the `d` in `d[i] = (a[i] * b[i]) - c[i]`. - @inlinable - public static func subtract(multiplication: (a: T, b: U), - _ vector: S) -> [Double] - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - S.Element == Double, T.Element == Double, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - subtract(multiplication: multiplication, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise difference of `vector` - /// and the product of the two vectors in `multiplication`, - /// double-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) - c[i]`. - /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) - c[i]`. - /// - Parameter result: the `d` in `d[i] = (a[i] * b[i]) - c[i]`. - @inlinable - public static func subtract(multiplication: (a: T, b: U), - _ vector: S, - result: inout V) - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - S.Element == Double, T.Element == Double, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(multiplication.a.count == n && - multiplication.b.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplication.a.withUnsafeBufferPointer { a in - multiplication.b.withUnsafeBufferPointer { b in - vector.withUnsafeBufferPointer { c in - vDSP_vmsbD(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - // MARK: e[i] = (a[i] * b) + (c[i] * d) vDSP_vsmsma - - /// Returns the elementwise sum of two elementwise - /// vector-scalar products, single-precision. - /// - /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b) + (c[i] * d)`. - /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b) + (c[i] * d)`. - /// - Returns: the `e` in `e[i] = (a[i] * b) + (c[i] * d)`. - @inlinable - public static func add(multiplication multiplicationAB: (a: T, b: Float), - multiplication multiplicationCD: (c: U, d: Float)) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: multiplicationAB.a.count) { - buffer, initializedCount in - - add(multiplication: multiplicationAB, - multiplication: multiplicationCD, - result: &buffer) - - initializedCount = multiplicationAB.a.count - } - - return result - } - - /// Populates `result` with the elementwise sum of two elementwise - /// vector-scalar products, single-precision. - /// - /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b) + (c[i] * d)`. - /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b) + (c[i] * d)`. - /// - Parameter result: the `e` in `e[i] = (a[i] * b) + (c[i] * d)`. - @inlinable - public static func add(multiplication multiplicationAB: (a: T, b: Float), - multiplication multiplicationCD: (c: U, d: Float), - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - let n = result.count - precondition(multiplicationAB.a.count == n && - multiplicationCD.c.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplicationAB.a.withUnsafeBufferPointer { a in - multiplicationCD.c.withUnsafeBufferPointer { c in - withUnsafePointer(to: multiplicationAB.b) { b in - withUnsafePointer(to: multiplicationCD.d) { d in - vDSP_vsmsma(a.baseAddress!, 1, - b, - c.baseAddress!, 1, - d, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - } - - /// Returns the elementwise sum of two elementwise - /// vector-scalar products, double-precision. - /// - /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b) + (c[i] * d)`. - /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b) + (c[i] * d)`. - /// - Returns: the `e` in `e[i] = (a[i] * b) + (c[i] * d)`. - @inlinable - public static func add(multiplication multiplicationAB: (a: T, b: Double), - multiplication multiplicationCD: (c: U, d: Double)) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: multiplicationAB.a.count) { - buffer, initializedCount in - - add(multiplication: multiplicationAB, - multiplication: multiplicationCD, - result: &buffer) - - initializedCount = multiplicationAB.a.count - } - - return result - } - - /// Populates `result` with the elementwise sum of two elementwise - /// vector-scalar products, double-precision. - /// - /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b) + (c[i] * d)`. - /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b) + (c[i] * d)`. - /// - Parameter result: the `e` in `e[i] = (a[i] * b) + (c[i] * d)`. - @inlinable - public static func add(multiplication multiplicationAB: (a: T, b: Double), - multiplication multiplicationCD: (c: U, d: Double), - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - let n = result.count - precondition(multiplicationAB.a.count == n && - multiplicationCD.c.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplicationAB.a.withUnsafeBufferPointer { a in - multiplicationCD.c.withUnsafeBufferPointer { c in - withUnsafePointer(to: multiplicationAB.b) { b in - withUnsafePointer(to: multiplicationCD.d) { d in - vDSP_vsmsmaD(a.baseAddress!, 1, - b, - c.baseAddress!, 1, - d, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - } - - // MARK: e[i] = (a[i] * b[i]) + (c[i] * d[i]) vDSP_vmma - - /// Returns the elementwise sum of two elementwise - /// vector-vector products, single-precision. - /// - /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. - /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. - /// - Returns: the `e` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. - @inlinable - public static func add(multiplication multiplicationAB: (a: R, b: S), - multiplication multiplicationCD: (c: T, d: U)) -> [Float] - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - R.Element == Float, - S.Element == Float, T.Element == Float, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: multiplicationAB.a.count) { - buffer, initializedCount in - - add(multiplication: multiplicationAB, - multiplication: multiplicationCD, - result: &buffer) - - initializedCount = multiplicationAB.a.count - } - - return result - } - - /// Populates `result` with the elementwise sum of two elementwise - /// vector-vector products, single-precision. - /// - /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. - /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. - /// - Parameter result: the `e` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. - @inlinable - public static func add(multiplication multiplicationAB: (a: R, b: S), - multiplication multiplicationCD: (c: T, d: U), - result: inout V) - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - R.Element == Float, - S.Element == Float, T.Element == Float, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(multiplicationAB.a.count == n && - multiplicationAB.b.count == n && - multiplicationCD.c.count == n && - multiplicationCD.d.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplicationAB.a.withUnsafeBufferPointer { a in - multiplicationAB.b.withUnsafeBufferPointer { b in - multiplicationCD.c.withUnsafeBufferPointer { c in - multiplicationCD.d.withUnsafeBufferPointer { d in - vDSP_vmma(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - d.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - } - - /// Returns the elementwise sum of two elementwise - /// vector-vector products, single-precision. - /// - /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. - /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. - /// - Returns: the `e` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. - @inlinable - public static func add(multiplication multiplicationAB: (a: R, b: S), - multiplication multiplicationCD: (c: T, d: U)) -> [Double] - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - R.Element == Double, - S.Element == Double, T.Element == Double, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: multiplicationAB.a.count) { - buffer, initializedCount in - - add(multiplication: multiplicationAB, - multiplication: multiplicationCD, - result: &buffer) - - initializedCount = multiplicationAB.a.count - } - - return result - } - - /// Populates `result` with the elementwise sum of two elementwise - /// vector-vector products, double-precision. - /// - /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. - /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. - /// - Parameter result: the `e` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. - @inlinable - public static func add(multiplication multiplicationAB: (a: R, b: S), - multiplication multiplicationCD: (c: T, d: U), - result: inout V) - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - R.Element == Double, - S.Element == Double, T.Element == Double, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(multiplicationAB.a.count == n && - multiplicationAB.b.count == n && - multiplicationCD.c.count == n && - multiplicationCD.d.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplicationAB.a.withUnsafeBufferPointer { a in - multiplicationAB.b.withUnsafeBufferPointer { b in - multiplicationCD.c.withUnsafeBufferPointer { c in - multiplicationCD.d.withUnsafeBufferPointer { d in - vDSP_vmmaD(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - d.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - } - - // MARK: e[i] = (a[i] + b[i]) * (c[i] + d[i]) vDSP_vaam - - /// Returns the elementwise product of two elementwise - /// vector-vector sums, single-precision. - /// - /// - Parameter additionAB: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. - /// - Parameter additionCD: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. - /// - Returns: the `e` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. - @inlinable - public static func multiply(addition additionAB: (a: S, b: T), - addition additionCD: (c: U, d: U)) -> [Float] - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - S.Element == Float, T.Element == Float, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: additionAB.a.count) { - buffer, initializedCount in - - multiply(addition: additionAB, - addition: additionCD, - result: &buffer) - - initializedCount = additionAB.a.count - } - - return result - } - - /// Populates `result` with the elementwise product of two elementwise - /// vector-vector sums, single-precision. - /// - /// - Parameter additionAB: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. - /// - Parameter additionCD: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. - /// - Parameter result: the `e` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. - @inlinable - public static func multiply(addition additionAB: (a: S, b: T), - addition additionCD: (c: U, d: U), - result: inout V) - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - S.Element == Float, T.Element == Float, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(additionAB.a.count == n && - additionAB.b.count == n && - additionCD.c.count == n && - additionCD.d.count == n) - - result.withUnsafeMutableBufferPointer { r in - additionAB.a.withUnsafeBufferPointer { a in - additionAB.b.withUnsafeBufferPointer { b in - additionCD.c.withUnsafeBufferPointer { c in - additionCD.d.withUnsafeBufferPointer { d in - vDSP_vaam(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - d.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - } - - /// Returns the elementwise product of two elementwise - /// vector-vector sums, double-precision. - /// - /// - Parameter additionAB: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. - /// - Parameter additionCD: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. - /// - Returns: the `e` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. - @inlinable - public static func multiply(addition additionAB: (a: S, b: T), - addition additionCD: (c: U, d: U)) -> [Double] - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - S.Element == Double, T.Element == Double, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: additionAB.a.count) { - buffer, initializedCount in - - multiply(addition: additionAB, - addition: additionCD, - result: &buffer) - - initializedCount = additionAB.a.count - } - - return result - } - - /// Populates `result` with the elementwise product of two elementwise - /// vector-vector sums, double-precision. - /// - /// - Parameter additionAB: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. - /// - Parameter additionCD: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. - /// - Parameter result: the `e` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. - @inlinable - public static func multiply(addition additionAB: (a: S, b: T), - addition additionCD: (c: U, d: U), - result: inout V) - where - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - S.Element == Double, T.Element == Double, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(additionAB.a.count == n && - additionAB.b.count == n && - additionCD.c.count == n && - additionCD.d.count == n) - - result.withUnsafeMutableBufferPointer { r in - additionAB.a.withUnsafeBufferPointer { a in - additionAB.b.withUnsafeBufferPointer { b in - additionCD.c.withUnsafeBufferPointer { c in - additionCD.d.withUnsafeBufferPointer { d in - vDSP_vaamD(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - d.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - } - - // MARK: e[i] = (a[i] * b[i]) - (c[i] * d[i]) vDSP_vmmsb - - /// Returns the elementwise difference of two elementwise - /// vector-vector products, single-precision. - /// - /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. - /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. - /// - Returns: the `e` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. - @inlinable - public static func subtract(multiplication multiplicationAB: (a: T, b: U), - multiplication multiplicationCD: (c: R, d: S)) -> [Float] - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - R.Element == Float, - S.Element == Float, T.Element == Float, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: multiplicationAB.a.count) { - buffer, initializedCount in - - subtract(multiplication: multiplicationAB, - multiplication: multiplicationCD, - result: &buffer) - - initializedCount = multiplicationAB.a.count - } - - return result - } - - /// Populates `result` with the elementwise difference of two elementwise - /// vector-vector products, single-precision. - /// - /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. - /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. - /// - Parameter result: the `e` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. - @inlinable - public static func subtract(multiplication multiplicationAB: (a: T, b: U), - multiplication multiplicationCD: (c: R, d: S), - result: inout V) - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - R.Element == Float, - S.Element == Float, T.Element == Float, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(multiplicationAB.a.count == n && - multiplicationAB.b.count == n && - multiplicationCD.c.count == n && - multiplicationCD.d.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplicationAB.a.withUnsafeBufferPointer { a in - multiplicationAB.b.withUnsafeBufferPointer { b in - multiplicationCD.c.withUnsafeBufferPointer { c in - multiplicationCD.d.withUnsafeBufferPointer { d in - vDSP_vmmsb(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - d.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - } - - /// Returns the elementwise difference of two elementwise - /// vector-vector products, double-precision. - /// - /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. - /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. - /// - Returns: the `e` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. - @inlinable - public static func subtract(multiplication multiplicationAB: (a: T, b: U), - multiplication multiplicationCD: (c: R, d: S)) -> [Double] - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - R.Element == Double, - S.Element == Double, T.Element == Double, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: multiplicationAB.a.count) { - buffer, initializedCount in - - subtract(multiplication: multiplicationAB, - multiplication: multiplicationCD, - result: &buffer) - - initializedCount = multiplicationAB.a.count - } - - return result - } - - /// Populates `result` with the elementwise difference of two elementwise - /// vector-vector products, double-precision. - /// - /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. - /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. - /// - Parameter result: the `e` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. - @inlinable - public static func subtract(multiplication multiplicationAB: (a: T, b: U), - multiplication multiplicationCD: (c: R, d: S), - result: inout V) - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - R.Element == Double, - S.Element == Double, T.Element == Double, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(multiplicationAB.a.count == n && - multiplicationAB.b.count == n && - multiplicationCD.c.count == n && - multiplicationCD.d.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplicationAB.a.withUnsafeBufferPointer { a in - multiplicationAB.b.withUnsafeBufferPointer { b in - multiplicationCD.c.withUnsafeBufferPointer { c in - multiplicationCD.d.withUnsafeBufferPointer { d in - vDSP_vmmsbD(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - d.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - } - - // MARK: e[i] = (a[i] - b[i]) * (c[i] - d[i]) vDSP_vsbsbm - - /// Returns the elementwise product of two elementwise - /// vector-vector differences, single-precision. - /// - /// - Parameter subtractionAB: the `a` and `b` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. - /// - Parameter subtractionCD: the `c` and `d` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. - /// - Returns: the `e` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. - @inlinable - public static func multiply(subtraction subtractionAB: (a: R, b: S), - subtraction subtractionCD: (c: T, d: U)) -> [Float] - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - R.Element == Float, - S.Element == Float, T.Element == Float, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: subtractionAB.a.count) { - buffer, initializedCount in - - multiply(subtraction: subtractionAB, - subtraction: subtractionCD, - result: &buffer) - - initializedCount = subtractionAB.a.count - } - - return result - } - - /// Populates `result` with the elementwise product of two elementwise - /// vector-vector differences, single-precision. - /// - /// - Parameter subtractionAB: the `a` and `b` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. - /// - Parameter subtractionCD: the `c` and `d` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. - /// - Parameter result: the `e` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. - @inlinable - public static func multiply(subtraction subtractionAB: (a: R, b: S), - subtraction subtractionCD: (c: T, d: U), - result: inout V) - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - R.Element == Float, - S.Element == Float, T.Element == Float, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(subtractionAB.a.count == n && - subtractionAB.b.count == n && - subtractionCD.c.count == n && - subtractionCD.d.count == n) - - result.withUnsafeMutableBufferPointer { r in - subtractionAB.a.withUnsafeBufferPointer { a in - subtractionAB.b.withUnsafeBufferPointer { b in - subtractionCD.c.withUnsafeBufferPointer { c in - subtractionCD.d.withUnsafeBufferPointer { d in - vDSP_vsbsbm(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - d.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - } - - /// Returns the elementwise product of two elementwise - /// vector-vector differences, double-precision. - /// - /// - Parameter subtractionAB: the `a` and `b` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. - /// - Parameter subtractionCD: the `c` and `d` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. - /// - Returns: the `e` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. - @inlinable - public static func multiply(subtraction subtractionAB: (a: R, b: S), - subtraction subtractionCD: (c: T, d: U)) -> [Double] - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - R.Element == Double, - S.Element == Double, T.Element == Double, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: subtractionAB.a.count) { - buffer, initializedCount in - - multiply(subtraction: subtractionAB, - subtraction: subtractionCD, - result: &buffer) - - initializedCount = subtractionAB.a.count - } - - return result - } - - /// Populates `result` with the elementwise product of two elementwise - /// vector-vector differences, double-precision. - /// - /// - Parameter subtractionAB: the `a` and `b` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. - /// - Parameter subtractionCD: the `c` and `d` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. - /// - Parameter result: the `e` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. - @inlinable - public static func multiply(subtraction subtractionAB: (a: R, b: S), - subtraction subtractionCD: (c: T, d: U), - result: inout V) - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - R.Element == Double, - S.Element == Double, T.Element == Double, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(subtractionAB.a.count == n && - subtractionAB.b.count == n && - subtractionCD.c.count == n && - subtractionCD.d.count == n) - - result.withUnsafeMutableBufferPointer { r in - subtractionAB.a.withUnsafeBufferPointer { a in - subtractionAB.b.withUnsafeBufferPointer { b in - subtractionCD.c.withUnsafeBufferPointer { c in - subtractionCD.d.withUnsafeBufferPointer { d in - vDSP_vsbsbmD(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - d.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - } - - // MARK: e[i] = (a[i] + b[i]) * (c[i] - d[i]) vDSP_vasbm - - /// Returns the elementwise product of an elementwise - /// vector-vector sum and an elementwise vector-vector sum, single-precision. - /// - /// - Parameter addition: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. - /// - Parameter subtraction: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. - /// - Returns: the `e` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. - @inlinable - public static func multiply(addition: (a: R, b: S), - subtraction: (c: T, d: U)) -> [Float] - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - R.Element == Float, - S.Element == Float, T.Element == Float, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: addition.a.count) { - buffer, initializedCount in - - multiply(addition: addition, - subtraction: subtraction, - result: &buffer) - - initializedCount = addition.a.count - } - - return result - } - - /// Populates `result` with the elementwise product of an elementwise - /// vector-vector sum and an elementwise vector-vector sum, single-precision. - /// - /// - Parameter addition: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. - /// - Parameter subtraction: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. - /// - Parameter result: the `e` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. - @inlinable - public static func multiply(addition: (a: R, b: S), - subtraction: (c: T, d: U), - result: inout V) - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - R.Element == Float, - S.Element == Float, T.Element == Float, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(addition.a.count == n && - addition.b.count == n && - subtraction.c.count == n && - subtraction.d.count == n) - - result.withUnsafeMutableBufferPointer { r in - addition.a.withUnsafeBufferPointer { a in - addition.b.withUnsafeBufferPointer { b in - subtraction.c.withUnsafeBufferPointer { c in - subtraction.d.withUnsafeBufferPointer { d in - vDSP_vasbm(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - d.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - } - - /// Returns the elementwise product of an elementwise - /// vector-vector sum and an elementwise vector-vector sum, double-precision. - /// - /// - Parameter addition: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. - /// - Parameter subtraction: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. - /// - Returns: the `e` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. - @inlinable - public static func multiply(addition: (a: R, b: S), - subtraction: (c: T, d: U)) -> [Double] - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - R.Element == Double, - S.Element == Double, T.Element == Double, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: addition.a.count) { - buffer, initializedCount in - - multiply(addition: addition, - subtraction: subtraction, - result: &buffer) - - initializedCount = addition.a.count - } - - return result - } - - /// Populates `result` with the elementwise product of an elementwise - /// vector-vector sum and an elementwise vector-vector sum, double-precision. - /// - /// - Parameter addition: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. - /// - Parameter subtraction: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. - /// - Parameter result: the `e` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. - @inlinable - public static func multiply(addition: (a: R, b: S), - subtraction: (c: T, d: U), - result: inout V) - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - R.Element == Double, - S.Element == Double, T.Element == Double, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(addition.a.count == n && - addition.b.count == n && - subtraction.c.count == n && - subtraction.d.count == n) - - result.withUnsafeMutableBufferPointer { r in - addition.a.withUnsafeBufferPointer { a in - addition.b.withUnsafeBufferPointer { b in - subtraction.c.withUnsafeBufferPointer { c in - subtraction.d.withUnsafeBufferPointer { d in - vDSP_vasbmD(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - d.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - } - - // MARK: d[n] = a[n]*b + c vDSP_vsmsa - - /// Returns the elementwise sum of an elementwise - /// vector-scalar product and aa scalar value, single-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[n] = a[n]*b + c`. - /// - Parameter scalar: the `c` in `d[n] = a[n]*b + c`. - /// - Returns: the `e` in `d[n] = a[n]*b + c`. - @inlinable - public static func add(multiplication: (a: U, b: Float), - _ scalar: Float) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: multiplication.a.count) { - buffer, initializedCount in - - add(multiplication: multiplication, - scalar, - result: &buffer) - - initializedCount = multiplication.a.count - } - - return result - } - - /// Populates `result` with the elementwise sum of an elementwise - /// vector-scalar product and aa scalar value, single-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[n] = a[n]*b + c`. - /// - Parameter scalar: the `c` in `d[n] = a[n]*b + c`. - /// - Parameter result: the `e` in `d[n] = a[n]*b + c`. - @inlinable - public static func add(multiplication: (a: U, b: Float), - _ scalar: Float, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - let n = result.count - precondition(multiplication.a.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplication.a.withUnsafeBufferPointer { a in - withUnsafePointer(to: multiplication.b) { b in - withUnsafePointer(to: scalar) { c in - vDSP_vsmsa(a.baseAddress!, 1, - b, - c, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - /// Returns the elementwise sum of an elementwise - /// vector-scalar product and aa scalar value, double-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[n] = a[n]*b + c`. - /// - Parameter scalar: the `c` in `d[n] = a[n]*b + c`. - /// - Returns: the `e` in `d[n] = a[n]*b + c`. - @inlinable - public static func add(multiplication: (a: U, b: Double), - _ scalar: Double) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: multiplication.a.count) { - buffer, initializedCount in - - add(multiplication: multiplication, - scalar, - result: &buffer) - - initializedCount = multiplication.a.count - } - - return result - } - - /// Populates `result` with the elementwise sum of an elementwise - /// vector-scalar product and aa scalar value, double-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `d[n] = a[n]*b + c`. - /// - Parameter scalar: the `c`in `d[n] = a[n]*b + c`. - /// - Parameter result: the `e` in `d[n] = a[n]*b + c`. - @inlinable - public static func add(multiplication: (a: U, b: Double), - _ scalar: Double, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - let n = result.count - precondition(multiplication.a.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplication.a.withUnsafeBufferPointer { a in - withUnsafePointer(to: multiplication.b) { b in - withUnsafePointer(to: scalar) { c in - vDSP_vsmsaD(a.baseAddress!, 1, - b, - c, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - // MARK: D[n] = A[n]*B - C[n]; vDSP_vsmsb - - /// Returns the elementwise difference of `vector` - /// and the product of the vector and scalar in `multiplication`, - /// single-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `D[n] = A[n]*B - C[n]`. - /// - Parameter vector: the `c` in `D[n] = A[n]*B - C[n]`. - /// - Returns: the `d` in `D[n] = A[n]*B - C[n]`. - @inlinable - public static func subtract(multiplication: (a: U, b: Float), - _ vector: T) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - subtract(multiplication: multiplication, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise difference of `vector` - /// and the product of the vector and scalar in `multiplication`, - /// single-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `D[n] = A[n]*B - C[n]`. - /// - Parameter vector: the `c` in `D[n] = A[n]*B - C[n]`. - /// - Parameter result: the `d` in `D[n] = A[n]*B - C[n]`. - @inlinable - public static func subtract(multiplication: (a: U, b: Float), - _ vector: T, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(multiplication.a.count == n) - precondition(vector.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplication.a.withUnsafeBufferPointer { a in - withUnsafePointer(to: multiplication.b) { b in - vector.withUnsafeBufferPointer { c in - vDSP_vsmsb(a.baseAddress!, 1, - b, - c.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - /// Returns the elementwise difference of `vector` - /// and the product of the vector and scalar in `multiplication`, - /// double-precision. - /// - /// - Parameter multiplication: the `a` and `b` in `D[n] = A[n]*B - C[n]`. - /// - Parameter vector: the `c` in `D[n] = A[n]*B - C[n]`. - /// - Returns: the `d` in `D[n] = A[n]*B - C[n]`. - @inlinable - public static func subtract(multiplication: (a: U, b: Double), - _ vector: T) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - subtract(multiplication: multiplication, - vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elementwise difference of `vector` - /// and the product of the vector and scalar in `multiplication`, - /// double-precision. - /// - /// - Parameter vector: the `c` in `D[n] = A[n]*B - C[n]`. - /// - Parameter multiplication: the `a` and `b` in `D[n] = A[n]*B - C[n]`. - /// - Parameter result: the `d` in `D[n] = A[n]*B - C[n]`. - @inlinable - public static func subtract(multiplication: (a: U, b: Double), - _ vector: T, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(multiplication.a.count == n) - precondition(vector.count == n) - - result.withUnsafeMutableBufferPointer { r in - multiplication.a.withUnsafeBufferPointer { a in - withUnsafePointer(to: multiplication.b) { b in - vector.withUnsafeBufferPointer { c in - vDSP_vsmsbD(a.baseAddress!, 1, - b, - c.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } -} - diff --git a/stdlib/public/Darwin/Accelerate/vDSP_Biquad.swift b/stdlib/public/Darwin/Accelerate/vDSP_Biquad.swift deleted file mode 100644 index 9e666da33faa1..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_Biquad.swift +++ /dev/null @@ -1,414 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -//===----------------------------------------------------------------------===// -// -// Biquad Structure -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - public struct Biquad { - - private var biquadRef: BiquadRef - - /// Initializes a new single or multichannel cascaded biquad IIR structure. - /// - /// - Parameter coefficients: Array of double-precision real coefficients. Its length should be 5 times the number of sections in the biquad filter. - /// - Parameter sectionCount: The number of sections in the biquad filter. The same number of sections is used for each channel, so only one value is specified. - /// - Parameter channelCount: The number of input/output channels. - /// - Parameter ofType: Specifies single- or double-precision. - public init?(coefficients: [Double], - channelCount: vDSP_Length, - sectionCount: vDSP_Length, - ofType: T.Type) { - - if coefficients.count != 5 * channelCount * sectionCount { - return nil - } - - guard let ref = BiquadRef(coefficients: coefficients, - channelCount: channelCount, - sectionCount: sectionCount, - ofType: ofType) else { - return nil - } - - biquadRef = ref - } - - /// Applies a single- or double-precision single or multichannel biquad IIR filter, returning the filtered signal. - public mutating func apply(input: U) -> [T] - where - U: AccelerateBuffer, - U.Element == T { - - let result = Array(unsafeUninitializedCapacity: input.count) { - buffer, initializedCount in - - apply(input: input, - output: &buffer) - - initializedCount = input.count - } - - return result - } - - /// Applies a single- or double-precision single or multichannel biquad IIR filter, overwriting the supplied output. - public mutating func apply(input: U, output: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == T, V.Element == T { - - // `apply(input:output:)` mutates `delays` and `setup`. - if !isKnownUniquelyReferenced(&biquadRef) { - biquadRef = BiquadRef(coefficients: biquadRef.coefficients, - channelCount: biquadRef.channelCount, - sectionCount: biquadRef.sectionCount, - ofType: T.self)! - } - - biquadRef.apply(input: input, - output: &output) - } - - } - - private class BiquadRef { - - let coefficients: [Double] - let channelCount: vDSP_Length - let sectionCount: vDSP_Length - var delays: [T] - - private let biquadSetup: OpaquePointer - - /// Initializes a new single or multichannel cascaded biquad IIR instance. - /// - /// - Parameter coefficients: Array of double-precision real coefficients. Its length should be 5 times the number of sections in the biquad filter. - /// - Parameter sectionCount: The number of sections in the biquad filter. The same number of sections is used for each channel, so only one value is specified. - /// - Parameter channelCount: The number of input/output channels. - /// - Parameter ofType: Specifies single- or double-precision. - /// - /// For multiple channel signals, this class supports data in non-interleaved format. For example, when applying - /// a filter to a signal represented by an array of 100 elements, elements 0...49 contain the data for channel 0, - /// and elements 50...99 contain the data for channel 1. - - init?(coefficients: [Double], - channelCount: vDSP_Length, - sectionCount: vDSP_Length, - ofType: T.Type) { - - self.coefficients = coefficients - self.channelCount = channelCount - self.sectionCount = sectionCount - - delays = [T](repeating: 0.0, - count: Int(2 * sectionCount) + 2) - - guard let setup = T.BiquadFunctions.makeBiquadSetup(channelCount: channelCount, - coefficients: coefficients, - sectionCount: sectionCount) else { - return nil - } - - biquadSetup = setup - } - - /// Applies a single- or double-precision single or multichannel biquad IIR filter, overwriting the supplied output. - func apply(input: U, output: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == T, V.Element == T { - - let n = vDSP_Length(min(input.count, output.count)) - - if channelCount == 1 { - BiquadFunctions.applyBiquadSingle(source: input, - destination: &output, - delays: &delays, - setup: biquadSetup, - sectionCount: sectionCount, - count: n) - } else { - BiquadFunctions.applyBiquadMulti(source: input, - destination: &output, - setup: biquadSetup, - channelCount: channelCount, - count: n) - } - } - - deinit { - BiquadFunctions.destroySetup(ofType: T.self, - channelCount: channelCount, - biquadSetup: biquadSetup) - } - } - - struct BiquadFunctions { - - @inlinable - static func applyBiquadSingle(source: U, - destination: inout V, - delays: inout [Scalar], - setup: OpaquePointer, - sectionCount: UInt, - count: UInt) - where - Scalar: vDSP_FloatingPointBiquadFilterable, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Scalar, - V.Element == Scalar { - - Scalar.BiquadFunctions.applySingle(source: source, - destination: &destination, - delays: &delays, - setup: setup, - sectionCount: sectionCount, - count: count) - } - - @inlinable - static func applyBiquadMulti(source: U, - destination: inout V, - setup: OpaquePointer, - channelCount: UInt, - count: UInt) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element: vDSP_FloatingPointBiquadFilterable, - V.Element: vDSP_FloatingPointBiquadFilterable { - - source.withUnsafeBufferPointer { biquadInput in - let inputPointer = biquadInput.baseAddress! - destination.withUnsafeMutableBufferPointer { page in - let outputPointer = page.baseAddress! - - let length = count / channelCount - - var inputs: [UnsafePointer] = (0 ..< channelCount).map { i in - return inputPointer.advanced(by: Int(i * length)) - } - - var outputs: [UnsafeMutablePointer] = (0 ..< channelCount).map { i in - return (outputPointer as! UnsafeMutablePointer).advanced(by: Int(i * length)) - } - - U.Element.BiquadFunctions.applyMulti(setup: setup, - pInputs: &inputs, - pOutputs: &outputs, - count: count / channelCount) - } - } - } - - static func destroySetup(ofType: T.Type, - channelCount: UInt, - biquadSetup: OpaquePointer) { - T.BiquadFunctions.destroySetup(channelCount: channelCount, - biquadSetup: biquadSetup) - } - } - -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public protocol vDSP_FloatingPointBiquadFilterable: BinaryFloatingPoint { - associatedtype BiquadFunctions: vDSP_BiquadFunctions where BiquadFunctions.Scalar == Self -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension Float: vDSP_FloatingPointBiquadFilterable { - public typealias BiquadFunctions = vDSP.VectorizableFloat -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension Double: vDSP_FloatingPointBiquadFilterable { - public typealias BiquadFunctions = vDSP.VectorizableDouble -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public protocol vDSP_BiquadFunctions { - associatedtype Scalar - - /// Returns a data structure that contains precalculated data for use by the cascaded biquad IIR filter function. - static func makeBiquadSetup(channelCount: vDSP_Length, - coefficients: [Double], - sectionCount: vDSP_Length) -> OpaquePointer? - - /// Applies a single-channel biquad IIR filter. - static func applySingle(source: U, - destination: inout V, - delays: UnsafeMutablePointer, - setup: vDSP_biquad_Setup, - sectionCount: vDSP_Length, - count: vDSP_Length) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Scalar, V.Element == Scalar - - /// Applies a multichannel biquad IIR filter. - static func applyMulti(setup: vDSP_biquadm_SetupD, - pInputs: UnsafeMutablePointer>, - pOutputs: UnsafeMutablePointer>, - count: vDSP_Length) - - /// Destroys a setup object. - static func destroySetup(channelCount: UInt, - biquadSetup: OpaquePointer) -} - -//===----------------------------------------------------------------------===// -// -// Type-specific Biquad function implementations -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP.VectorizableFloat: vDSP_BiquadFunctions { - - /// Returns a data structure that contains precalculated data for use by the cascaded biquad IIR filter function. - @inlinable - public static func makeBiquadSetup(channelCount: UInt, - coefficients: [Double], - sectionCount: UInt) -> OpaquePointer? { - if channelCount == 1 { - return vDSP_biquad_CreateSetup(coefficients, - sectionCount) - } else { - return vDSP_biquadm_CreateSetup(coefficients, - sectionCount, - channelCount) - } - } - - /// Applies a single-channel biquad IIR filter. - @inlinable - public static func applySingle(source: U, - destination: inout V, - delays: UnsafeMutablePointer, - setup: vDSP_biquad_Setup, - sectionCount: vDSP_Length, - count: vDSP_Length) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_biquad(setup, - delays, - src.baseAddress!, 1, - dest.baseAddress!, 1, - count) - } - } - } - - /// Applies a multichannel biquad IIR filter. - @inlinable - public static func applyMulti(setup: vDSP_biquadm_SetupD, - pInputs: UnsafeMutablePointer>, - pOutputs: UnsafeMutablePointer>, - count: vDSP_Length) { - vDSP_biquadm(setup, - pInputs, 1, - pOutputs, 1, - count) - } - - /// Destroys a setup object. - @inlinable - public static func destroySetup(channelCount: UInt, - biquadSetup: OpaquePointer) { - if channelCount == 1 { - vDSP_biquad_DestroySetup(biquadSetup) - } else { - vDSP_biquadm_DestroySetup(biquadSetup) - } - } -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP.VectorizableDouble: vDSP_BiquadFunctions { - - /// Returns a data structure that contains precalculated data for use by the cascaded biquad IIR filter function. - @inlinable - public static func makeBiquadSetup(channelCount: vDSP_Length, - coefficients: [Double], - sectionCount: vDSP_Length) -> OpaquePointer? { - if channelCount == 1 { - return vDSP_biquad_CreateSetupD(coefficients, - sectionCount) - } else { - return vDSP_biquadm_CreateSetupD(coefficients, - sectionCount, - channelCount) - } - } - - /// Applies a single-channel biquad IIR filter. - @inlinable - public static func applySingle(source: U, - destination: inout V, - delays: UnsafeMutablePointer, - setup: vDSP_biquad_Setup, - sectionCount: vDSP_Length, - count: vDSP_Length) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_biquadD(setup, - delays, - src.baseAddress!, 1, - dest.baseAddress!, 1, - count) - } - } - } - - /// Applies a multichannel biquad IIR filter. - @inlinable - public static func applyMulti(setup: vDSP_biquadm_SetupD, - pInputs: UnsafeMutablePointer>, - pOutputs: UnsafeMutablePointer>, - count: vDSP_Length) { - vDSP_biquadmD(setup, - pInputs, 1, - pOutputs, 1, - count) - } - - /// Destroys a setup object. - @inlinable - public static func destroySetup(channelCount: UInt, - biquadSetup: OpaquePointer) { - if channelCount == 1 { - vDSP_biquad_DestroySetupD(biquadSetup) - } else { - vDSP_biquadm_DestroySetupD(biquadSetup) - } - } -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_ClippingLimitThreshold.swift b/stdlib/public/Darwin/Accelerate/vDSP_ClippingLimitThreshold.swift deleted file mode 100644 index 693a155bc9d6b..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_ClippingLimitThreshold.swift +++ /dev/null @@ -1,600 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - // MARK: Clip - - /// Returns the elements of `vector` clipped to the specified range. Single-precision. - /// - /// - Parameter vector: Source vector. - /// - Parameter bounds: Clipping threshold. - /// - Returns: The clipped result. - @inlinable - public static func clip(_ vector: U, - to bounds: ClosedRange) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - clip(vector, - to: bounds, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elements of `vector` clipped to the specified range. Single-precision. - /// - /// - Parameter vector: Source vector. - /// - Parameter bounds: Clipping threshold. - /// - Parameter result: The clipped result. - @inlinable - public static func clip(_ vector: U, - to bounds: ClosedRange, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vector.count == n) - - withUnsafePointer(to: bounds.lowerBound) { lowerBound in - withUnsafePointer(to: bounds.upperBound) { upperBound in - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - vDSP_vclip(v.baseAddress!, 1, - lowerBound, - upperBound, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - /// Returns the elements of `vector` clipped to the specified range. Double-precision. - /// - /// - Parameter vector: Source vector. - /// - Parameter bounds: Clipping threshold. - /// - Returns: The clipped result. - @inlinable - public static func clip(_ vector: U, - to bounds: ClosedRange) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - clip(vector, - to: bounds, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elements of `vector` clipped to the specified range. Double-precision. - /// - /// - Parameter vector: Source vector. - /// - Parameter bounds: Clipping threshold. - /// - Parameter result: The clipped result. - @inlinable - public static func clip(_ vector: U, - to bounds: ClosedRange, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vector.count == n) - - withUnsafePointer(to: bounds.lowerBound) { lowerBound in - withUnsafePointer(to: bounds.upperBound) { upperBound in - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - vDSP_vclipD(v.baseAddress!, 1, - lowerBound, - upperBound, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - // MARK: Inverted Clip - - /// Returns the elements of `vector` inverted-clipped to the specified range. Single-precision. - /// - /// - Parameter vector: Source vector. - /// - Parameter bounds: Clipping threshold. - /// - Returns: The clipped result. - /// - /// This function performs the following operation where `A` is `vector`, `B` is `bounds.lowerBound`, - /// `C` is `bounds.upperBound`, and `D` is the inverted clip result: - /// ``` - /// for (int n = 0; n < N; ++n) { - /// if (A[n] <= *B || A[n] >= *C) - /// D[n] = A[n]; - /// else if (A[n] < 0) - /// D[n] = *B; - /// else - /// D[n] = *C; - /// } - /// ``` - @inlinable - public static func invertedClip(_ vector: U, - to bounds: ClosedRange) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - invertedClip(vector, - to: bounds, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elements of `vector` inverted-clipped to the specified range. Single-precision. - /// - /// - Parameter vector: Source vector. - /// - Parameter bounds: Clipping threshold. - /// - Parameter result: The clipped result. - /// - /// This function performs the following operation where `A` is `vector`, `B` is `bounds.lowerBound`, - /// `C` is `bounds.upperBound`, and `D` is the inverted clip result: - /// ``` - /// for (int n = 0; n < N; ++n) { - /// if (A[n] <= *B || A[n] >= *C) - /// D[n] = A[n]; - /// else if (A[n] < 0) - /// D[n] = *B; - /// else - /// D[n] = *C; - /// } - /// ``` - @inlinable - public static func invertedClip(_ vector: U, - to bounds: ClosedRange, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vector.count == n) - - withUnsafePointer(to: bounds.lowerBound) { lowerBound in - withUnsafePointer(to: bounds.upperBound) { upperBound in - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - vDSP_viclip(v.baseAddress!, 1, - lowerBound, - upperBound, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - /// Returns the elements of `vector` inverted-clipped to the specified range. Double-precision. - /// - /// - Parameter vector: Source vector. - /// - Parameter bounds: Clipping threshold. - /// - Returns: The clipped result. - /// - /// This function performs the following operation where `A` is `vector`, `B` is `bounds.lowerBound`, - /// `C` is `bounds.upperBound`, and `D` is the inverted clip result: - /// ``` - /// for (int n = 0; n < N; ++n) { - /// if (A[n] <= *B || A[n] >= *C) - /// D[n] = A[n]; - /// else if (A[n] < 0) - /// D[n] = *B; - /// else - /// D[n] = *C; - /// } - /// ``` - @inlinable - public static func invertedClip(_ vector: U, - to bounds: ClosedRange) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - invertedClip(vector, - to: bounds, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the elements of `vector` inverted-clipped to the specified range. Double-precision. - /// - /// - Parameter vector: Source vector. - /// - Parameter bounds: Clipping threshold. - /// - Parameter result: The clipped result. - /// - /// This function performs the following operation where `A` is `vector`, `B` is `bounds.lowerBound`, - /// `C` is `bounds.upperBound`, and `D` is the inverted clip result: - /// ``` - /// for (int n = 0; n < N; ++n) { - /// if (A[n] <= *B || A[n] >= *C) - /// D[n] = A[n]; - /// else if (A[n] < 0) - /// D[n] = *B; - /// else - /// D[n] = *C; - /// } - /// ``` - @inlinable - public static func invertedClip(_ vector: U, - to bounds: ClosedRange, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vector.count == n) - - withUnsafePointer(to: bounds.lowerBound) { lowerBound in - withUnsafePointer(to: bounds.upperBound) { upperBound in - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - vDSP_viclipD(v.baseAddress!, 1, - lowerBound, - upperBound, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - // MARK: Vector threshold. - - public enum ThresholdRule { - /// Returns threshold if input is less than threshold; otherwise input value. - case clampToThreshold - /// Returns zero if input is less than threshold; otherwise input value. - case zeroFill - /// Returns `-x` if input is less than threshold; otherwise `+x`. - case signedConstant(_ x: T) - } - - /// Returns the elements of `vector` after applying a specified thresholding rule. Single-precision. - /// - /// - Parameter vector: Source vector. - /// - Parameter bounds: Clipping threshold. - /// - Returns: The clipped result. - @inlinable - public static func threshold(_ vector: U, - to lowerBound: Float, - with rule: ThresholdRule) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - threshold(vector, - to: lowerBound, - with: rule, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with with the corresponding value in `vector` after applying a specified thresholding rule. Single-precision. - /// - /// This function supports the following rules: - /// - /// * `clampToThreshold` - Returns `lowerBound` if input is less than `lowerBound`; otherwise returns input value. - /// * `zeroFill` - Returns `0` if input is less than `lowerBound`; otherwise returns input value. - /// * `signedConstant(x)` - returns `-x` if input is less than `lowerBound`; otherwise `+x`. - /// - /// - Parameter vector: Source vector. - /// - Parameter lowerBound: Low clipping threshold. - /// - Parameter rule: The thresholding rule. - /// - Parameter result: The threshold result. - public static func threshold(_ vector: U, - to lowerBound: Float, - with rule: ThresholdRule, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vector.count == n) - - withUnsafePointer(to: lowerBound) { lowerBound in - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - switch rule { - case .clampToThreshold: - vDSP_vthr(src.baseAddress!, 1, - lowerBound, - dest.baseAddress!, 1, - vDSP_Length(n)) - case .zeroFill: - vDSP_vthres(src.baseAddress!, 1, - lowerBound, - dest.baseAddress!, 1, - vDSP_Length(n)) - case .signedConstant(let x): - vDSP_vthrsc(src.baseAddress!, 1, - lowerBound, - [x], - dest.baseAddress!, 1, - vDSP_Length(n)) - - } - } - } - } - } - - /// Returns the elements of `vector` after applying a specified thresholding rule. Double-precision. - /// - /// - Parameter vector: Source vector. - /// - Parameter bounds: Clipping threshold. - /// - Returns: The clipped result. - @inlinable - public static func threshold(_ vector: U, - to lowerBound: Double, - with rule: ThresholdRule) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - threshold(vector, - to: lowerBound, - with: rule, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with with the corresponding value in `vector` after applying a specified thresholding rule. Double-precision. - /// - /// This function supports the following rules: - /// - /// * `clampToThreshold` - Returns `lowerBound` if input is less than `lowerBound`; otherwise returns input value. - /// * `zeroFill` - Returns `0` if input is less than `lowerBound`; otherwise returns input value. - /// * `signedConstant(x)` - returns `-x` if input is less than `lowerBound`; otherwise `+x`. - /// - /// - Parameter vector: Source vector. - /// - Parameter lowerBound: Low clipping threshold. - /// - Parameter rule: The thresholding rule. - /// - Parameter result: The threshold result. - public static func threshold(_ vector: U, - to lowerBound: Double, - with rule: ThresholdRule, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vector.count == n) - - withUnsafePointer(to: lowerBound) { lowerBound in - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - switch rule { - case .clampToThreshold: - vDSP_vthrD(src.baseAddress!, 1, - lowerBound, - dest.baseAddress!, 1, - vDSP_Length(n)) - case .zeroFill: - vDSP_vthresD(src.baseAddress!, 1, - lowerBound, - dest.baseAddress!, 1, - vDSP_Length(n)) - case .signedConstant(let x): - vDSP_vthrscD(src.baseAddress!, 1, - lowerBound, - [x], - dest.baseAddress!, 1, - vDSP_Length(n)) - - } - } - } - } - } - - // MARK: Limit (vlim) - - /// Vector test limit; single-precision. - /// - /// Compares values from source vector to `limit`. For inputs greater than or equal to `limit`, `outputConstant` is written to `result`. For inputs less than `limit`, the negated value of `outputConstant` is written to `result`. - /// - /// - Parameter vector: Source vector. - /// - Parameter limit: Limit. - /// - Parameter x: Value written to result. - /// - Returns: The clipped result. - @inlinable - public static func limit(_ vector: U, - limit: Float, - withOutputConstant outputConstant: Float) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - vDSP.limit(vector, - limit: limit, - withOutputConstant: outputConstant, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Vector test limit; single-precision. - /// - /// Compares values from source vector to `limit`. For inputs greater than or equal to `limit`, `outputConstant` is written to `result`. For inputs less than `limit`, the negated value of `outputConstant` is written to `result`. - /// - /// - Parameter vector: Source vector. - /// - Parameter limit: Limit. - /// - Parameter x: Value written to result. - /// - Parameter result: The clipped result. - @inlinable - public static func limit(_ vector: U, - limit: Float, - withOutputConstant outputConstant: Float, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vector.count == n) - - withUnsafePointer(to: limit) { limit in - withUnsafePointer(to: outputConstant) { x in - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - vDSP_vlim(v.baseAddress!, 1, - limit, - x, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } - - /// Vector test limit; double-precision. - /// - /// Compares values from source vector to `limit`. For inputs greater than or equal to `limit`, `outputConstant` is written to `result`. For inputs less than `limit`, the negated value of `outputConstant` is written to `result`. - /// - /// - Parameter vector: Source vector. - /// - Parameter limit: Limit. - /// - Parameter x: Value written to result. - /// - Returns: The clipped result. - @inlinable - public static func limit(_ vector: U, - limit: Double, - withOutputConstant outputConstant: Double) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - vDSP.limit(vector, - limit: limit, - withOutputConstant: outputConstant, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Vector test limit; double-precision. - /// - /// Compares values from source vector to `limit`. For inputs greater than or equal to `limit`, `outputConstant` is written to `result`. For inputs less than `limit`, the negated value of `outputConstant` is written to `result`. - /// - /// - Parameter vector: Source vector. - /// - Parameter limit: Limit. - /// - Parameter x: Value written to result. - /// - Parameter result: The clipped result. - @inlinable - public static func limit(_ vector: U, - limit: Double, - withOutputConstant outputConstant: Double, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vector.count == n) - - withUnsafePointer(to: limit) { limit in - withUnsafePointer(to: outputConstant) { x in - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - vDSP_vlimD(v.baseAddress!, 1, - limit, - x, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - } - } -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_ComplexConversion.swift b/stdlib/public/Darwin/Accelerate/vDSP_ComplexConversion.swift deleted file mode 100644 index fac607037142f..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_ComplexConversion.swift +++ /dev/null @@ -1,71 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - /// Converts split complex to interleaved complex; single-precision. - /// - /// - Parameter splitComplexVector: Source vector. - /// - Parameter interleavedComplexVector: Destination vector. - @inlinable - public static func convert(splitComplexVector: DSPSplitComplex, - toInterleavedComplexVector interleavedComplexVector: inout [DSPComplex]) { - - withUnsafePointer(to: splitComplexVector) { - vDSP_ztoc($0, 1, - &interleavedComplexVector, 2, - vDSP_Length(interleavedComplexVector.count)) - } - } - - /// Converts interleaved complex to split complex; single-precision. - /// - /// - Parameter interleavedComplexVector: Source vector. - /// - Parameter splitComplexVector: Destination vector. - @inlinable - public static func convert(interleavedComplexVector: [DSPComplex], - toSplitComplexVector splitComplexVector: inout DSPSplitComplex) { - - vDSP_ctoz(interleavedComplexVector, 2, - &splitComplexVector, 1, - vDSP_Length(interleavedComplexVector.count)) - } - - /// Converts split complex to interleaved complex; double-precision. - /// - /// - Parameter splitComplexVector: Source vector. - /// - Parameter interleavedComplexVector: Destination vector. - @inlinable - public static func convert(splitComplexVector: DSPDoubleSplitComplex, - toInterleavedComplexVector interleavedComplexVector: inout [DSPDoubleComplex]) { - - withUnsafePointer(to: splitComplexVector) { - vDSP_ztocD($0, 1, - &interleavedComplexVector, 2, - vDSP_Length(interleavedComplexVector.count)) - } - } - - /// Converts interleaved complex to split complex; double-precision. - /// - /// - Parameter interleavedComplexVector: Source vector. - /// - Parameter splitComplexVector: Destination vector. - @inlinable - public static func convert(interleavedComplexVector: [DSPDoubleComplex], - toSplitComplexVector splitComplexVector: inout DSPDoubleSplitComplex) { - - vDSP_ctozD(interleavedComplexVector, 2, - &splitComplexVector, 1, - vDSP_Length(interleavedComplexVector.count)) - } -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_ComplexOperations.swift b/stdlib/public/Darwin/Accelerate/vDSP_ComplexOperations.swift deleted file mode 100644 index b4be22e8fff76..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_ComplexOperations.swift +++ /dev/null @@ -1,543 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - //===----------------------------------------------------------------------===// - // - // Phase calculation - // - //===----------------------------------------------------------------------===// - - /// Populates `result` with the elementwise phase values, in radians, of the supplied complex vector; single-precision. - /// - /// - Parameter splitComplex: Single-precision complex input vector. - /// - Parameter result: Single-precision real output vector. - @inlinable - public static func phase(_ splitComplex: DSPSplitComplex, - result: inout V) - where - V: AccelerateMutableBuffer, - V.Element == Float { - - let n = vDSP_Length(result.count) - - result.withUnsafeMutableBufferPointer { dest in - withUnsafePointer(to: splitComplex) { src in - vDSP_zvphas(src, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Populates `result` with the elementwise phase values, in radians, of the supplied complex vector; double-precision. - /// - /// - Parameter splitComplex: Double-precision complex input vector. - /// - Parameter result: Double-precision real output vector. - @inlinable - public static func phase(_ splitComplex: DSPDoubleSplitComplex, - result: inout V) - where - V: AccelerateMutableBuffer, - V.Element == Double { - - let n = vDSP_Length(result.count) - - result.withUnsafeMutableBufferPointer { dest in - withUnsafePointer(to: splitComplex) { src in - vDSP_zvphasD(src, 1, - dest.baseAddress!, 1, - n) - } - } - } - - //===----------------------------------------------------------------------===// - // - // Complex vector copying - // - //===----------------------------------------------------------------------===// - - /// Copies a complex vector; single-precision. - /// - /// - Parameter source: Single-precision complex input vector. - /// - Parameter destination: Single-precision real output vector. - @inlinable - public static func copy(_ source: DSPSplitComplex, - to destination: inout DSPSplitComplex, - count: Int) { - - let n = vDSP_Length(count) - - withUnsafePointer(to: source) { src in - vDSP_zvmov(src, 1, - &destination, 1, - n) - } - } - - /// Copies a complex vector; double-precision. - /// - /// - Parameter source: Double-precision complex input vector. - /// - Parameter destination: Double-precision real output vector. - @inlinable - public static func copy(_ source: DSPDoubleSplitComplex, - to destination: inout DSPDoubleSplitComplex, - count: Int) { - - let n = vDSP_Length(count) - - withUnsafePointer(to: source) { src in - vDSP_zvmovD(src, 1, - &destination, 1, - n) - } - } - - //===----------------------------------------------------------------------===// - // - // Complex vector conjugate - // - //===----------------------------------------------------------------------===// - - /// Populates `result` with the conjugate of `splitComplex`; single-precision. - /// - /// - Parameter splitComplex: the `A` in `C[n] = conj(A[n])`. - /// - Parameter result: The `C` in `C[n] = conj(A[n])`. - @inlinable - public static func conjugate(_ splitComplex: DSPSplitComplex, - count: Int, - result: inout DSPSplitComplex) { - - withUnsafePointer(to: splitComplex) { a in - vDSP_zvconj(a, 1, - &result, 1, - vDSP_Length(count)) - } - } - - /// Populates `result` with the conjugate of `splitComplex`; double-precision. - /// - /// - Parameter splitComplex: the `A` in `C[n] = conj(A[n])`. - /// - Parameter result: The `C` in `C[n] = conj(A[n])`. - @inlinable - public static func conjugate(_ splitComplex: DSPDoubleSplitComplex, - count: Int, - result: inout DSPDoubleSplitComplex) { - - withUnsafePointer(to: splitComplex) { a in - vDSP_zvconjD(a, 1, - &result, 1, - vDSP_Length(count)) - } - } - - //===----------------------------------------------------------------------===// - // - // Complex vector arithmetic - // - //===----------------------------------------------------------------------===// - - /// Populates `result` with the elementwise division of `splitComplex` and `vector`, - /// single-precision. - /// - /// - Parameter splitComplex: the `a` in `c[i] = a[i] / b[i]`. - /// - Parameter vector: the `b` in `c[i] = a[i] / b[i]`. - /// - Parameter result: The `c` in `c[i] = a[i] / b[i]`. - @inlinable - public static func divide(_ splitComplex: DSPSplitComplex, - by vector: U, - result: inout DSPSplitComplex) - where - U: AccelerateBuffer, - U.Element == Float { - - withUnsafePointer(to: splitComplex) { a in - vector.withUnsafeBufferPointer { b in - vDSP_zrvdiv(a, 1, - b.baseAddress!, 1, - &result, 1, - vDSP_Length(vector.count)) - } - } - } - - /// Populates `result` with the elementwise division of `splitComplex` and `vector`, - /// double-precision. - /// - /// - Parameter splitComplex: the `a` in `c[i] = a[i] / b[i]`. - /// - Parameter vector: the `b` in `c[i] = a[i] / b[i]`. - /// - Parameter result: The `c` in `c[i] = a[i] / b[i]`. - @inlinable - public static func divide(_ splitComplex: DSPDoubleSplitComplex, - by vector: U, - result: inout DSPDoubleSplitComplex) - where - U: AccelerateBuffer, - U.Element == Double { - - withUnsafePointer(to: splitComplex) { a in - vector.withUnsafeBufferPointer { b in - vDSP_zrvdivD(a, 1, - b.baseAddress!, 1, - &result, 1, - vDSP_Length(vector.count)) - } - } - } - - /// Populates `result` with the elementwise product of `splitComplex` and `vector`, - /// single-precision. - /// - /// - Parameter splitComplex: the `a` in `c[i] = a[i] * b[i]`. - /// - Parameter vector: the `b` in `c[i] = a[i] * b[i]`. - /// - Parameter result: The `c` in `c[i] = a[i] * b[i]`. - @inlinable - public static func multiply(_ splitComplex: DSPSplitComplex, - by vector: U, - result: inout DSPSplitComplex) - where - U: AccelerateBuffer, - U.Element == Float { - - withUnsafePointer(to: splitComplex) { a in - vector.withUnsafeBufferPointer { b in - vDSP_zrvmul(a, 1, - b.baseAddress!, 1, - &result, 1, - vDSP_Length(vector.count)) - } - } - } - - /// Populates `result` with the elementwise product of `splitComplex` and `vector`, - /// double-precision. - /// - /// - Parameter splitComplex: the `a` in `c[i] = a[i] * b[i]`. - /// - Parameter vector: the `b` in `c[i] = a[i] * b[i]`. - /// - Parameter result: The `c` in `c[i] = a[i] * b[i]`. - @inlinable - public static func multiply(_ splitComplex: DSPDoubleSplitComplex, - by vector: U, - result: inout DSPDoubleSplitComplex) - where - U: AccelerateBuffer, - U.Element == Double { - - withUnsafePointer(to: splitComplex) { a in - vector.withUnsafeBufferPointer { b in - vDSP_zrvmulD(a, 1, - b.baseAddress!, 1, - &result, 1, - vDSP_Length(vector.count)) - } - } - } - - /// Populates `result` with the elementwise product of `splitComplexA` and `splitComplexB`, - /// optionally conjugating one of them; single-precision - /// - /// - Parameter splitComplexA: The `a` in `c[i] = a[i] * b[i]` or `c[i] = conj(a[i]) * b[i]`. - /// - Parameter splitComplexB: The `b` in `c[i] = a[i] * b[i]` or `c[i] = conj(a[i]) * b[i]`. - /// - Parameter count: The number of elements to process. - /// - Parameter useConjugate: Specifies whether to multiply the complex conjugates of `splitComplexA`. - /// - Parameter result: The `c` in `c[i] = a[i] * b[i]` or `c[i] = conj(a[i]) * b[i]`. - @inlinable - public static func multiply(_ splitComplexA: DSPSplitComplex, - by splitComplexB: DSPSplitComplex, - count: Int, - useConjugate: Bool, - result: inout DSPSplitComplex) { - - let conjugate: Int32 = useConjugate ? -1 : 1 - - withUnsafePointer(to: splitComplexA) { a in - withUnsafePointer(to: splitComplexB) { b in - vDSP_zvmul(a, 1, - b, 1, - &result, 1, - vDSP_Length(count), - conjugate) - } - } - } - - /// Populates `result` with the elementwise product of `splitComplexA` and `splitComplexB`, - /// optionally conjugating one of them; double-precision - /// - /// - Parameter splitComplexA: The `a` in `c[i] = a[i] * b[i]` or `c[i] = conj(a[i]) * b[i]`. - /// - Parameter splitComplexB: The `b` in `c[i] = a[i] * b[i]` or `c[i] = conj(a[i]) * b[i]`. - /// - Parameter count: The number of elements to process. - /// - Parameter useConjugate: Specifies whether to multiply the complex conjugates of `splitComplexA`. - /// - Parameter result: The `c` in `c[i] = a[i] * b[i]` or `c[i] = conj(a[i]) * b[i]`. - @inlinable - public static func multiply(_ splitComplexA: DSPDoubleSplitComplex, - by splitComplexB: DSPDoubleSplitComplex, - count: Int, - useConjugate: Bool, - result: inout DSPDoubleSplitComplex) { - - let conjugate: Int32 = useConjugate ? -1 : 1 - - withUnsafePointer(to: splitComplexA) { a in - withUnsafePointer(to: splitComplexB) { b in - vDSP_zvmulD(a, 1, - b, 1, - &result, 1, - vDSP_Length(count), - conjugate) - } - } - } - - /// Populates `result` with the elementwise sum of `splitComplexA` and `splitComplexB`, - /// single-precision. - /// - /// - Parameter splitComplexA: the `a` in `c[i] = a[i] + b[i]`. - /// - Parameter splitComplexB: the `b` in `c[i] = a[i] + b[i]`. - /// - Parameter count: The number of elements to process. - /// - Parameter result: The `c` in `c[i] = a[i] + b[i]`. - @inlinable - public static func add(_ splitComplexA: DSPSplitComplex, - to splitComplexB: DSPSplitComplex, - count: Int, - result: inout DSPSplitComplex) { - - withUnsafePointer(to: splitComplexA) { a in - withUnsafePointer(to: splitComplexB) { b in - vDSP_zvadd(a, 1, - b, 1, - &result, 1, - vDSP_Length(count)) - } - } - } - - /// Populates `result` with the elementwise sum of `splitComplexA` and `splitComplexB`, - /// double-precision. - /// - /// - Parameter splitComplexA: the `a` in `c[i] = a[i] + b[i]`. - /// - Parameter splitComplexB: the `b` in `c[i] = a[i] + b[i]`. - /// - Parameter count: The number of elements to process. - /// - Parameter result: The `c` in `c[i] = a[i] + b[i]`. - @inlinable - public static func add(_ splitComplexA: DSPDoubleSplitComplex, - to splitComplexB: DSPDoubleSplitComplex, - count: Int, - result: inout DSPDoubleSplitComplex) { - - withUnsafePointer(to: splitComplexA) { a in - withUnsafePointer(to: splitComplexB) { b in - vDSP_zvaddD(a, 1, - b, 1, - &result, 1, - vDSP_Length(count)) - } - } - } - - /// Populates `result` with the elementwise division of `splitComplexA` and `splitComplexB`, - /// single-precision. - /// - /// - Parameter splitComplexA: the `a` in `c[i] = a[i] / b[i]`. - /// - Parameter splitComplexB: the `b` in `c[i] = a[i] / b[i]`. - /// - Parameter count: The number of elements to process. - /// - Parameter result: The `c` in `c[i] = a[i] / b[i]`. - @inlinable - public static func divide(_ splitComplexA: DSPSplitComplex, - by splitComplexB: DSPSplitComplex, - count: Int, - result: inout DSPSplitComplex) { - - withUnsafePointer(to: splitComplexA) { a in - withUnsafePointer(to: splitComplexB) { b in - vDSP_zvdiv(b, 1, - a, 1, - &result, 1, - vDSP_Length(count)) - } - } - } - - /// Populates `result` with the elementwise division of `splitComplexA` and `splitComplexB`, - /// single-precision. - /// - /// - Parameter splitComplexA: the `a` in `c[i] = a[i] / b[i]`. - /// - Parameter splitComplexB: the `b` in `c[i] = a[i] / b[i]`. - /// - Parameter count: The number of elements to process. - /// - Parameter result: The `c` in `c[i] = a[i] / b[i]`. - @inlinable - public static func divide(_ splitComplexA: DSPDoubleSplitComplex, - by splitComplexB: DSPDoubleSplitComplex, - count: Int, - result: inout DSPDoubleSplitComplex) { - - withUnsafePointer(to: splitComplexA) { a in - withUnsafePointer(to: splitComplexB) { b in - vDSP_zvdivD(b, 1, - a, 1, - &result, 1, - vDSP_Length(count)) - } - } - } - - /// Populates `result` with the elementwise difference of `splitComplexA` and `splitComplexB`, - /// single-precision. - /// - /// - Parameter splitComplexA: the `a` in `c[i] = a[i] - b[i]`. - /// - Parameter splitComplexB: the `b` in `c[i] = a[i] - b[i]`. - /// - Parameter count: The number of elements to process. - /// - Parameter result: The `c` in `c[i] = a[i] - b[i]`. - @inlinable - public static func subtract(_ splitComplexB: DSPSplitComplex, - from splitComplexA: DSPSplitComplex, - count: Int, - result: inout DSPSplitComplex) { - - withUnsafePointer(to: splitComplexA) { a in - withUnsafePointer(to: splitComplexB) { b in - vDSP_zvsub(b, 1, - a, 1, - &result, 1, - vDSP_Length(count)) - } - } - } - - /// Populates `result` with the elementwise difference of `splitComplexA` and `splitComplexB`, - /// double-precision. - /// - /// - Parameter splitComplexA: the `a` in `c[i] = a[i] - b[i]`. - /// - Parameter splitComplexB: the `b` in `c[i] = a[i] - b[i]`. - /// - Parameter count: The number of elements to process. - /// - Parameter result: The `c` in `c[i] = a[i] - b[i]`. - @inlinable - public static func subtract(_ splitComplexB: DSPDoubleSplitComplex, - from splitComplexA: DSPDoubleSplitComplex, - count: Int, - result: inout DSPDoubleSplitComplex) { - - withUnsafePointer(to: splitComplexA) { a in - withUnsafePointer(to: splitComplexB) { b in - vDSP_zvsubD(b, 1, - a, 1, - &result, 1, - vDSP_Length(count)) - } - } - } - - //===----------------------------------------------------------------------===// - // - // Complex vector absolute - // - //===----------------------------------------------------------------------===// - - /// Populates `result` with the absolute values of `vector`, - /// single-precision. - /// - /// - Parameter vector: The input vector. - /// - Parameter result: The output vector. - @inlinable - public static func absolute(_ vector: DSPSplitComplex, - result: inout V) - where - V: AccelerateMutableBuffer, - V.Element == Float { - - let n = result.count - - result.withUnsafeMutableBufferPointer { r in - withUnsafePointer(to: vector) { v in - vDSP_zvabs(v, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - - /// Populates `result` with the absolute values of `vector`, - /// double-precision. - /// - /// - Parameter vector: The input vector. - /// - Parameter result: The output vector. - @inlinable - public static func absolute(_ vector: DSPDoubleSplitComplex, - result: inout V) - where - V: AccelerateMutableBuffer, - V.Element == Double { - - let n = result.count - - result.withUnsafeMutableBufferPointer { r in - withUnsafePointer(to: vector) { v in - vDSP_zvabsD(v, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - - //===----------------------------------------------------------------------===// - // - // Complex squared magnitude - // - //===----------------------------------------------------------------------===// - - /// Calculates the squared magnitude of each element in `vector`, writing the result to `result`; single-precision. - /// - /// - Parameter splitComplex: Input values. - /// - Parameter result: Output values. - @inlinable - public static func squareMagnitudes(_ splitComplex: DSPSplitComplex, - result: inout V) - where - V : AccelerateMutableBuffer, - V.Element == Float { - - let n = vDSP_Length(result.count) - - result.withUnsafeMutableBufferPointer { dest in - withUnsafePointer(to: splitComplex) { src in - vDSP_zvmags(src, 1, - dest.baseAddress!, 1, - n) - } - } - } - - @inlinable - /// Calculates the squared magnitude of each element in `vector`, writing the result to `result`; double-precision. - /// - /// - Parameter splitComplex: Input values. - /// - Parameter result: Output values. - public static func squareMagnitudes(_ splitComplex: DSPDoubleSplitComplex, - result: inout V) - where - V : AccelerateMutableBuffer, - V.Element == Double { - - let n = vDSP_Length(result.count) - - result.withUnsafeMutableBufferPointer { dest in - withUnsafePointer(to: splitComplex) { src in - vDSP_zvmagsD(src, 1, - dest.baseAddress!, 1, - n) - } - } - } -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_Conversion.swift b/stdlib/public/Darwin/Accelerate/vDSP_Conversion.swift deleted file mode 100644 index fbc0e97d94250..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_Conversion.swift +++ /dev/null @@ -1,1256 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - // MARK: Integer to floating-point conversion - - /// Converts an array of unsigned 8-bit integers to single-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - @inlinable - public static func convertElements(of source: U, - to destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == UInt8, - V.Element == Float { - - precondition(source.count == destination.count) - - let n = vDSP_Length(source.count) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_vfltu8(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Converts an array of unsigned 8-bit integers to double-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - @inlinable - public static func convertElements(of source: U, - to destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == UInt8, - V.Element == Double { - - precondition(source.count == destination.count) - - let n = vDSP_Length(source.count) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_vfltu8D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Converts an array of unsigned 16-bit integers to single-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - @inlinable - public static func convertElements(of source: U, - to destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == UInt16, - V.Element == Float { - - precondition(source.count == destination.count) - - let n = vDSP_Length(source.count) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_vfltu16(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Converts an array of unsigned 16-bit integers to double-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - @inlinable - public static func convertElements(of source: U, - to destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == UInt16, - V.Element == Double { - - precondition(source.count == destination.count) - - let n = vDSP_Length(source.count) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_vfltu16D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Converts an array of unsigned 32-bit integers to single-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - @inlinable - public static func convertElements(of source: U, - to destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == UInt32, - V.Element == Float { - - precondition(source.count == destination.count) - - let n = vDSP_Length(source.count) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_vfltu32(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Converts an array of unsigned 32-bit integers to double-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - @inlinable - public static func convertElements(of source: U, - to destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == UInt32, - V.Element == Double { - - precondition(source.count == destination.count) - - let n = vDSP_Length(source.count) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_vfltu32D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Converts an array of signed 8-bit integers to single-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - @inlinable - public static func convertElements(of source: U, - to destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Int8, - V.Element == Float { - - precondition(source.count == destination.count) - - let n = vDSP_Length(source.count) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_vflt8(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Converts an array of signed 8-bit integers to double-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - @inlinable - public static func convertElements(of source: U, - to destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Int8, - V.Element == Double { - - precondition(source.count == destination.count) - - let n = vDSP_Length(source.count) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_vflt8D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Converts an array of signed 16-bit integers to single-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - @inlinable - public static func convertElements(of source: U, - to destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Int16, - V.Element == Float { - - precondition(source.count == destination.count) - - let n = vDSP_Length(source.count) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_vflt16(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Converts an array of signed 16-bit integers to double-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - @inlinable - public static func convertElements(of source: U, - to destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Int16, - V.Element == Double { - - precondition(source.count == destination.count) - - let n = vDSP_Length(source.count) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_vflt16D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Converts an array of signed 32-bit integers to single-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - @inlinable - public static func convertElements(of source: U, - to destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Int32, - V.Element == Float { - - precondition(source.count == destination.count) - - let n = vDSP_Length(source.count) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_vflt32(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Converts an array of signed 32-bit integers to double-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - @inlinable - public static func convertElements(of source: U, - to destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Int32, - V.Element == Double { - - precondition(source.count == destination.count) - - let n = vDSP_Length(source.count) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_vflt32D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - // MARK: Floating-point to integer conversion - public enum RoundingMode { - case towardZero - case towardNearestInteger - } - - /// Converts an array of single-precision floating-point values to signed 32-bit integer values using specified rounding. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - public static func convertElements(of source: U, - to destination: inout V, - rounding: RoundingMode) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, - V.Element == Int32 { - let n = vDSP_Length(min(source.count, - destination.count)) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - switch rounding { - case .towardZero: - vDSP_vfix32(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - case .towardNearestInteger: - vDSP_vfixr32(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Converts an array of double-precision floating-point values to signed 32-bit integer values using specified rounding. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - public static func convertElements(of source: U, - to destination: inout V, - rounding: RoundingMode) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, - V.Element == Int32 { - let n = vDSP_Length(min(source.count, - destination.count)) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - switch rounding { - case .towardZero: - vDSP_vfix32D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - case .towardNearestInteger: - vDSP_vfixr32D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Converts an array of single-precision floating-point values to unsigned 16-bit integer values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - public static func convertElements(of source: U, - to destination: inout V, - rounding: RoundingMode) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, - V.Element == UInt16 { - let n = vDSP_Length(min(source.count, - destination.count)) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - switch rounding { - case .towardZero: - vDSP_vfixu16(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - case .towardNearestInteger: - vDSP_vfixru16(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Converts an array of double-precision floating-point values to unsigned 16-bit integer values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - public static func convertElements(of source: U, - to destination: inout V, - rounding: RoundingMode) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, - V.Element == UInt16 { - let n = vDSP_Length(min(source.count, - destination.count)) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - switch rounding { - case .towardZero: - vDSP_vfixu16D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - case .towardNearestInteger: - vDSP_vfixru16D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Converts an array of single-precision floating-point values to unsigned 32-bit integer values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - public static func convertElements(of source: U, - to destination: inout V, - rounding: RoundingMode) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, - V.Element == UInt32 { - let n = vDSP_Length(min(source.count, - destination.count)) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - switch rounding { - case .towardZero: - vDSP_vfixu32(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - case .towardNearestInteger: - vDSP_vfixru32(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Converts an array of double-precision floating-point values to unsigned 32-bit integer values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - public static func convertElements(of source: U, - to destination: inout V, - rounding: RoundingMode) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, - V.Element == UInt32 { - let n = vDSP_Length(min(source.count, - destination.count)) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - switch rounding { - case .towardZero: - vDSP_vfixu32D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - case .towardNearestInteger: - vDSP_vfixru32D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - - - /// Converts an array of single-precision floating-point values to signed 16-bit integer values using specified rounding. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - public static func convertElements(of source: U, - to destination: inout V, - rounding: RoundingMode) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, - V.Element == Int16 { - let n = vDSP_Length(min(source.count, - destination.count)) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - switch rounding { - case .towardZero: - vDSP_vfix16(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - case .towardNearestInteger: - vDSP_vfixr16(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Converts an array of double-precision floating-point values to signed 16-bit integer values using specified rounding. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - public static func convertElements(of source: U, - to destination: inout V, - rounding: RoundingMode) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, - V.Element == Int16 { - let n = vDSP_Length(min(source.count, - destination.count)) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - switch rounding { - case .towardZero: - vDSP_vfix16D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - case .towardNearestInteger: - vDSP_vfixr16D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Converts an array of single-precision floating-point values to signed 8-bit integer values using specified rounding. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - public static func convertElements(of source: U, - to destination: inout V, - rounding: RoundingMode) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, - V.Element == Int8 { - let n = vDSP_Length(min(source.count, - destination.count)) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - switch rounding { - case .towardZero: - vDSP_vfix8(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - case .towardNearestInteger: - vDSP_vfixr8(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Converts an array of double-precision floating-point values to signed 8-bit integer values using specified rounding. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - public static func convertElements(of source: U, - to destination: inout V, - rounding: RoundingMode) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, - V.Element == Int8 { - let n = vDSP_Length(min(source.count, - destination.count)) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - switch rounding { - case .towardZero: - vDSP_vfix8D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - case .towardNearestInteger: - vDSP_vfixr8D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Converts an array of single-precision floating-point values to unsigned 8-bit integer values using specified rounding. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - public static func convertElements(of source: U, - to destination: inout V, - rounding: RoundingMode) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, - V.Element == UInt8 { - let n = vDSP_Length(min(source.count, - destination.count)) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - switch rounding { - case .towardZero: - vDSP_vfixu8(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - case .towardNearestInteger: - vDSP_vfixru8(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Converts an array of double-precision floating-point values to unsigned 8-bit integer values using specified rounding. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - public static func convertElements(of source: U, - to destination: inout V, - rounding: RoundingMode) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, - V.Element == UInt8 { - let n = vDSP_Length(min(source.count, - destination.count)) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - switch rounding { - case .towardZero: - vDSP_vfixu8D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - case .towardNearestInteger: - vDSP_vfixru8D(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Converts an array of single-precision floating-point values to double-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - @inlinable - public static func convertElements(of source: U, - to destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, - V.Element == Double { - let n = vDSP_Length(min(source.count, - destination.count)) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_vspdp(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Converts an array of double-precision floating-point values to single-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Parameter destination: Destination vector. - @inlinable - public static func convertElements(of source: U, - to destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, - V.Element == Float { - let n = vDSP_Length(min(source.count, - destination.count)) - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_vdpsp(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } -} - -//===----------------------------------------------------------------------===// -// -// Conversion functions that return the result -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public protocol vDSP_IntegerConvertable {} -extension UInt8: vDSP_IntegerConvertable {} -extension UInt16: vDSP_IntegerConvertable {} -extension UInt32: vDSP_IntegerConvertable {} -extension Int8: vDSP_IntegerConvertable {} -extension Int16: vDSP_IntegerConvertable {} -extension Int32: vDSP_IntegerConvertable {} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public protocol vDSP_FloatingPointConvertable {} -extension Float: vDSP_FloatingPointConvertable {} -extension Double: vDSP_FloatingPointConvertable {} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - // MARK: Integer to floating-point conversion - - /// Converts an array of unsigned 8-bit integers to floating-point values. - /// - /// - Parameter source: Source vector. - /// - Returns: Conversion result. - @inlinable - public static func integerToFloatingPoint(_ vector: T, - floatingPointType: U.Type) -> [U] - where - T: AccelerateBuffer, - T.Element == UInt8, - U: vDSP_FloatingPointConvertable { - - switch floatingPointType { - case is Float.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer) - - initializedCount = vector.count - } - - return result as! [U] - case is Double.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer) - - initializedCount = vector.count - } - - return result as! [U] - - default: - fatalError("\(floatingPointType) not supported as a destination type.") - } - } - - /// Converts an array of unsigned 16-bit integers to floating-point values. - /// - /// - Parameter source: Source vector. - /// - Returns: Conversion result. - @inlinable - public static func integerToFloatingPoint(_ vector: T, - floatingPointType: U.Type) -> [U] - where - T: AccelerateBuffer, - T.Element == UInt16, - U: vDSP_FloatingPointConvertable { - - switch floatingPointType { - case is Float.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer) - - initializedCount = vector.count - } - - return result as! [U] - case is Double.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer) - - initializedCount = vector.count - } - - return result as! [U] - - default: - fatalError("\(floatingPointType) not supported as a destination type.") - } - } - - /// Converts an array of unsigned 32-bit integers to floating-point values. - /// - /// - Parameter source: Source vector. - /// - Returns: Conversion result. - @inlinable - public static func integerToFloatingPoint(_ vector: T, - floatingPointType: U.Type) -> [U] - where - T: AccelerateBuffer, - T.Element == UInt32, - U: vDSP_FloatingPointConvertable { - - switch floatingPointType { - case is Float.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer) - - initializedCount = vector.count - } - - return result as! [U] - case is Double.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer) - - initializedCount = vector.count - } - - return result as! [U] - - default: - fatalError("\(floatingPointType) not supported as a destination type.") - } - } - - /// Converts an array of signed 8-bit integers to floating-point values. - /// - /// - Parameter source: Source vector. - /// - Returns: Conversion result. - @inlinable - public static func integerToFloatingPoint(_ vector: T, - floatingPointType: U.Type) -> [U] - where - T: AccelerateBuffer, - T.Element == Int8, - U: vDSP_FloatingPointConvertable { - - switch floatingPointType { - case is Float.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer) - - initializedCount = vector.count - } - - return result as! [U] - case is Double.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer) - - initializedCount = vector.count - } - - return result as! [U] - - default: - fatalError("\(floatingPointType) not supported as a destination type.") - } - } - - /// Converts an array of signed 16-bit integers to floating-point values. - /// - /// - Parameter source: Source vector. - /// - Returns: Conversion result. - @inlinable - public static func integerToFloatingPoint(_ vector: T, - floatingPointType: U.Type) -> [U] - where - T: AccelerateBuffer, - T.Element == Int16, - U: vDSP_FloatingPointConvertable { - - switch floatingPointType { - case is Float.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer) - - initializedCount = vector.count - } - - return result as! [U] - case is Double.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer) - - initializedCount = vector.count - } - - return result as! [U] - - default: - fatalError("\(floatingPointType) not supported as a destination type.") - } - } - - /// Converts an array of signed 32-bit integers to floating-point values. - /// - /// - Parameter source: Source vector. - /// - Returns: Conversion result. - @inlinable - public static func integerToFloatingPoint(_ vector: T, - floatingPointType: U.Type) -> [U] - where - T: AccelerateBuffer, - T.Element == Int32, - U: vDSP_FloatingPointConvertable { - - switch floatingPointType { - case is Float.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer) - - initializedCount = vector.count - } - - return result as! [U] - case is Double.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer) - - initializedCount = vector.count - } - - return result as! [U] - - default: - fatalError("\(floatingPointType) not supported as a destination type.") - } - } - - // MARK: Floating-point to integer conversion - - /// Converts an array of single-precision floating-point values to integer values using specified rounding. - /// - /// - Parameter source: Source vector. - /// - Returns: Conversion result. - @inlinable - public static func floatingPointToInteger(_ vector: T, - integerType: U.Type, - rounding: RoundingMode) -> [U] - where - T: AccelerateBuffer, - T.Element == Float, - U: vDSP_IntegerConvertable { - - switch integerType { - case is UInt8.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer, - rounding: rounding) - - initializedCount = vector.count - } - - return result as! [U] - case is UInt16.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer, - rounding: rounding) - - initializedCount = vector.count - } - - return result as! [U] - case is UInt32.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer, - rounding: rounding) - - initializedCount = vector.count - } - - return result as! [U] - case is Int8.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer, - rounding: rounding) - - initializedCount = vector.count - } - - return result as! [U] - case is Int16.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer, - rounding: rounding) - - initializedCount = vector.count - } - - return result as! [U] - case is Int32.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer, - rounding: rounding) - - initializedCount = vector.count - } - - return result as! [U] - default: - fatalError("\(integerType) not supported as a destination type.") - } - } - - /// Converts an array of double-precision floating-point values to integer values using specified rounding. - /// - /// - Parameter source: Source vector. - /// - Returns: Conversion result. - @inlinable - public static func floatingPointToInteger(_ vector: T, - integerType: U.Type, - rounding: RoundingMode) -> [U] - where - T: AccelerateBuffer, - T.Element == Double, - U: vDSP_IntegerConvertable { - - switch integerType { - case is UInt8.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer, - rounding: rounding) - - initializedCount = vector.count - } - - return result as! [U] - case is UInt16.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer, - rounding: rounding) - - initializedCount = vector.count - } - - return result as! [U] - case is UInt32.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer, - rounding: rounding) - - initializedCount = vector.count - } - - return result as! [U] - case is Int8.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer, - rounding: rounding) - - initializedCount = vector.count - } - - return result as! [U] - case is Int16.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer, - rounding: rounding) - - initializedCount = vector.count - } - - return result as! [U] - case is Int32.Type: - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convertElements(of: vector, - to: &buffer, - rounding: rounding) - - initializedCount = vector.count - } - - return result as! [U] - default: - fatalError("\(integerType) not supported as a destination type.") - } - } - - // MARK: Floating-point to floating-point conversion - - /// Converts an array of single-precision floating-point values to double-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Returns: Conversion result. - @inlinable - public static func floatToDouble(_ source: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Float { - let result = Array(unsafeUninitializedCapacity: source.count) { - buffer, initializedCount in - - convertElements(of: source, - to: &buffer) - - initializedCount = source.count - } - - return result - } - - /// Converts an array of double-precision floating-point values to single-precision floating-point values. - /// - /// - Parameter source: Source vector. - /// - Returns: Conversion result. - @inlinable - public static func doubleToFloat(_ source: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Double { - let result = Array(unsafeUninitializedCapacity: source.count) { - buffer, initializedCount in - - convertElements(of: source, - to: &buffer) - - initializedCount = source.count - } - - return result - } -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_Convolution.swift b/stdlib/public/Darwin/Accelerate/vDSP_Convolution.swift deleted file mode 100644 index 71f37c85093d0..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_Convolution.swift +++ /dev/null @@ -1,731 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - // MARK: One-dimensional convolution - - /// Returns one-dimensional convolution, single-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter kernel: Single-precision convolution kernel. - /// - Returns: Convolution result. - @inlinable - public static func convolve(_ vector: T, - withKernel kernel: U) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let n = vector.count - kernel.count - - let result = Array(unsafeUninitializedCapacity: n) { - buffer, initializedCount in - - convolve(vector, - withKernel: kernel, - result: &buffer) - - initializedCount = n - } - - return result - } - - /// One-dimensional convolution, single-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter kernel: Single-precision convolution kernel. - /// - Parameter result: Destination vector. - - @inlinable - public static func convolve(_ vector: T, - withKernel kernel: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vector.count >= n + kernel.count - 1, - "Source vector count must be at least the sum of the result and kernel counts, minus one.") - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - kernel.withUnsafeBufferPointer { k in - vDSP_conv(src.baseAddress!, 1, - k.baseAddress!.advanced(by: kernel.count - 1), -1, - dest.baseAddress!, 1, - vDSP_Length(n), - vDSP_Length(kernel.count)) - } - } - } - } - - /// Returns one-dimensional convolution, double-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter kernel: Double-precision convolution kernel. - /// - Returns: Convolution result. - @inlinable - public static func convolve(_ vector: T, - withKernel kernel: U) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let n = vector.count - kernel.count - - let result = Array(unsafeUninitializedCapacity: n) { - buffer, initializedCount in - - convolve(vector, - withKernel: kernel, - result: &buffer) - - initializedCount = n - } - - return result - } - - /// One-dimensional convolution, double-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter kernel: Double-precision convolution kernel. - /// - Parameter result: Destination vector. - - @inlinable - public static func convolve(_ vector: T, - withKernel kernel: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vector.count >= n + kernel.count - 1, - "Source vector count must be at least the sum of the result and kernel counts, minus one.") - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - kernel.withUnsafeBufferPointer { k in - vDSP_convD(src.baseAddress!, 1, - k.baseAddress!.advanced(by: kernel.count - 1), -1, - dest.baseAddress!, 1, - vDSP_Length(n), - vDSP_Length(kernel.count)) - } - } - } - } - - // MARK: One-dimensional correlation - - /// Returns one-dimensional correlation, single-precision. - /// - /// - Parameter vector: The vector to correlate. - /// - Parameter kernel: Single-precision convolution kernel. - /// - Returns: Correlation result. - @inlinable - public static func correlate(_ vector: T, - withKernel kernel: U) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let n = vector.count - kernel.count - - let result = Array(unsafeUninitializedCapacity: n) { - buffer, initializedCount in - - correlate(vector, - withKernel: kernel, - result: &buffer) - - initializedCount = n - } - - return result - } - - /// One-dimensional correlation, single-precision. - /// - /// - Parameter vector: The vector to correlate. - /// - Parameter kernel: Single-precision convolution kernel. - /// - Parameter result: Destination vector. - - @inlinable - public static func correlate(_ vector: T, - withKernel kernel: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vector.count >= n + kernel.count - 1, - "Source vector count must be at least the sum of the result and kernel counts, minus one.") - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - kernel.withUnsafeBufferPointer { k in - vDSP_conv(src.baseAddress!, 1, - k.baseAddress!, 1, - dest.baseAddress!, 1, - vDSP_Length(n), - vDSP_Length(kernel.count)) - } - } - } - } - - /// Returns one-dimensional correlation, double-precision. - /// - /// - Parameter vector: The vector to correlate. - /// - Parameter kernel: Single-precision convolution kernel. - /// - Returns: Correlation result. - @inlinable - public static func correlate(_ vector: T, - withKernel kernel: U) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let n = vector.count - kernel.count - - let result = Array(unsafeUninitializedCapacity: n) { - buffer, initializedCount in - - correlate(vector, - withKernel: kernel, - result: &buffer) - - initializedCount = n - } - - return result - } - - /// One-dimensional correlation, double-precision. - /// - /// - Parameter vector: The vector to correlate. - /// - Parameter kernel: Single-precision convolution kernel. - /// - Parameter result: Destination vector. - - @inlinable - public static func correlate(_ vector: T, - withKernel kernel: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vector.count >= n + kernel.count - 1, - "Source vector count must be at least the sum of the result and kernel counts, minus one.") - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - kernel.withUnsafeBufferPointer { k in - vDSP_convD(src.baseAddress!, 1, - k.baseAddress!, 1, - dest.baseAddress!, 1, - vDSP_Length(n), - vDSP_Length(kernel.count)) - } - } - } - } - -} - - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - // MARK: Two-dimensional convolution - - /// Returns two-dimensional convolution with a 3 x 3 kernel; single-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter rowCount: The number of rows in the input vector. - /// - Parameter columnCount: The number of columns in the input vector. - /// - Parameter kernel: Single-precision 3x3 convolution kernel. - /// - Returns: Convolution result. - @inlinable - public static func convolve(_ vector: T, - rowCount: Int, columnCount: Int, - with3x3Kernel kernel: U) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convolve(vector, - rowCount: rowCount, columnCount: columnCount, - with3x3Kernel: kernel, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Two-dimensional convolution with a 3 x 3 kernel; single-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter rowCount: The number of rows in the input vector. - /// - Parameter columnCount: The number of columns in the input vector. - /// - Parameter kernel: Single-precision 3x3 convolution kernel. - /// - Parameter result: Destination vector. - - @inlinable - public static func convolve(_ vector: T, - rowCount: Int, columnCount: Int, - with3x3Kernel kernel: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - precondition(rowCount >= 3, - "Row count must be greater than or equal to 3.") - - precondition(columnCount >= 4, - "Column count must be even and greater than or equal to 4") - - precondition(rowCount * columnCount == vector.count, - "Row count `x` column count must equal source vector count.") - - precondition(kernel.count == 9, - "Kernel must contain 9 elements.") - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - kernel.withUnsafeBufferPointer { k in - vDSP_f3x3(src.baseAddress!, - vDSP_Length(rowCount), vDSP_Length(columnCount), - k.baseAddress!, - dest.baseAddress!) - } - } - } - } - - /// Returns two-dimensional convolution with a 3 x 3 kernel; double-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter rowCount: The number of rows in the input vector. - /// - Parameter columnCount: The number of columns in the input vector. - /// - Parameter kernel: Double-precision 3x3 convolution kernel. - /// - Returns: Convolution result. - @inlinable - public static func convolve(_ vector: T, - rowCount: Int, columnCount: Int, - with3x3Kernel kernel: U) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convolve(vector, - rowCount: rowCount, columnCount: columnCount, - with3x3Kernel: kernel, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Two-dimensional convolution with a 3 x 3 kernel; double-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter rowCount: The number of rows in the input vector. - /// - Parameter columnCount: The number of columns in the input vector. - /// - Parameter kernel: Double-precision 3x3 convolution kernel. - /// - Parameter result: Destination vector. - - @inlinable - public static func convolve(_ vector: T, - rowCount: Int, columnCount: Int, - with3x3Kernel kernel: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - precondition(rowCount >= 3, - "Row count must be greater than or equal to 3.") - - precondition(columnCount >= 4, - "Column count must be even and greater than or equal to 4") - - precondition(rowCount * columnCount == vector.count, - "Row count `x` column count must equal source vector count.") - - precondition(kernel.count == 9, - "Kernel must contain 9 elements.") - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - kernel.withUnsafeBufferPointer { k in - vDSP_f3x3D(src.baseAddress!, - vDSP_Length(rowCount), vDSP_Length(columnCount), - k.baseAddress!, - dest.baseAddress!) - } - } - } - } - - /// Returns two-dimensional convolution with a 5 x 5 kernel; single-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter rowCount: The number of rows in the input vector. - /// - Parameter columnCount: The number of columns in the input vector. - /// - Parameter kernel: Single-precision 5x5 convolution kernel. - /// - Returns: Convolution result. - @inlinable - public static func convolve(_ vector: T, - rowCount: Int, columnCount: Int, - with5x5Kernel kernel: U) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convolve(vector, - rowCount: rowCount, columnCount: columnCount, - with5x5Kernel: kernel, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Two-dimensional convolution with a 5 x 5 kernel; single-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter rowCount: The number of rows in the input vector. - /// - Parameter columnCount: The number of columns in the input vector. - /// - Parameter kernel: Single-precision 5x5 convolution kernel. - /// - Parameter result: Destination vector. - - @inlinable - public static func convolve(_ vector: T, - rowCount: Int, columnCount: Int, - with5x5Kernel kernel: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - precondition(rowCount >= 3, - "Row count must be greater than or equal to 3.") - - precondition(columnCount >= 4, - "Column count must be even and greater than or equal to 4") - - precondition(rowCount * columnCount == vector.count, - "Row count `x` column count must equal source vector count.") - - precondition(kernel.count == 25, - "Kernel must contain 25 elements.") - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - kernel.withUnsafeBufferPointer { k in - vDSP_f5x5(src.baseAddress!, - vDSP_Length(rowCount), vDSP_Length(columnCount), - k.baseAddress!, - dest.baseAddress!) - } - } - } - } - - /// Returns two-dimensional convolution with a 5 x 5 kernel; double-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter rowCount: The number of rows in the input vector. - /// - Parameter columnCount: The number of columns in the input vector. - /// - Parameter kernel: Double-precision 3x3 convolution kernel. - /// - Returns: Convolution result. - @inlinable - public static func convolve(_ vector: T, - rowCount: Int, columnCount: Int, - with5x5Kernel kernel: U) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convolve(vector, - rowCount: rowCount, columnCount: columnCount, - with5x5Kernel: kernel, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Two-dimensional convolution with a 5 x 5 kernel; double-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter rowCount: The number of rows in the input vector. - /// - Parameter columnCount: The number of columns in the input vector. - /// - Parameter kernel: Double-precision 5x5 convolution kernel. - /// - Parameter result: Destination vector. - - @inlinable - public static func convolve(_ vector: T, - rowCount: Int, columnCount: Int, - with5x5Kernel kernel: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - precondition(rowCount >= 3, - "Row count must be greater than or equal to 3.") - - precondition(columnCount >= 4, - "Column count must be even and greater than or equal to 4") - - precondition(rowCount * columnCount == vector.count, - "Row count `x` column count must equal source vector count.") - - precondition(kernel.count == 25, - "Kernel must contain 25 elements.") - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - kernel.withUnsafeBufferPointer { k in - vDSP_f5x5D(src.baseAddress!, - vDSP_Length(rowCount), vDSP_Length(columnCount), - k.baseAddress!, - dest.baseAddress!) - } - } - } - } - - /// Returns two-dimensional convolution with arbitrarily sized kernel; single-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter rowCount: The number of rows in the input vector. - /// - Parameter columnCount: The number of columns in the input vector. - /// - Parameter kernel: Single-precision convolution kernel. - /// - Parameter kernelRowCount: The number of rows in the kernel. - /// - Parameter kernelColumnCount: The number of columns in the kernel. - /// - Returns: Convolution result. - @inlinable - public static func convolve(_ vector: T, - rowCount: Int, columnCount: Int, - withKernel kernel: U, - kernelRowCount: Int, kernelColumnCount: Int) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convolve(vector, - rowCount: rowCount, columnCount: columnCount, - withKernel: kernel, - kernelRowCount: kernelRowCount, kernelColumnCount: kernelColumnCount, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Two-dimensional convolution with arbitrarily sized kernel; single-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter rowCount: The number of rows in the input vector. - /// - Parameter columnCount: The number of columns in the input vector. - /// - Parameter kernel: Single-precision convolution kernel. - /// - Parameter kernelRowCount: The number of rows in the kernel. - /// - Parameter kernelColumnCount: The number of columns in the kernel. - /// - Parameter result: Destination vector. - @inlinable - public static func convolve(_ vector: T, - rowCount: Int, columnCount: Int, - withKernel kernel: U, - kernelRowCount: Int, kernelColumnCount: Int, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - precondition(rowCount >= 3, - "Row count must be greater than or equal to 3.") - - precondition(columnCount >= 4, - "Column count must be even and greater than or equal to 4") - - precondition(rowCount * columnCount == vector.count, - "Row count `x` column count must equal source vector count.") - - precondition(kernelRowCount % 2 == 1, - "Kernel row count must be odd.") - - precondition(kernelColumnCount % 2 == 1, - "Kernel column count must be odd.") - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - kernel.withUnsafeBufferPointer { k in - vDSP_imgfir(src.baseAddress!, - vDSP_Length(rowCount), vDSP_Length(columnCount), - k.baseAddress!, - dest.baseAddress!, - vDSP_Length(kernelRowCount), vDSP_Length(kernelColumnCount)) - } - } - } - } - - /// Returns two-dimensional convolution with arbitrarily sized kernel; double-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter rowCount: The number of rows in the input vector. - /// - Parameter columnCount: The number of columns in the input vector. - /// - Parameter kernel: Single-precision convolution kernel. - /// - Parameter kernelRowCount: The number of rows in the kernel. - /// - Parameter kernelColumnCount: The number of columns in the kernel. - /// - Returns: Convolution result. - @inlinable - public static func convolve(_ vector: T, - rowCount: Int, columnCount: Int, - withKernel kernel: U, - kernelRowCount: Int, kernelColumnCount: Int) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - convolve(vector, - rowCount: rowCount, columnCount: columnCount, - withKernel: kernel, - kernelRowCount: kernelRowCount, kernelColumnCount: kernelColumnCount, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Two-dimensional convolution with arbitrarily sized kernel; double-precision. - /// - /// - Parameter vector: The vector to convolve. - /// - Parameter rowCount: The number of rows in the input vector. - /// - Parameter columnCount: The number of columns in the input vector. - /// - Parameter kernel: Double-precision convolution kernel. - /// - Parameter kernelRowCount: The number of rows in the kernel. - /// - Parameter kernelColumnCount: The number of columns in the kernel. - /// - Parameter result: Destination vector. - - @inlinable - public static func convolve(_ vector: T, - rowCount: Int, columnCount: Int, - withKernel kernel: U, - kernelRowCount: Int, kernelColumnCount: Int, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - precondition(rowCount >= 3, - "Row count must be greater than or equal to 3.") - - precondition(columnCount >= 4, - "Column count must be even and greater than or equal to 4") - - precondition(rowCount * columnCount == vector.count, - "Row count `x` column count must equal source vector count.") - - precondition(kernelRowCount % 2 == 1, - "Kernel row count must be odd.") - - precondition(kernelColumnCount % 2 == 1, - "Kernel column count must be odd.") - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - kernel.withUnsafeBufferPointer { k in - vDSP_imgfirD(src.baseAddress!, - vDSP_Length(rowCount), vDSP_Length(columnCount), - k.baseAddress!, - dest.baseAddress!, - vDSP_Length(kernelRowCount), vDSP_Length(kernelColumnCount)) - } - } - } - } - -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_DCT.swift b/stdlib/public/Darwin/Accelerate/vDSP_DCT.swift deleted file mode 100644 index 319b51ec22526..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_DCT.swift +++ /dev/null @@ -1,157 +0,0 @@ -///===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - /// An enum that specifies which DCT variant to perform. - public enum DCTTransformType: CaseIterable { - case II - case III - case IV - - public var dctType: vDSP_DCT_Type { - switch self { - case .II: - return .II - case .III: - return .III - case .IV: - return .IV - } - } - } - - /// A class that provides single-precision discrete cosine transform. - public class DCT { - - fileprivate let dctSetup: vDSP_DFT_Setup - - /// Initializes a new discrete cosine transform instance. - /// - /// - Parameter previous: a previous vDSP_DCT instance to share data with. - /// - Parameter count: the number of real elements to be transformed. - /// - Parameter transformType: Specifies the transform type (type II for forward and type III for inverse). - public init?(previous: DCT? = nil, - count: Int, - transformType: DCTTransformType) { - - guard let setup = vDSP.VectorizableFloat.makeDCTSetup(previous: previous, - count: count, - transformType: transformType) else { - return nil - } - - dctSetup = setup - } - - /// Returns the single-precision real discrete cosine transform. - /// - /// - Parameter input: Real input vector. - /// - Returns: Real output vector. - public func transform(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - transform(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Computes an out-of-place single-precision real discrete cosine transform. - /// - /// - Parameter input: Real input vector. - /// - Parameter output: Real output vector. - public func transform(_ vector: U, result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - vDSP.VectorizableFloat.transform(dctSetup: dctSetup, - source: vector, - destination: &result) - } - - deinit { - vDSP_DFT_DestroySetup(dctSetup) - } - } -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -fileprivate protocol vDSP_FloatingPointDiscreteCosineTransformable: BinaryFloatingPoint { - associatedtype DCTFunctions: vDSP_DCTFunctions where DCTFunctions.Scalar == Self -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension Float: vDSP_FloatingPointDiscreteCosineTransformable { - typealias DCTFunctions = vDSP.VectorizableFloat -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -fileprivate protocol vDSP_DCTFunctions { - associatedtype Scalar - - static func makeDCTSetup(previous: vDSP.DCT?, - count: Int, - transformType: vDSP.DCTTransformType) -> OpaquePointer? - - static func transform(dctSetup: OpaquePointer, - source: U, - destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Scalar, V.Element == Scalar -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP.VectorizableFloat: vDSP_DCTFunctions { - - fileprivate static func makeDCTSetup(previous: vDSP.DCT? = nil, - count: Int, - transformType: vDSP.DCTTransformType) -> OpaquePointer? { - - return vDSP_DCT_CreateSetup(previous?.dctSetup, - vDSP_Length(count), - transformType.dctType) - } - - fileprivate static func transform(dctSetup: OpaquePointer, - source: U, - destination: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, - V.Element == Float { - - destination.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_DCT_Execute(dctSetup, - src.baseAddress!, - dest.baseAddress!) - } - } - } -} - - diff --git a/stdlib/public/Darwin/Accelerate/vDSP_DFT.swift b/stdlib/public/Darwin/Accelerate/vDSP_DFT.swift deleted file mode 100644 index ef0a0ffdf8c9b..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_DFT.swift +++ /dev/null @@ -1,328 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -//===----------------------------------------------------------------------===// -// -// Discrete Fourier Transform -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - /// An enumeration that specifies whether to perform complex-to-complex or - /// complex-to-real discrete Fourier transform. - // TODO: Should probably be @_frozen; check with Accelerate. - public enum DFTTransformType { - /// Specifies complex-to-complex discrete Fourier transform, forward - /// or inverse - case complexComplex - - /// Specifies real-to-complex (forward) or complex-to-real (inverse) - /// discrete Fourier transform. - case complexReal - } - - /// A class that provides single- and double-precision discrete Fourier transform. - public class DFT { - fileprivate let dftSetup: vDSP_DFT_Setup - - /// Initializes a new discrete Fourier transform structure. - /// - /// - Parameter previous: a previous vDSP_DFT instance to share data with. - /// - Parameter count: the number of real elements to be transformed. - /// - Parameter direction: Specifies the transform direction. - /// - Parameter transformType: Specficies whether to forward transform is real-to-complex or complex-to-complex. - public init?(previous: DFT? = nil, - count: Int, - direction: vDSP.FourierTransformDirection, - transformType: DFTTransformType, - ofType: T.Type) { - - guard let setup = T.DFTFunctions.makeDFTSetup(previous: previous, - count: count, - direction: direction, - transformType: transformType) else { - return nil - } - - self.transformType = transformType - - dftSetup = setup - } - - /// The transform type of this DFT. - private let transformType: DFTTransformType - - /// Returns a single-precision real discrete Fourier transform. - /// - /// - Parameter inputReal: Input vector - real part. - /// - Parameter inputImaginary: Input vector - imaginary part. - /// - Returns: A tuple of two arrays representing the real and imaginary parts of the output. - /// - /// When the `transformType` is `complexComplex`, each input array (Ir, Ii) - /// must have `count` elements, and the returned arrays have `count` elements. - /// - /// When the `transformType` is `complexReal`, each input array (Ir, Ii) - /// must have `count` elements, and the returned arrays have `count / 2` elements. - public func transform(inputReal: U, - inputImaginary: U) -> (real:[T], imaginary: [T]) - where - U: AccelerateBuffer, - U.Element == T { - - let n = transformType == .complexReal ? inputReal.count / 2 : inputReal.count - - var imaginaryResult: Array! - - let realResult = Array(unsafeUninitializedCapacity: n) { - realBuffer, realInitializedCount in - - imaginaryResult = Array(unsafeUninitializedCapacity: n) { - imaginaryBuffer, imaginaryInitializedCount in - - transform(inputReal: inputReal, - inputImaginary: inputImaginary, - outputReal: &realBuffer, - outputImaginary: &imaginaryBuffer) - - imaginaryInitializedCount = n - } - - realInitializedCount = n - } - - return (real: realResult, - imaginary: imaginaryResult) - } - - /// Computes an out-of-place single-precision real discrete Fourier transform. - /// - /// - Parameter inputReal: Input vector - real part. - /// - Parameter inputImaginary: Input vector - imaginary part. - /// - Parameter outputReal: Output vector - real part. - /// - Parameter outputImaginary: Output vector - imaginary part. - /// - /// When the `transformType` is `complexComplex`, each array (Ir, Ii, - /// Or, and Oi) must have `count` elements. - /// - /// When the `transformType` is `complexReal`, each array (Ir, Ii, - /// Or, and Oi) must have `count/2` elements. - public func transform(inputReal: U, - inputImaginary: U, - outputReal: inout V, - outputImaginary: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == T, V.Element == T { - - T.DFTFunctions.transform(dftSetup: dftSetup, - inputReal: inputReal, - inputImaginary: inputImaginary, - outputReal: &outputReal, - outputImaginary: &outputImaginary) - } - - deinit { - T.DFTFunctions.destroySetup(dftSetup) - } - } -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public protocol vDSP_FloatingPointDiscreteFourierTransformable: BinaryFloatingPoint { - associatedtype DFTFunctions: vDSP_DFTFunctions where DFTFunctions.Scalar == Self -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension Float: vDSP_FloatingPointDiscreteFourierTransformable { - public typealias DFTFunctions = vDSP.VectorizableFloat -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension Double: vDSP_FloatingPointDiscreteFourierTransformable { - public typealias DFTFunctions = vDSP.VectorizableDouble -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public protocol vDSP_DFTFunctions { - associatedtype Scalar - - /// Returns a setup structure to perform a discrete Fourier transform - /// - /// - Parameter previous: a previous vDSP_DFT instance to share data with. - /// - Parameter count: the number of real elements to be transformed. - /// - Parameter direction: Specifies the transform direction. - /// - Parameter transformType: Specficies whether to forward transform is real-to-complex or complex-to-complex. - static func makeDFTSetup(previous: vDSP.DFT?, - count: Int, - direction: vDSP.FourierTransformDirection, - transformType: vDSP.DFTTransformType) -> OpaquePointer? - - /// Computes an out-of-place single-precision real discrete Fourier transform. - /// - /// - Parameter dftSetup: A DCT setup object. - /// - Parameter inputReal: Input vector - real part. - /// - Parameter inputImaginary: Input vector - imaginary part. - /// - Parameter outputReal: Output vector - real part. - /// - Parameter outputImaginary: Output vector - imaginary part. - static func transform(dftSetup: OpaquePointer, - inputReal: U, - inputImaginary: U, - outputReal: inout V, - outputImaginary: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Scalar, V.Element == Scalar - - /// Releases a DFT setup object. - static func destroySetup(_ setup: OpaquePointer) -} - -//===----------------------------------------------------------------------===// -// -// Type-specific DFT function implementations -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP.VectorizableFloat: vDSP_DFTFunctions { - - /// Returns a setup structure to perform a discrete Fourier transform - /// - /// - Parameter previous: a previous vDSP_DFT instance to share data with. - /// - Parameter count: the number of real elements to be transformed. - /// - Parameter direction: Specifies the transform direction. - /// - Parameter transformType: Specficies whether to forward transform is real-to-complex or complex-to-complex. - public static func makeDFTSetup(previous: vDSP.DFT? = nil, - count: Int, - direction: vDSP.FourierTransformDirection, - transformType: vDSP.DFTTransformType) -> OpaquePointer? - where T : vDSP_FloatingPointDiscreteFourierTransformable { - - switch transformType { - case .complexComplex: - return vDSP_DFT_zop_CreateSetup(previous?.dftSetup, - vDSP_Length(count), - direction.dftDirection) - case .complexReal: - return vDSP_DFT_zrop_CreateSetup(previous?.dftSetup, - vDSP_Length(count), - direction.dftDirection) - } - } - - /// Computes an out-of-place single-precision real discrete Fourier transform. - /// - /// - Parameter dftSetup: A DCT setup object. - /// - Parameter inputReal: Input vector - real part. - /// - Parameter inputImaginary: Input vector - imaginary part. - /// - Parameter outputReal: Output vector - real part. - /// - Parameter outputImaginary: Output vector - imaginary part. - public static func transform(dftSetup: OpaquePointer, - inputReal: U, - inputImaginary: U, - outputReal: inout V, - outputImaginary: inout V) - where - U : AccelerateBuffer, - V : AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - inputReal.withUnsafeBufferPointer { Ir in - inputImaginary.withUnsafeBufferPointer { Ii in - outputReal.withUnsafeMutableBufferPointer { Or in - outputImaginary.withUnsafeMutableBufferPointer { Oi in - - vDSP_DFT_Execute(dftSetup, - Ir.baseAddress!, - Ii.baseAddress!, - Or.baseAddress!, - Oi.baseAddress!) - } - } - } - } - } - - /// Releases a DFT setup object. - public static func destroySetup(_ setup: OpaquePointer) { - vDSP_DFT_DestroySetup(setup) - } -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP.VectorizableDouble: vDSP_DFTFunctions { - - /// Returns a data structure for use with to perform a discrete Fourier transform - /// - /// - Parameter previous: a previous vDSP_DFT instance to share data with. - /// - Parameter count: the number of real elements to be transformed. - /// - Parameter direction: Specifies the transform direction. - /// - Parameter transformType: Specficies whether to forward transform is real-to-complex or complex-to-complex. - public static func makeDFTSetup(previous: vDSP.DFT? = nil, - count: Int, - direction: vDSP.FourierTransformDirection, - transformType: vDSP.DFTTransformType) -> OpaquePointer? - where T : vDSP_FloatingPointDiscreteFourierTransformable { - - switch transformType { - case .complexComplex: - return vDSP_DFT_zop_CreateSetupD(previous?.dftSetup, - vDSP_Length(count), - direction.dftDirection) - case .complexReal: - return vDSP_DFT_zrop_CreateSetupD(previous?.dftSetup, - vDSP_Length(count), - direction.dftDirection) - } - } - - /// Computes an out-of-place single-precision real discrete Fourier transform. - /// - /// - Parameter dftSetup: A DCT setup object. - /// - Parameter inputReal: Input vector - real part. - /// - Parameter inputImaginary: Input vector - imaginary part. - /// - Parameter outputReal: Output vector - real part. - /// - Parameter outputImaginary: Output vector - imaginary part. - public static func transform(dftSetup: OpaquePointer, - inputReal: U, inputImaginary: U, - outputReal: inout V, outputImaginary: inout V) - where - U : AccelerateBuffer, - V : AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - inputReal.withUnsafeBufferPointer { Ir in - inputImaginary.withUnsafeBufferPointer { Ii in - outputReal.withUnsafeMutableBufferPointer { Or in - outputImaginary.withUnsafeMutableBufferPointer { Oi in - - vDSP_DFT_ExecuteD(dftSetup, - Ir.baseAddress!, - Ii.baseAddress!, - Or.baseAddress!, - Oi.baseAddress!) - } - } - } - } - } - - /// Releases a DFT setup object. - public static func destroySetup(_ setup: OpaquePointer) { - vDSP_DFT_DestroySetupD(setup) - } -} - diff --git a/stdlib/public/Darwin/Accelerate/vDSP_DecibelConversion.swift b/stdlib/public/Darwin/Accelerate/vDSP_DecibelConversion.swift deleted file mode 100644 index ed0a76ec9e84f..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_DecibelConversion.swift +++ /dev/null @@ -1,235 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - /// Converts power to decibels, single-precision. - /// - /// - Parameter power: Source vector. - /// - Parameter zeroReference: Zero reference. - /// - Returns: `power` converted to decibels. - @inlinable - public static func powerToDecibels(_ power: U, - zeroReference: Float) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: power.count) { - buffer, initializedCount in - - convert(power: power, - toDecibels: &buffer, - zeroReference: zeroReference) - - initializedCount = power.count - } - - return result - } - - /// Converts power to decibels, single-precision. - /// - /// - Parameter power: Source vector. - /// - Parameter decibels: Destination vector. - /// - Parameter zeroReference: Zero reference. - @inlinable - public static func convert(power: U, - toDecibels decibels: inout V, - zeroReference: Float) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = decibels.count - precondition(power.count == n) - - decibels.withUnsafeMutableBufferPointer { db in - power.withUnsafeBufferPointer { pwr in - withUnsafePointer(to: zeroReference) { zref in - vDSP_vdbcon(pwr.baseAddress!, 1, - zref, - db.baseAddress!, 1, - vDSP_Length(n), - 0) - } - } - } - } - - /// Converts power to decibels, double-precision. - /// - /// - Parameter power: Source vector. - /// - Parameter zeroReference: Zero reference. - /// - Returns: `power` converted to decibels. - @inlinable - public static func powerToDecibels(_ power: U, - zeroReference: Double) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: power.count) { - buffer, initializedCount in - - convert(power: power, - toDecibels: &buffer, - zeroReference: zeroReference) - - initializedCount = power.count - } - - return result - } - - /// Converts power to decibels, double-precision. - /// - /// - Parameter power: Source vector. - /// - Parameter decibels: Destination vector. - /// - Parameter zeroReference: Zero reference. - @inlinable - public static func convert(power: U, - toDecibels decibels: inout V, - zeroReference: Double) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = decibels.count - precondition(power.count == n) - - decibels.withUnsafeMutableBufferPointer { db in - power.withUnsafeBufferPointer { pwr in - withUnsafePointer(to: zeroReference) { zref in - vDSP_vdbconD(pwr.baseAddress!, 1, - zref, - db.baseAddress!, 1, - vDSP_Length(n), - 0) - } - } - } - } - - /// Converts amplitude to decibels, single-precision. - /// - /// - Parameter amplitude: Source vector. - /// - Parameter zeroReference: Zero reference. - /// - Returns: `amplitude` converted to decibels. - @inlinable - public static func amplitudeToDecibels(_ amplitude: U, - zeroReference: Float) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: amplitude.count) { - buffer, initializedCount in - - convert(amplitude: amplitude, - toDecibels: &buffer, - zeroReference: zeroReference) - - initializedCount = amplitude.count - } - - return result - } - - /// Converts amplitude to decibels, single-precision. - /// - /// - Parameter amplitude: Source vector. - /// - Parameter decibels: Destination vector. - /// - Parameter zeroReference: Zero reference. - @inlinable - public static func convert(amplitude: U, - toDecibels decibels: inout V, - zeroReference: Float) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = decibels.count - precondition(amplitude.count == n) - - decibels.withUnsafeMutableBufferPointer { db in - amplitude.withUnsafeBufferPointer { amp in - withUnsafePointer(to: zeroReference) { zref in - vDSP_vdbcon(amp.baseAddress!, 1, - zref, - db.baseAddress!, 1, - vDSP_Length(n), - 1) - } - } - } - } - - /// Converts amplitude to decibels, double-precision. - /// - /// - Parameter amplitude: Source vector. - /// - Parameter zeroReference: Zero reference. - /// - Returns: `amplitude` converted to decibels. - @inlinable - public static func amplitudeToDecibels(_ amplitude: U, - zeroReference: Double) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: amplitude.count) { - buffer, initializedCount in - - convert(amplitude: amplitude, - toDecibels: &buffer, - zeroReference: zeroReference) - - initializedCount = amplitude.count - } - - return result - } - - /// Converts amplitude to decibels, double-precision. - /// - /// - Parameter amplitude: Source vector. - /// - Parameter decibels: Destination vector. - /// - Parameter zeroReference: Zero reference. - @inlinable - public static func convert(amplitude: U, - toDecibels decibels: inout V, - zeroReference: Double) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = decibels.count - precondition(amplitude.count == n) - - decibels.withUnsafeMutableBufferPointer { db in - amplitude.withUnsafeBufferPointer { amp in - withUnsafePointer(to: zeroReference) { zref in - vDSP_vdbconD(amp.baseAddress!, 1, - zref, - db.baseAddress!, 1, - vDSP_Length(n), - 1) - } - } - } - } -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_FFT.swift b/stdlib/public/Darwin/Accelerate/vDSP_FFT.swift deleted file mode 100644 index aa6861d6041c6..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_FFT.swift +++ /dev/null @@ -1,450 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -//===----------------------------------------------------------------------===// -// -// 1D and 2D Fast Fourier Transform -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - /// An enumeration that defines the size of the FFT decomposition. - public enum Radix { - case radix2 - case radix3 - case radix5 - - public var fftRadix: FFTRadix { - switch self { - case .radix2: - return FFTRadix(kFFTRadix2) - case .radix3: - return FFTRadix(kFFTRadix3) - case .radix5: - return FFTRadix(kFFTRadix5) - } - } - } - - /// A class that provides forward and inverse FFT on `DSPSplitComplex` or `DSPDoubleSplitComplex` structure. - public class FFT { - - let log2n: vDSP_Length - let radix: Radix - - fileprivate let fftSetup: OpaquePointer - - /// Initializes a new fast Fourier transform structure. - /// - /// - Parameter log2n: The base-two logarithm of the maximum number of elements to be transformed. - /// - Parameter radix: Specifies radix options. - public init?(log2n: vDSP_Length, - radix: Radix, - ofType: T.Type) { - - self.log2n = log2n - self.radix = radix - - guard let setup = T.FFTFunctions.makeFFTSetup(log2n: log2n, - radix: radix) else { - return nil - } - - fftSetup = setup - } - - /// Computes an out-of-place single-precision real forward or inverse fast Fourier transform. - /// - /// - Parameter input: Complex input vector. - /// - Parameter output: Complex output vector. - /// - Parameter direction: The transform direction. - public func transform(input: T, - output: inout T, - direction: vDSP.FourierTransformDirection) { - - vDSP_FFTFunctions.fftTransform(fftSetup: fftSetup, - log2n: log2n, - source: input, - destination: &output, - direction: direction) - } - - /// Computes an out-of-place single-precision real forward fast Fourier transform. - /// - /// - Parameter input: Complex input vector. - /// - Parameter output: Complex output vector. - public func forward(input: DSPSplitComplex, - output: inout DSPSplitComplex) { - transform(input: input, - output: &output, - direction: .forward) - } - - /// Computes an out-of-place single-precision real inverse fast Fourier transform. - /// - /// - Parameter input: Complex input vector. - /// - Parameter output: Complex output vector. - public func inverse(input: DSPSplitComplex, - output: inout DSPSplitComplex) { - transform(input: input, - output: &output, - direction: .inverse) - } - - /// Frees memory associated with this `FFT` struct. - deinit { - T.FFTFunctions.destroySetup(fftSetup) - } - } - - // MARK: 2D FFT - - /// A class that provides forward and inverse 2D FFT on `DSPSplitComplex` or `DSPDoubleSplitComplex` structure. - public class FFT2D: FFT { - - let width: Int - let height: Int - - /// Initializes a new fast Fourier transform structure for 2D FFT. - /// - /// - Parameter width: The width of the matrix to be transformed. - /// - Parameter height: The width of the matrix to be transformed. - required public init?(width: Int, - height: Int, - ofType: T.Type) { - self.width = width - self.height = height - - let log2n = vDSP_Length(log2(Float(width * height))) - - super.init(log2n: log2n, - radix: .radix2, - ofType: ofType) - } - - /// Computes an out-of-place 2D fast Fourier transform. - /// - /// - Parameter input: Complex input vector. - /// - Parameter output: Complex output vector. - /// - Parameter direction: Specifies transform direction. - override public func transform(input: T, - output: inout T, - direction: vDSP.FourierTransformDirection) { - vDSP_FFTFunctions.fftTransform2D(fftSetup: fftSetup, - width: width, - height: height, - source: input, - destination: &output, - direction: direction) - } - } - -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public protocol vDSP_FourierTransformFunctions { - associatedtype SplitComplex - - static func makeFFTSetup(log2n: vDSP_Length, - radix: vDSP.Radix) -> OpaquePointer? - - static func transform(fftSetup: OpaquePointer, - log2n: vDSP_Length, - source: UnsafePointer, - destination: UnsafeMutablePointer, - direction: vDSP.FourierTransformDirection) - - static func transform2D(fftSetup: OpaquePointer, - width: Int, - height: Int, - source: UnsafePointer, - destination: UnsafeMutablePointer, - direction: vDSP.FourierTransformDirection) - - static func destroySetup(_ setup: OpaquePointer) -} - -//===----------------------------------------------------------------------===// -// -// Type-specific FFT function implementations -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public struct vDSP_SplitComplexFloat: vDSP_FourierTransformFunctions { - public typealias SplitComplex = DSPSplitComplex - - /// Returns a setup structure to perform a fast Fourier transform. - public static func makeFFTSetup(log2n: vDSP_Length, - radix: vDSP.Radix) -> OpaquePointer? { - - return vDSP_create_fftsetup( - log2n, - radix.fftRadix) - } - - /// Performs a 1D fast Fourier transform. - public static func transform(fftSetup: OpaquePointer, - log2n: vDSP_Length, - source: UnsafePointer, - destination: UnsafeMutablePointer, - direction: vDSP.FourierTransformDirection) { - vDSP_fft_zrop(fftSetup, - source, 1, - destination, 1, - log2n, - direction.fftDirection) - } - - /// Performs a 2D fast Fourier transform. - public static func transform2D(fftSetup: OpaquePointer, - width: Int, - height: Int, - source: UnsafePointer, - destination: UnsafeMutablePointer, - direction: vDSP.FourierTransformDirection) { - vDSP_fft2d_zrop(fftSetup, - source, 1, 0, - destination, 1, 0, - vDSP_Length(log2(Float(width))), - vDSP_Length(log2(Float(height))), - direction.fftDirection) - } - - /// Releases an FFT setup object. - public static func destroySetup(_ setup: OpaquePointer) { - vDSP_destroy_fftsetup(setup) - } -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public struct vDSP_SplitComplexDouble: vDSP_FourierTransformFunctions { - public typealias SplitComplex = DSPDoubleSplitComplex - - /// Returns a setup structure to perform a fast Fourier transform. - public static func makeFFTSetup(log2n: vDSP_Length, - radix: vDSP.Radix) -> OpaquePointer? { - - return vDSP_create_fftsetupD( - log2n, - radix.fftRadix) - } - - /// Performs a 1D fast Fourier transform. - public static func transform(fftSetup: OpaquePointer, - log2n: vDSP_Length, - source: UnsafePointer, - destination: UnsafeMutablePointer, - direction: vDSP.FourierTransformDirection) { - vDSP_fft_zropD(fftSetup, - source, 1, - destination, 1, - log2n, - direction.fftDirection) - } - - /// Performs a 2D fast Fourier transform. - public static func transform2D(fftSetup: OpaquePointer, - width: Int, - height: Int, - source: UnsafePointer, - destination: UnsafeMutablePointer, - direction: vDSP.FourierTransformDirection) { - vDSP_fft2d_zropD(fftSetup, - source, 1, 0, - destination, 1, 0, - vDSP_Length(log2(Float(width))), - vDSP_Length(log2(Float(height))), - direction.fftDirection) - } - - /// Releases an FFT setup object. - public static func destroySetup(_ setup: OpaquePointer) { - vDSP_destroy_fftsetupD(setup) - } -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public protocol vDSP_FourierTransformable { - associatedtype FFTFunctions: vDSP_FourierTransformFunctions where FFTFunctions.SplitComplex == Self -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension DSPSplitComplex: vDSP_FourierTransformable { - public typealias FFTFunctions = vDSP_SplitComplexFloat -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension DSPDoubleSplitComplex: vDSP_FourierTransformable { - public typealias FFTFunctions = vDSP_SplitComplexDouble -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -struct vDSP_FFTFunctions { - /// Performs a 1D fast Fourier transform. - @inlinable - static func fftTransform(fftSetup: OpaquePointer, - log2n: vDSP_Length, - source: SplitComplex, - destination: inout SplitComplex, - direction: vDSP.FourierTransformDirection) where SplitComplex: vDSP_FourierTransformable { - - withUnsafePointer(to: source) { sourcePointer in - SplitComplex.FFTFunctions.transform(fftSetup: fftSetup, - log2n: log2n, - source: sourcePointer, - destination: &destination, - direction: direction) - } - } - - /// Performs a 2D fast Fourier transform. - @inlinable - static func fftTransform2D(fftSetup: OpaquePointer, - width: Int, - height: Int, - source: SplitComplex, - destination: inout SplitComplex, - direction: vDSP.FourierTransformDirection) where SplitComplex: vDSP_FourierTransformable { - - withUnsafePointer(to: source) { sourcePointer in - SplitComplex.FFTFunctions.transform2D(fftSetup: fftSetup, - width: width, - height: height, - source: sourcePointer, - destination: &destination, - direction: direction) - } - } -} - -@available(macOS, introduced: 10.15, deprecated, message: "Use the `withUnsafeMutableBufferPointer` method on the real and imaginary arrays to create `DSPSplitComplex` for a defined scope.") -@available(iOS, introduced: 13.0, deprecated, message: "Use the `withUnsafeMutableBufferPointer` method on the real and imaginary arrays to create `DSPSplitComplex` for a defined scope.") -@available(watchOS, introduced: 6.0, deprecated, message: "Use the `withUnsafeMutableBufferPointer` method on the real and imaginary arrays to create `DSPSplitComplex` for a defined scope.") -@available(tvOS, introduced: 13.0, deprecated, message: "Use the `withUnsafeMutableBufferPointer` method on the real and imaginary arrays to create `DSPSplitComplex` for a defined scope.") -@available(*, deprecated, message: "Use the `withUnsafeMutableBufferPointer` method on the real and imaginary arrays to create `DSPSplitComplex` for a defined scope.") -extension DSPSplitComplex { - - /// Creates a new `DSPSplitComplex` structure from a real array not in even-odd split configuration. - /// - /// - Parameter inputArray: The source array of contiguous values. - /// - Parameter realParts: An array of real parts of the complex numbers. - /// - Parameter imaginaryParts: An array of imaginary parts of the complex numbers. - public init(fromInputArray inputArray: [Float], - realParts: inout [Float], - imaginaryParts: inout [Float]) { - - self.init(realp: &realParts, - imagp: &imaginaryParts) - - inputArray.withUnsafeBytes{ - vDSP_ctoz([DSPComplex]($0.bindMemory(to: DSPComplex.self)), 2, - &self, 1, - vDSP_Length(inputArray.count / 2)) - } - } -} - -@available(macOS, introduced: 10.15, deprecated, message: "Use the `withUnsafeMutableBufferPointer` method on the real and imaginary arrays to create `DSPSplitComplex` for a defined scope.") -@available(iOS, introduced: 13.0, deprecated, message: "Use the `withUnsafeMutableBufferPointer` method on the real and imaginary arrays to create `DSPSplitComplex` for a defined scope.") -@available(watchOS, introduced: 6.0, deprecated, message: "Use the `withUnsafeMutableBufferPointer` method on the real and imaginary arrays to create `DSPSplitComplex` for a defined scope.") -@available(tvOS, introduced: 13.0, deprecated, message: "Use the `withUnsafeMutableBufferPointer` method on the real and imaginary arrays to create `DSPSplitComplex` for a defined scope.") -@available(*, deprecated, message: "Use the `withUnsafeMutableBufferPointer` method on the real and imaginary arrays to create `DSPSplitComplex` for a defined scope.") -extension DSPDoubleSplitComplex { - - /// Creates a new `DSPDoubleSplitComplex` structure from a real array not in even-odd split configuration. - /// - /// - Parameter inputArray: The source array of contiguous values. - /// - Parameter realParts: An array of real parts of the complex numbers. - /// - Parameter imaginaryParts: An array of imaginary parts of the complex numbers. - public init(fromInputArray inputArray: [Double], - realParts: inout [Double], - imaginaryParts: inout [Double]) { - - self.init(realp: &realParts, - imagp: &imaginaryParts) - - inputArray.withUnsafeBytes{ - vDSP_ctozD([DSPDoubleComplex]($0.bindMemory(to: DSPDoubleComplex.self)), 2, - &self, 1, - vDSP_Length(inputArray.count / 2)) - } - } -} - -extension Array where Element == Float { - /// Creates a new array of single-precision values from a `DSPSplitComplex` structure. - /// - /// - Parameter scale: A multiplier to apply during conversion. - /// - Parameter count: The length of the required resulting array (typically half the count of either the real or imaginary parts of the `DSPSplitComplex`. - @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - public init(fromSplitComplex splitComplex: DSPSplitComplex, - scale: Float, - count: Int) { - var complexPairs = [DSPComplex](repeating: DSPComplex(real: 0, imag: 0), - count: count / 2) - - withUnsafePointer(to: splitComplex) { - vDSP_ztoc($0, 1, - &complexPairs, 2, - vDSP_Length(count / 2)) - } - - self = [Float](repeating: 0, count: count) - - complexPairs.withUnsafeBytes { - guard let complexPairsUnsafePointer = $0.bindMemory(to: Float.self).baseAddress else { - fatalError("Internal error") - } - - vDSP_vsmul(complexPairsUnsafePointer, 1, - [scale], - &self, 1, - vDSP_Length(count)) - } - } -} - -extension Array where Element == Double { - /// Creates a new array of single-precision values from a `DSPDoubleSplitComplex` structure. - /// - /// - Parameter scale: A multiplier to apply during conversion. - /// - Parameter count: The length of the required resulting array (typically half the count of either the real or imaginary parts of the `DSPSplitComplex`. - @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - public init(fromSplitComplex splitComplex: DSPDoubleSplitComplex, - scale: Double, - count: Int) { - var complexPairs = [DSPDoubleComplex](repeating: DSPDoubleComplex(real: 0, imag: 0), - count: count / 2) - - withUnsafePointer(to: splitComplex) { - vDSP_ztocD($0, 1, - &complexPairs, 2, - vDSP_Length(count / 2)) - } - - self = [Double](repeating: 0, count: count) - - complexPairs.withUnsafeBytes { - guard let complexPairsUnsafePointer = $0.bindMemory(to: Double.self).baseAddress else { - fatalError("Internal error") - } - - vDSP_vsmulD(complexPairsUnsafePointer, 1, - [scale], - &self, 1, - vDSP_Length(count)) - } - } -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_FFT_DFT_Common.swift b/stdlib/public/Darwin/Accelerate/vDSP_FFT_DFT_Common.swift deleted file mode 100644 index e4ba1c37c2a31..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_FFT_DFT_Common.swift +++ /dev/null @@ -1,37 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - public enum FourierTransformDirection { - case forward - case inverse - - public var dftDirection: vDSP_DFT_Direction { - switch self { - case .forward: - return .FORWARD - case .inverse: - return .INVERSE - } - } - - public var fftDirection: FFTDirection { - switch self { - case .forward: - return FFTDirection(kFFTDirection_Forward) - case .inverse: - return FFTDirection(kFFTDirection_Inverse) - } - } - } -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_FIR.swift b/stdlib/public/Darwin/Accelerate/vDSP_FIR.swift deleted file mode 100644 index 54b2284aafe82..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_FIR.swift +++ /dev/null @@ -1,157 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - /// FIR filtering with decimation and antialiasing; single-precision. - /// - /// - Parameter source: Single-precision input vector. - /// - Parameter decimationFactor: The integer factor by which to divide the sampling rate. - /// - Parameter filter: Filter to use during the downsampling operation. - /// - Returns: Single-precision output vector. - @inlinable - public static func downsample(_ source: U, - decimationFactor: Int, - filter: T) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, - U.Element == Float { - - let n = (source.count - filter.count) / decimationFactor + 1 - - let result = Array(unsafeUninitializedCapacity: n) { - buffer, initializedCount in - - downsample(source, - decimationFactor: decimationFactor, - filter: filter, - result: &buffer) - - initializedCount = n - } - - return result - } - - /// FIR filtering with decimation and antialiasing; single-precision. - /// - /// - Parameter source: Single-precision input vector. - /// - Parameter decimationFactor: The integer factor by which to divide the sampling rate. - /// - Parameter filter: Filter to use during the downsampling operation. - /// - Parameter result: Single-precision output vector. - @inlinable - public static func downsample(_ source: U, - decimationFactor: Int, - filter: T, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, - U.Element == Float, - V.Element == Float { - - let p = filter.count - let n = result.count - - precondition(source.count == decimationFactor * (n - 1) + p) - - result.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - filter.withUnsafeBufferPointer { f in - - vDSP_desamp(src.baseAddress!, - vDSP_Stride(decimationFactor), - f.baseAddress!, - dest.baseAddress!, - vDSP_Length(n), - vDSP_Length(p)) - } - } - } - } - - /// FIR filtering with decimation and antialiasing; double-precision. - /// - /// - Parameter source: Double-precision input vector. - /// - Parameter decimationFactor: The integer factor by which to divide the sampling rate. - /// - Parameter filter: Filter to use during the downsampling operation. - /// - Returns: Double-precision output vector. - @inlinable - public static func downsample(_ source: U, - decimationFactor: Int, - filter: T) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, - U.Element == Double { - let n = (source.count - filter.count) / decimationFactor + 1 - - let result = Array(unsafeUninitializedCapacity: n) { - buffer, initializedCount in - - downsample(source, - decimationFactor: decimationFactor, - filter: filter, - result: &buffer) - - initializedCount = n - } - - return result - } - - /// FIR filtering with decimation and antialiasing; double-precision. - /// - /// - Parameter source: Double-precision input vector. - /// - Parameter decimationFactor: The integer factor by which to divide the sampling rate. - /// - Parameter filter: Filter to use during the downsampling operation. - /// - Parameter result: Double-precision output vector. - @inlinable - public static func downsample(_ source: U, - decimationFactor: Int, - filter: T, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, - U.Element == Double, - V.Element == Double { - - let p = filter.count - let n = result.count - - precondition(source.count == decimationFactor * (n - 1) + p) - - result.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - filter.withUnsafeBufferPointer { f in - - vDSP_desampD(src.baseAddress!, - vDSP_Stride(decimationFactor), - f.baseAddress!, - dest.baseAddress!, - vDSP_Length(n), - vDSP_Length(p)) - } - } - } - } - -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_FillClearGenerate.swift b/stdlib/public/Darwin/Accelerate/vDSP_FillClearGenerate.swift deleted file mode 100644 index 4e27aadb7523d..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_FillClearGenerate.swift +++ /dev/null @@ -1,735 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -/// Types that support vectorized window generation. -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -public protocol vDSP_FloatingPointGeneratable: BinaryFloatingPoint { -} -extension Float: vDSP_FloatingPointGeneratable {} -extension Double: vDSP_FloatingPointGeneratable {} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - /// Fill vector with specified scalar value, single-precision. - /// - /// - Parameter vector: The vector to fill. - /// - Parameter value: The fill value. - @inlinable - public static func fill(_ vector: inout V, - with value: Float) - where V: AccelerateMutableBuffer, - V.Element == Float { - - let n = vDSP_Length(vector.count) - - vector.withUnsafeMutableBufferPointer { v in - withUnsafePointer(to: value) { - vDSP_vfill($0, - v.baseAddress!, 1, - n) - } - } - } - - /// Fill vector with specified scalar value, double-precision. - /// - /// - Parameter vector: The vector to fill. - /// - Parameter value: The fill value. - @inlinable - public static func fill(_ vector: inout V, - with value: Double) - where V: AccelerateMutableBuffer, - V.Element == Double { - - let n = vDSP_Length(vector.count) - - vector.withUnsafeMutableBufferPointer { v in - withUnsafePointer(to: value) { - vDSP_vfillD($0, - v.baseAddress!, 1, - n) - } - } - } - - /// Fill vector with zeros, single-precision. - /// - /// - Parameter vector: The vector to fill. - @inlinable - public static func clear(_ vector: inout V) - where V: AccelerateMutableBuffer, - V.Element == Float { - - let n = vDSP_Length(vector.count) - - vector.withUnsafeMutableBufferPointer { v in - vDSP_vclr(v.baseAddress!, 1, - n) - } - } - - /// Fill vector with zeros, double-precision. - /// - /// - Parameter vector: The vector to fill. - @inlinable - public static func clear(_ vector: inout V) - where V: AccelerateMutableBuffer, - V.Element == Double { - - let n = vDSP_Length(vector.count) - - vector.withUnsafeMutableBufferPointer { v in - vDSP_vclrD(v.baseAddress!, 1, - n) - } - } - - /// Enum specifying window sequence. - public enum WindowSequence { - /// Creates a normalized Hanning window. - case hanningNormalized - - /// Creates a denormalized Hanning window. - case hanningDenormalized - - /// Creates a Hamming window. - case hamming - - /// Creates a Blackman window. - case blackman - } - - /// Creates an array containing the specified window. - /// - /// - Parameter ofType: Specifies single- or double-precision. - /// - Parameter sequence: Specifies the window sequence. - /// - Parameter count: The number of elements in the array. - /// - Parameter isHalfWindow: When true, creates a window with only the first `(N+1)/2` points. - /// - Returns: An array containing the specified window. - @inlinable - public static func window(ofType: T.Type, - usingSequence sequence: WindowSequence, - count: Int, - isHalfWindow: Bool) -> [T] { - - precondition(count > 0) - - if T.self == Float.self { - - let result = Array(unsafeUninitializedCapacity: count) { - buffer, initializedCount in - - formWindow(usingSequence: sequence, - result: &buffer, - isHalfWindow: isHalfWindow) - - initializedCount = count - } - return result as! [T] - - } else if T.self == Double.self { - - let result = Array(unsafeUninitializedCapacity: count) { - buffer, initializedCount in - - formWindow(usingSequence: sequence, - result: &buffer, - isHalfWindow: isHalfWindow) - - initializedCount = count - } - return result as! [T] - - } else { - fatalError("This operation only supports `Float` and `Double` types.") - } - } - - /// Fills a supplied array with the specified window, single-precision. - /// - /// - Parameter sequence: Specifies the window sequence. - /// - Parameter result: Output values. - /// - Parameter isHalfWindow: When true, creates a window with only the first `(N+1)/2` points. - public static func formWindow(usingSequence sequence: WindowSequence, - result: inout V, - isHalfWindow: Bool) - where V: AccelerateMutableBuffer, - V.Element == Float { - - let n = vDSP_Length(result.count) - - result.withUnsafeMutableBufferPointer { v in - switch sequence { - case .hanningNormalized: - vDSP_hann_window(v.baseAddress!, - n, - Int32(vDSP_HANN_NORM) | - Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0)) - case .hanningDenormalized: - vDSP_hann_window(v.baseAddress!, - n, - Int32(vDSP_HANN_DENORM) | - Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0)) - case .hamming: - vDSP_hamm_window(v.baseAddress!, - n, - Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0)) - case .blackman: - vDSP_blkman_window(v.baseAddress!, - n, - Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0)) - } - } - } - - /// Fills a supplied array with the specified window, double-precision. - /// - /// - Parameter sequence: Specifies the window sequence. - /// - Parameter result: Output values. - /// - Parameter isHalfWindow: When true, creates a window with only the first `(N+1)/2` points. - public static func formWindow(usingSequence sequence: WindowSequence, - result: inout V, - isHalfWindow: Bool) - where V: AccelerateMutableBuffer, - V.Element == Double { - - let n = vDSP_Length(result.count) - - result.withUnsafeMutableBufferPointer { v in - switch sequence { - case .hanningNormalized: - vDSP_hann_windowD(v.baseAddress!, - n, - Int32(vDSP_HANN_NORM) | - Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0)) - case .hanningDenormalized: - vDSP_hann_windowD(v.baseAddress!, - n, - Int32(vDSP_HANN_DENORM) | - Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0)) - case .hamming: - vDSP_hamm_windowD(v.baseAddress!, - n, - Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0)) - case .blackman: - vDSP_blkman_windowD(v.baseAddress!, - n, - Int32(isHalfWindow ? vDSP_HALF_WINDOW : 0)) - } - } - } - - // MARK: Ramps - - //===----------------------------------------------------------------------===// - // withInitialValue and increment - //===----------------------------------------------------------------------===// - - /// Returns an array containing monotonically incrementing or decrementing values, single-precision. - /// - /// - Parameter initialValue: Specifies the initial value. - /// - Parameter increment: The increment (or decrement if negative) between consecutive elements. - /// - Parameter count: The number of elements in the array. - /// - Returns: An array containing the specified ramp. - @inlinable - public static func ramp(withInitialValue initialValue: Float, - increment: Float, - count: Int) -> [Float] { - - precondition(count > 0) - - let result = Array(unsafeUninitializedCapacity: count) { - buffer, initializedCount in - - formRamp(withInitialValue: initialValue, - increment: increment, - result: &buffer) - - initializedCount = count - } - - return result - } - - /// Fills a supplied array with monotonically incrementing or decrementing values, single-precision. - /// - /// - Parameter initialValue: Specifies the initial value. - /// - Parameter increment: The increment (or decrement if negative) between consecutive elements. - /// - Parameter result: Output values. - @inlinable - public static func formRamp(withInitialValue initialValue: Float, - increment: Float, - result: inout V) - where V: AccelerateMutableBuffer, - V.Element == Float { - - let n = vDSP_Length(result.count) - - withUnsafePointer(to: initialValue) { a in - withUnsafePointer(to: increment) { b in - result.withUnsafeMutableBufferPointer { c in - vDSP_vramp(a, - b, - c.baseAddress!, 1, - n) - } - } - } - } - - /// Returns an array containing monotonically incrementing or decrementing values, double-precision. - /// - /// - Parameter initialValue: Specifies the initial value. - /// - Parameter increment: The increment (or decrement if negative) between consecutive elements. - /// - Parameter count: The number of elements in the array. - /// - Returns: An array containing the specified ramp. - @inlinable - public static func ramp(withInitialValue initialValue: Double, - increment: Double, - count: Int) -> [Double] { - - precondition(count > 0) - - let result = Array(unsafeUninitializedCapacity: count) { - buffer, initializedCount in - - formRamp(withInitialValue: initialValue, - increment: increment, - result: &buffer) - - initializedCount = count - } - - return result - } - - /// Fills a supplied array with monotonically incrementing or decrementing values, double-precision. - /// - /// - Parameter initialValue: Specifies the initial value. - /// - Parameter increment: The increment (or decrement if negative) between consecutive elements. - /// - Parameter result: Output values. - @inlinable - public static func formRamp(withInitialValue initialValue: Double, - increment: Double, - result: inout V) - where V: AccelerateMutableBuffer, - V.Element == Double { - - let n = vDSP_Length(result.count) - - withUnsafePointer(to: initialValue) { a in - withUnsafePointer(to: increment) { b in - result.withUnsafeMutableBufferPointer { c in - vDSP_vrampD(a, - b, - c.baseAddress!, 1, - n) - } - } - } - } - - //===----------------------------------------------------------------------===// - // range - //===----------------------------------------------------------------------===// - - /// Returns an array containing monotonically incrementing or decrementing values within a specified range, single-precision. - /// - /// - Parameter range: Specifies range of the ramp.. - /// - Parameter count: The number of elements in the array. - /// - Returns: An array containing the specified ramp. - @inlinable - public static func ramp(in range: ClosedRange, - count: Int) -> [Float] { - - precondition(count > 0) - - let result = Array(unsafeUninitializedCapacity: count) { - buffer, initializedCount in - - formRamp(in: range, - result: &buffer) - - initializedCount = count - } - - return result - } - - /// Fills a supplied array with monotonically incrementing or decrementing values within a specified range, single-precision. - /// - /// - Parameter range: Specifies range of the ramp. - /// - Parameter result: Output values. - @inlinable - public static func formRamp(in range: ClosedRange, - result: inout V) - where V: AccelerateMutableBuffer, - V.Element == Float { - - let n = vDSP_Length(result.count) - - withUnsafePointer(to: range.lowerBound) { a in - withUnsafePointer(to: range.upperBound) { b in - result.withUnsafeMutableBufferPointer { c in - vDSP_vgen(a, - b, - c.baseAddress!, 1, - n) - } - } - } - } - - /// Returns an array containing monotonically incrementing or decrementing values within a specified range, double-precision. - /// - /// - Parameter range: Specifies range of the ramp.. - /// - Parameter count: The number of elements in the array. - /// - Returns: An array containing the specified ramp. - @inlinable - public static func ramp(in range: ClosedRange, - count: Int) -> [Double] { - - precondition(count > 0) - - let result = Array(unsafeUninitializedCapacity: count) { - buffer, initializedCount in - - formRamp(in: range, - result: &buffer) - - initializedCount = count - } - - return result - } - - /// Fills a supplied array with monotonically incrementing or decrementing values within a specified range, double-precision. - /// - /// - Parameter range: Specifies range of the ramp. - /// - Parameter result: Output values. - @inlinable - public static func formRamp(in range: ClosedRange, - result: inout V) - where V: AccelerateMutableBuffer, - V.Element == Double { - - let n = vDSP_Length(result.count) - - withUnsafePointer(to: range.lowerBound) { a in - withUnsafePointer(to: range.upperBound) { b in - result.withUnsafeMutableBufferPointer { c in - vDSP_vgenD(a, - b, - c.baseAddress!, 1, - n) - } - } - } - } - - //===----------------------------------------------------------------------===// - // initialValue, multiplyingBy, and increment - //===----------------------------------------------------------------------===// - - /// Returns an array containing monotonically incrementing or decrementing values, multiplying by a source vector, single-precision. - /// - /// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly. - /// - Parameter multiplyingBy: Input values multiplied by the ramp function. - /// - Parameter increment: The increment (or decrement if negative) between consecutive elements - /// - Parameter count: The number of elements in the array. - /// - Returns: An array containing the specified ramp. - @inlinable - public static func ramp(withInitialValue initialValue: inout Float, - multiplyingBy vector: U, - increment: Float) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - formRamp(withInitialValue: &initialValue, - multiplyingBy: vector, - increment: increment, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Fills a supplied array with monotonically incrementing or decrementing values, multiplying by a source vector, single-precision. - /// - /// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly. - /// - Parameter multiplyingBy: Input values multiplied by the ramp function. - /// - Parameter increment: The increment (or decrement if negative) between consecutive elements. - /// - Parameter result: Output values. - @inlinable - public static func formRamp(withInitialValue initialValue: inout Float, - multiplyingBy vector: U, - increment: Float, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - let n = vDSP_Length(result.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - withUnsafePointer(to: increment) { step in - vDSP_vrampmul(src.baseAddress!, 1, - &initialValue, - step, - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Returns an array containing monotonically incrementing or decrementing values, multiplying by a source vector, double-precision. - /// - /// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly. - /// - Parameter multiplyingBy: Input values multiplied by the ramp function. - /// - Parameter increment: The increment (or decrement if negative) between consecutive elements - /// - Parameter count: The number of elements in the array. - /// - Returns: An array containing the specified ramp. - @inlinable - public static func ramp(withInitialValue initialValue: inout Double, - multiplyingBy vector: U, - increment: Double) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - formRamp(withInitialValue: &initialValue, - multiplyingBy: vector, - increment: increment, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Fills a supplied array with monotonically incrementing or decrementing values, multiplying by a source vector, double-precision. - /// - /// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly. - /// - Parameter multiplyingBy: Input values multiplied by the ramp function. - /// - Parameter increment: The increment (or decrement if negative) between consecutive elements. - /// - Parameter result: Output values. - @inlinable - public static func formRamp(withInitialValue initialValue: inout Double, - multiplyingBy vector: U, - increment: Double, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - let n = vDSP_Length(result.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - withUnsafePointer(to: increment) { step in - vDSP_vrampmulD(src.baseAddress!, 1, - &initialValue, - step, - dest.baseAddress!, 1, - n) - } - } - } - } - - //===----------------------------------------------------------------------===// - // stereo - //===----------------------------------------------------------------------===// - - /// Returns two arraya containing monotonically monotonically incrementing or decrementing values, multiplying by a source vector, stereo, single-precision. - /// - /// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly. - /// - Parameter multiplierOne: Input values multiplied by the ramp function. - /// - Parameter multiplierTwo: Input values multiplied by the ramp function. - /// - Parameter increment: The increment (or decrement if negative) between consecutive elements. - /// - Returns: A tuple of two arrays containing the specified ramps. - @inlinable - public static func stereoRamp(withInitialValue initialValue: inout Float, - multiplyingBy multiplierOne: U, _ multiplierTwo: U, - increment: Float) -> (firstOutput:[Float], secondOutput: [Float]) - where - U: AccelerateBuffer, - U.Element == Float { - - let n = multiplierOne.count - - var firstOutput: Array! - - let secondOutput = Array(unsafeUninitializedCapacity: n) { - secondBuffer, secondInitializedCount in - - firstOutput = Array(unsafeUninitializedCapacity: n) { - firstBuffer, firstInitializedCount in - - formStereoRamp(withInitialValue: &initialValue, - multiplyingBy: multiplierOne, multiplierTwo, - increment: increment, - results: &firstBuffer, &secondBuffer) - - firstInitializedCount = n - } - - secondInitializedCount = n - } - - return (firstOutput: firstOutput, - secondOutput: secondOutput) - } - - /// Fills a supplied array with monotonically incrementing or decrementing values, multiplying by a source vector, stereo, single-precision. - /// - /// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly. - /// - Parameter multiplierOne: Input values multiplied by the ramp function. - /// - Parameter multiplierTwo: Input values multiplied by the ramp function. - /// - Parameter increment: The increment (or decrement if negative) between consecutive elements. - /// - Parameter resultOne: Output values. - /// - Parameter resultTwo: Output values. - @inlinable - public static func formStereoRamp(withInitialValue initialValue: inout Float, - multiplyingBy multiplierOne: U, _ multiplierTwo: U, - increment: Float, - results resultOne: inout V, _ resultTwo: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(multiplierOne.count == multiplierTwo.count) - precondition(resultOne.count == resultTwo.count) - precondition(multiplierOne.count == resultOne.count) - let n = vDSP_Length(resultTwo.count) - - resultOne.withUnsafeMutableBufferPointer { o0 in - resultTwo.withUnsafeMutableBufferPointer { o1 in - multiplierOne.withUnsafeBufferPointer { i0 in - multiplierTwo.withUnsafeBufferPointer { i1 in - withUnsafePointer(to: increment) { step in - vDSP_vrampmul2(i0.baseAddress!, - i1.baseAddress!, 1, - &initialValue, - step, - o0.baseAddress!, - o1.baseAddress!, 1, - n) - } - } - } - } - } - } - - /// Returns two arraya containing monotonically monotonically incrementing or decrementing values, multiplying by a source vector, stereo, double-precision. - /// - /// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly. - /// - Parameter multiplierOne: Input values multiplied by the ramp function. - /// - Parameter multiplierTwo: Input values multiplied by the ramp function. - /// - Parameter increment: The increment (or decrement if negative) between consecutive elements. - /// - Returns: A tuple of two arrays containing the specified ramps. - @inlinable - public static func stereoRamp(withInitialValue initialValue: inout Double, - multiplyingBy multiplierOne: U, _ multiplierTwo: U, - increment: Double) -> (firstOutput:[Double], secondOutput: [Double]) - where - U: AccelerateBuffer, - U.Element == Double { - - let n = multiplierOne.count - - var firstOutput: Array! - - let secondOutput = Array(unsafeUninitializedCapacity: n) { - secondBuffer, secondInitializedCount in - - firstOutput = Array(unsafeUninitializedCapacity: n) { - firstBuffer, firstInitializedCount in - - formStereoRamp(withInitialValue: &initialValue, - multiplyingBy: multiplierOne, multiplierTwo, - increment: increment, - results: &firstBuffer, &secondBuffer) - - firstInitializedCount = n - } - - secondInitializedCount = n - } - - return (firstOutput: firstOutput, - secondOutput: secondOutput) - } - - /// Fills a supplied array with monotonically incrementing or decrementing values, multiplying by a source vector, stereo, double-precision. - /// - /// - Parameter initialValue: Specifies the initial value. Modified on return to hold the next value (including accumulated errors) so that the ramp function can be continued smoothly. - /// - Parameter multiplierOne: Input values multiplied by the ramp function. - /// - Parameter multiplierTwo: Input values multiplied by the ramp function. - /// - Parameter increment: The increment (or decrement if negative) between consecutive elements. - /// - Parameter resultOne: Output values. - /// - Parameter resultTwo: Output values. - @inlinable - public static func formStereoRamp(withInitialValue initialValue: inout Double, - multiplyingBy multiplierOne: U, _ multiplierTwo: U, - increment: Double, - results resultOne: inout V, _ resultTwo: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(multiplierOne.count == multiplierTwo.count) - precondition(resultOne.count == resultTwo.count) - precondition(multiplierOne.count == resultOne.count) - let n = vDSP_Length(resultTwo.count) - - resultOne.withUnsafeMutableBufferPointer { o0 in - resultTwo.withUnsafeMutableBufferPointer { o1 in - multiplierOne.withUnsafeBufferPointer { i0 in - multiplierTwo.withUnsafeBufferPointer { i1 in - withUnsafePointer(to: increment) { step in - vDSP_vrampmul2D(i0.baseAddress!, - i1.baseAddress!, 1, - &initialValue, - step, - o0.baseAddress!, - o1.baseAddress!, 1, - n) - } - } - } - } - } - } - - -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_Geometry.swift b/stdlib/public/Darwin/Accelerate/vDSP_Geometry.swift deleted file mode 100644 index b237af23c7173..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_Geometry.swift +++ /dev/null @@ -1,424 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - // MARK Dot product - - /// Returns the dot or scalar product of vectors A and B; single-precision. - /// - /// - Parameter vectorA: Single-precision real input vector A. - /// - Parameter vectorB: Single-precision real input vector B. - /// - Returns: The dot product of vectors A and B. - @inlinable - public static func dot(_ vectorA: U, - _ vectorB: U) -> Float - where - U: AccelerateBuffer, - U.Element == Float { - - precondition(vectorA.count == vectorB.count) - - let n = vDSP_Length(vectorA.count) - var result = Float.nan - - vectorA.withUnsafeBufferPointer { a in - vectorB.withUnsafeBufferPointer { b in - - vDSP_dotpr(a.baseAddress!, 1, - b.baseAddress!, 1, - &result, n) - - } - } - - return result - } - - /// Returns the dot or scalar product of vectors A and B; double-precision. - /// - /// - Parameter vectorA: Double-precision real input vector A. - /// - Parameter vectorB: Double-precision real input vector B. - /// - Returns: The dot product of vectors A and B. - @inlinable - public static func dot(_ vectorA: U, - _ vectorB: U) -> Double - where - U: AccelerateBuffer, - U.Element == Double { - - precondition(vectorA.count == vectorB.count) - - let n = vDSP_Length(vectorA.count) - var result = Double.nan - - vectorA.withUnsafeBufferPointer { a in - vectorB.withUnsafeBufferPointer { b in - - vDSP_dotprD(a.baseAddress!, 1, - b.baseAddress!, 1, - &result, n) - - } - } - - return result - } - - // MARK: Distance - - /// Returns the hypotenuse of right-angled triangles with sides that are the lengths of - /// corresponding elements in vectors `x` and `y`; single-precision. - /// - /// - Parameter x: The `x` in `z[i] = sqrt(x[i]² + y[i]²)`. - /// - Parameter y: The `y` in `z[i] = sqrt(x[i]² + y[i]²)`. - /// - Parameter result: The `z` in `z[i] = sqrt(x[i]² + y[i]²)`. - @inlinable - public static func hypot(_ x: U, - _ y: V) -> [Float] - where - U: AccelerateBuffer, - V: AccelerateBuffer, - U.Element == Float, V.Element == Float { - - precondition(x.count == y.count) - - let result = Array(unsafeUninitializedCapacity: x.count) { - buffer, initializedCount in - - hypot(x, y, - result: &buffer) - - initializedCount = x.count - } - - return result - } - - /// Calculates the hypotenuse of right-angled triangles with sides that are the lengths of - /// corresponding elements in vectors `x` and `y`; single-precision. - /// - /// - Parameter x: The `x` in `z[i] = sqrt(x[i]² + y[i]²)`. - /// - Parameter y: The `y` in `z[i] = sqrt(x[i]² + y[i]²)`. - /// - Parameter result: The `z` in `z[i] = sqrt(x[i]² + y[i]²)`. - @inlinable - public static func hypot(_ x: T, - _ y: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - precondition(x.count == y.count && y.count == result.count) - let n = vDSP_Length(result.count) - - x.withUnsafeBufferPointer { a in - y.withUnsafeBufferPointer { b in - result.withUnsafeMutableBufferPointer { dest in - vDSP_vdist(a.baseAddress!, 1, - b.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Returns the hypotenuse of right-angled triangles with sides that are the lengths of - /// corresponding elements in vectors `x` and `y`; double-precision. - /// - /// - Parameter x: The `x` in `z[i] = sqrt(x[i]² + y[i]²)`. - /// - Parameter y: The `y` in `z[i] = sqrt(x[i]² + y[i]²)`. - /// - Parameter result: The `z` in `z[i] = sqrt(x[i]² + y[i]²)`. - @inlinable - public static func hypot(_ x: U, - _ y: V) -> [Double] - where - U: AccelerateBuffer, - V: AccelerateBuffer, - U.Element == Double, V.Element == Double { - - precondition(x.count == y.count) - - let result = Array(unsafeUninitializedCapacity: x.count) { - buffer, initializedCount in - - hypot(x, y, - result: &buffer) - - initializedCount = x.count - } - - return result - } - - /// Calculates the hypotenuse of right-angled triangles with sides that are the lengths of - /// corresponding elements in vectors `x` and `y`; double-precision. - /// - /// - Parameter x: The `x` in `z[i] = sqrt(x[i]² + y[i]²)`. - /// - Parameter y: The `y` in `z[i] = sqrt(x[i]² + y[i]²)`. - /// - Parameter result: The `z` in `z[i] = sqrt(x[i]² + y[i]²)`. - @inlinable - public static func hypot(_ x: T, - _ y: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - precondition(x.count == y.count && y.count == result.count) - let n = vDSP_Length(result.count) - - x.withUnsafeBufferPointer { a in - y.withUnsafeBufferPointer { b in - result.withUnsafeMutableBufferPointer { dest in - vDSP_vdistD(a.baseAddress!, 1, - b.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - - // MARK: Pythagoras - - /// Returns the hypotenuse of right-angled triangles with sides that are the differences of - /// corresponding values in x0 and x1, and y0 and y1. Single-precision. - /// - /// - Parameter x0: The `x0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter x1: The `x1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter y0: The `y0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter y1: The `y1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter result: The `z` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - @inlinable - public static func hypot(x0: R, x1: S, - y0: T, y1: U) -> [Float] - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - R.Element == Float, S.Element == Float, - T.Element == Float, U.Element == Float { - - precondition(x0.count == x1.count) - precondition(y0.count == y1.count) - precondition(x0.count == y0.count) - - let result = Array(unsafeUninitializedCapacity: x0.count) { - buffer, initializedCount in - - hypot(x0: x0, x1: x1, - y0: y0, y1: y1, - result: &buffer) - - initializedCount = x0.count - } - - return result - } - - /// Calculates the hypotenuse of right-angled triangles with sides that are the differences of - /// corresponding values in x0 and x1, and y0 and y1. Single-precision. - /// - /// - Parameter x0: The `x0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter x1: The `x1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter y0: The `y0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter y1: The `y1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter result: The `z` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - @inlinable - public static func hypot(x0: R, x1: S, - y0: T, y1: U, - result: inout V) - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - R.Element == Float, S.Element == Float, - T.Element == Float, U.Element == Float, - V.Element == Float { - - precondition(x0.count == x1.count && x0.count == result.count) - precondition(y0.count == y1.count && y0.count == result.count) - - let n = vDSP_Length(result.count) - - x0.withUnsafeBufferPointer { a in - x1.withUnsafeBufferPointer { c in - y0.withUnsafeBufferPointer { b in - y1.withUnsafeBufferPointer { d in - result.withUnsafeMutableBufferPointer { dest in - vDSP_vpythg(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - d.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - } - } - - /// Returns the hypotenuse of right-angled triangles with sides that are the differences of - /// corresponding values in x0 and x1, and y0 and y1. Double-precision. - /// - /// - Parameter x0: The `x0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter x1: The `x1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter y0: The `y0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter y1: The `y1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter result: The `z` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - @inlinable - public static func hypot(x0: R, x1: S, - y0: T, y1: U) -> [Double] - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - R.Element == Double, S.Element == Double, - T.Element == Double, U.Element == Double { - - precondition(x0.count == x1.count) - precondition(y0.count == y1.count) - precondition(x0.count == y0.count) - - let result = Array(unsafeUninitializedCapacity: x0.count) { - buffer, initializedCount in - - hypot(x0: x0, x1: x1, - y0: y0, y1: y1, - result: &buffer) - - initializedCount = x0.count - } - - return result - } - - /// Calculates the hypotenuse of right-angled triangles with sides that are the differences of - /// corresponding values in x0 and x1, and y0 and y1. Double-precision. - /// - /// - Parameter x0: The `x0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter x1: The `x1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter y0: The `y0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter y1: The `y1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - /// - Parameter result: The `z` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`. - @inlinable - public static func hypot(x0: R, x1: S, - y0: T, y1: U, - result: inout V) - where - R: AccelerateBuffer, - S: AccelerateBuffer, - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - R.Element == Double, S.Element == Double, - T.Element == Double, U.Element == Double, - V.Element == Double { - - precondition(x0.count == x1.count && x0.count == result.count) - precondition(y0.count == y1.count && y0.count == result.count) - - let n = vDSP_Length(result.count) - - x0.withUnsafeBufferPointer { a in - x1.withUnsafeBufferPointer { c in - y0.withUnsafeBufferPointer { b in - y1.withUnsafeBufferPointer { d in - result.withUnsafeMutableBufferPointer { dest in - vDSP_vpythgD(a.baseAddress!, 1, - b.baseAddress!, 1, - c.baseAddress!, 1, - d.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - } - } - } - - // MARK: Distance Squared - - /// Returns the distance squared between two points in `n` dimensional space. Single-precision. - /// - /// - Parameter pointA: First point in `n` dimensional space, where `n` is the collection count. - /// - Parameter pointB: Second point in `n` dimensional space, where `n` is the collection count. - /// - Returns: The distance squared between `pointA` and `pointB`. - @inlinable - public static func distanceSquared(_ pointA: U, - _ pointB: V) -> Float - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(pointA.count == pointB.count) - - let n = vDSP_Length(pointA.count) - var result = Float.nan - - pointA.withUnsafeBufferPointer { a in - pointB.withUnsafeBufferPointer { b in - vDSP_distancesq(a.baseAddress!, 1, - b.baseAddress!, 1, - &result, - n) - } - } - - return result - } - - /// Returns the distance squared between two points in `n` dimensional space. Double-precision. - /// - /// - Parameter pointA: First point in `n` dimensional space, where `n` is the collection count. - /// - Parameter pointB: Second point in `n` dimensional space, where `n` is the collection count. - /// - Returns: The distance squared between `pointA` and `pointB`. - @inlinable - public static func distanceSquared(_ pointA: U, - _ pointB: V) -> Double - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(pointA.count == pointB.count) - - let n = vDSP_Length(pointA.count) - var result = Double.nan - - pointA.withUnsafeBufferPointer { a in - pointB.withUnsafeBufferPointer { b in - vDSP_distancesqD(a.baseAddress!, 1, - b.baseAddress!, 1, - &result, - n) - } - } - - return result - } - -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_Integration.swift b/stdlib/public/Darwin/Accelerate/vDSP_Integration.swift deleted file mode 100644 index 78a7665c0fc52..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_Integration.swift +++ /dev/null @@ -1,157 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - public enum IntegrationRule { - case runningSum - case simpson - case trapezoidal - } - - /// Integrates source vector using specified rule, single-precision. - /// - /// - Parameter vector: The vector to integrate. - /// - Parameter rule: The integration rule. - /// - Parameter stepSize: The integration step size (weighting factor for running sum). - /// - Returns: The integration result. - @inlinable - public static func integrate(_ vector: U, - using rule: IntegrationRule, - stepSize: Float = 1) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - integrate(vector, - using: rule, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Integrates source vector using specified rule, single-precision. - /// - /// - Parameter vector: The vector to integrate. - /// - Parameter rule: The integration rule. - /// - Parameter stepSize: The integration step size (weighting factor for running sum). - /// - Parameter result: The destination vector to receive the result. - public static func integrate(_ vector: U, - using rule: IntegrationRule, - stepSize: Float = 1, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = vDSP_Length(min(vector.count, - result.count)) - - result.withUnsafeMutableBufferPointer { output in - vector.withUnsafeBufferPointer { input in - switch rule { - case .runningSum: - vDSP_vrsum(input.baseAddress!, 1, - [stepSize], - output.baseAddress!, 1, - n) - case .simpson: - vDSP_vsimps(input.baseAddress!, 1, - [stepSize], - output.baseAddress!, 1, - n) - case .trapezoidal: - vDSP_vtrapz(input.baseAddress!, 1, - [stepSize], - output.baseAddress!, 1, - n) - } - } - } - } - - /// Integrates source vector using specified rule, double-precision. - /// - /// - Parameter vector: The vector to integrate. - /// - Parameter rule: The integration rule. - /// - Parameter stepSize: The integration step size (weighting factor for running sum). - /// - Returns: The integration result. - @inlinable - public static func integrate(_ vector: U, - using rule: IntegrationRule, - stepSize: Double = 1) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - integrate(vector, - using: rule, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Integrates source vector using specified rule, double-precision. - /// - /// - Parameter vector: The vector to integrate. - /// - Parameter rule: The integration rule. - /// - Parameter stepSize: The integration step size (weighting factor for running sum). - /// - Parameter result: The destination vector to receive the result. - public static func integrate(_ vector: U, - using rule: IntegrationRule, - stepSize: Double = 1, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = vDSP_Length(min(vector.count, - result.count)) - - result.withUnsafeMutableBufferPointer { output in - vector.withUnsafeBufferPointer { input in - switch rule { - case .runningSum: - vDSP_vrsumD(input.baseAddress!, 1, - [stepSize], - output.baseAddress!, 1, - n) - case .simpson: - vDSP_vsimpsD(input.baseAddress!, 1, - [stepSize], - output.baseAddress!, 1, - n) - case .trapezoidal: - vDSP_vtrapzD(input.baseAddress!, 1, - [stepSize], - output.baseAddress!, 1, - n) - } - } - } - } -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_Interpolation.swift b/stdlib/public/Darwin/Accelerate/vDSP_Interpolation.swift deleted file mode 100644 index 23f37f6b22ec1..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_Interpolation.swift +++ /dev/null @@ -1,303 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - /// Vector linear interpolation between vectors; single-precision. - /// - /// - Parameter vectorA: The `A` in `D[n] = A[n] + C * (B[n] - A[n])`. - /// - Parameter vectorB: The `B` in `D[n] = A[n] + C * (B[n] - A[n])`. - /// - Parameter interpolationConstant: The `C` in `D[n] = A[n] + C * (B[n] - A[n])`. - /// - Returns: The `D` in `D[n] = A[n] + C * (B[n] - A[n])`. - @inlinable - public static func linearInterpolate(_ vectorA: T, - _ vectorB: U, - using interpolationConstant: Float) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float{ - - let result = Array(unsafeUninitializedCapacity: vectorA.count) { - buffer, initializedCount in - - linearInterpolate(vectorA, - vectorB, - using: interpolationConstant, - result: &buffer) - - initializedCount = vectorA.count - } - - return result - } - - /// Vector linear interpolation between vectors; single-precision. - /// - /// - Parameter vectorA: The `A` in `D[n] = A[n] + C * (B[n] - A[n])`. - /// - Parameter vectorB: The `B` in `D[n] = A[n] + C * (B[n] - A[n])`. - /// - Parameter interpolationConstant: The `C` in `D[n] = A[n] + C * (B[n] - A[n])`. - /// - Parameter result: The `D` in `D[n] = A[n] + C * (B[n] - A[n])`. - @inlinable - public static func linearInterpolate(_ vectorA: T, - _ vectorB: U, - using interpolationConstant: Float, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - precondition(vectorA.count == result.count) - precondition(vectorB.count == result.count) - let n = vDSP_Length(result.count) - - vectorA.withUnsafeBufferPointer { a in - vectorB.withUnsafeBufferPointer { b in - result.withUnsafeMutableBufferPointer { dest in - - vDSP_vintb(a.baseAddress!, 1, - b.baseAddress!, 1, - [interpolationConstant], - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Vector linear interpolation between vectors; double-precision. - /// - /// - Parameter vectorA: The `A` in `D[n] = A[n] + C * (B[n] - A[n])`. - /// - Parameter vectorB: The `B` in `D[n] = A[n] + C * (B[n] - A[n])`. - /// - Parameter interpolationConstant: The `C` in `D[n] = A[n] + C * (B[n] - A[n])`. - /// - Returns: The `D` in `D[n] = A[n] + C * (B[n] - A[n])`. - @inlinable - public static func linearInterpolate(_ vectorA: T, - _ vectorB: U, - using interpolationConstant: Double) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double{ - - let result = Array(unsafeUninitializedCapacity: vectorA.count) { - buffer, initializedCount in - - linearInterpolate(vectorA, - vectorB, - using: interpolationConstant, - result: &buffer) - - initializedCount = vectorA.count - } - - return result - } - - /// Vector linear interpolation between vectors; double-precision. - /// - /// - Parameter vectorA: The `A` in `D[n] = A[n] + C * (B[n] - A[n])`. - /// - Parameter vectorB: The `B` in `D[n] = A[n] + C * (B[n] - A[n])`. - /// - Parameter interpolationConstant: The `C` in `D[n] = A[n] + C * (B[n] - A[n])`. - /// - Parameter result: The `D` in `D[n] = A[n] + C * (B[n] - A[n])`. - @inlinable - public static func linearInterpolate(_ vectorA: T, - _ vectorB: U, - using interpolationConstant: Double, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - precondition(vectorA.count == result.count) - precondition(vectorB.count == result.count) - let n = vDSP_Length(result.count) - - vectorA.withUnsafeBufferPointer { a in - vectorB.withUnsafeBufferPointer { b in - result.withUnsafeMutableBufferPointer { dest in - - vDSP_vintbD(a.baseAddress!, 1, - b.baseAddress!, 1, - [interpolationConstant], - dest.baseAddress!, 1, - n) - } - } - } - } - - /// Vector linear interpolation between neighboring elements; single-precision. - /// - /// This function interpolates between the elements of `vector` using the following: - /// - /// for (n = 0; n < N; ++n) { - /// b = trunc(B[n]); - /// a = B[n] - b; - /// C[n] = A[b] + a * (A[b+1] - A[b]); - /// } - /// - /// Where `A` is the input vector, `B` is the control vector, and - /// `C` is the output vector. - /// - /// - Parameter vector: Input values. - /// - Parameter controlVector: Vector that controls interpolation. - /// - Returns: Output values. - @inlinable - public static func linearInterpolate(elementsOf vector: T, - using controlVector: U) -> [Float] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Float, U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: controlVector.count) { - buffer, initializedCount in - - linearInterpolate(elementsOf: vector, - using: controlVector, - result: &buffer) - - initializedCount = controlVector.count - } - - return result - } - - /// Vector linear interpolation between neighboring elements; single-precision. - /// - /// This function interpolates between the elements of `vector` using the following: - /// - /// for (n = 0; n < N; ++n) { - /// b = trunc(B[n]); - /// a = B[n] - b; - /// C[n] = A[b] + a * (A[b+1] - A[b]); - /// } - /// - /// Where `A` is the input vector, `B` is the control vector, and - /// `C` is the output vector. - /// - /// - Parameter vector: Input values. - /// - Parameter controlVector: Vector that controls interpolation. - /// - Parameter result: Output values. - @inlinable - public static func linearInterpolate(elementsOf vector: T, - using controlVector: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - precondition(controlVector.count == result.count) - - let n = vDSP_Length(result.count) - let m = vDSP_Length(vector.count) - - vector.withUnsafeBufferPointer { a in - controlVector.withUnsafeBufferPointer { b in - result.withUnsafeMutableBufferPointer { dest in - vDSP_vlint(a.baseAddress!, - b.baseAddress!, 1, - dest.baseAddress!, 1, - n, m) - } - } - } - } - - /// Vector linear interpolation between neighboring elements; double-precision. - /// - /// This function interpolates between the elements of `vector` using the following: - /// - /// for (n = 0; n < N; ++n) { - /// b = trunc(B[n]); - /// a = B[n] - b; - /// C[n] = A[b] + a * (A[b+1] - A[b]); - /// } - /// - /// Where `A` is the input vector, `B` is the control vector, and - /// `C` is the output vector. - /// - /// - Parameter vector: Input values. - /// - Parameter controlVector: Vector that controls interpolation. - /// - Returns: Output values. - @inlinable - public static func linearInterpolate(elementsOf vector: T, - using controlVector: U) -> [Double] - where - T: AccelerateBuffer, - U: AccelerateBuffer, - T.Element == Double, U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: controlVector.count) { - buffer, initializedCount in - - linearInterpolate(elementsOf: vector, - using: controlVector, - result: &buffer) - - initializedCount = controlVector.count - } - - return result - } - - /// Vector linear interpolation between neighboring elements; double-precision. - /// - /// This function interpolates between the elements of `vector` using the following: - /// - /// for (n = 0; n < N; ++n) { - /// b = trunc(B[n]); - /// a = B[n] - b; - /// C[n] = A[b] + a * (A[b+1] - A[b]); - /// } - /// - /// Where `A` is the input vector, `B` is the control vector, and - /// `C` is the output vector. - /// - /// - Parameter vector: Input values. - /// - Parameter controlVector: Vector that controls interpolation. - /// - Parameter result: Output values. - @inlinable - public static func linearInterpolate(elementsOf vector: T, - using controlVector: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - precondition(controlVector.count == result.count) - - let n = vDSP_Length(result.count) - let m = vDSP_Length(vector.count) - - vector.withUnsafeBufferPointer { a in - controlVector.withUnsafeBufferPointer { b in - result.withUnsafeMutableBufferPointer { dest in - vDSP_vlintD(a.baseAddress!, - b.baseAddress!, 1, - dest.baseAddress!, 1, - n, m) - } - } - } - } -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_PolarRectangularConversion.swift b/stdlib/public/Darwin/Accelerate/vDSP_PolarRectangularConversion.swift deleted file mode 100644 index fd14bff63b315..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_PolarRectangularConversion.swift +++ /dev/null @@ -1,203 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - /// Rectangular to polar conversion, single-precision. - /// - /// - Parameter rectangularCoordinates: Source vector, represented as consecutive x, y pairs. - /// - Returns: Polar coordinates, represented as consecutive rho, (radius) theta (angle in radians) pairs. - @inlinable - public static func rectangularToPolar(_ rectangularCoordinates: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: rectangularCoordinates.count) { - buffer, initializedCount in - - convert(rectangularCoordinates: rectangularCoordinates, - toPolarCoordinates: &buffer) - - initializedCount = rectangularCoordinates.count - } - - return result - } - - /// Rectangular to polar conversion, single-precision. - /// - /// - Parameter rectangularCoordinates: Source vector, represented as consecutive x, y pairs. - /// - Parameter polarCoordinates: Destination vector, represented as consecutive rho, (radius) theta (angle in radians) pairs. - @inlinable - public static func convert(rectangularCoordinates: U, - toPolarCoordinates polarCoordinates: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, - V.Element == Float { - - let n = rectangularCoordinates.count - precondition(polarCoordinates.count == n) - - polarCoordinates.withUnsafeMutableBufferPointer { dest in - rectangularCoordinates.withUnsafeBufferPointer { src in - vDSP_polar(src.baseAddress!, 2, - dest.baseAddress!, 2, - vDSP_Length(n / 2)) - } - } - } - - /// Rectangular to polar conversion, double-precision. - /// - /// - Parameter rectangularCoordinates: Source vector, represented as consecutive x, y pairs. - /// - Returns: Polar coordinates, represented as consecutive rho, (radius) theta (angle in radians) pairs. - @inlinable - public static func rectangularToPolar(_ rectangularCoordinates: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: rectangularCoordinates.count) { - buffer, initializedCount in - - convert(rectangularCoordinates: rectangularCoordinates, - toPolarCoordinates: &buffer) - - initializedCount = rectangularCoordinates.count - } - - return result - } - - /// Rectangular to polar conversion, double-precision. - /// - /// - Parameter rectangularCoordinates: Source vector, represented as consecutive x, y pairs. - /// - Parameter polarCoordinates: Destination vector, represented as consecutive rho, (radius) theta (angle in radians) pairs. - @inlinable - public static func convert(rectangularCoordinates: U, - toPolarCoordinates polarCoordinates: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, - V.Element == Double { - - let n = rectangularCoordinates.count - precondition(polarCoordinates.count == n) - - polarCoordinates.withUnsafeMutableBufferPointer { dest in - rectangularCoordinates.withUnsafeBufferPointer { src in - vDSP_polarD(src.baseAddress!, 2, - dest.baseAddress!, 2, - vDSP_Length(n / 2)) - } - } - } - - /// Polar to rectangular conversion, single-precision. - /// - /// - Parameter polarCoordinates: Source vector, represented as consecutive rho, (radius) theta (angle in radians) pairs. - /// - Returns: Rectangular coordinates, represented as consecutive x, y pairs. - @inlinable - public static func polarToRectangular(_ polarCoordinates: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: polarCoordinates.count) { - buffer, initializedCount in - - convert(polarCoordinates: polarCoordinates, - toRectangularCoordinates: &buffer) - - initializedCount = polarCoordinates.count - } - - return result - } - - /// Polar to rectangular conversion, single-precision. - /// - /// - Parameter polarCoordinates: Source vector, represented as consecutive rho, (radius) theta (angle in radians) pairs. - /// - Parameter rectangularCoordinates: Destination vector, represented as consecutive x, y pairs. - @inlinable - public static func convert(polarCoordinates: U, - toRectangularCoordinates rectangularCoordinates: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, - V.Element == Float { - - let n = rectangularCoordinates.count - precondition(polarCoordinates.count == n) - - rectangularCoordinates.withUnsafeMutableBufferPointer { dest in - polarCoordinates.withUnsafeBufferPointer { src in - vDSP_rect(src.baseAddress!, 2, - dest.baseAddress!, 2, - vDSP_Length(n / 2)) - } - } - } - - /// Polar to rectangular conversion, double-precision. - /// - /// - Parameter polarCoordinates: Source vector, represented as consecutive rho, (radius) theta (angle in radians) pairs. - /// - Returns: Rectangular coordinates, represented as consecutive x, y pairs. - @inlinable - public static func polarToRectangular(_ polarCoordinates: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: polarCoordinates.count) { - buffer, initializedCount in - - convert(polarCoordinates: polarCoordinates, - toRectangularCoordinates: &buffer) - - initializedCount = polarCoordinates.count - } - - return result - } - - /// Polar to rectangular conversion, double-precision. - /// - /// - Parameter polarCoordinates: Source vector, represented as consecutive rho, (radius) theta (angle in radians) pairs. - /// - Parameter rectangularCoordinates: Destination vector, represented as consecutive x, y pairs. - @inlinable - public static func convert(polarCoordinates: U, - toRectangularCoordinates rectangularCoordinates: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, - V.Element == Double { - - let n = rectangularCoordinates.count - precondition(polarCoordinates.count == n) - - rectangularCoordinates.withUnsafeMutableBufferPointer { dest in - polarCoordinates.withUnsafeBufferPointer { src in - vDSP_rectD(src.baseAddress!, 2, - dest.baseAddress!, 2, - vDSP_Length(n / 2)) - } - } - } -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_PolynomialEvaluation.swift b/stdlib/public/Darwin/Accelerate/vDSP_PolynomialEvaluation.swift deleted file mode 100644 index 1f3b90004b956..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_PolynomialEvaluation.swift +++ /dev/null @@ -1,154 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - /// Evaluates a polynomial using specified coefficients and independent variables. Single-precision. - /// - /// - Parameter coefficients: Coefficients. - /// - Parameter variables: Independent variables. - /// - Returns: The polynomial evaluation result. - /// - /// For example, given the coefficients `[10, 20, 30]`, and independent variables `[2, 5]`, - /// the result is calculated as: - /// - /// `result[0] = (10 * 2²) + (20 * 2¹) + (30 * 2⁰) // 110` - /// - /// `result[1] = (10 * 5²) + (20 * 5¹) + (30 * 5⁰) // 380` - @inlinable - public static func evaluatePolynomial(usingCoefficients coefficients: [Float], - withVariables variables: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: variables.count) { - buffer, initializedCount in - - evaluatePolynomial(usingCoefficients: coefficients, - withVariables: variables, - result: &buffer) - - initializedCount = variables.count - } - - return result - } - - /// Evaluates a polynomial using specified coefficients and independent variables. Single-precision. - /// - /// - Parameter coefficients: Coefficients. - /// - Parameter variables: Independent variables. - /// - Parameter result: Destination vector. - /// - /// For example, given the coefficients `[10, 20, 30]`, and independent variables `[2, 5]`, - /// the result is calculated as: - /// - /// `result[0] = (10 * 2²) + (20 * 2¹) + (30 * 2⁰) // 110` - /// - /// `result[1] = (10 * 5²) + (20 * 5¹) + (30 * 5⁰) // 380` - @inlinable - public static func evaluatePolynomial(usingCoefficients coefficients: [Float], - withVariables variables: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = vDSP_Length(min(variables.count, - result.count)) - - let degreeOfPolynomial = vDSP_Length(coefficients.count - 1) - - result.withUnsafeMutableBufferPointer { dest in - variables.withUnsafeBufferPointer { src in - vDSP_vpoly(coefficients, 1, - src.baseAddress!, 1, - dest.baseAddress!, 1, - n, - degreeOfPolynomial) - } - } - } - - /// Evaluates a polynomial using specified coefficients and independent variables. Double-precision. - /// - /// - Parameter coefficients: Coefficients. - /// - Parameter variables: Independent variables. - /// - Returns: The polynomial evaluation result. - /// - /// For example, given the coefficients `[10, 20, 30]`, and independent variables `[2, 5]`, - /// the result is calculated as: - /// - /// `result[0] = (10 * 2²) + (20 * 2¹) + (30 * 2⁰) // 110` - /// - /// `result[1] = (10 * 5²) + (20 * 5¹) + (30 * 5⁰) // 380` - @inlinable - public static func evaluatePolynomial(usingCoefficients coefficients: [Double], - withVariables variables: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: variables.count) { - buffer, initializedCount in - - evaluatePolynomial(usingCoefficients: coefficients, - withVariables: variables, - result: &buffer) - - initializedCount = variables.count - } - - return result - } - - /// Evaluates a polynomial using specified coefficients and independent variables. Double-precision. - /// - /// - Parameter coefficients: Coefficients. - /// - Parameter variables: Independent variables. - /// - Parameter result: Destination vector. - /// - /// For example, given the coefficients `[10, 20, 30]`, and independent variables `[2, 5]`, - /// the result is calculated as: - /// - /// `result[0] = (10 * 2²) + (20 * 2¹) + (30 * 2⁰) // 110` - /// - /// `result[1] = (10 * 5²) + (20 * 5¹) + (30 * 5⁰) // 380` - @inlinable - public static func evaluatePolynomial(usingCoefficients coefficients: [Double], - withVariables variables: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = vDSP_Length(min(variables.count, - result.count)) - - let degreeOfPolynomial = vDSP_Length(coefficients.count - 1) - - result.withUnsafeMutableBufferPointer { dest in - variables.withUnsafeBufferPointer { src in - vDSP_vpolyD(coefficients, 1, - src.baseAddress!, 1, - dest.baseAddress!, 1, - n, - degreeOfPolynomial) - } - } - } - -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_RecursiveFilters.swift b/stdlib/public/Darwin/Accelerate/vDSP_RecursiveFilters.swift deleted file mode 100644 index f9bf29d5f31d0..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_RecursiveFilters.swift +++ /dev/null @@ -1,186 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - /// Performs two-pole two-zero recursive filtering; single-precision. - /// - /// - Parameter source: Single-precision input vector. - /// - Parameter coefficients: Filter coefficients. - /// - Returns: Single-precision output vector. - /// - /// This function performs the following calculation: - /// - /// for (n = 2; n < N+2; ++n) - /// C[n] = - /// + A[n-0]*B[0] - /// + A[n-1]*B[1] - /// + A[n-2]*B[2] - /// - C[n-1]*B[3] - /// - C[n-2]*B[4]; - /// - /// Where `A` is the input vector, `B` is the filter coefficients, and `C` - /// is the output vector. Note that outputs start with C[2]. - @inlinable - public static func twoPoleTwoZeroFilter(_ source: U, - coefficients: (Float, Float, Float, Float, Float)) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: source.count) { - buffer, initializedCount in - - buffer[0] = 0 - buffer[1] = 0 - - twoPoleTwoZeroFilter(source, - coefficients: coefficients, - result: &buffer) - - initializedCount = source.count - } - - return result - } - - /// Performs two-pole two-zero recursive filtering; single-precision. - /// - /// - Parameter source: Single-precision input vector. - /// - Parameter coefficients: Filter coefficients. - /// - Parameter result: Single-precision output vector. - /// - /// This function performs the following calculation: - /// - /// for (n = 2; n < N+2; ++n) - /// C[n] = - /// + A[n-0]*B[0] - /// + A[n-1]*B[1] - /// + A[n-2]*B[2] - /// - C[n-1]*B[3] - /// - C[n-2]*B[4]; - /// - /// Where `A` is the input vector, `B` is the filter coefficients, and `C` - /// is the output vector. Note that outputs start with C[2]. - @inlinable - public static func twoPoleTwoZeroFilter(_ source: U, - coefficients: (Float, Float, Float, Float, Float), - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, - V.Element == Float { - - precondition(source.count == result.count) - - let n = vDSP_Length(source.count - 2) - - result.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_deq22(src.baseAddress!, 1, - [coefficients.0, coefficients.1, - coefficients.2, coefficients.3, - coefficients.4], - dest.baseAddress!, 1, - n) - } - } - } - - /// Performs two-pole two-zero recursive filtering; double-precision. - /// - /// - Parameter source: Double-precision input vector. - /// - Parameter coefficients: Filter coefficients. - /// - Returns: Double-precision output vector. - /// - /// This function performs the following calculation: - /// - /// for (n = 2; n < N+2; ++n) - /// C[n] = - /// + A[n-0]*B[0] - /// + A[n-1]*B[1] - /// + A[n-2]*B[2] - /// - C[n-1]*B[3] - /// - C[n-2]*B[4]; - /// - /// Where `A` is the input vector, `B` is the filter coefficients, and `C` - /// is the output vector. Note that outputs start with C[2]. - @inlinable - public static func twoPoleTwoZeroFilter(_ source: U, - coefficients: (Double, Double, Double, Double, Double)) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: source.count) { - buffer, initializedCount in - - buffer[0] = 0 - buffer[1] = 0 - - twoPoleTwoZeroFilter(source, - coefficients: coefficients, - result: &buffer) - - initializedCount = source.count - } - - return result - } - - /// Performs two-pole two-zero recursive filtering; double-precision. - /// - /// - Parameter source: single-precision input vector. - /// - Parameter coefficients: Filter coefficients. - /// - Parameter result: single-precision output vector. - /// - /// This function performs the following calculation: - /// - /// for (n = 2; n < N+2; ++n) - /// C[n] = - /// + A[n-0]*B[0] - /// + A[n-1]*B[1] - /// + A[n-2]*B[2] - /// - C[n-1]*B[3] - /// - C[n-2]*B[4]; - /// - /// Where `A` is the input vector, `B` is the filter coefficients, and `C` - /// is the output vector. Note that outputs start with C[2]. - @inlinable - public static func twoPoleTwoZeroFilter(_ source: U, - coefficients: (Double, Double, Double, Double, Double), - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, - V.Element == Double { - - precondition(source.count == result.count) - - let n = vDSP_Length(source.count - 2) - - result.withUnsafeMutableBufferPointer { dest in - source.withUnsafeBufferPointer { src in - vDSP_deq22D(src.baseAddress!, 1, - [coefficients.0, coefficients.1, - coefficients.2, coefficients.3, - coefficients.4], - dest.baseAddress!, 1, - n) - } - } - } - -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_Reduction.swift b/stdlib/public/Darwin/Accelerate/vDSP_Reduction.swift deleted file mode 100644 index f0f9fca78686e..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_Reduction.swift +++ /dev/null @@ -1,671 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - // MARK: Maximum - - /// Returns vector maximum value; single-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: The maximum value in `vector`. - @inlinable - public static func maximum(_ vector: U) -> Float - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var output = Float.nan - - vector.withUnsafeBufferPointer { v in - vDSP_maxv(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - /// Returns vector maximum value; single-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: The maximum value in `vector`. - @inlinable - public static func maximum(_ vector: U) -> Double - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var output = Double.nan - - vector.withUnsafeBufferPointer { v in - vDSP_maxvD(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - // MARK: Maximum magnitude - - /// Returns vector maximum magnitude; single-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: The maximum magnitude in `vector`. - @inlinable - public static func maximumMagnitude(_ vector: U) -> Float - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var output = Float.nan - - vector.withUnsafeBufferPointer { v in - vDSP_maxmgv(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - /// Returns vector maximum magnitude; double-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: The maximum magnitude in `vector`. - @inlinable - public static func maximumMagnitude(_ vector: U) -> Double - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var output = Double.nan - - vector.withUnsafeBufferPointer { v in - vDSP_maxmgvD(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - // MARK: Minimum - - /// Returns vector minimum value; single-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: The minimum value in `vector`. - @inlinable - public static func minimum(_ vector: U) -> Float - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var output = Float.nan - - vector.withUnsafeBufferPointer { v in - vDSP_minv(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - /// Returns vector minimum value; single-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: The minimum value in `vector`. - @inlinable - public static func minimum(_ vector: U) -> Double - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var output = Double.nan - - vector.withUnsafeBufferPointer { v in - vDSP_minvD(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - // MARK: Summation - - /// Returns vector sum; single-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: The sum of values in `vector`. - @inlinable - public static func sum(_ vector: U) -> Float - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var output = Float.nan - - vector.withUnsafeBufferPointer { v in - vDSP_sve(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - /// Returns vector sum; double-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: The sum of values in `vector`. - @inlinable - public static func sum(_ vector: U) -> Double - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var output = Double.nan - - vector.withUnsafeBufferPointer { v in - vDSP_sveD(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - /// Returns vector sum of squares; single-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: The sum of squares in `vector`. - @inlinable - public static func sumOfSquares(_ vector: U) -> Float - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var output = Float.nan - - vector.withUnsafeBufferPointer { v in - vDSP_svesq(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - /// Returns vector sum of squares; double-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: The sum of squares in `vector`. - @inlinable - public static func sumOfSquares(_ vector: U) -> Double - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var output = Double.nan - - vector.withUnsafeBufferPointer { v in - vDSP_svesqD(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - /// Returns sum of elements and sum of elements' squares; single-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: The sum of values and the sum of squares in `vector`. - @inlinable - public static func sumAndSumOfSquares(_ vector: U) -> (elementsSum: Float, squaresSum: Float) - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var sum = Float.nan - var sumOfSquares = Float.nan - - vector.withUnsafeBufferPointer { v in - vDSP_sve_svesq(v.baseAddress!, 1, - &sum, - &sumOfSquares, - n) - } - - return (elementsSum: sum, squaresSum: sumOfSquares) - } - - /// Returns sum of elements and sum of elements' squares; double-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: The sum of values and the sum of squares in `vector`. - @inlinable - public static func sumAndSumOfSquares(_ vector: U) -> (elementsSum: Double, squaresSum: Double) - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var sum = Double.nan - var sumOfSquares = Double.nan - - vector.withUnsafeBufferPointer { v in - vDSP_sve_svesqD(v.baseAddress!, 1, - &sum, - &sumOfSquares, - n) - } - - return (elementsSum: sum, squaresSum: sumOfSquares) - } - - /// Returns vector sum of magnitudes; single-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: The sum of magnitudes in `vector`. - @inlinable - public static func sumOfMagnitudes(_ vector: U) -> Float - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var output = Float.nan - - vector.withUnsafeBufferPointer { v in - vDSP_svemg(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - /// Returns vector sum of magnitudes; double-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: The sum of magnitudes in `vector`. - @inlinable - public static func sumOfMagnitudes(_ vector: U) -> Double - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var output = Double.nan - - vector.withUnsafeBufferPointer { v in - vDSP_svemgD(v.baseAddress!, 1, - &output, - n) - } - - return output - } -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - // MARK: Maximum with index - - /// Returns vector maximum with index; single-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: A tuple containing the maximum value and its index. - @inlinable - public static func indexOfMaximum(_ vector: U) -> (UInt, Float) - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var output = Float.nan - var index: vDSP_Length = 0 - - vector.withUnsafeBufferPointer { v in - vDSP_maxvi(v.baseAddress!, 1, - &output, - &index, - n) - } - - return (index, output) - } - - /// Returns vector maximum with index; double-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: A tuple containing the maximum value and its index. - @inlinable - public static func indexOfMaximum(_ vector: U) -> (UInt, Double) - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var output = Double.nan - var index: vDSP_Length = 0 - - vector.withUnsafeBufferPointer { v in - vDSP_maxviD(v.baseAddress!, 1, - &output, - &index, - n) - } - - return (index, output) - } - - // MARK: Maximum magnitude with index - - /// Returns vector maximum magnitude with index; single-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: A tuple containing the maximum magnitude and its index. - @inlinable - public static func indexOfMaximumMagnitude(_ vector: U) -> (UInt, Float) - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var output = Float.nan - var index: vDSP_Length = 0 - - vector.withUnsafeBufferPointer { v in - vDSP_maxmgvi(v.baseAddress!, 1, - &output, - &index, - n) - } - - return (index, output) - } - - /// Returns vector maximum magnitude with index; double-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: A tuple containing the maximum magnitude and its index. - @inlinable - public static func indexOfMaximumMagnitude(_ vector: U) -> (UInt, Double) - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var output = Double.nan - var index: vDSP_Length = 0 - - vector.withUnsafeBufferPointer { v in - vDSP_maxmgviD(v.baseAddress!, 1, - &output, - &index, - n) - } - - return (index, output) - } - - // MARK: Minimum with index - - /// Returns vector minimum with index; single-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: A tuple containing the minimum value and its index. - @inlinable - public static func indexOfMinimum(_ vector: U) -> (UInt, Float) - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var output = Float.nan - var index: vDSP_Length = 0 - - vector.withUnsafeBufferPointer { v in - vDSP_minvi(v.baseAddress!, 1, - &output, - &index, - n) - } - - return (index, output) - } - - /// Returns vector minimum with index; double-precision. - /// - /// - Parameter vector: The input vector. - /// - Returns: A tuple containing the minimum value and its index. - @inlinable - public static func indexOfMinimum(_ vector: U) -> (UInt, Double) - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var output = Double.nan - var index: vDSP_Length = 0 - - vector.withUnsafeBufferPointer { v in - vDSP_minviD(v.baseAddress!, 1, - &output, - &index, - n) - } - - return (index, output) - } -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - // MARK: Mean Square (vDSP_measqv) - - /// Returns the mean square of the supplied single-precision vector. - /// - /// - Parameter vector: The input vector. - @inlinable - public static func meanSquare(_ vector: U) -> Float - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var output = Float.nan - - vector.withUnsafeBufferPointer { v in - vDSP_measqv(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - /// Returns the mean square of the supplied double-precision vector. - /// - /// - Parameter vector: The input vector. - @inlinable - public static func meanSquare(_ vector: U) -> Double - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var output = Double.nan - - vector.withUnsafeBufferPointer { v in - vDSP_measqvD(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - // MARK: Mean Magnitude - - /// Returns the mean magnitude of the supplied single-precision vector. - /// - /// - Parameter vector: The input vector. - @inlinable - public static func meanMagnitude(_ vector: U) -> Float - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var output = Float.nan - - vector.withUnsafeBufferPointer { v in - vDSP_meamgv(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - /// Returns the mean magnitude of the supplied double-precision vector. - /// - /// - Parameter vector: The input vector. - @inlinable - public static func meanMagnitude(_ vector: U) -> Double - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var output = Double.nan - - vector.withUnsafeBufferPointer { v in - vDSP_meamgvD(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - - // MARK: Mean - - /// Returns the mean magnitude of the supplied single-precision vector. - /// - /// - Parameter vector: The input vector. - @inlinable - public static func mean(_ vector: U) -> Float - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var output = Float.nan - - vector.withUnsafeBufferPointer { v in - vDSP_meanv(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - /// Returns the mean of the supplied double-precision vector. - /// - /// - Parameter vector: The input vector. - @inlinable - public static func mean(_ vector: U) -> Double - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var output = Double.nan - - vector.withUnsafeBufferPointer { v in - vDSP_meanvD(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - // MARK: Root Mean Square - - /// Returns the root-mean-square of the supplied single-precision vector. - /// - /// - Parameter vector: The input vector. - @inlinable - public static func rootMeanSquare(_ vector: U) -> Float - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var output = Float.nan - - vector.withUnsafeBufferPointer { v in - vDSP_rmsqv(v.baseAddress!, 1, - &output, - n) - } - - return output - } - - /// Returns the root-mean-square of the supplied double-precision vector. - /// - /// - Parameter vector: The input vector. - @inlinable - public static func rootMeanSquare(_ vector: U) -> Double - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var output = Double.nan - - vector.withUnsafeBufferPointer { v in - vDSP_rmsqvD(v.baseAddress!, 1, - &output, - n) - } - - return output - } - -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_SingleVectorOperations.swift b/stdlib/public/Darwin/Accelerate/vDSP_SingleVectorOperations.swift deleted file mode 100644 index a01b02e1a32eb..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_SingleVectorOperations.swift +++ /dev/null @@ -1,990 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -//===----------------------------------------------------------------------===// -// -// vDSP Extrema -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - // MARK: Elementwise minimum - - /// Returns an array containing the lesser of the corresponding values in `vectorA` and `vectorB`, single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - @inlinable - public static func minimum(_ vectorA: U, - _ vectorB: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - precondition(vectorA.count == vectorB.count) - - let result = Array(unsafeUninitializedCapacity: vectorA.count) { - buffer, initializedCount in - - minimum(vectorA, - vectorB, - result: &buffer) - - initializedCount = vectorA.count - } - - return result - } - - /// Populates `result` with the lesser of the corresponding values in `vectorA` and `vectorB`, single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Parameter result: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - @inlinable - public static func minimum(_ vectorA: U, - _ vectorB: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = vDSP_Length(min(vectorA.count, - vectorB.count, - result.count)) - - result.withUnsafeMutableBufferPointer { r in - vectorA.withUnsafeBufferPointer { a in - vectorB.withUnsafeBufferPointer { b in - vDSP_vmin(a.baseAddress!, 1, - b.baseAddress!, 1, - r.baseAddress!, 1, - n) - } - } - } - } - - /// Returns an array containing the lesser of the corresponding values in `vectorA` and `vectorB`, double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - @inlinable - public static func minimum(_ vectorA: U, - _ vectorB: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - precondition(vectorA.count == vectorB.count) - - let result = Array(unsafeUninitializedCapacity: vectorA.count) { - buffer, initializedCount in - - minimum(vectorA, - vectorB, - result: &buffer) - - initializedCount = vectorA.count - } - - return result - } - - /// Populates `result` with the lesser of the corresponding values in `vectorA` and `vectorB`, double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Parameter result: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - @inlinable - public static func minimum(_ vectorA: U, - _ vectorB: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = vDSP_Length(min(vectorA.count, - vectorB.count, - result.count)) - - result.withUnsafeMutableBufferPointer { r in - vectorA.withUnsafeBufferPointer { a in - vectorB.withUnsafeBufferPointer { b in - vDSP_vminD(a.baseAddress!, 1, - b.baseAddress!, 1, - r.baseAddress!, 1, - n) - } - } - } - } - - // MARK: Elementwise maximum - - /// Returns an array containing the greater of the corresponding values in `vectorA` and `vectorB`, single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] > b[i] ? a[i] : b[i]` - /// - Parameter vectorB: the `b` in `c[i] = a[i] > b[i] ? a[i] : b[i]` - /// - Returns: the `c` in `c[i] = a[i] > b[i] ? a[i] : b[i]` - @inlinable - public static func maximum(_ vectorA: U, - _ vectorB: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - precondition(vectorA.count == vectorB.count) - - let result = Array(unsafeUninitializedCapacity: vectorA.count) { - buffer, initializedCount in - - maximum(vectorA, - vectorB, - result: &buffer) - - initializedCount = vectorA.count - } - - return result - } - - /// Populates `result` with the greater of the corresponding values in `vectorA` and `vectorB`, single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] > b[i] ? a[i] : b[i]` - /// - Parameter vectorB: the `b` in `c[i] = a[i] > b[i] ? a[i] : b[i]` - /// - Parameter result: the `c` in `c[i] = a[i] > b[i] ? a[i] : b[i]` - @inlinable - public static func maximum(_ vectorA: U, - _ vectorB: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = vDSP_Length(min(vectorA.count, - vectorB.count, - result.count)) - - result.withUnsafeMutableBufferPointer { r in - vectorA.withUnsafeBufferPointer { a in - vectorB.withUnsafeBufferPointer { b in - vDSP_vmax(a.baseAddress!, 1, - b.baseAddress!, 1, - r.baseAddress!, 1, - n) - } - } - } - } - - /// Returns an array containing the greater of the corresponding values in `vectorA` and `vectorB`, double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] > b[i] ? a[i] : b[i]` - /// - Parameter vectorB: the `b` in `c[i] = a[i] > b[i] ? a[i] : b[i]` - /// - Returns: the `c` in `c[i] = `c[i] = a[i] > b[i] ? a[i] : b[i]` - @inlinable - public static func maximum(_ vectorA: U, - _ vectorB: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - precondition(vectorA.count == vectorB.count) - - let result = Array(unsafeUninitializedCapacity: vectorA.count) { - buffer, initializedCount in - - maximum(vectorA, - vectorB, - result: &buffer) - - initializedCount = vectorA.count - } - - return result - } - - /// Populates `result` with the greater of the corresponding values in `vectorA` and `vectorB`, double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] > b[i] ? a[i] : b[i]` - /// - Parameter vectorB: the `b` in `c[i] = a[i] > b[i] ? a[i] : b[i]` - /// - Parameter result: the `c` in `c[i] = a[i] > b[i] ? a[i] : b[i]` - @inlinable - public static func maximum(_ vectorA: U, - _ vectorB: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = vDSP_Length(min(vectorA.count, - vectorB.count, - result.count)) - - result.withUnsafeMutableBufferPointer { r in - vectorA.withUnsafeBufferPointer { a in - vectorB.withUnsafeBufferPointer { b in - vDSP_vmaxD(a.baseAddress!, 1, - b.baseAddress!, 1, - r.baseAddress!, 1, - n) - } - } - } - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP Absolute and Negation -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - /// Returns an array containing the absolute values of `vector`, - /// single-precision. - /// - /// - Parameter vector: The input vector. - /// - Parameter result: The output vector. - @inlinable - public static func absolute(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - absolute(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the absolute values of `vector`, - /// single-precision. - /// - /// - Parameter vector: The input vector. - /// - Parameter result: The output vector. - @inlinable - public static func absolute(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vector.count == n) - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - vDSP_vabs(v.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - - } - - /// Returns an array containing the absolute values of `vector`, - /// double-precision. - /// - /// - Parameter vector: The input vector. - /// - Parameter result: The output vector. - @inlinable - public static func absolute(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - absolute(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the absolute values of `vector`, - /// double-precision. - /// - /// - Parameter vector: The input vector. - /// - Parameter result: The output vector. - @inlinable - public static func absolute(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vector.count == n) - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - vDSP_vabsD(v.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - - /// Returns an array containing the negative absolute values of `vector`, - /// single-precision. - /// - /// - Parameter vector: The input vector. - /// - Parameter result: The output vector. - @inlinable - public static func negativeAbsolute(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - negativeAbsolute(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the negative absolute values of `vector`, - /// single-precision. - /// - /// - Parameter vector: The input vector. - /// - Parameter result: The output vector. - @inlinable - public static func negativeAbsolute(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vector.count == n) - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - vDSP_vnabs(v.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - - /// Returns an array containing the negative absolute values of `vector`, - /// double-precision. - /// - /// - Parameter vector: The input vector. - /// - Parameter result: The output vector. - @inlinable - public static func negativeAbsolute(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - negativeAbsolute(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the negative absolute values of `vector`, - /// double-precision. - /// - /// - Parameter vector: The input vector. - /// - Parameter result: The output vector. - @inlinable - public static func negativeAbsolute(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vector.count == n) - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - vDSP_vnabsD(v.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - - /// Returns an array containing the negative values of `vector`, - /// single-precision. - /// - /// - Parameter vector: The input vector. - /// - Parameter result: The output vector. - @inlinable - public static func negative(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - negative(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the negative values of `vector`, - /// single-precision. - /// - /// - Parameter vector: The input vector. - /// - Parameter result: The output vector. - @inlinable - public static func negative(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - let n = result.count - precondition(vector.count == n) - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - vDSP_vneg(v.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } - - /// Returns an array containing the negative values of `vector`, - /// double-precision. - /// - /// - Parameter vector: The input vector. - /// - Parameter result: The output vector. - @inlinable - public static func negative(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - negative(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Populates `result` with the negative values of `vector`, - /// double-precision. - /// - /// - Parameter vector: The input vector. - /// - Parameter result: The output vector. - @inlinable - public static func negative(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - let n = result.count - precondition(vector.count == n) - result.withUnsafeMutableBufferPointer { r in - vector.withUnsafeBufferPointer { v in - vDSP_vnegD(v.baseAddress!, 1, - r.baseAddress!, 1, - vDSP_Length(n)) - } - } - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP In-place reversing and sorting -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - // MARK: Reversing - - /// Reverses an array of single-precision values in-place. - /// - /// - Parameter vector: The array to reverse. - @inlinable - public static func reverse(_ vector: inout V) - where - V: AccelerateMutableBuffer, - V.Element == Float { - - let n = vDSP_Length(vector.count) - - vector.withUnsafeMutableBufferPointer { v in - vDSP_vrvrs(v.baseAddress!, 1, - n) - } - } - - /// Reverses an array of double-precision values in-place. - /// - /// - Parameter vector: The array to reverse. - @inlinable - public static func reverse(_ vector: inout V) - where - V: AccelerateMutableBuffer, - V.Element == Double { - - let n = vDSP_Length(vector.count) - - vector.withUnsafeMutableBufferPointer { v in - vDSP_vrvrsD(v.baseAddress!, 1, - n) - } - } - - // MARK: Sorting - public enum SortOrder: Int32 { - case ascending = 1 - case descending = -1 - } - - /// Sorts an array of single-precision values in-place. - /// - /// - Parameter vector: The array to sort. - /// - Parameter sortOrder: The sort direction. - @inlinable - public static func sort(_ vector: inout V, - sortOrder: SortOrder) - where - V: AccelerateMutableBuffer, - V.Element == Float { - - let n = vDSP_Length(vector.count) - - vector.withUnsafeMutableBufferPointer { v in - vDSP_vsort(v.baseAddress!, - n, - sortOrder.rawValue) - } - } - - /// Sorts an array of double-precision values in-place. - /// - /// - Parameter vector: The array to sort. - /// - Parameter sortOrder: The sort direction. - @inlinable - public static func sort(_ vector: inout V, - sortOrder: SortOrder) - where - V: AccelerateMutableBuffer, - V.Element == Double { - - let n = vDSP_Length(vector.count) - - vector.withUnsafeMutableBufferPointer { v in - vDSP_vsortD(v.baseAddress!, - n, - sortOrder.rawValue) - } - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP Single vector arithmetic -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - // MARK: Square - - /// Returns an array containing the square of each element in `vector`, single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - @inlinable - public static func square(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - square(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the square of each element in `vector`, writing the result to `result`; single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func square(_ vector: U, - result: inout V) - where - U : AccelerateBuffer, - V : AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - let n = vDSP_Length(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vDSP_vsq(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Returns an array containing the square of each element in `vector`, double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - @inlinable - public static func square(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - square(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the square of each element in `vector`, writing the result to `result`; double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func square(_ vector: U, - result: inout V) - where - U : AccelerateBuffer, - V : AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - let n = vDSP_Length(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vDSP_vsqD(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - // MARK: Signed Square - - /// Returns an array containing the signed square of each element in `vector`, single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - @inlinable - public static func signedSquare(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - signedSquare(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the signed square of each element in `vector`, writing the result to `result`; single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func signedSquare(_ vector: U, - result: inout V) - where - U : AccelerateBuffer, - V : AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - let n = vDSP_Length(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vDSP_vssq(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Returns an array containing the signed square of each element in `vector`, double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - @inlinable - public static func signedSquare(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - signedSquare(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the signed square of each element in `vector`, writing the result to `result`; double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func signedSquare(_ vector: U, - result: inout V) - where - U : AccelerateBuffer, - V : AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - let n = vDSP_Length(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vDSP_vssqD(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - // MARK: Truncate to Fraction - - /// Returns an array containing each element in `vector` truncated to fraction, single-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - @inlinable - public static func trunc(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - trunc(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Truncates to fraction each element in `vector`, writing the result to `result`; single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func trunc(_ vector: U, - result: inout V) - where - U : AccelerateBuffer, - V : AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - let n = vDSP_Length(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vDSP_vfrac(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - /// Returns an array containing each element in `vector` truncated to fraction, double-precision. - /// - /// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - /// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]` - @inlinable - public static func trunc(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - trunc(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Truncates to fraction each element in `vector`, writing the result to `result`; double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func trunc(_ vector: U, - result: inout V) - where - U : AccelerateBuffer, - V : AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - let n = vDSP_Length(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vDSP_vfracD(src.baseAddress!, 1, - dest.baseAddress!, 1, - n) - } - } - } - - // Zero crossing - - /// Returns the number of zero crossings in `vector`; single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: The total number of transitions from positive to negative values and from negative to positive values. - @inlinable - public static func countZeroCrossings(_ vector: U) -> UInt - where - U : AccelerateBuffer, - U.Element == Float { - - let n = vDSP_Length(vector.count) - var crossingCount: vDSP_Length = 0 - var lastCrossingIndex: vDSP_Length = 0 - - vector.withUnsafeBufferPointer { src in - vDSP_nzcros(src.baseAddress!, 1, - n, - &lastCrossingIndex, - &crossingCount, - n) - } - - return crossingCount - } - - /// Returns the number of zero crossings in `vector`; double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: The total number of transitions from positive to negative values and from negative to positive values. - @inlinable - public static func countZeroCrossings(_ vector: U) -> UInt - where - U : AccelerateBuffer, - U.Element == Double { - - let n = vDSP_Length(vector.count) - var crossingCount: vDSP_Length = 0 - var lastCrossingIndex: vDSP_Length = 0 - - vector.withUnsafeBufferPointer { src in - vDSP_nzcrosD(src.baseAddress!, 1, - n, - &lastCrossingIndex, - &crossingCount, - n) - } - - return crossingCount - } -} diff --git a/stdlib/public/Darwin/Accelerate/vDSP_SlidingWindow.swift b/stdlib/public/Darwin/Accelerate/vDSP_SlidingWindow.swift deleted file mode 100644 index 44e728df236bd..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vDSP_SlidingWindow.swift +++ /dev/null @@ -1,127 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vDSP { - - /// Vector sliding window sum; single-precision. - /// - /// - Parameter source: Single-precision input vector. - /// - Parameter windowLength: The number of consecutive elements to sum. - /// - Returns: Single-precision output vector. - @inlinable - public static func slidingWindowSum(_ vector: U, - usingWindowLength windowLength: Int) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let n = vector.count - windowLength + 1 - - let result = Array(unsafeUninitializedCapacity: n) { - buffer, initializedCount in - - slidingWindowSum(vector, - usingWindowLength: windowLength, - result: &buffer) - - initializedCount = n - } - - return result - } - - /// Vector sliding window sum; single-precision. - /// - /// - Parameter source: Single-precision input vector. - /// - Parameter windowLength: The number of consecutive elements to sum. - /// - Parameter result: Single-precision output vector. - @inlinable - public static func slidingWindowSum(_ vector: U, - usingWindowLength windowLength: Int, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, - V.Element == Float { - - let n = result.count - precondition(vector.count == n + windowLength - 1) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vDSP_vswsum(src.baseAddress!, 1, - dest.baseAddress!, 1, - vDSP_Length(n), - vDSP_Length(windowLength)) - } - } - - } - - /// Vector sliding window sum; double-precision. - /// - /// - Parameter source: Single-precision input vector. - /// - Parameter windowLength: The number of consecutive elements to sum. - /// - Returns: Single-precision output vector. - @inlinable - public static func slidingWindowSum(_ vector: U, - usingWindowLength windowLength: Int) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let n = vector.count - windowLength + 1 - - let result = Array(unsafeUninitializedCapacity: n) { - buffer, initializedCount in - - slidingWindowSum(vector, - usingWindowLength: windowLength, - result: &buffer) - - initializedCount = n - } - - return result - } - - /// Vector sliding window sum; double-precision. - /// - /// - Parameter source: Double-precision input vector. - /// - Parameter windowLength: The number of consecutive elements to sum. - /// - Parameter result: Double-precision output vector. - @inlinable - public static func slidingWindowSum(_ vector: U, - usingWindowLength windowLength: Int, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, - V.Element == Double { - - let n = result.count - precondition(vector.count == n + windowLength - 1) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vDSP_vswsumD(src.baseAddress!, 1, - dest.baseAddress!, 1, - vDSP_Length(n), - vDSP_Length(windowLength)) - } - } - - } -} diff --git a/stdlib/public/Darwin/Accelerate/vForce_Operations.swift b/stdlib/public/Darwin/Accelerate/vForce_Operations.swift deleted file mode 100644 index f0b9949e2e944..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vForce_Operations.swift +++ /dev/null @@ -1,3311 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -// TODO: Support vectors with `count > Int32.max` by calling vvceilf in a -// loop, processing 0x40000000 elements at a go. - -// Array-Oriented Arithmetic and Auxiliary Functions - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vForce { - - // MARK: Ceiling - - /// Returns the ceiling of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func ceil(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - ceil(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the ceiling of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func ceil(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvceilf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the ceiling of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func ceil(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - ceil(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the ceiling of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func ceil(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvceil(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Floor - - /// Returns the floor of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func floor(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - floor(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the floor of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func floor(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvfloorf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the floor of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func floor(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - floor(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the floor of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func floor(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvfloor(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Copy sign - - /// Returns the sign of each element in `signs` to the corresponding element in `magnitudes`, single-precision. - /// - /// - Parameter magnitudes: Input magnitudes. - /// - Parameter signs: Input signs. - /// - Returns: Output values. - @inlinable - public static func copysign(magnitudes: U, - signs: V) -> [Float] - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(magnitudes.count == signs.count) - - let result = Array(unsafeUninitializedCapacity: magnitudes.count) { - buffer, initializedCount in - - copysign(magnitudes: magnitudes, - signs: signs, - result: &buffer) - - initializedCount = magnitudes.count - } - - return result - } - - /// Copies the sign of each element in `signs` to the corresponding element in `magnitudes`, writing the result to `result`, single-precision. - /// - /// - Parameter magnitudes: Input magnitudes. - /// - Parameter signs: Input signs. - /// - Parameter result: Output values. - @inlinable - public static func copysign(magnitudes: T, - signs: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - precondition(magnitudes.count == signs.count && signs.count == result.count) - - var n = Int32(magnitudes.count) - - result.withUnsafeMutableBufferPointer { dest in - magnitudes.withUnsafeBufferPointer { mag in - signs.withUnsafeBufferPointer { sgn in - vvcopysignf(dest.baseAddress!, - mag.baseAddress!, - sgn.baseAddress!, - &n) - } - } - } - } - - /// Returns the sign of each element in `signs` to the corresponding element in `magnitudes`, double-precision. - /// - /// - Parameter magnitudes: Input magnitudes. - /// - Parameter signs: Input signs. - /// - Returns: Output values. - @inlinable - public static func copysign(magnitudes: U, - signs: V) -> [Double] - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(magnitudes.count == signs.count) - - let result = Array(unsafeUninitializedCapacity: magnitudes.count) { - buffer, initializedCount in - - copysign(magnitudes: magnitudes, - signs: signs, - result: &buffer) - - initializedCount = magnitudes.count - } - - return result - } - - /// Copies the sign of each element in `signs` to the corresponding element in `magnitudes`, writing the result to `result`, double-precision. - /// - /// - Parameter magnitudes: Input magnitudes. - /// - Parameter signs: Input signs. - /// - Parameter result: Output values. - @inlinable - public static func copysign(magnitudes: T, - signs: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - precondition(magnitudes.count == signs.count && signs.count == result.count) - - var n = Int32(magnitudes.count) - - result.withUnsafeMutableBufferPointer { dest in - magnitudes.withUnsafeBufferPointer { mag in - signs.withUnsafeBufferPointer { sgn in - vvcopysign(dest.baseAddress!, - mag.baseAddress!, - sgn.baseAddress!, - &n) - } - } - } - } - - // `vvdiv(_:_:_:_:)` omitted, we have `vDSP_vdiv` in vDSP already. - // `vvfabs(_:_:_:)` omitted, we have `vDSP_zvabs` in vDSP already. - - // MARK: Modulus - - /// Returns the remainder of the elements in `dividends` divided by the the elements in `divisors` using truncating division; single-precision. - /// - /// - Parameter dividends: Input dividends. - /// - Parameter divisors: Input divisors. - /// - Returns: Output values. - /// - /// For each corresponding `a` from `dividends` and `b` from `divisors`, the result `r` satisfies: - /// a = bq + r - /// where q is the integer formed by rounding `a/b` towards zero, so `abs(r) < abs(b)` and `r` has the same sign as `a`. - @inlinable - public static func truncatingRemainder(dividends: U, - divisors: V) -> [Float] - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(dividends.count == divisors.count) - - let result = Array(unsafeUninitializedCapacity: dividends.count) { - buffer, initializedCount in - - truncatingRemainder(dividends: dividends, - divisors: divisors, - result: &buffer) - - initializedCount = dividends.count - } - - return result - } - - /// Calculates the remainder of the elements in `dividends` divided by the the elements - /// in `divisors` using truncating division; single-precision. - /// - /// - Parameter dividends: Input dividends. - /// - Parameter divisors: Input divisors. - /// - Parameter result: Output values. - /// - /// For each corresponding `a` from `dividends` and `b` from `divisors`, the result `r` satisfies: - /// a = bq + r - /// where q is the integer formed by rounding `a/b` towards zero, so `abs(r) < abs(b)` and `r` has the same sign as `a`. - @inlinable - public static func truncatingRemainder(dividends: T, - divisors: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - precondition(dividends.count == divisors.count && divisors.count == result.count) - - var n = Int32(result.count) - - result.withUnsafeMutableBufferPointer { dest in - dividends.withUnsafeBufferPointer { a in - divisors.withUnsafeBufferPointer { b in - vvfmodf(dest.baseAddress!, - a.baseAddress!, - b.baseAddress!, - &n) - } - } - } - } - - /// Returns the remainder of the elements in `dividends` divided by the the elements in `divisors` using truncating division; double-precision. - /// - /// - Parameter dividends: Input dividends. - /// - Parameter divisors: Input divisors. - /// - Returns: Output values. - /// - /// For each corresponding `a` from `dividends` and `b` from `divisors`, the result `r` satisfies: - /// a = bq + r - /// where q is the integer formed by rounding `a/b` towards zero, so `abs(r) < abs(b)` and `r` has the same sign as `a`. - @inlinable - public static func truncatingRemainder(dividends: U, - divisors: V) -> [Double] - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(dividends.count == divisors.count) - - let result = Array(unsafeUninitializedCapacity: dividends.count) { - buffer, initializedCount in - - truncatingRemainder(dividends: dividends, - divisors: divisors, - result: &buffer) - - initializedCount = dividends.count - } - - return result - } - - /// Calculates the remainder of the elements in `dividends` divided by the the elements - /// in `divisors` using truncating division; single-precision. - /// - /// - Parameter dividends: Input dividends. - /// - Parameter divisors: Input divisors. - /// - Parameter result: Output values. - /// - /// For each corresponding `a` from `dividends` and `b` from `divisors`, the result `r` satisfies: - /// a = bq + r - /// where q is the integer formed by rounding `a/b` towards zero, so `abs(r) < abs(b)` and `r` has the same sign as `a`. - @inlinable - public static func truncatingRemainder(dividends: T, - divisors: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - precondition(dividends.count == divisors.count && divisors.count == result.count) - - var n = Int32(result.count) - - result.withUnsafeMutableBufferPointer { dest in - dividends.withUnsafeBufferPointer { a in - divisors.withUnsafeBufferPointer { b in - vvfmod(dest.baseAddress!, - a.baseAddress!, - b.baseAddress!, - &n) - } - } - } - } - - // MARK: Remainder - - /// Returns the remainder after dividing each element in `dividends` by the corresponding element in `divisors`, single-precision. - /// - /// - Parameter dividends: Input dividends. - /// - Parameter divisors: Input divisors. - /// - Returns: Output values. - /// - /// For each corresponding `a` from `dividends` and `b` from `divisors`, the result `r` satisfies: - /// a = bq + r - /// where q is `a/b` rounded to the nearest integer, so `abs(r) <= abs(b/2)`. - @inlinable - public static func remainder(dividends: U, - divisors: V) -> [Float] - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(dividends.count == divisors.count) - - let result = Array(unsafeUninitializedCapacity: dividends.count) { - buffer, initializedCount in - - remainder(dividends: dividends, - divisors: divisors, - result: &buffer) - - initializedCount = dividends.count - } - - return result - } - - /// Calculates the remainder after dividing each element in `dividends` by the corresponding element in `divisors`, single-precision. - /// - /// - Parameter dividends: Input dividends. - /// - Parameter divisors: Input divisors. - /// - Parameter result: Output values. - /// - /// For each corresponding `a` from `dividends` and `b` from `divisors`, the result `r` satisfies: - /// a = bq + r - /// where q is `a/b` rounded to the nearest integer, so `abs(r) <= abs(b/2)`. - @inlinable - public static func remainder(dividends: T, - divisors: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - precondition(dividends.count == divisors.count && divisors.count == result.count) - - var n = Int32(result.count) - - result.withUnsafeMutableBufferPointer { dest in - dividends.withUnsafeBufferPointer { a in - divisors.withUnsafeBufferPointer { b in - vvremainderf(dest.baseAddress!, - a.baseAddress!, - b.baseAddress!, - &n) - } - } - } - } - - /// Returns the remainder after dividing each element in `dividends` by the corresponding element in `divisors`, double-precision. - /// - /// - Parameter dividends: Input dividends. - /// - Parameter divisors: Input divisors. - /// - Returns: Output values. - /// - /// For each corresponding `a` from `dividends` and `b` from `divisors`, the result `r` satisfies: - /// a = bq + r - /// where q is `a/b` rounded to the nearest integer, so `abs(r) <= abs(b/2)`. - @inlinable - public static func remainder(dividends: U, - divisors: V) -> [Double] - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(dividends.count == divisors.count) - - let result = Array(unsafeUninitializedCapacity: dividends.count) { - buffer, initializedCount in - - remainder(dividends: dividends, - divisors: divisors, - result: &buffer) - - initializedCount = dividends.count - } - - return result - } - - /// Calculates the remainder after dividing each element in `dividends` by the corresponding element in `divisors`, double-precision. - /// - /// - Parameter dividends: Input dividends. - /// - Parameter divisors: Input divisors. - /// - Parameter result: Output values. - /// - /// For each corresponding `a` from `dividends` and `b` from `divisors`, the result `r` satisfies: - /// a = bq + r - /// where q is `a/b` rounded to the nearest integer, so `abs(r) <= abs(b/2)`. - @inlinable - public static func remainder(dividends: T, - divisors: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - precondition(dividends.count == divisors.count && divisors.count == result.count) - - var n = Int32(result.count) - - result.withUnsafeMutableBufferPointer { dest in - dividends.withUnsafeBufferPointer { a in - divisors.withUnsafeBufferPointer { b in - vvremainder(dest.baseAddress!, - a.baseAddress!, - b.baseAddress!, - &n) - } - } - } - } - - // MARK: Integer Truncation - - /// Returns the integer truncation of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func trunc(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - trunc(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the integer truncation of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func trunc(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvintf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the integer truncation of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func trunc(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - trunc(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the integer truncation of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func trunc(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvint(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Nearest Integer - - /// Returns the nearest integer to each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func nearestInteger(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - nearestInteger(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the nearest integer to each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func nearestInteger(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvnintf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the nearest integer to each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func nearestInteger(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - nearestInteger(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the nearest integer to each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func nearestInteger(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvnint(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Reciprocal Square Root - - /// Returns the reciprocal square root of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func rsqrt(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - rsqrt(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the reciprocal square root of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func rsqrt(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvrsqrtf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the reciprocal square root of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func rsqrt(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - rsqrt(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the reciprocal square root of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func rsqrt(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvrsqrt(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Square Root - - /// Returns the square root of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func sqrt(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - sqrt(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the square root of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func sqrt(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvsqrtf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the square root of each element in `vector`, double-precision. - /// - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func sqrt(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - sqrt(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the square root of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func sqrt(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvsqrt(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Reciprocal - - /// Returns the reciprocal of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func reciprocal(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - reciprocal(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the reciprocal of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func reciprocal(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvrecf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the reciprocal of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func reciprocal(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - reciprocal(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the reciprocal of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func reciprocal(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvrec(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } -} - -// Array-Oriented Exponential and Logarithmic Functions - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vForce { - - // MARK: Exponential - - /// Returns e raised to the power of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func exp(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - exp(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates e raised to the power of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func exp(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvexpf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns e raised to the power of each element minus one in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func expm1(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - expm1(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates e raised to the power of each element minus one in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func expm1(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvexpm1f(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns 2 raised to the power of each element minus one in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func exp2(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - exp2(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates 2 raised to the power of each element minus one in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func exp2(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvexp2f(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns e raised to the power of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func exp(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - exp(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates e raised to the power of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func exp(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvexp(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns e raised to the power of each element minus one in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func expm1(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - expm1(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates e raised to the power of each element minus one in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func expm1(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvexpm1(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns 2 raised to the power of each element minus one in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func exp2(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - exp2(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates 2 raised to the power of each element minus one in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func exp2(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvexp2(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Logarithm - - /// Returns the base two logarithm of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func log2(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - log2(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the base two logarithm of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func log2(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvlog2f(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the base ten logarithm of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func log10(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - log10(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the base ten logarithm of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func log10(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvlog10f(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the base two logarithm of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func log2(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - log2(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the base two logarithm of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func log2(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvlog2(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the base ten logarithm of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func log10(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - log10(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the ten logarithm of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func log10(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvlog10(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Unbiased Exponent - - /// Returns the unbiased exponent of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func logb(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - logb(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the unbiased exponent of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - /// - /// This function calculates `floor(log2(vector))`. - @inlinable - public static func logb(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvlogbf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the unbiased exponent of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func logb(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - logb(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the unbiased exponent of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Parameter result: Output values. - /// - /// This function calculates `floor(log2(vector))`. - @inlinable - public static func logb(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvlogb(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } -} - -// Array-Oriented Power Functions - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vForce { - - // MARK: Power - - /// Returns each element in `bases` rasied to the power of the corresponding element in `exponents`, single-precision. - /// - /// - Parameter bases: Input base values. - /// - Parameter exponents: Input exponents. - /// - Returns: Output values. - @inlinable - public static func pow(bases: U, - exponents: V) -> [Float] - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(bases.count == exponents.count) - - let result = Array(unsafeUninitializedCapacity: exponents.count) { - buffer, initializedCount in - - pow(bases: bases, - exponents: exponents, - result: &buffer) - - initializedCount = exponents.count - } - - return result - } - - /// Calculates each element in `bases` rasied to the power of the corresponding element in `exponents`, writing the result to `result`, single-precision. - /// - /// - Parameter bases: Input base values. - /// - Parameter exponents: Input exponents. - /// - Parameter result: Output values. - @inlinable - public static func pow(bases: T, - exponents: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - precondition(bases.count == exponents.count && exponents.count == result.count) - - var n = Int32(bases.count) - - result.withUnsafeMutableBufferPointer { dest in - bases.withUnsafeBufferPointer { bases in - exponents.withUnsafeBufferPointer { exponents in - vvpowf(dest.baseAddress!, - exponents.baseAddress!, - bases.baseAddress!, - &n) - } - } - } - } - - /// Returns each element in `bases` rasied to the power of the corresponding element in `exponents`, double-precision. - /// - /// - Parameter bases: Input base values. - /// - Parameter exponents: Input exponents. - /// - Returns: Output values. - @inlinable - public static func pow(bases: U, - exponents: V) -> [Double] - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(bases.count == exponents.count) - - let result = Array(unsafeUninitializedCapacity: exponents.count) { - buffer, initializedCount in - - pow(bases: bases, - exponents: exponents, - result: &buffer) - - initializedCount = exponents.count - } - - return result - } - - /// Calculates each element in `bases` rasied to the power of the corresponding element in `exponents`, writing the result to `result`, double-precision. - /// - /// - Parameter bases: Input base values. - /// - Parameter exponents: Input exponents. - /// - Parameter result: Output values. - @inlinable - public static func pow(bases: T, - exponents: U, - result: inout V) - where - T: AccelerateBuffer, - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, - U.Element == Double, - V.Element == Double { - - precondition(bases.count == exponents.count && exponents.count == result.count) - - var n = Int32(bases.count) - - result.withUnsafeMutableBufferPointer { dest in - bases.withUnsafeBufferPointer { bases in - exponents.withUnsafeBufferPointer { exponents in - vvpow(dest.baseAddress!, - exponents.baseAddress!, - bases.baseAddress!, - &n) - } - } - } - } - - -} - -// Array-Oriented Trigonometric Functions - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vForce { - - // MARK: Sine - - /// Returns the sine of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func sin(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - sin(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the sine of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func sin(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvsinf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the sine of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func sin(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - sin(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the sine of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func sin(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvsin(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the sine of pi multiplied of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func sinPi(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - sinPi(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the sine of pi multiplied by each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func sinPi(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvsinpif(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the sine of pi multiplied of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func sinPi(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - sinPi(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the sine of pi multiplied by each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func sinPi(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvsinpi(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Cosine - - /// Returns the cosine of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func cos(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - cos(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the cosine of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func cos(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvcosf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the cosine of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func cos(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - cos(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the cosine of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func cos(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvcos(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the cosine of pi multiplied of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func cosPi(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - cosPi(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the cosine of pi multiplied by each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func cosPi(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvcospif(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the cosine of pi multiplied of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func cosPi(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - cosPi(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the cosine of pi multiplied by each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func cosPi(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvcospi(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Cosine & Sine - - /// Calculates the sine and cosine of each element in `vector`, writing the results to `sinresult` and `cosresult` respectively, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter sinresult: Output sine values. - /// - Parameter cosresult: Output cosine values. - @inlinable - public static func sincos(_ vector: T, - sinResult: inout U, - cosResult: inout V) - where - T: AccelerateBuffer, - U: AccelerateMutableBuffer, - V: AccelerateMutableBuffer, - T.Element == Float, U.Element == Float, V.Element == Float { - - precondition(vector.count == sinResult.count && sinResult.count == cosResult.count) - - var n = Int32(vector.count) - - sinResult.withUnsafeMutableBufferPointer { sinDest in - cosResult.withUnsafeMutableBufferPointer { cosDest in - vector.withUnsafeBufferPointer { src in - vvsincosf(sinDest.baseAddress!, - cosDest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - } - - /// Calculates the sine and cosine of each element in `vector`, writing the results to `sinresult` and `cosresult` respectively, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter sinresult: Output sine values. - /// - Parameter cosresult: Output cosine values. - @inlinable - public static func sincos(_ vector: T, - sinResult: inout U, - cosResult: inout V) - where - T: AccelerateBuffer, - U: AccelerateMutableBuffer, - V: AccelerateMutableBuffer, - T.Element == Double, U.Element == Double, V.Element == Double { - - precondition(vector.count == sinResult.count && sinResult.count == cosResult.count) - - var n = Int32(vector.count) - - sinResult.withUnsafeMutableBufferPointer { sinDest in - cosResult.withUnsafeMutableBufferPointer { cosDest in - vector.withUnsafeBufferPointer { src in - vvsincos(sinDest.baseAddress!, - cosDest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - } - - // MARK: Tan - - /// Returns the tangent of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func tan(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - tan(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the tangent of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func tan(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvtanf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the tangent of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func tan(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - tan(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - - /// Calculates the tangent of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func tan(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvtan(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the tangent of pi multiplied of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func tanPi(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - tanPi(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the tangent of pi multiplied by each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func tanPi(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvtanpif(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the tangent of pi multiplied of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func tanPi(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - tanPi(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the tangent of pi multiplied by each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func tanPi(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvtanpi(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Arcsine - - /// Returns the arcsine of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func asin(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - asin(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the arcsine of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func asin(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvasinf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the arcsine of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func asin(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - asin(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the arcsine of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func asin(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvasin(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Arccosine - - /// Returns the arccosine of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func acos(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - acos(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the arccosine of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func acos(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvacosf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the arccosine of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func acos(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - acos(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the arccosine of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func acos(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvacos(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Arctangent - - /// Returns the arctangent of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func atan(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - atan(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the arctangent of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func atan(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvatanf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the arctangent of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func atan(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - atan(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the arctangent of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func atan(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvatan(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } -} - -// Array-Oriented Hyperbolic Functions - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vForce { - - // MARK: Hyperbolic Sine - - /// Returns the hyperbolic sine of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func sinh(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - sinh(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the hyperbolic sine of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func sinh(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvsinhf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the hyperbolic sine of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func sinh(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - sinh(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the hyperbolic sine of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func sinh(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvsinh(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Hyperbolic Cosine - - /// Returns the hyperbolic cosine of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func cosh(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - cosh(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the hyperbolic cosine of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func cosh(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvcoshf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the hyperbolic cosine of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func cosh(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - cosh(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the hyperbolic cosine of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func cosh(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvcosh(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Hyperbolic Tangent - - /// Returns the hyperbolic tangent of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func tanh(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - tanh(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the hyperbolic tangent of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func tanh(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvtanhf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the hyperbolic tangent of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func tanh(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - tanh(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the hyperbolic tangent of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func tanh(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvtanh(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Inverse Hyperbolic Sine - - /// Returns the inverse hyperbolic sine of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func asinh(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - asinh(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the inverse hyperbolic sine of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func asinh(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvasinhf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the inverse hyperbolic sine of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func asinh(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - asinh(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the inverse hyperbolic sine of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func asinh(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvasinh(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Inverse Hyperbolic Cosine - - /// Returns the inverse hyperbolic cosine of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func acosh(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - acosh(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the inverse hyperbolic cosine of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func acosh(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvacoshf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the inverse hyperbolic cosine of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func acosh(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - acosh(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the inverse hyperbolic cosine of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func acosh(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvacosh(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - // MARK: Inverse Hyperbolic Tangent - - /// Returns the inverse hyperbolic tangent of each element in `vector`, single-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func atanh(_ vector: U) -> [Float] - where - U: AccelerateBuffer, - U.Element == Float { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - atanh(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the inverse hyperbolic tangent of each element in `vector`, writing the result to `result`, single-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func atanh(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Float, V.Element == Float { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvatanhf(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } - - /// Returns the inverse hyperbolic tangent of each element in `vector`, double-precision. - /// - /// - Parameter _ vector: Input values. - /// - Returns: Output values. - @inlinable - public static func atanh(_ vector: U) -> [Double] - where - U: AccelerateBuffer, - U.Element == Double { - - let result = Array(unsafeUninitializedCapacity: vector.count) { - buffer, initializedCount in - - atanh(vector, - result: &buffer) - - initializedCount = vector.count - } - - return result - } - - /// Calculates the inverse hyperbolic tangent of each element in `vector`, writing the result to `result`, double-precision. - /// - /// - Parameter vector: Input values. - /// - Parameter result: Output values. - @inlinable - public static func atanh(_ vector: U, - result: inout V) - where - U: AccelerateBuffer, - V: AccelerateMutableBuffer, - U.Element == Double, V.Element == Double { - - precondition(vector.count == result.count) - - var n = Int32(vector.count) - - result.withUnsafeMutableBufferPointer { dest in - vector.withUnsafeBufferPointer { src in - vvatanh(dest.baseAddress!, - src.baseAddress!, - &n) - } - } - } -} diff --git a/stdlib/public/Darwin/Accelerate/vImage_Buffer.swift b/stdlib/public/Darwin/Accelerate/vImage_Buffer.swift deleted file mode 100644 index 69950cc7e93d1..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vImage_Buffer.swift +++ /dev/null @@ -1,232 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -//===----------------------------------------------------------------------===// -// -// vImage_Buffer -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vImage_Buffer { - - /// The size of the vImage buffer. - /// - /// The `CGSize` is rounded down to the nearest representable `CGFloat` that - /// is less than or equal to the actual size of the image. In practice the - /// conversion will always be exact, except for really big images. In that - /// case, some part of the bottom or right edge might be truncated. - public var size: CGSize { - var mutableSelf = self - return vImageBuffer_GetSize(&mutableSelf) - } - - //===----------------------------------------------------------------------===// - - /// Returns the preferred alignment and row bytes for a specified buffer - /// size and bits-per-pixel. - /// - /// - Parameter width: The width of the buffer. - /// - Parameter height: The height of the buffer. - /// - Parameter bitsPerPixel: The number of bits in a pixel of image data. - /// - /// - Returns: The preferred alignment and row bytes. - public static func preferredAlignmentAndRowBytes(width: Int, - height: Int, - bitsPerPixel: UInt32) throws -> (alignment: Int, rowBytes: Int) { - - if width < 0 || height < 0 { - throw vImage.Error.invalidParameter - } - - var buffer = vImage_Buffer() - - let error = vImageBuffer_Init(&buffer, - vImagePixelCount(height), - vImagePixelCount(width), - bitsPerPixel, - vImage_Flags(kvImageNoAllocate)) - - if error < kvImageNoError { - throw vImage.Error(vImageError: error) - } else { - return(alignment: error, - rowBytes: buffer.rowBytes) - } - } - - //===----------------------------------------------------------------------===// - // - // Initializers. - // - //===----------------------------------------------------------------------===// - - /// Initializes a vImage buffer of a specified size. - /// - /// - Parameter width: The width of the buffer. - /// - Parameter height: The height of the buffer. - /// - Parameter bitsPerPixel: The number of bits in a pixel of image data. - /// - /// - Returns: An initialized vImage buffer. - public init(width: Int, - height: Int, - bitsPerPixel: UInt32) throws { - - if width < 0 || height < 0 { - throw vImage.Error.invalidParameter - } - - self.init() - - let error = vImageBuffer_Init(&self, - vImagePixelCount(height), - vImagePixelCount(width), - bitsPerPixel, - vImage_Flags(kvImageNoFlags)) - - if error < kvImageNoError { - throw vImage.Error(vImageError: error) - } - } - - public func free() { - Darwin.free(data) - } -} - -// MARK: Core Graphics Support - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vImage_Buffer { - - /// Initialize a vImage buffer with the contents of a Core Graphics image. - /// - /// - Parameter cgImage: A `CGImage` instance to be used as the source. - /// - Parameter options: The options to use when performing this operation. - /// - /// - Returns: An initialized vImage buffer. - /// - /// This function will instantiate and initialize a vImage buffer from a `CGImage` using a `CGImageFormat` based on the provided image's properties. - public init(cgImage: CGImage, - flags options: vImage.Options = .noFlags) throws { - - self.init() - - guard var format = vImage_CGImageFormat(cgImage: cgImage) else { - throw vImage.Error.invalidImageFormat - } - - let error = vImageBuffer_InitWithCGImage(&self, - &format, - nil, - cgImage, - options.flags) - - if error != kvImageNoError { - throw vImage.Error(vImageError: error) - } - } - - //===----------------------------------------------------------------------===// - - /// Initialize a vImage buffer with the contents of a Core Graphics image, - /// using a supplied format. - /// - /// - Parameter cgImage: A `CGImage` instance to be used as the source. - /// - Parameter format: A `vImage_CGImageFormat` that describes the source image/ - /// - Parameter options: The options to use when performing this operation. - /// - /// - Returns: An initialized vImage buffer. - /// - /// This function will instantiate and initialize a vImage buffer from a `CGImage` using a provided `CGImageFormat`. - public init(cgImage: CGImage, - format: vImage_CGImageFormat, - flags options: vImage.Options = .noFlags) throws { - - self.init() - - var format = format - let error = vImageBuffer_InitWithCGImage(&self, - &format, - nil, - cgImage, - options.flags) - - if error != kvImageNoError { - throw vImage.Error(vImageError: error) - } - } - - //===----------------------------------------------------------------------===// - - /// Creates a `CGImage` instance from a vImage buffer - /// - /// - Parameter format: The image format of this vImage buffer. - /// - Parameter options: The options to use when performing this operation. - /// - /// - Returns: A Core Graphics image containing a representation of the vImage buffer. - public func createCGImage(format: vImage_CGImageFormat, - flags options: vImage.Options = .noFlags) throws -> CGImage { - var format = format - var error = kvImageNoError - - var cgImage: CGImage? - - withUnsafePointer(to: self) { - cgImage = vImageCreateCGImageFromBuffer( - $0, - &format, - nil, - nil, - options.flags, - &error).takeRetainedValue() - } - - if error != kvImageNoError { - throw vImage.Error(vImageError: error) - } else if cgImage == nil { - throw vImage.Error.internalError - } - - return cgImage! - } - - //===----------------------------------------------------------------------===// - - /// Copies this buffer to `destinationBuffer`. - /// - /// - Parameter destinationBuffer: The destination vImage buffer. - /// - Parameter pixelSize: The number of bytes for one pixel. - /// - Parameter options: The options to use when performing this operation. - public func copy(destinationBuffer: inout vImage_Buffer, - pixelSize: Int, - flags options: vImage.Options = .noFlags) throws { - - if Int(width) == 0 { - throw vImage.Error(vImageError: kvImageInvalidParameter) - } - - var error = kvImageNoError - - withUnsafePointer(to: self) { - error = vImageCopyBuffer($0, - &destinationBuffer, - pixelSize, - options.flags) - } - - if error != kvImageNoError { - throw vImage.Error(vImageError: error) - } - } - -} diff --git a/stdlib/public/Darwin/Accelerate/vImage_CGImageFormat.swift b/stdlib/public/Darwin/Accelerate/vImage_CGImageFormat.swift deleted file mode 100644 index 4ec2521db74e6..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vImage_CGImageFormat.swift +++ /dev/null @@ -1,81 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -//===----------------------------------------------------------------------===// -// -// vImage_CGImageFormat -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vImage_CGImageFormat { - - /// Initializes an image format from a Core Graphics image. - /// - /// - Parameter cgImage: The image from which to derive the image format. - /// - /// - Returns: An initialized `vImage_CGImageFormat`. - public init?(cgImage: CGImage) { - guard - let colorSpace = cgImage.colorSpace else { - return nil - } - - self = vImage_CGImageFormat( - bitsPerComponent: UInt32(cgImage.bitsPerComponent), - bitsPerPixel: UInt32(cgImage.bitsPerPixel), - colorSpace: Unmanaged.passRetained(colorSpace), - bitmapInfo: cgImage.bitmapInfo, - version: 0, - decode: nil, - renderingIntent: cgImage.renderingIntent) - } - - /// Initializes an image format. - /// - /// - Parameter bitsPerComponent: The number of bits needed to represent one - /// channel of data in one pixel. - /// - Parameter bitsPerPixel: The number of bits needed to represent one pixel. - /// - Parameter colorSpace: The color space for the format. - /// - Parameter bitmapInfo: The component information describing the color channels. - /// - Parameter renderingIntent: A rendering intent constant that specifies how - /// Core Graphics should handle colors that are not located within the gamut of the - /// destination color space of a graphics context. - /// - /// - Returns: An initialized `vImage_CGImageFormat`. - public init?(bitsPerComponent: Int, - bitsPerPixel: Int, - colorSpace: CGColorSpace, - bitmapInfo: CGBitmapInfo, - renderingIntent: CGColorRenderingIntent = .defaultIntent) { - - if bitsPerComponent < 1 || bitsPerPixel < 0 { - return nil - } - - self = vImage_CGImageFormat( - bitsPerComponent: UInt32(bitsPerComponent), - bitsPerPixel: UInt32(bitsPerPixel), - colorSpace: Unmanaged.passRetained(colorSpace), - bitmapInfo: bitmapInfo, - version: 0, - decode: nil, - renderingIntent: renderingIntent) - } - - /// The number of color channels. - public var componentCount: Int { - var mutableSelf = self - return Int(vImageCGImageFormat_GetComponentCount(&mutableSelf)) - } -} - diff --git a/stdlib/public/Darwin/Accelerate/vImage_CVImageFormat.swift b/stdlib/public/Darwin/Accelerate/vImage_CVImageFormat.swift deleted file mode 100644 index b2deca43162bd..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vImage_CVImageFormat.swift +++ /dev/null @@ -1,638 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -//===----------------------------------------------------------------------===// -// -// vImageCVImageFormat -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vImageCVImageFormat { - - /// Creates the description of how an image is encoded in a Core Video pixel buffer. - /// - /// - Parameter format: The format type of the image. - /// - Parameter matrix: A `vImage_ARGBToYpCbCrMatrix` that describes the conversion from RGB to the YpCbCr format. - /// - Parameter chromaSiting: The chroma location. - /// - Parameter colorSpace: The color space of the RGB and monochrome images. - /// - Parameter alphaIsOpaqueHint: A hint indicating that an image with an alpha channel should be treated as opaque. - /// - /// - Returns: A `vImageCVImageFormatRef` instance encoded with the function's parameters. - public static func make(format: Format, - matrix: vImage_ARGBToYpCbCrMatrix, - chromaSiting: ChromaSiting, - colorSpace: CGColorSpace, - alphaIsOpaqueHint: Bool) -> vImageCVImageFormat? { - - var mutableMatrix = matrix - - return vImageCVImageFormat_Create(format.ostype, - &mutableMatrix, - chromaSiting.cfString, - colorSpace, - alphaIsOpaqueHint ? 1 : 0)?.takeRetainedValue() - } - - /// Creates the description of how an image is encoded in an existing Core Video pixel buffer. - /// - /// - Parameter buffer: The CVPixelBufferRef on which to base the returned vImageCVImageFormatRef. - /// - /// - Returns: A `vImageCVImageFormatRef` instance encoded with the supplied pixel buffer's pixel format. - public static func make(buffer: CVPixelBuffer) -> vImageCVImageFormat? { - - return vImageCVImageFormat_CreateWithCVPixelBuffer(buffer).takeRetainedValue() - } - - /// The alpha hint of a Core Video image format. - public var alphaIsOpaqueHint: Bool { - get { - return vImageCVImageFormat_GetAlphaHint(cvConstImageFormat) != 0 - } - set { - let error = vImageCVImageFormat_SetAlphaHint(self, - newValue ? 2 : 0) - - if error != kvImageNoError { - fatalError("Unable to set `alphaIsOpaqueHint`") - } - } - } - - /// The number of channels, including alpha, for the Core Video image format. - public var channelCount: UInt32 { - return vImageCVImageFormat_GetChannelCount(cvConstImageFormat) - } - - /// The names of the channels of a Core Video image format. - public var channels: [vImage.BufferType] { - let channels = Array(UnsafeBufferPointer(start: vImageCVImageFormat_GetChannelNames(cvConstImageFormat), - count: Int(channelCount))) - - return channels.compactMap { - return vImage.BufferType(bufferTypeCode: Int($0), - model: colorSpace?.model) - } - } - - /// Returns the channel description for a particular channel type. - public func channelDescription(bufferType: vImage.BufferType) -> vImageChannelDescription? { - guard let description = vImageCVImageFormat_GetChannelDescription(cvConstImageFormat, - bufferType.bufferTypeCode) else { - return nil - } - - return vImageChannelDescription(min: description.pointee.min, - zero: description.pointee.zero, - full: description.pointee.full, - max: description.pointee.max) - } - - /// The chroma siting of a Core Video image format. - public var chromaSiting: ChromaSiting? { - get { - return ChromaSiting(location: vImageCVImageFormat_GetChromaSiting(cvConstImageFormat)?.takeRetainedValue()) - } - set { - let error = vImageCVImageFormat_SetChromaSiting(self, - newValue?.cfString) - - if error != kvImageNoError { - fatalError("Unable to set `chromaSiting`") - } - } - } - - /// The color space of a Core Video image format. - public var colorSpace: CGColorSpace? { - get { - return vImageCVImageFormat_GetColorSpace(cvConstImageFormat)?.takeRetainedValue() - } - set { - let error = vImageCVImageFormat_SetColorSpace(self, - newValue) - - if error != kvImageNoError { - fatalError("Unable to set `colorSpace`") - } - } - } - - /// The format code of a Core Video image format. - public var formatCode: UInt32 { - return vImageCVImageFormat_GetFormatCode(cvConstImageFormat) - } - - /// Utility to return immuatable copy of self for use in getters. - private var cvConstImageFormat: vImageConstCVImageFormat { - - let cvImageFormatPointer = UnsafeMutableRawPointer.allocate(byteCount: MemoryLayout.size, - alignment: MemoryLayout.alignment) - cvImageFormatPointer.storeBytes(of: self, - as: vImageCVImageFormat.self) - return cvImageFormatPointer.load(as: vImageConstCVImageFormat.self) - } - -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vImage { - /// Type codes for what is in a `vImage_Buffer`, such as red or luminance. - public enum BufferType: Int { - - /// The buffer contains the alpha channel / coverage component - case alpha - - /// The buffer contains data describable as a `vImage_CGImageFormat` as a - /// single (likely chunky) buffer. - case coreGraphics - - /// If the image has a CMYK color model, the buffer contains the black channel. - case cmykBlack - - /// If the image has a CMYK color model, the buffer contains the cyan channel. - case cmykCyan - - /// If the image has a CMYK color model, the buffer contains the magenta channel. - case cmykMagenta - - /// If the image has a CMYK color model, the buffer contains the yellow channel. - case cmykYellow - - /// The buffer contains luminance, and both chroma channels interleaved - /// according to the vImageConstCVImageFormatRef image type. - case YCbCr - - /// The buffer contains the blue chrominance channel. - case Cb - - /// The buffer contains the red chrominance channel. - case Cr - - /// The buffer contains both chrominance channels, interleaved. - case chroma - - /// The buffer contains chunky data not describable as a `vImage_CGImageFormat`. - case chunky - - /// The buffer contains data in an indexed colorspace. - case indexed - - /// If the image has a LAB color model, the buffer contains the a* channel. - case labA - - /// If the image has a LAB color model, the buffer contains the b* channel. - case labB - - /// If the image has a LAB color model, the buffer contains the L* channel. - case labL - - /// The buffer contains only luminance data. - case luminance - - /// The buffer contains monochrome data. - case monochrome - - /// If the image has a RGB color model, the buffer contains the red channel. - case rgbRed - - /// If the image has a RGB color model, the buffer contains the green channel. - case rgbGreen - - /// If the image has a RGB color model, the buffer contains the blue channel. - case rgbBlue - - /// If the image has a XYZ color model, the buffer contains the X channel. - case xyzX - - /// If the image has a XYZ color model, the buffer contains the Y channel. - case xyzY - - /// If the image has a XYZ color model, the buffer contains the Z channel. - case xyzZ - - public init?(rawValue: Int) { - fatalError("Not supported, use `BufferType.init(bufferTypeCode:model:)`.") - } - - /// Returns a new `BufferType` enum from the supplied code and color - /// space model. - public init?(bufferTypeCode: Int, model: CGColorSpaceModel?) { - - switch bufferTypeCode { - - // kvImageBufferTypeCode_RGB_Red - // kvImageBufferTypeCode_CMYK_Cyan - // kvImageBufferTypeCode_LAB_L - // kvImageBufferTypeCode_XYZ_X - // kvImageBufferTypeCode_Monochrome - case kvImageBufferTypeCode_ColorSpaceChannel1: - switch model ?? .unknown { - case .monochrome: - self = .monochrome - case .cmyk: - self = .cmykCyan - case .lab: - self = .labL - case .XYZ: - self = .xyzX - default: - self = .rgbRed - } - - // kvImageBufferTypeCode_RGB_Green - // kvImageBufferTypeCode_CMYK_Magenta - // kvImageBufferTypeCode_LAB_A - // kvImageBufferTypeCode_XYZ_Y - case kvImageBufferTypeCode_ColorSpaceChannel2: - switch model ?? .unknown { - case .cmyk: - self = .cmykMagenta - case .lab: - self = .labA - case .XYZ: - self = .xyzY - default: - self = .rgbGreen - } - - // kvImageBufferTypeCode_RGB_Blue - // kvImageBufferTypeCode_CMYK_Yellow - // kvImageBufferTypeCode_LAB_B - // kvImageBufferTypeCode_XYZ_Z - case kvImageBufferTypeCode_ColorSpaceChannel3: - switch model ?? .unknown { - case .cmyk: - self = .cmykYellow - case .lab: - self = .labB - case .XYZ: - self = .xyzZ - default: - self = .rgbBlue - } - - case kvImageBufferTypeCode_Alpha: - self = .alpha - case kvImageBufferTypeCode_CGFormat: - self = .coreGraphics - case kvImageBufferTypeCode_CMYK_Black: - self = .cmykBlack - case kvImageBufferTypeCode_CVPixelBuffer_YCbCr: - self = .YCbCr - case kvImageBufferTypeCode_Cb: - self = .Cb - case kvImageBufferTypeCode_Cr: - self = .Cr - case kvImageBufferTypeCode_Chroma: - self = .chroma - case kvImageBufferTypeCode_Chunky: - self = .chunky - case kvImageBufferTypeCode_Indexed: - self = .indexed - case kvImageBufferTypeCode_Luminance: - self = .luminance - - default: - return nil - } - } - - /// The `vImageBufferTypeCode` for this `BufferType` enum. - public var bufferTypeCode: vImageBufferTypeCode { - var code = -1 - switch self { - case .alpha: - code = kvImageBufferTypeCode_Alpha - case .coreGraphics: - code = kvImageBufferTypeCode_CGFormat - case .cmykBlack: - code = kvImageBufferTypeCode_CMYK_Black - case .cmykCyan: - code = kvImageBufferTypeCode_CMYK_Cyan - case .cmykMagenta: - code = kvImageBufferTypeCode_CMYK_Magenta - case .cmykYellow: - code = kvImageBufferTypeCode_CMYK_Yellow - case .YCbCr: - code = kvImageBufferTypeCode_CVPixelBuffer_YCbCr - case .Cb: - code = kvImageBufferTypeCode_Cb - case .Cr: - code = kvImageBufferTypeCode_Cr - case .chroma: - code = kvImageBufferTypeCode_Chroma - case .chunky: - code = kvImageBufferTypeCode_Chunky - case .indexed: - code = kvImageBufferTypeCode_Indexed - case .labA: - code = kvImageBufferTypeCode_LAB_A - case .labB: - code = kvImageBufferTypeCode_LAB_B - case .labL: - code = kvImageBufferTypeCode_LAB_L - case .luminance: - code = kvImageBufferTypeCode_Luminance - case .monochrome: - code = kvImageBufferTypeCode_Monochrome - case .rgbRed: - code = kvImageBufferTypeCode_RGB_Red - case .rgbGreen: - code = kvImageBufferTypeCode_RGB_Green - case .rgbBlue: - code = kvImageBufferTypeCode_RGB_Blue - case .xyzX: - code = kvImageBufferTypeCode_XYZ_X - case .xyzY: - code = kvImageBufferTypeCode_XYZ_Y - case .xyzZ: - code = kvImageBufferTypeCode_XYZ_Z - } - - return vImageBufferTypeCode(code) - } - } -} - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vImageCVImageFormat { - /// Core Video pixel format type enum. - public enum Format { - case format1Monochrome - case format2Indexed - case format4Indexed - case format8Indexed - case format1IndexedGray_WhiteIsZero - case format2IndexedGray_WhiteIsZero - case format4IndexedGray_WhiteIsZero - case format8IndexedGray_WhiteIsZero - case format16BE555 - case format16LE555 - case format16LE5551 - case format16BE565 - case format16LE565 - case format24RGB - case format24BGR - case format32ARGB - case format32BGRA - case format32ABGR - case format32RGBA - case format64ARGB - case format48RGB - case format32AlphaGray - case format16Gray - case format30RGB - case format422YpCbCr8 - case format4444YpCbCrA8 - case format4444YpCbCrA8R - case format4444AYpCbCr8 - case format4444AYpCbCr16 - case format444YpCbCr8 - case format422YpCbCr16 - case format422YpCbCr10 - case format444YpCbCr10 - case format420YpCbCr8Planar - case format420YpCbCr8PlanarFullRange - case format422YpCbCr_4A_8BiPlanar - case format420YpCbCr8BiPlanarVideoRange - case format420YpCbCr8BiPlanarFullRange - case format422YpCbCr8_yuvs - case format422YpCbCr8FullRange - case formatOneComponent8 - case formatTwoComponent8 - case format30RGBLEPackedWideGamut - case formatARGB2101010LEPacked - case formatOneComponent16Half - case formatOneComponent32Float - case formatTwoComponent16Half - case formatTwoComponent32Float - case format64RGBAHalf - case format128RGBAFloat - case format14Bayer_GRBG - case format14Bayer_RGGB - case format14Bayer_BGGR - case format14Bayer_GBRG - case formatDisparityFloat16 - case formatDisparityFloat32 - case formatDepthFloat16 - case formatDepthFloat32 - case format420YpCbCr10BiPlanarVideoRange - case format422YpCbCr10BiPlanarVideoRange - case format444YpCbCr10BiPlanarVideoRange - case format420YpCbCr10BiPlanarFullRange - case format422YpCbCr10BiPlanarFullRange - case format444YpCbCr10BiPlanarFullRange - - var ostype: OSType { - switch self { - case .format1Monochrome: - return kCVPixelFormatType_1Monochrome - case .format2Indexed: - return kCVPixelFormatType_2Indexed - case .format4Indexed: - return kCVPixelFormatType_4Indexed - case .format8Indexed: - return kCVPixelFormatType_8Indexed - case .format1IndexedGray_WhiteIsZero: - return kCVPixelFormatType_1IndexedGray_WhiteIsZero - case .format2IndexedGray_WhiteIsZero: - return kCVPixelFormatType_2IndexedGray_WhiteIsZero - case .format4IndexedGray_WhiteIsZero: - return kCVPixelFormatType_4IndexedGray_WhiteIsZero - case .format8IndexedGray_WhiteIsZero: - return kCVPixelFormatType_8IndexedGray_WhiteIsZero - case .format16BE555: - return kCVPixelFormatType_16BE555 - case .format16LE555: - return kCVPixelFormatType_16LE555 - case .format16LE5551: - return kCVPixelFormatType_16LE5551 - case .format16BE565: - return kCVPixelFormatType_16BE565 - case .format16LE565: - return kCVPixelFormatType_16LE565 - case .format24RGB: - return kCVPixelFormatType_24RGB - case .format24BGR: - return kCVPixelFormatType_24BGR - case .format32ARGB: - return kCVPixelFormatType_32ARGB - case .format32BGRA: - return kCVPixelFormatType_32BGRA - case .format32ABGR: - return kCVPixelFormatType_32ABGR - case .format32RGBA: - return kCVPixelFormatType_32RGBA - case .format64ARGB: - return kCVPixelFormatType_64ARGB - case .format48RGB: - return kCVPixelFormatType_48RGB - case .format32AlphaGray: - return kCVPixelFormatType_32AlphaGray - case .format16Gray: - return kCVPixelFormatType_16Gray - case .format30RGB: - return kCVPixelFormatType_30RGB - case .format422YpCbCr8: - return kCVPixelFormatType_422YpCbCr8 - case .format4444YpCbCrA8: - return kCVPixelFormatType_4444YpCbCrA8 - case .format4444YpCbCrA8R: - return kCVPixelFormatType_4444YpCbCrA8R - case .format4444AYpCbCr8: - return kCVPixelFormatType_4444AYpCbCr8 - case .format4444AYpCbCr16: - return kCVPixelFormatType_4444AYpCbCr16 - case .format444YpCbCr8: - return kCVPixelFormatType_444YpCbCr8 - case .format422YpCbCr16: - return kCVPixelFormatType_422YpCbCr16 - case .format422YpCbCr10: - return kCVPixelFormatType_422YpCbCr10 - case .format444YpCbCr10: - return kCVPixelFormatType_444YpCbCr10 - case .format420YpCbCr8Planar: - return kCVPixelFormatType_420YpCbCr8Planar - case .format420YpCbCr8PlanarFullRange: - return kCVPixelFormatType_420YpCbCr8PlanarFullRange - case .format422YpCbCr_4A_8BiPlanar: - return kCVPixelFormatType_422YpCbCr_4A_8BiPlanar - case .format420YpCbCr8BiPlanarVideoRange: - return kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange - case .format420YpCbCr8BiPlanarFullRange: - return kCVPixelFormatType_420YpCbCr8BiPlanarFullRange - case .format422YpCbCr8_yuvs: - return kCVPixelFormatType_422YpCbCr8_yuvs - case .format422YpCbCr8FullRange: - return kCVPixelFormatType_422YpCbCr8FullRange - case .formatOneComponent8: - return kCVPixelFormatType_OneComponent8 - case .formatTwoComponent8: - return kCVPixelFormatType_TwoComponent8 - case .format30RGBLEPackedWideGamut: - return kCVPixelFormatType_30RGBLEPackedWideGamut - case .formatARGB2101010LEPacked: - return kCVPixelFormatType_ARGB2101010LEPacked - case .formatOneComponent16Half: - return kCVPixelFormatType_OneComponent16Half - case .formatOneComponent32Float: - return kCVPixelFormatType_OneComponent32Float - case .formatTwoComponent16Half: - return kCVPixelFormatType_TwoComponent16Half - case .formatTwoComponent32Float: - return kCVPixelFormatType_TwoComponent32Float - case .format64RGBAHalf: - return kCVPixelFormatType_64RGBAHalf - case .format128RGBAFloat: - return kCVPixelFormatType_128RGBAFloat - case .format14Bayer_GRBG: - return kCVPixelFormatType_14Bayer_GRBG - case .format14Bayer_RGGB: - return kCVPixelFormatType_14Bayer_RGGB - case .format14Bayer_BGGR: - return kCVPixelFormatType_14Bayer_BGGR - case .format14Bayer_GBRG: - return kCVPixelFormatType_14Bayer_GBRG - case .formatDisparityFloat16: - return kCVPixelFormatType_DisparityFloat16 - case .formatDisparityFloat32: - return kCVPixelFormatType_DisparityFloat32 - case .formatDepthFloat16: - return kCVPixelFormatType_DepthFloat16 - case .formatDepthFloat32: - return kCVPixelFormatType_DepthFloat32 - case .format420YpCbCr10BiPlanarVideoRange: - return kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange - case .format422YpCbCr10BiPlanarVideoRange: - return kCVPixelFormatType_422YpCbCr10BiPlanarVideoRange - case .format444YpCbCr10BiPlanarVideoRange: - return kCVPixelFormatType_444YpCbCr10BiPlanarVideoRange - case .format420YpCbCr10BiPlanarFullRange: - return kCVPixelFormatType_420YpCbCr10BiPlanarFullRange - case .format422YpCbCr10BiPlanarFullRange: - return kCVPixelFormatType_422YpCbCr10BiPlanarFullRange - case .format444YpCbCr10BiPlanarFullRange: - return kCVPixelFormatType_444YpCbCr10BiPlanarFullRange - } - } - } - - public enum ChromaSiting { - /// Chroma sample is horizontally co-sited with the left column of luma - /// samples, but centered vertically. - case left - - /// Chroma sample is fully centered - case center - - /// Chroma sample is co-sited with the top-left luma sample. - case topLeft - - /// Chroma sample is horizontally centered, but co-sited with the top - /// row of luma samples. - case top - - /// Chroma sample is co-sited with the bottom-left luma sample. - case bottomLeft - - /// Chroma sample is horizontally centered, but co-sited with the - /// bottom row of luma samples. - case bottom - - /// Cr and Cb samples are alternately co-sited with the left luma - /// samples of the same field. - case dv420 - - /// Returns a new `ChromaSiting` enum from the supplied location. - init?(location: CFString?) { - switch location { - case kCVImageBufferChromaLocation_Left: - self = .left - case kCVImageBufferChromaLocation_Center: - self = .center - case kCVImageBufferChromaLocation_TopLeft: - self = .topLeft - case kCVImageBufferChromaLocation_Top: - self = .top - case kCVImageBufferChromaLocation_BottomLeft: - self = .bottomLeft - case kCVImageBufferChromaLocation_Bottom: - self = .bottom - case kCVImageBufferChromaLocation_DV420: - self = .dv420 - default: - return nil - } - } - - /// Returns a `CFString` describing this `ChromaSiting`. - var cfString: CFString { - switch self { - case .left: - return kCVImageBufferChromaLocation_Left - case .center: - return kCVImageBufferChromaLocation_Center - case .topLeft: - return kCVImageBufferChromaLocation_TopLeft - case .top: - return kCVImageBufferChromaLocation_Top - case .bottomLeft: - return kCVImageBufferChromaLocation_BottomLeft - case .bottom: - return kCVImageBufferChromaLocation_Bottom - case .dv420: - return kCVImageBufferChromaLocation_DV420 - } - } - } -} diff --git a/stdlib/public/Darwin/Accelerate/vImage_Converter.swift b/stdlib/public/Darwin/Accelerate/vImage_Converter.swift deleted file mode 100644 index 9a3774df25bb5..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vImage_Converter.swift +++ /dev/null @@ -1,240 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -//===----------------------------------------------------------------------===// -// -// vImageConverter -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vImageConverter { - - //===----------------------------------------------------------------------===// - - /// Returns an array of vImage source buffer types specifying the order of planes. - /// - /// - Parameter colorSpace: The color space of the source format. - public func sourceBuffers(colorSpace: CGColorSpace) -> [vImage.BufferType?] { - let sourceBuffers = vImageConverter_GetSourceBufferOrder(self) - let codes = Array(UnsafeBufferPointer(start: sourceBuffers, - count: sourceBufferCount)) - - return codes.map { - vImage.BufferType(bufferTypeCode: Int($0), - model: colorSpace.model) - } - } - - /// Returns an array of vImage source buffer types specifying the order of planes. - /// - /// - Parameter colorSpace: The color space of the destination format. - public func destinationBuffers(colorSpace: CGColorSpace) -> [vImage.BufferType?] { - let destinationBuffers = vImageConverter_GetDestinationBufferOrder(self) - let codes = Array(UnsafeBufferPointer(start: destinationBuffers, - count: destinationBufferCount)) - - return codes.map { - vImage.BufferType(bufferTypeCode: Int($0), - model: colorSpace.model) - } - } - - /// The number of source buffers consumed by the converter. - public var sourceBufferCount: Int { - return Int(vImageConverter_GetNumberOfSourceBuffers(self)) - } - - /// The number of destination buffers written to by the converter. - public var destinationBufferCount: Int { - return Int(vImageConverter_GetNumberOfDestinationBuffers(self)) - } - - //===----------------------------------------------------------------------===// - - /// Determines whether a converter is capable of operating in place. - /// - /// - Parameter source: The source buffer. - /// - Parameter destination: The destination buffer. - /// - Parameter options: The options to use when performing this operation. - /// - /// - Returns: `true` if the conversion must operate out of place or `false` - /// if the operation will work in place. - public func mustOperateOutOfPlace(source: vImage_Buffer, - destination: vImage_Buffer, - flags options: vImage.Options = .noFlags) throws -> Bool { - var error = kvImageNoError - - withUnsafePointer(to: source) { src in - withUnsafePointer(to: destination) { dest in - error = vImageConverter_MustOperateOutOfPlace(self, - src, - dest, - vImage_Flags(options.rawValue)) - } - } - - switch error { - case kvImageOutOfPlaceOperationRequired: - return true - case kvImageNoError: - return false - default: - throw vImage.Error(vImageError: error) - } - } - - //===----------------------------------------------------------------------===// - // - // MARK: CG -> CG - // - //===----------------------------------------------------------------------===// - - /// Creates a vImage converter to convert from one vImage Core Graphics image format to another. - /// - /// - Parameter sourceFormat: A `vImage_CGImageFormat` structure describing the image format of the source image - /// - Parameter destinationFormat: A `vImage_CGImageFormat` structure describing the image format of the destination image - /// - Parameter options: The options to use when performing this operation. - /// - /// - Returns: a vImage converter to convert from one vImage Core Graphics image format to another. - public static func make(sourceFormat: vImage_CGImageFormat, - destinationFormat: vImage_CGImageFormat, - flags options: vImage.Options = .noFlags) throws -> vImageConverter { - - var error = kvImageNoError - var unmanagedConverter: Unmanaged? - - withUnsafePointer(to: destinationFormat) { dest in - withUnsafePointer(to: sourceFormat) { src in - unmanagedConverter = vImageConverter_CreateWithCGImageFormat( - src, - dest, - nil, - vImage_Flags(options.rawValue), - &error) - } - } - - if error != kvImageNoError { - throw vImage.Error(vImageError: error) - } else if unmanagedConverter == nil { - throw vImage.Error.internalError - } - - return unmanagedConverter!.takeRetainedValue() - } - - //===----------------------------------------------------------------------===// - // - // MARK: CG -> CV - // - //===----------------------------------------------------------------------===// - - /// Creates a vImage converter that converts a Core Graphics-formatted image to a Core Video-formatted image. - /// - /// - Parameter sourceFormat: A `vImage_CGImageFormat` structure describing the image format of the source image - /// - Parameter destinationFormat: A `vImageCVImageFormat` structure describing the image format of the destination image - /// - Parameter options: The options to use when performing this operation. - /// - /// - Returns: a vImage converter to convert a Core Graphics-formatted image to a Core Video-formatted image. - public static func make(sourceFormat: vImage_CGImageFormat, - destinationFormat: vImageCVImageFormat, - flags options: vImage.Options = .noFlags) throws -> vImageConverter { - - var error = kvImageNoError - var unmanagedConverter: Unmanaged? - - withUnsafePointer(to: sourceFormat) { src in - unmanagedConverter = vImageConverter_CreateForCGToCVImageFormat( - src, - destinationFormat, - nil, - vImage_Flags(options.rawValue), - &error) - } - - if error != kvImageNoError { - throw vImage.Error(vImageError: error) - } else if unmanagedConverter == nil { - throw vImage.Error.internalError - } - - return unmanagedConverter!.takeRetainedValue() - } - - //===----------------------------------------------------------------------===// - // - // MARK: CV -> CG - // - //===----------------------------------------------------------------------===// - - /// Creates a vImage converter that converts a Core Video-formatted image to a Core Graphics-formatted image. - /// - /// - Parameter sourceFormat: A `vImageCVImageFormat` structure describing the image format of the source image - /// - Parameter destinationFormat: A `vImage_CGImageFormat` structure describing the image format of the destination image - /// - Parameter options: The options to use when performing this operation. - /// - /// - Returns: a vImage converter to convert a Core Video-formatted image to a Core Graphics-formatted image. - public static func make(sourceFormat: vImageCVImageFormat, - destinationFormat: vImage_CGImageFormat, - flags options: vImage.Options = .noFlags) throws -> vImageConverter { - - var error = kvImageInternalError - var unmanagedConverter: Unmanaged? - - withUnsafePointer(to: destinationFormat) { dest in - unmanagedConverter = vImageConverter_CreateForCVToCGImageFormat( - sourceFormat, - dest, - nil, - vImage_Flags(options.rawValue), - &error) - } - - if error != kvImageNoError { - throw vImage.Error(vImageError: error) - } else if unmanagedConverter == nil { - throw vImage.Error.internalError - } - - return unmanagedConverter!.takeRetainedValue() - } - - //===----------------------------------------------------------------------===// - - /// Converts the pixels in a vImage buffer to another format. - /// - /// - Parameter source: The source buffer. - /// - Parameter destination: The destination buffer. - /// - Parameter options: The options to use when performing this operation. - /// - /// - Returns: `kvImageNoError`; otherwise, one of the error codes described in _Data Types and Constants. - public func convert(source: vImage_Buffer, - destination: inout vImage_Buffer, - flags options: vImage.Options = .noFlags) throws { - - var error = kvImageNoError - - withUnsafePointer(to: source) { src in - error = vImageConvert_AnyToAny(self, - src, - &destination, - nil, - vImage_Flags(options.rawValue)) - } - - if error != kvImageNoError { - throw vImage.Error(vImageError: error) - } - } -} - diff --git a/stdlib/public/Darwin/Accelerate/vImage_Error.swift b/stdlib/public/Darwin/Accelerate/vImage_Error.swift deleted file mode 100644 index 7dfa41e4c0e6f..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vImage_Error.swift +++ /dev/null @@ -1,97 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -//===----------------------------------------------------------------------===// -// -// vImage_Error -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vImage { - - /// Error codes returned by vImage operations. - public enum Error: Int, Swift.Error { - /// The vImage function completed without error. - case noError = 0 - - // The region of interest, as specified by the `srcOffsetToROI_X` and - // `srcOffsetToROI_Y` parameters and the height and width of the destination - // buffer, extends beyond the bottom edge or right edge of the source buffer. - case roiLargerThanInputBuffer = -21766 - - /// Either the kernel height, the kernel width, or both, are even. - case invalidKernelSize = -21767 - - /// The edge style specified is invalid. - case invalidEdgeStyle = -21768 - - /// The `srcOffsetToROI_X` parameter that specifies the left edge of - /// the region of interest is greater than the width of the source image. - case invalidOffset_X = -21769 - - /// The `srcOffsetToROI_X` parameter that specifies the left edge of - /// the region of interest is greater than the height of the source image. - case invalidOffset_Y = -21770 - - /// An attempt to allocate memory failed. - case memoryAllocationError = -21771 - - /// A pointer parameter is NULL and it must not be. - case nullPointerArgument = -21772 - - /// Invalid parameter. - case invalidParameter = -21773 - - /// The function requires the source and destination buffers to have - /// the same height and the same width, but they do not. - case bufferSizeMismatch = -21774 - - /// The flag is not recognized. - case unknownFlagsBit = -21775 - - /// A serious error occured inside vImage, which prevented vImage - /// from continuing. - case internalError = -21776 - - /// The vImage_Buffer.rowBytes field is invalid. - case invalidRowBytes = -21777 - - /// a `vImage_CGImageFormat` or `vImageCVImageFormatRef` contains - /// an invalid format. - case invalidImageFormat = -21778 - - /// ColorSync.framework is completely missing. - case colorSyncIsAbsent = -21779 - - /// The source images and destination images may not alias the same image data. - case outOfPlaceOperationRequired = -21780 - - /// An invalid `CGImageRef` or `CVPixelBufferRef` was passed to the function. - case invalidImageObject = -21781 - - /// A `vImageCVImageFormatRef` contains an invalid format. - case invalidCVImageFormat = -21782 - - /// Some lower level conversion APIs only support conversion among a - /// sparse matrix of image formats. - case unsupportedConversion = -21783 - - /// Core Video is absent. - case coreVideoIsAbsent = -21784 - - public init(vImageError: vImage_Error) { - self = Error(rawValue: vImageError) ?? .internalError - } - } - -} diff --git a/stdlib/public/Darwin/Accelerate/vImage_Options.swift b/stdlib/public/Darwin/Accelerate/vImage_Options.swift deleted file mode 100644 index 20f277da7290f..0000000000000 --- a/stdlib/public/Darwin/Accelerate/vImage_Options.swift +++ /dev/null @@ -1,94 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -//===----------------------------------------------------------------------===// -// -// vImage_Options -// -//===----------------------------------------------------------------------===// - -@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) -extension vImage { - - /// An option set that represents `vImage_Flags`. - /// - /// You can also use this option set with the existing vImage API with the - /// `flags` property. For example: - /// - /// vImageTentConvolve_ARGB8888(&src, &dst, nil, - /// 0, 0, 11, 11, - /// [0,0,0,0], - /// vImage_Options([.backgroundColorFill, - /// .doNotTile]).flags) - public struct Options: OptionSet { - - public init(rawValue: vImage_Flags) { - self.rawValue = rawValue - } - - public let rawValue: vImage_Flags - - public static let noFlags = Options(rawValue: vImage_Flags(kvImageNoFlags)) - - /// Operate on red, green and blue channels only. Alpha is copied from source - /// to destination. For Interleaved formats only - public static let leaveAlphaUnchanged = Options(rawValue: vImage_Flags(kvImageLeaveAlphaUnchanged)) - - /// Copy edge pixels. Convolution Only. - public static let copyInPlace = Options(rawValue: vImage_Flags(kvImageCopyInPlace)) - - /// Use the background color for missing pixels. - public static let backgroundColorFill = Options(rawValue: vImage_Flags(kvImageBackgroundColorFill)) - - /// Use the nearest pixel for missing pixels. - public static let imageExtend = Options(rawValue: vImage_Flags(kvImageEdgeExtend)) - - /// Pass to turn off internal tiling and disable internal multithreading. Use this if - /// you want to do your own tiling, or to use the Min/Max filters in place. - public static let doNotTile = Options(rawValue: vImage_Flags(kvImageDoNotTile)) - - /// Use a higher quality, slower resampling filter for Geometry operations - /// (shear, scale, rotate, affine transform, etc.) - public static let highQualityResampling = Options(rawValue: vImage_Flags(kvImageHighQualityResampling)) - - /// Use only the part of the kernel that overlaps the image. For integer kernels, - /// real_divisor = divisor * (sum of used kernel elements) / (sum of kernel elements). - /// This should preserve image brightness at the edges. Convolution only. - public static let truncateKernel = Options(rawValue: vImage_Flags(kvImageTruncateKernel)) - - /// The function will return the number of bytes required for the temp buffer. - /// If this value is negative, it is an error, per standard usage. - public static let getTempBufferSize = Options(rawValue: vImage_Flags(kvImageGetTempBufferSize)) - - /// Some functions such as vImageConverter_CreateWithCGImageFormat have so many possible error conditions - /// that developers may need more help than a simple error code to diagnose problems. When this - /// flag is set and an error is encountered, an informative error message will be logged to the Apple - /// System Logger (ASL). The output should be visible in Console.app. - public static let printDiagnosticsToConsole = Options(rawValue: vImage_Flags(kvImagePrintDiagnosticsToConsole)) - - /// Pass this flag to prevent vImage from allocating additional storage. - public static let noAllocate = Options(rawValue: vImage_Flags(kvImageNoAllocate)) - - /// Use methods that are HDR-aware, capable of providing correct results for input images with pixel values - /// outside the otherwise limited (typically [-2,2]) range. This may be slower. - public static let hdrContent = Options(rawValue: vImage_Flags(kvImageHDRContent)) - - /// Pass to disable clamping is some conversions to floating point formats. Use this if the input data - /// may describe values outside [0,1] which should be preserved. - public static let doNotClamp = Options(rawValue: vImage_Flags(kvImageDoNotClamp)) - - public var flags: vImage_Flags { - return self.rawValue - } - } - -} diff --git a/stdlib/public/Darwin/AppKit/AppKit.swift b/stdlib/public/Darwin/AppKit/AppKit.swift deleted file mode 100644 index a7162014bf72b..0000000000000 --- a/stdlib/public/Darwin/AppKit/AppKit.swift +++ /dev/null @@ -1,162 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -import Foundation -@_exported import AppKit - -extension NSCursor : __DefaultCustomPlaygroundQuickLookable { - @available(*, deprecated, message: "NSCursor._defaultCustomPlaygroundQuickLook will be removed in a future Swift version") - public var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook { - return .image(image) - } -} - -internal struct _NSViewQuickLookState { - static var views = Set() -} - -extension NSView : __DefaultCustomPlaygroundQuickLookable { - @available(*, deprecated, message: "NSView._defaultCustomPlaygroundQuickLook will be removed in a future Swift version") - public var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook { - // if you set NSView.needsDisplay, you can get yourself in a recursive scenario where the same view - // could need to draw itself in order to get a QLObject for itself, which in turn if your code was - // instrumented to log on-draw, would cause yourself to get back here and so on and so forth - // until you run out of stack and crash - // This code checks that we aren't trying to log the same view recursively - and if so just returns - // an empty view, which is probably a safer option than crashing - // FIXME: is there a way to say "cacheDisplayInRect butDoNotRedrawEvenIfISaidSo"? - if _NSViewQuickLookState.views.contains(self) { - return .view(NSImage()) - } else { - _NSViewQuickLookState.views.insert(self) - let result: PlaygroundQuickLook - if let b = bitmapImageRepForCachingDisplay(in: bounds) { - cacheDisplay(in: bounds, to: b) - result = .view(b) - } else { - result = .view(NSImage()) - } - _NSViewQuickLookState.views.remove(self) - return result - } - } -} - -// Overlays for variadics. - -public extension NSGradient { - convenience init?(colorsAndLocations objects: (NSColor, CGFloat)...) { - self.init( - colors: objects.map { $0.0 }, - atLocations: objects.map { $0.1 }, - colorSpace: NSColorSpace.genericRGB) - } -} - -// Fix the ARGV type of NSApplicationMain, which nonsensically takes -// argv as a const char**. -public func NSApplicationMain( - _ argc: Int32, _ argv: UnsafeMutablePointer?> -) -> Int32 { - return argv.withMemoryRebound(to: UnsafePointer.self, capacity: Int(argc)) { - __NSApplicationMain(argc, $0) - } -} - -extension NSApplication { - @available(swift 4) - public static func loadApplication() { - __NSApplicationLoad() - } -} - -extension NSColor : _ExpressibleByColorLiteral { - @nonobjc - public required convenience init(_colorLiteralRed red: Float, green: Float, - blue: Float, alpha: Float) { - self.init(red: CGFloat(red), green: CGFloat(green), - blue: CGFloat(blue), alpha: CGFloat(alpha)) - } -} - -public typealias _ColorLiteralType = NSColor - -extension NSImage : _ExpressibleByImageLiteral { - private convenience init!(failableImageLiteral name: String) { - self.init(named: .init(name)) - } - - @nonobjc - public required convenience init(imageLiteralResourceName name: String) { - self.init(failableImageLiteral: name) - } -} - -public typealias _ImageLiteralType = NSImage - -// Numeric backed types - -@available(swift 4) -public protocol _AppKitKitNumericRawRepresentable : RawRepresentable, Comparable - where RawValue: Comparable & Numeric { } - -extension _AppKitKitNumericRawRepresentable { - public static func <(lhs: Self, rhs: Self) -> Bool { - return lhs.rawValue < rhs.rawValue - } - - public static func +(lhs: Self, rhs: RawValue) -> Self { - return Self(rawValue: lhs.rawValue + rhs)! - } - - public static func +(lhs: RawValue, rhs: Self) -> Self { - return Self(rawValue: lhs + rhs.rawValue)! - } - - public static func -(lhs: Self, rhs: RawValue) -> Self { - return Self(rawValue: lhs.rawValue - rhs)! - } - - public static func -(lhs: Self, rhs: Self) -> RawValue { - return lhs.rawValue - rhs.rawValue - } - - public static func +=(lhs: inout Self, rhs: RawValue) { - lhs = Self(rawValue: lhs.rawValue + rhs)! - } - - public static func -=(lhs: inout Self, rhs: RawValue) { - lhs = Self(rawValue: lhs.rawValue - rhs)! - } -} - -@available(swift 4) -extension NSAppKitVersion : _AppKitKitNumericRawRepresentable { } - -@available(swift 4) -extension NSLayoutConstraint.Priority : _AppKitKitNumericRawRepresentable { } - -@available(swift 4) -extension NSStackView.VisibilityPriority : _AppKitKitNumericRawRepresentable { } - -@available(swift 4) -extension NSToolbarItem.VisibilityPriority : _AppKitKitNumericRawRepresentable { } - -@available(macOS 10.12.2, *) -@available(swift 4) -extension NSTouchBarItem.Priority : _AppKitKitNumericRawRepresentable { } - -@available(swift 4) -extension NSWindow.Level : _AppKitKitNumericRawRepresentable { } - -@available(swift 4) -extension NSFont.Weight : _AppKitKitNumericRawRepresentable { } diff --git a/stdlib/public/Darwin/AppKit/AppKit_FoundationExtensions.swift b/stdlib/public/Darwin/AppKit/AppKit_FoundationExtensions.swift deleted file mode 100644 index de20813aaab11..0000000000000 --- a/stdlib/public/Darwin/AppKit/AppKit_FoundationExtensions.swift +++ /dev/null @@ -1,82 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -import Foundation -@_exported import AppKit - -// NSCollectionView extensions -extension IndexPath { - - /// Initialize for use with `NSCollectionView`. - public init(item: Int, section: Int) { - self.init(indexes: [section, item]) - } - - /// The item of this index path, when used with `NSCollectionView`. - /// - /// - precondition: The index path must have exactly two elements. - public var item : Int { - get { - precondition(count == 2, "Invalid index path for use with NSCollectionView. This index path must contain exactly two indices specifying the section and item.") - return self[1] - } - set { - precondition(count == 2, "Invalid index path for use with NSCollectionView. This index path must contain exactly two indices specifying the section and item.") - self[1] = newValue - } - } - - /// The section of this index path, when used with `NSCollectionView`. - /// - /// - precondition: The index path must have exactly two elements. - public var section : Int { - get { - precondition(count == 2, "Invalid index path for use with NSCollectionView. This index path must contain exactly two indices specifying the section and item.") - return self[0] - } - set { - precondition(count == 2, "Invalid index path for use with NSCollectionView. This index path must contain exactly two indices specifying the section and item.") - self[0] = newValue - } - } - -} - -extension URLResourceValues { - /// Returns all thumbnails as a single NSImage. - @available(macOS 10.10, *) - public var thumbnail : NSImage? { - return allValues[URLResourceKey.thumbnailKey] as? NSImage - } - - /// The color of the assigned label. - public var labelColor: NSColor? { - return allValues[URLResourceKey.labelColorKey] as? NSColor - } - - /// The icon normally displayed for the resource - public var effectiveIcon: AnyObject? { - return allValues[URLResourceKey.effectiveIconKey] as? NSImage - } - - /// The custom icon assigned to the resource, if any (Currently not implemented) - public var customIcon: NSImage? { - return allValues[URLResourceKey.customIconKey] as? NSImage - } - - /// Returns a dictionary of NSImage objects keyed by size. - @available(macOS 10.10, *) - public var thumbnailDictionary : [URLThumbnailDictionaryItem : NSImage]? { - return allValues[URLResourceKey.thumbnailDictionaryKey] as? [URLThumbnailDictionaryItem : NSImage] - } - -} diff --git a/stdlib/public/Darwin/AppKit/CMakeLists.txt b/stdlib/public/Darwin/AppKit/CMakeLists.txt deleted file mode 100644 index de7289090159a..0000000000000 --- a/stdlib/public/Darwin/AppKit/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftAppKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - AppKit.swift - AppKit_FoundationExtensions.swift - NSError.swift - NSEvent.swift - NSGraphics.swift - NSOpenGL.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX - SWIFT_MODULE_DEPENDS_OSX Darwin CoreImage CoreGraphics Metal Dispatch IOKit Foundation CoreData QuartzCore XPC CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS AppKit - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_APPKIT_OSX} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/AppKit/NSError.swift b/stdlib/public/Darwin/AppKit/NSError.swift deleted file mode 100644 index d6fa31db22011..0000000000000 --- a/stdlib/public/Darwin/AppKit/NSError.swift +++ /dev/null @@ -1,257 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// -@_exported import AppKit - -extension CocoaError.Code { - public static var textReadInapplicableDocumentType: CocoaError.Code { - return CocoaError.Code(rawValue: 65806) - } - public static var textWriteInapplicableDocumentType: CocoaError.Code { - return CocoaError.Code(rawValue: 66062) - } - public static var serviceApplicationNotFound: CocoaError.Code { - return CocoaError.Code(rawValue: 66560) - } - public static var serviceApplicationLaunchFailed: CocoaError.Code { - return CocoaError.Code(rawValue: 66561) - } - public static var serviceRequestTimedOut: CocoaError.Code { - return CocoaError.Code(rawValue: 66562) - } - public static var serviceInvalidPasteboardData: CocoaError.Code { - return CocoaError.Code(rawValue: 66563) - } - public static var serviceMalformedServiceDictionary: CocoaError.Code { - return CocoaError.Code(rawValue: 66564) - } - public static var serviceMiscellaneousError: CocoaError.Code { - return CocoaError.Code(rawValue: 66800) - } - public static var sharingServiceNotConfigured: CocoaError.Code { - return CocoaError.Code(rawValue: 67072) - } - @available(macOS 10.13, *) - public static var fontAssetDownloadError: CocoaError.Code { - return CocoaError.Code(rawValue: 66304) - } -} - -// Names deprecated late in Swift 3 -extension CocoaError.Code { - @available(*, deprecated, renamed: "textReadInapplicableDocumentType") - public static var textReadInapplicableDocumentTypeError: CocoaError.Code { - return CocoaError.Code(rawValue: 65806) - } - @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") - public static var textWriteInapplicableDocumentTypeError: CocoaError.Code { - return CocoaError.Code(rawValue: 66062) - } - @available(*, deprecated, renamed: "serviceApplicationNotFound") - public static var serviceApplicationNotFoundError: CocoaError.Code { - return CocoaError.Code(rawValue: 66560) - } - @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") - public static var serviceApplicationLaunchFailedError: CocoaError.Code { - return CocoaError.Code(rawValue: 66561) - } - @available(*, deprecated, renamed: "serviceRequestTimedOut") - public static var serviceRequestTimedOutError: CocoaError.Code { - return CocoaError.Code(rawValue: 66562) - } - @available(*, deprecated, renamed: "serviceInvalidPasteboardData") - public static var serviceInvalidPasteboardDataError: CocoaError.Code { - return CocoaError.Code(rawValue: 66563) - } - @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") - public static var serviceMalformedServiceDictionaryError: CocoaError.Code { - return CocoaError.Code(rawValue: 66564) - } - @available(*, deprecated, renamed: "serviceMiscellaneousError") - public static var serviceMiscellaneous: CocoaError.Code { - return CocoaError.Code(rawValue: 66800) - } - @available(*, deprecated, renamed: "sharingServiceNotConfigured") - public static var sharingServiceNotConfiguredError: CocoaError.Code { - return CocoaError.Code(rawValue: 67072) - } -} - -extension CocoaError { - public static var textReadInapplicableDocumentType: CocoaError.Code { - return CocoaError.Code(rawValue: 65806) - } - public static var textWriteInapplicableDocumentType: CocoaError.Code { - return CocoaError.Code(rawValue: 66062) - } - public static var serviceApplicationNotFound: CocoaError.Code { - return CocoaError.Code(rawValue: 66560) - } - public static var serviceApplicationLaunchFailed: CocoaError.Code { - return CocoaError.Code(rawValue: 66561) - } - public static var serviceRequestTimedOut: CocoaError.Code { - return CocoaError.Code(rawValue: 66562) - } - public static var serviceInvalidPasteboardData: CocoaError.Code { - return CocoaError.Code(rawValue: 66563) - } - public static var serviceMalformedServiceDictionary: CocoaError.Code { - return CocoaError.Code(rawValue: 66564) - } - public static var serviceMiscellaneous: CocoaError.Code { - return CocoaError.Code(rawValue: 66800) - } - public static var sharingServiceNotConfigured: CocoaError.Code { - return CocoaError.Code(rawValue: 67072) - } - @available(macOS 10.13, *) - public static var fontAssetDownloadError: CocoaError.Code { - return CocoaError.Code(rawValue: 66304) - } -} - -// Names deprecated late in Swift 3 -extension CocoaError { - @available(*, deprecated, renamed: "textReadInapplicableDocumentType") - public static var textReadInapplicableDocumentTypeError: CocoaError.Code { - return CocoaError.Code(rawValue: 65806) - } - @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") - public static var textWriteInapplicableDocumentTypeError: CocoaError.Code { - return CocoaError.Code(rawValue: 66062) - } - @available(*, deprecated, renamed: "serviceApplicationNotFound") - public static var serviceApplicationNotFoundError: CocoaError.Code { - return CocoaError.Code(rawValue: 66560) - } - @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") - public static var serviceApplicationLaunchFailedError: CocoaError.Code { - return CocoaError.Code(rawValue: 66561) - } - @available(*, deprecated, renamed: "serviceRequestTimedOut") - public static var serviceRequestTimedOutError: CocoaError.Code { - return CocoaError.Code(rawValue: 66562) - } - @available(*, deprecated, renamed: "serviceInvalidPasteboardData") - public static var serviceInvalidPasteboardDataError: CocoaError.Code { - return CocoaError.Code(rawValue: 66563) - } - @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") - public static var serviceMalformedServiceDictionaryError: CocoaError.Code { - return CocoaError.Code(rawValue: 66564) - } - @available(*, deprecated, renamed: "serviceMiscellaneous") - public static var serviceMiscellaneousError: CocoaError.Code { - return CocoaError.Code(rawValue: 66800) - } - @available(*, deprecated, renamed: "sharingServiceNotConfigured") - public static var sharingServiceNotConfiguredError: CocoaError.Code { - return CocoaError.Code(rawValue: 67072) - } -} - -extension CocoaError { - public var isServiceError: Bool { - return code.rawValue >= 66560 && code.rawValue <= 66817 - } - - public var isSharingServiceError: Bool { - return code.rawValue >= 67072 && code.rawValue <= 67327 - } - - public var isTextReadWriteError: Bool { - return code.rawValue >= 65792 && code.rawValue <= 66303 - } - - @available(macOS 10.13, *) - public var isFontError: Bool { - return code.rawValue >= 66304 && code.rawValue <= 66335 - } -} - -extension CocoaError { - @available(*, deprecated, renamed: "textReadInapplicableDocumentType") - public static var TextReadInapplicableDocumentTypeError: CocoaError.Code { - return CocoaError.Code(rawValue: 65806) - } - @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") - public static var TextWriteInapplicableDocumentTypeError: CocoaError.Code { - return CocoaError.Code(rawValue: 66062) - } - @available(*, deprecated, renamed: "serviceApplicationNotFound") - public static var ServiceApplicationNotFoundError: CocoaError.Code { - return CocoaError.Code(rawValue: 66560) - } - @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") - public static var ServiceApplicationLaunchFailedError: CocoaError.Code { - return CocoaError.Code(rawValue: 66561) - } - @available(*, deprecated, renamed: "serviceRequestTimedOut") - public static var ServiceRequestTimedOutError: CocoaError.Code { - return CocoaError.Code(rawValue: 66562) - } - @available(*, deprecated, renamed: "serviceInvalidPasteboardData") - public static var ServiceInvalidPasteboardDataError: CocoaError.Code { - return CocoaError.Code(rawValue: 66563) - } - @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") - public static var ServiceMalformedServiceDictionaryError: CocoaError.Code { - return CocoaError.Code(rawValue: 66564) - } - @available(*, deprecated, renamed: "serviceMiscellaneous") - public static var ServiceMiscellaneousError: CocoaError.Code { - return CocoaError.Code(rawValue: 66800) - } - @available(*, deprecated, renamed: "sharingServiceNotConfigured") - public static var SharingServiceNotConfiguredError: CocoaError.Code { - return CocoaError.Code(rawValue: 67072) - } -} - -extension CocoaError.Code { - @available(*, deprecated, renamed: "textReadInapplicableDocumentType") - public static var TextReadInapplicableDocumentTypeError: CocoaError.Code { - return CocoaError.Code(rawValue: 65806) - } - @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") - public static var TextWriteInapplicableDocumentTypeError: CocoaError.Code { - return CocoaError.Code(rawValue: 66062) - } - @available(*, deprecated, renamed: "serviceApplicationNotFound") - public static var ServiceApplicationNotFoundError: CocoaError.Code { - return CocoaError.Code(rawValue: 66560) - } - @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") - public static var ServiceApplicationLaunchFailedError: CocoaError.Code { - return CocoaError.Code(rawValue: 66561) - } - @available(*, deprecated, renamed: "serviceRequestTimedOut") - public static var ServiceRequestTimedOutError: CocoaError.Code { - return CocoaError.Code(rawValue: 66562) - } - @available(*, deprecated, renamed: "serviceInvalidPasteboardData") - public static var ServiceInvalidPasteboardDataError: CocoaError.Code { - return CocoaError.Code(rawValue: 66563) - } - @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") - public static var ServiceMalformedServiceDictionaryError: CocoaError.Code { - return CocoaError.Code(rawValue: 66564) - } - @available(*, deprecated, renamed: "serviceMiscellaneous") - public static var ServiceMiscellaneousError: CocoaError.Code { - return CocoaError.Code(rawValue: 66800) - } - @available(*, deprecated, renamed: "sharingServiceNotConfigured") - public static var SharingServiceNotConfiguredError: CocoaError.Code { - return CocoaError.Code(rawValue: 67072) - } -} diff --git a/stdlib/public/Darwin/AppKit/NSEvent.swift b/stdlib/public/Darwin/AppKit/NSEvent.swift deleted file mode 100644 index ed4d2ef7117fb..0000000000000 --- a/stdlib/public/Darwin/AppKit/NSEvent.swift +++ /dev/null @@ -1,162 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import AppKit - -extension NSEvent { - public struct SpecialKey : RawRepresentable, Equatable, Hashable { - public init(rawValue: Int) { - self.rawValue = rawValue - } - public let rawValue: Int - public var unicodeScalar: Unicode.Scalar { - return Unicode.Scalar(rawValue)! - } - } - - /// Returns nil if the receiver is not a "special" key event. - open var specialKey: SpecialKey? { - guard let unicodeScalars = charactersIgnoringModifiers?.unicodeScalars else { - return nil - } - guard unicodeScalars.count == 1 else { - return nil - } - guard let codePoint = unicodeScalars.first?.value else { - return nil - } - switch codePoint { - case 0x0003: - return .enter - - case 0x0008: - return .backspace - - case 0x0009: - return .tab - - case 0x000a: - return .newline - - case 0x000c: - return .formFeed - - case 0x000d: - return .carriageReturn - - case 0x0019: - return .backTab - - case 0x007f: - return .delete - - case 0x2028: - return .lineSeparator - - case 0x2029: - return .paragraphSeparator - - case 0xF700..<0xF900: - return SpecialKey(rawValue: Int(codePoint)) - - default: - return nil - } - } -} - -extension NSEvent.SpecialKey { - - static public let upArrow = NSEvent.SpecialKey(rawValue: 0xF700) - static public let downArrow = NSEvent.SpecialKey(rawValue: 0xF701) - static public let leftArrow = NSEvent.SpecialKey(rawValue: 0xF702) - static public let rightArrow = NSEvent.SpecialKey(rawValue: 0xF703) - static public let f1 = NSEvent.SpecialKey(rawValue: 0xF704) - static public let f2 = NSEvent.SpecialKey(rawValue: 0xF705) - static public let f3 = NSEvent.SpecialKey(rawValue: 0xF706) - static public let f4 = NSEvent.SpecialKey(rawValue: 0xF707) - static public let f5 = NSEvent.SpecialKey(rawValue: 0xF708) - static public let f6 = NSEvent.SpecialKey(rawValue: 0xF709) - static public let f7 = NSEvent.SpecialKey(rawValue: 0xF70A) - static public let f8 = NSEvent.SpecialKey(rawValue: 0xF70B) - static public let f9 = NSEvent.SpecialKey(rawValue: 0xF70C) - static public let f10 = NSEvent.SpecialKey(rawValue: 0xF70D) - static public let f11 = NSEvent.SpecialKey(rawValue: 0xF70E) - static public let f12 = NSEvent.SpecialKey(rawValue: 0xF70F) - static public let f13 = NSEvent.SpecialKey(rawValue: 0xF710) - static public let f14 = NSEvent.SpecialKey(rawValue: 0xF711) - static public let f15 = NSEvent.SpecialKey(rawValue: 0xF712) - static public let f16 = NSEvent.SpecialKey(rawValue: 0xF713) - static public let f17 = NSEvent.SpecialKey(rawValue: 0xF714) - static public let f18 = NSEvent.SpecialKey(rawValue: 0xF715) - static public let f19 = NSEvent.SpecialKey(rawValue: 0xF716) - static public let f20 = NSEvent.SpecialKey(rawValue: 0xF717) - static public let f21 = NSEvent.SpecialKey(rawValue: 0xF718) - static public let f22 = NSEvent.SpecialKey(rawValue: 0xF719) - static public let f23 = NSEvent.SpecialKey(rawValue: 0xF71A) - static public let f24 = NSEvent.SpecialKey(rawValue: 0xF71B) - static public let f25 = NSEvent.SpecialKey(rawValue: 0xF71C) - static public let f26 = NSEvent.SpecialKey(rawValue: 0xF71D) - static public let f27 = NSEvent.SpecialKey(rawValue: 0xF71E) - static public let f28 = NSEvent.SpecialKey(rawValue: 0xF71F) - static public let f29 = NSEvent.SpecialKey(rawValue: 0xF720) - static public let f30 = NSEvent.SpecialKey(rawValue: 0xF721) - static public let f31 = NSEvent.SpecialKey(rawValue: 0xF722) - static public let f32 = NSEvent.SpecialKey(rawValue: 0xF723) - static public let f33 = NSEvent.SpecialKey(rawValue: 0xF724) - static public let f34 = NSEvent.SpecialKey(rawValue: 0xF725) - static public let f35 = NSEvent.SpecialKey(rawValue: 0xF726) - static public let insert = NSEvent.SpecialKey(rawValue: 0xF727) - static public let deleteForward = NSEvent.SpecialKey(rawValue: 0xF728) - static public let home = NSEvent.SpecialKey(rawValue: 0xF729) - static public let begin = NSEvent.SpecialKey(rawValue: 0xF72A) - static public let end = NSEvent.SpecialKey(rawValue: 0xF72B) - static public let pageUp = NSEvent.SpecialKey(rawValue: 0xF72C) - static public let pageDown = NSEvent.SpecialKey(rawValue: 0xF72D) - static public let printScreen = NSEvent.SpecialKey(rawValue: 0xF72E) - static public let scrollLock = NSEvent.SpecialKey(rawValue: 0xF72F) - static public let pause = NSEvent.SpecialKey(rawValue: 0xF730) - static public let sysReq = NSEvent.SpecialKey(rawValue: 0xF731) - static public let `break` = NSEvent.SpecialKey(rawValue: 0xF732) - static public let reset = NSEvent.SpecialKey(rawValue: 0xF733) - static public let stop = NSEvent.SpecialKey(rawValue: 0xF734) - static public let menu = NSEvent.SpecialKey(rawValue: 0xF735) - static public let user = NSEvent.SpecialKey(rawValue: 0xF736) - static public let system = NSEvent.SpecialKey(rawValue: 0xF737) - static public let print = NSEvent.SpecialKey(rawValue: 0xF738) - static public let clearLine = NSEvent.SpecialKey(rawValue: 0xF739) - static public let clearDisplay = NSEvent.SpecialKey(rawValue: 0xF73A) - static public let insertLine = NSEvent.SpecialKey(rawValue: 0xF73B) - static public let deleteLine = NSEvent.SpecialKey(rawValue: 0xF73C) - static public let insertCharacter = NSEvent.SpecialKey(rawValue: 0xF73D) - static public let deleteCharacter = NSEvent.SpecialKey(rawValue: 0xF73E) - static public let prev = NSEvent.SpecialKey(rawValue: 0xF73F) - static public let next = NSEvent.SpecialKey(rawValue: 0xF740) - static public let select = NSEvent.SpecialKey(rawValue: 0xF741) - static public let execute = NSEvent.SpecialKey(rawValue: 0xF742) - static public let undo = NSEvent.SpecialKey(rawValue: 0xF743) - static public let redo = NSEvent.SpecialKey(rawValue: 0xF744) - static public let find = NSEvent.SpecialKey(rawValue: 0xF745) - static public let help = NSEvent.SpecialKey(rawValue: 0xF746) - static public let modeSwitch = NSEvent.SpecialKey(rawValue: 0xF747) - - static public let enter = NSEvent.SpecialKey(rawValue: 0x0003) - static public let backspace = NSEvent.SpecialKey(rawValue: 0x0008) - static public let tab = NSEvent.SpecialKey(rawValue: 0x0009) - static public let newline = NSEvent.SpecialKey(rawValue: 0x000a) - static public let formFeed = NSEvent.SpecialKey(rawValue: 0x000c) - static public let carriageReturn = NSEvent.SpecialKey(rawValue: 0x000d) - static public let backTab = NSEvent.SpecialKey(rawValue: 0x0019) - static public let delete = NSEvent.SpecialKey(rawValue: 0x007f) - static public let lineSeparator = NSEvent.SpecialKey(rawValue: 0x2028) - static public let paragraphSeparator = NSEvent.SpecialKey(rawValue: 0x2029) -} diff --git a/stdlib/public/Darwin/AppKit/NSGraphics.swift b/stdlib/public/Darwin/AppKit/NSGraphics.swift deleted file mode 100644 index f4e2a7c77a267..0000000000000 --- a/stdlib/public/Darwin/AppKit/NSGraphics.swift +++ /dev/null @@ -1,215 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -import Foundation -@_exported import AppKit - -extension NSRect { - /// Fills this rect in the current NSGraphicsContext in the context's fill - /// color. - /// The compositing operation of the fill defaults to the context's - /// compositing operation, not necessarily using `.copy` like `NSRectFill()`. - /// - precondition: There must be a set current NSGraphicsContext. - @available(swift 4) - public func fill(using operation: NSCompositingOperation = - NSGraphicsContext.current?.compositingOperation ?? .sourceOver) { - precondition(NSGraphicsContext.current != nil, - "There must be a set current NSGraphicsContext") - __NSRectFillUsingOperation(self, operation) - } - - /// Draws a frame around the inside of this rect in the current - /// NSGraphicsContext in the context's fill color - /// The compositing operation of the fill defaults to the context's - /// compositing operation, not necessarily using `.copy` like `NSFrameRect()`. - /// - precondition: There must be a set current NSGraphicsContext. - @available(swift 4) - public func frame(withWidth width: CGFloat = 1.0, - using operation: NSCompositingOperation = - NSGraphicsContext.current?.compositingOperation ?? .sourceOver) { - precondition(NSGraphicsContext.current != nil, - "There must be a set current NSGraphicsContext") - __NSFrameRectWithWidthUsingOperation(self, width, operation) - } - - /// Modifies the current graphics context clipping path by intersecting it - /// with this rect. - /// This permanently modifies the graphics state, so the current state should - /// be saved beforehand and restored afterwards. - /// - precondition: There must be a set current NSGraphicsContext. - @available(swift 4) - public func clip() { - precondition(NSGraphicsContext.current != nil, - "There must be a set current NSGraphicsContext") - __NSRectClip(self) - } -} - -extension Sequence where Iterator.Element == NSRect { - /// Fills this list of rects in the current NSGraphicsContext in the context's - /// fill color. - /// The compositing operation of the fill defaults to the context's - /// compositing operation, not necessarily using `.copy` like `NSRectFill()`. - /// - precondition: There must be a set current NSGraphicsContext. - @available(swift 4) - public func fill(using operation: NSCompositingOperation = - NSGraphicsContext.current?.compositingOperation ?? .sourceOver) { - precondition(NSGraphicsContext.current != nil, - "There must be a set current NSGraphicsContext") - let rects = Array(self) - let count = rects.count - guard count > 0 else { return } - rects.withUnsafeBufferPointer { rectBufferPointer in - guard let rectArray = rectBufferPointer.baseAddress else { return } - __NSRectFillListUsingOperation(rectArray, count, operation) - } - } - - /// Modifies the current graphics context clipping path by intersecting it - /// with the graphical union of this list of rects - /// This permanently modifies the graphics state, so the current state should - /// be saved beforehand and restored afterwards. - /// - precondition: There must be a set current NSGraphicsContext. - @available(swift 4) - public func clip() { - precondition(NSGraphicsContext.current != nil, - "There must be a set current NSGraphicsContext") - let rects = Array(self) - let count = rects.count - guard count > 0 else { return } - rects.withUnsafeBufferPointer { rectBufferPointer in - guard let rectArray = rectBufferPointer.baseAddress else { return } - __NSRectClipList(rectArray, count) - } - } -} - -extension Sequence where Iterator.Element == (CGRect, NSColor) { - /// Fills this list of rects in the current NSGraphicsContext with that rect's - /// associated color - /// The compositing operation of the fill defaults to the context's - /// compositing operation, not necessarily using `.copy` like `NSRectFill()`. - /// - precondition: There must be a set current NSGraphicsContext. - @available(swift 4) - public func fill(using operation: NSCompositingOperation = - NSGraphicsContext.current?.compositingOperation ?? .sourceOver) { - precondition(NSGraphicsContext.current != nil, - "There must be a set current NSGraphicsContext") - let rects = map { $0.0 } - let colors = map { $0.1 } - let count = rects.count - guard count > 0 else { return } - rects.withUnsafeBufferPointer { rectBufferPointer in - colors.withUnsafeBufferPointer { colorBufferPointer in - guard let rectArray = rectBufferPointer.baseAddress else { return } - guard let colorArray = colorBufferPointer.baseAddress else { return } - __NSRectFillListWithColorsUsingOperation( - rectArray, colorArray, count, operation) - } - } - } -} - -extension Sequence where Iterator.Element == (CGRect, gray: CGFloat) { - /// Fills this list of rects in the current NSGraphicsContext with that rect's - /// associated gray component value in the DeviceGray color space. - /// The compositing operation of the fill defaults to the context's - /// compositing operation, not necessarily using `.copy` like - /// `NSRectFillListWithGrays()`. - /// - precondition: There must be a set current NSGraphicsContext. - @available(swift 4) - public func fill(using operation: NSCompositingOperation = - NSGraphicsContext.current?.compositingOperation ?? .sourceOver) { - // NSRectFillListWithGrays does not have a variant taking an operation, but - // is added here for consistency with the other drawing operations. - guard let graphicsContext = NSGraphicsContext.current else { - fatalError("There must be a set current NSGraphicsContext") - } - let cgContext: CGContext - if #available(macOS 10.10, *) { - cgContext = graphicsContext.cgContext - } else { - cgContext = Unmanaged.fromOpaque( - graphicsContext.graphicsPort).takeUnretainedValue() - } - cgContext.saveGState() - forEach { - cgContext.setFillColor(gray: $0.gray, alpha: 1.0) - __NSRectFillUsingOperation($0.0, operation) - } - cgContext.restoreGState() - } -} - -extension NSWindow.Depth { - @available(swift 4) - public static func bestDepth( - colorSpaceName: NSColorSpaceName, - bitsPerSample: Int, - bitsPerPixel: Int, - isPlanar: Bool - ) -> (NSWindow.Depth, isExactMatch: Bool) { - var isExactMatch: ObjCBool = false - let depth = __NSBestDepth( - colorSpaceName, - bitsPerSample, bitsPerPixel, isPlanar, &isExactMatch) - return (depth, isExactMatch: isExactMatch.boolValue) - } - @available(swift 4) - public static var availableDepths: [NSWindow.Depth] { - // __NSAvailableWindowDepths is NULL terminated, the length is not known up front - let depthsCArray = __NSAvailableWindowDepths() - var depths: [NSWindow.Depth] = [] - var length = 0 - var depth = depthsCArray[length] - while depth.rawValue != 0 { - depths.append(depth) - length += 1 - depth = depthsCArray[length] - } - return depths - } -} - -extension NSAnimationEffect { - // NOTE: older overlays called this class _CompletionHandlerDelegate. - // The two must coexist without a conflicting ObjC class name, so it - // was renamed. The old name must not be used in the new runtime. - private class __CompletionHandlerDelegate : NSObject { - var completionHandler: () -> Void = { } - @objc func animationEffectDidEnd(_ contextInfo: UnsafeMutableRawPointer?) { - completionHandler() - } - } - @available(swift 4) - public func show(centeredAt centerLocation: NSPoint, size: NSSize, - completionHandler: @escaping () -> Void = { }) { - let delegate = __CompletionHandlerDelegate() - delegate.completionHandler = completionHandler - // Note that the delegate of `__NSShowAnimationEffect` is retained for the - // duration of the animation. - __NSShowAnimationEffect( - self, - centerLocation, - size, - delegate, - #selector(__CompletionHandlerDelegate.animationEffectDidEnd(_:)), - nil) - } -} - -extension NSSound { - @available(swift 4) - public static func beep() { - __NSBeep() - } -} diff --git a/stdlib/public/Darwin/AppKit/NSOpenGL.swift b/stdlib/public/Darwin/AppKit/NSOpenGL.swift deleted file mode 100644 index 02f967dae5fef..0000000000000 --- a/stdlib/public/Darwin/AppKit/NSOpenGL.swift +++ /dev/null @@ -1,38 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -import Foundation -@_exported import AppKit - -extension NSOpenGLGlobalOption { - @available(swift 4) - public var globalValue: GLint { - get { - var value: GLint = 0 - __NSOpenGLGetOption(self, &value) - return value - } - set { - __NSOpenGLSetOption(self, newValue) - } - } -} - -extension NSOpenGLContext { - @available(swift 4) - public static var openGLVersion: (major: GLint, minor: GLint) { - var major: GLint = 0 - var minor: GLint = 0 - __NSOpenGLGetVersion(&major, &minor) - return (major: major, minor: minor) - } -} diff --git a/stdlib/public/Darwin/AssetsLibrary/ALAssetsLibrary.swift b/stdlib/public/Darwin/AssetsLibrary/ALAssetsLibrary.swift deleted file mode 100644 index bad33f5eadced..0000000000000 --- a/stdlib/public/Darwin/AssetsLibrary/ALAssetsLibrary.swift +++ /dev/null @@ -1,32 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import AssetsLibrary // Clang module - -extension ALAssetsLibrary { - @available(iOS, deprecated: 9.0) - @nonobjc - public func enumerateGroupsWithTypes(_ types: UInt32, - usingBlock enumerationBlock: ALAssetsLibraryGroupsEnumerationResultsBlock!, - failureBlock: ALAssetsLibraryAccessFailureBlock!) { - var types = types - if types == ALAssetsGroupAll { - types = ALAssetsGroupLibrary | ALAssetsGroupAlbum | ALAssetsGroupEvent | - ALAssetsGroupFaces | ALAssetsGroupSavedPhotos | - ALAssetsGroupPhotoStream - } - return enumerateGroups( - withTypes: ALAssetsGroupType(types), - using: enumerationBlock, - failureBlock: failureBlock) - } -} diff --git a/stdlib/public/Darwin/AssetsLibrary/CMakeLists.txt b/stdlib/public/Darwin/AssetsLibrary/CMakeLists.txt deleted file mode 100644 index 4f893f26a514f..0000000000000 --- a/stdlib/public/Darwin/AssetsLibrary/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftAssetsLibrary ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - ALAssetsLibrary.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS IOS IOS_SIMULATOR - SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS AssetsLibrary - - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_ASSETSLIBRARY_IOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/CMakeLists.txt b/stdlib/public/Darwin/CMakeLists.txt index 3e2846d44445f..b8be8dfc71188 100644 --- a/stdlib/public/Darwin/CMakeLists.txt +++ b/stdlib/public/Darwin/CMakeLists.txt @@ -14,51 +14,12 @@ if(SWIFT_BUILD_STATIC_SDK_OVERLAY) endif() set(all_overlays - Accelerate - AppKit - ARKit - AssetsLibrary - AVFoundation - CallKit - CloudKit - Compression - Contacts - CoreAudio - CoreData CoreFoundation CoreGraphics - CoreImage - CoreLocation - CoreMedia - CryptoTokenKit Dispatch Foundation - GameplayKit - GLKit - HomeKit - IOKit - Intents - MapKit - MediaPlayer - Metal - MetalKit - ModelIO - NaturalLanguage - Network ObjectiveC - OpenCL - os - Photos - QuartzCore - SafariServices - SceneKit - simd - SpriteKit - UIKit - Vision - WatchKit XCTest - XPC ) if(DEFINED SWIFT_OVERLAY_TARGETS) diff --git a/stdlib/public/Darwin/CallKit/CMakeLists.txt b/stdlib/public/Darwin/CallKit/CMakeLists.txt deleted file mode 100644 index f44e1df43457f..0000000000000 --- a/stdlib/public/Darwin/CallKit/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftCallKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - CXProviderConfiguration.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS IOS IOS_SIMULATOR - SWIFT_MODULE_DEPENDS_IOS Darwin Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS_WEAK CallKit - - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_CALLKIT_IOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/CallKit/CXProviderConfiguration.swift b/stdlib/public/Darwin/CallKit/CXProviderConfiguration.swift deleted file mode 100644 index bb58f43d5dc76..0000000000000 --- a/stdlib/public/Darwin/CallKit/CXProviderConfiguration.swift +++ /dev/null @@ -1,30 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CallKit -import Foundation - -@available(iOS 10.0, *) -extension CXProviderConfiguration { - @nonobjc - public final var supportedHandleTypes: Set { - get { - return Set(__supportedHandleTypes.map { - CXHandle.HandleType(rawValue: $0.intValue)! - }) - } - set { - __supportedHandleTypes = - Set(newValue.lazy.map { $0.rawValue as NSNumber }) - } - } -} diff --git a/stdlib/public/Darwin/CloudKit/CKError.swift b/stdlib/public/Darwin/CloudKit/CKError.swift deleted file mode 100644 index eb280b9a6e7cc..0000000000000 --- a/stdlib/public/Darwin/CloudKit/CKError.swift +++ /dev/null @@ -1,49 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CloudKit -import Foundation - -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKError { - /// Retrieve partial error results associated by item ID. - public var partialErrorsByItemID: [AnyHashable: Error]? { - return userInfo[CKPartialErrorsByItemIDKey] as? [AnyHashable: NSError] - as [AnyHashable: Error]? - } - - /// The original CKRecord object that you used as the basis for - /// making your changes. - public var ancestorRecord: CKRecord? { - return userInfo[CKRecordChangedErrorAncestorRecordKey] as? CKRecord - } - - /// The CKRecord object that was found on the server. Use this - /// record as the basis for merging your changes. - public var serverRecord: CKRecord? { - return userInfo[CKRecordChangedErrorServerRecordKey] as? CKRecord - } - - /// The CKRecord object that you tried to save. This record is based - /// on the record in the CKRecordChangedErrorAncestorRecordKey key - /// but contains the additional changes you made. - public var clientRecord: CKRecord? { - return userInfo[CKRecordChangedErrorClientRecordKey] as? CKRecord - } - - /// The number of seconds after which you may retry a request. This - /// key may be included in an error of type - /// `CKErrorServiceUnavailable` or `CKErrorRequestRateLimited`. - public var retryAfterSeconds: Double? { - return userInfo[CKErrorRetryAfterKey] as? Double - } -} diff --git a/stdlib/public/Darwin/CloudKit/CKFetchRecordZoneChangesOperation.swift b/stdlib/public/Darwin/CloudKit/CKFetchRecordZoneChangesOperation.swift deleted file mode 100644 index 1b146b38b3b98..0000000000000 --- a/stdlib/public/Darwin/CloudKit/CKFetchRecordZoneChangesOperation.swift +++ /dev/null @@ -1,43 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CloudKit // Clang module - -@nonobjc -@available(macOS 10.14, iOS 12.0, tvOS 12.0, watchOS 5.0, *) -extension CKFetchRecordZoneChangesOperation.ZoneConfiguration { - /** - Declares which user-defined keys should be fetched and added to the resulting CKRecords. - - If nil, declares the entire record should be downloaded. If set to an empty array, declares that no user fields should be downloaded. - Defaults to nil. - */ - @available(swift 4.2) - public var desiredKeys: [CKRecord.FieldKey]? { - get { return self.__desiredKeys } - set { self.__desiredKeys = newValue } - } - - @available(swift 4.2) - public convenience init(previousServerChangeToken: CKServerChangeToken? = nil, resultsLimit: Int? = nil, desiredKeys: [CKRecord.FieldKey]? = nil) { - self.init() - if let previousServerChangeToken = previousServerChangeToken { - self.previousServerChangeToken = previousServerChangeToken - } - if let resultsLimit = resultsLimit { - self.resultsLimit = resultsLimit - } - if let desiredKeys = desiredKeys { - self.desiredKeys = desiredKeys - } - } -} diff --git a/stdlib/public/Darwin/CloudKit/CKRecord.swift b/stdlib/public/Darwin/CloudKit/CKRecord.swift deleted file mode 100644 index 1438b03756d8a..0000000000000 --- a/stdlib/public/Darwin/CloudKit/CKRecord.swift +++ /dev/null @@ -1,74 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CloudKit - -// MARK: - Iterate over records - -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -public struct CKRecordKeyValueIterator : IteratorProtocol { - private var keyArray: [CKRecord.FieldKey] - private var record: CKRecord - private var index: Array.Index - - fileprivate init(_ record: CKRecord) { - self.record = record - keyArray = record.allKeys() - index = keyArray.startIndex - } - - public mutating func next() -> (CKRecord.FieldKey, CKRecordValueProtocol)? { - var key: CKRecord.FieldKey? = nil - var objcValue: __CKRecordObjCValue? = nil - while objcValue == nil { - guard index < keyArray.endIndex else { return nil } - key = keyArray[index] - objcValue = record[key!] - index = index.advanced(by: 1) - } - - let swiftValue = objcValue!.asSwiftNativeValue() - - return (key!, swiftValue) - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKRecord : Sequence { - public func makeIterator() -> CKRecordKeyValueIterator { - return CKRecordKeyValueIterator(self) - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKRecord { - public typealias RecordType = String - public typealias FieldKey = String - - @available(swift 4.2) - public enum SystemType { - public static let userRecord: CKRecord.RecordType = __CKRecordTypeUserRecord - @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) - public static let share: CKRecord.RecordType = __CKRecordTypeShare - } - - @available(swift 4.2) - public enum SystemFieldKey { - @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) - public static let parent: CKRecord.FieldKey = __CKRecordParentKey - @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) - public static let share: CKRecord.FieldKey = __CKRecordShareKey - } -} - diff --git a/stdlib/public/Darwin/CloudKit/CKRecordValue.swift b/stdlib/public/Darwin/CloudKit/CKRecordValue.swift deleted file mode 100644 index 4ff765b5e2913..0000000000000 --- a/stdlib/public/Darwin/CloudKit/CKRecordValue.swift +++ /dev/null @@ -1,288 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CloudKit - -// __CKRecordObjCValue - an ObjC object that ObjectiveC clients use as CKRecord values -// CKRecordValueProtocol - a struct or class used only by Swift clients as CKRecord values -// CKRecordValueConvertible - an ObjectiveC object that should be converted to a native Swift type before being used in Swift clients. -// CKObjCRecordValueConvertible - a Swift struct or object that should be converted to a CKRecordObjCValue when set on a CKRecord - -/* CKRecordValueProtocol CKObjCRecordValueConvertible - __CKRecordObjCValue CKRecordValueConvertible -----------------|-----------|-----------|-----------|----------- - String | | X | | X - Date | | X | | X - Data | | X | | X - Bool | | X | | X - Int | | X | | X - UInt | | X | | X - Float | | X | | X - Double | | X | | X - [U]Int8 et al| | X | | X - Int64 | | X | | X - Array | | X | | X - NSString | X | X | X | - NSDate | X | X | X | - NSData | X | X | X | - NSNumber | X | X | X | - NSArray | X | X | X | - CKReference | X | X | | - aka CKRecord.Reference - CKAsset | X | X | | - CLLocation | X | X | | - - */ - -// MARK: - Protocols for bridging record value types - -/// Anything that can be a record value in Swift. -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -public protocol CKRecordValueProtocol {} - -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -public typealias CKRecordValue = __CKRecordObjCValue - -// A Swift data type that is convertible to and from a __CKRecordObjCValue -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -private protocol CKObjCRecordValueConvertible : CKRecordValueProtocol { - // Convert to __CKRecordObjCValue - func objcRecordValue() -> __CKRecordObjCValue - // Convert from __CKRecordObjCValue - static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> Self -} - -// An ObjC data type that is more naturally represented as a native Swift type when pulled from a CKRecord -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -internal protocol CKRecordValueConvertible : __CKRecordObjCValue { - // Convert to CKRecordValueProtocols - func swiftNativeValue() -> CKRecordValueProtocol -} - -// MARK: - Converting between record value types - -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension __CKRecordObjCValue { - internal func asSwiftNativeValue() -> CKRecordValueProtocol { - let swiftValue: CKRecordValueProtocol - if let convertibleObjcRecordValue = self as? CKRecordValueConvertible { - swiftValue = convertibleObjcRecordValue.swiftNativeValue() - } else { - swiftValue = self as! CKRecordValueProtocol - } - return swiftValue - } -} - -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKRecordValueProtocol { - fileprivate func asObjCRecordValue() -> __CKRecordObjCValue { - let objcValue: __CKRecordObjCValue - if let convertibleSwiftRecordValue = self as? CKObjCRecordValueConvertible { - objcValue = convertibleSwiftRecordValue.objcRecordValue() - } else { - objcValue = self as! __CKRecordObjCValue - } - return objcValue - } -} - -// MARK: - Get and Set RecordValues on records - -@available(macOS 10.11, iOS 9.0, watchOS 3.0, *) -extension CKRecordKeyValueSetting { - @nonobjc - public subscript(key: CKRecord.FieldKey) -> T? { - get { - if let objcValue: __CKRecordObjCValue = self.object(forKey: key) { - /* I'd really like to do this statically, by implementing a separate subscript that takes . But that doesn't seem to work: Can't overload subscript generics with inherited protocols in protocol extension */ - if let ConvertibleT = T.self as? CKObjCRecordValueConvertible.Type { - return (ConvertibleT.fromObjcRecordValue(objcValue) as! T) - } else { - return (objcValue.asSwiftNativeValue() as! T) - } - } - return nil - } - set { - self[key] = newValue?.asObjCRecordValue() - } - } - - @nonobjc - public subscript(key: CKRecord.FieldKey) -> CKRecordValueProtocol? { - get { - if let objcValue: __CKRecordObjCValue = self.object(forKey: key) { - return objcValue.asSwiftNativeValue() - } - return nil - } - set { - self[key] = newValue?.asObjCRecordValue() - } - } -} - -// MARK: - CKRecord Value Protocol conformance - -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKObjCRecordValueConvertible { - static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> Self { - return objcRecordValue as! Self - } -} - -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension String : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return self as NSString } -} - -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension Date : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return self as NSDate } -} - -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension Data : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return self as NSData } -} - -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension Bool : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return NSNumber(value: self) } - fileprivate static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> Bool { return (objcRecordValue as! NSNumber).boolValue } -} -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension Double : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return NSNumber(value: self) } - fileprivate static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> Double { return (objcRecordValue as! NSNumber).doubleValue } -} -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension Int : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return NSNumber(value: self) } - fileprivate static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> Int { return (objcRecordValue as! NSNumber).intValue } -} -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension UInt :CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return NSNumber(value: self) } - fileprivate static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> UInt { return (objcRecordValue as! NSNumber).uintValue } -} - -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension Int8 : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return NSNumber(value: self) } - fileprivate static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> Int8 { return (objcRecordValue as! NSNumber).int8Value } -} -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension UInt8 : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return NSNumber(value: self) } - fileprivate static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> UInt8 { return (objcRecordValue as! NSNumber).uint8Value } -} -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension Int16 : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return NSNumber(value: self) } - fileprivate static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> Int16 { return (objcRecordValue as! NSNumber).int16Value } -} -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension UInt16 : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return NSNumber(value: self) } - fileprivate static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> UInt16 { return (objcRecordValue as! NSNumber).uint16Value } -} -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension Int32 : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return NSNumber(value: self) } - fileprivate static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> Int32 { return (objcRecordValue as! NSNumber).int32Value } -} -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension UInt32 : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return NSNumber(value: self) } - fileprivate static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> UInt32 { return (objcRecordValue as! NSNumber).uint32Value } -} -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension Int64 : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return NSNumber(value: self) } - fileprivate static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> Int64 { return (objcRecordValue as! NSNumber).int64Value } -} -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension UInt64 : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return NSNumber(value: self) } - fileprivate static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> UInt64 { return (objcRecordValue as! NSNumber).uint64Value } -} -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension Float : CKRecordValueProtocol, CKObjCRecordValueConvertible { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { return NSNumber(value: self) } - fileprivate static func fromObjcRecordValue(_ objcRecordValue: __CKRecordObjCValue) -> Float { return (objcRecordValue as! NSNumber).floatValue } -} - - -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension Array : CKRecordValueProtocol, CKObjCRecordValueConvertible where Element: CKRecordValueProtocol { - fileprivate func objcRecordValue() -> __CKRecordObjCValue { - let retVal = NSMutableArray() - self.forEach { retVal.add($0.asObjCRecordValue()) } - return retVal - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension NSString : CKRecordValueProtocol, CKRecordValueConvertible { - internal func swiftNativeValue() -> CKRecordValueProtocol { return self as String } -} -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension NSDate : CKRecordValueProtocol, CKRecordValueConvertible { - internal func swiftNativeValue() -> CKRecordValueProtocol { return self as Date } -} -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension NSData : CKRecordValueProtocol, CKRecordValueConvertible { - internal func swiftNativeValue() -> CKRecordValueProtocol { return self as Data } -} -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension NSNumber: CKRecordValueProtocol, CKRecordValueConvertible { - internal func swiftNativeValue() -> CKRecordValueProtocol { - // All numbers come back as Int64 or Double, matching our protobuf conversion - // In some cases (record accessor methods) we have more type info, and can be smarter. But not here. - if CFNumberIsFloatType(self) { - return self.doubleValue - } else { - return self.int64Value - } - } -} -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension NSArray : CKRecordValueProtocol, CKRecordValueConvertible { - internal func swiftNativeValue() -> CKRecordValueProtocol { - var retVal = [CKRecordValueProtocol]() - for element in self { - let objcRecordValue = element as! __CKRecordObjCValue - let swiftValue = objcRecordValue.asSwiftNativeValue() - retVal.append(swiftValue) - } - return retVal as CKRecordValueProtocol - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKRecord.Reference : CKRecordValueProtocol {} -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKAsset : CKRecordValueProtocol {} -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CLLocation : CKRecordValueProtocol {} - - diff --git a/stdlib/public/Darwin/CloudKit/CKRecordZone_ID.swift b/stdlib/public/Darwin/CloudKit/CKRecordZone_ID.swift deleted file mode 100644 index 59eeb9d8c17e2..0000000000000 --- a/stdlib/public/Darwin/CloudKit/CKRecordZone_ID.swift +++ /dev/null @@ -1,37 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CloudKit // Clang module - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKRecordZone.ID { - /** - - parameter zoneName: Zone names must be 255 characters or less. Most UTF-8 characters are valid. Defaults to CKRecordZone.ID.defaultZoneName - - parameter ownerName: defaults to CurrentUserDefaultName - */ - public convenience init(zoneName: String = CKRecordZone.ID.defaultZoneName, ownerName: String = "__defaultOwner__") { - // CKCurrentUserDefaultName would be preferable to __defaultOwner__, but that only came around in macOS 10.12 and friends. - self.init(__zoneName: zoneName, ownerName: ownerName) - } - - public static let `default` = CKRecordZone.ID(zoneName: CKRecordZone.ID.defaultZoneName, ownerName: "__defaultOwner__") - // CKCurrentUserDefaultName would be preferable to __defaultOwner__, but that only came around in macOS 10.12 and friends. - public static let defaultZoneName = __CKRecordZoneDefaultName -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -@available(swift, obsoleted: 4.2, renamed: "CKRecordZone.ID.defaultZoneName") -public let CKRecordZoneDefaultName: String = __CKRecordZoneDefaultName - - diff --git a/stdlib/public/Darwin/CloudKit/CKRecord_ID.swift b/stdlib/public/Darwin/CloudKit/CKRecord_ID.swift deleted file mode 100644 index aecb5b2e2f1c2..0000000000000 --- a/stdlib/public/Darwin/CloudKit/CKRecord_ID.swift +++ /dev/null @@ -1,27 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CloudKit // Clang module - -/// A class coupling a record name and a record zone id -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKRecord.ID { - /** - - parameter recordName: CKRecord names must be 255 characters or less. Most UTF-8 characters are valid. Defaults to UUID().uuidString - - parameter zoneID: defaults to the default record zone id - */ - @available(swift 4.2) - public convenience init(recordName: String = UUID().uuidString, zoneID: CKRecordZone.ID = CKRecordZone.ID.default) { - self.init(__recordName: recordName, zoneID: zoneID) - } -} diff --git a/stdlib/public/Darwin/CloudKit/CKRecord_Reference.swift b/stdlib/public/Darwin/CloudKit/CKRecord_Reference.swift deleted file mode 100644 index e8a0240f9d318..0000000000000 --- a/stdlib/public/Darwin/CloudKit/CKRecord_Reference.swift +++ /dev/null @@ -1,22 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CloudKit // Clang module - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKRecord.Reference { - /// TODO: replace this with a .apinotes entry once there's a fix for 39261783 - @available(swift 4.2) - public typealias Action = CKRecord_Reference_Action -} - diff --git a/stdlib/public/Darwin/CloudKit/CKShare.swift b/stdlib/public/Darwin/CloudKit/CKShare.swift deleted file mode 100644 index 51409a3182b34..0000000000000 --- a/stdlib/public/Darwin/CloudKit/CKShare.swift +++ /dev/null @@ -1,25 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CloudKit - -@nonobjc -@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) -extension CKShare { - @available(swift 4.2) - public enum SystemFieldKey { - public static let title: CKRecord.FieldKey = __CKShareTitleKey - public static let thumbnailImageData: CKRecord.FieldKey = __CKShareThumbnailImageDataKey - public static let shareType: CKRecord.FieldKey = __CKShareTypeKey - } -} - diff --git a/stdlib/public/Darwin/CloudKit/CKShare_Participant.swift b/stdlib/public/Darwin/CloudKit/CKShare_Participant.swift deleted file mode 100644 index bacd8c710c482..0000000000000 --- a/stdlib/public/Darwin/CloudKit/CKShare_Participant.swift +++ /dev/null @@ -1,35 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CloudKit // Clang module - -@nonobjc -@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) -extension CKShare.Participant { - /// TODO: replace these with a .apinotes entry once there's a fix for 39261783 - @available(swift 4.2) - public typealias AcceptanceStatus = CKShare_Participant_AcceptanceStatus - - @available(swift 4.2) - public typealias Permission = CKShare_Participant_Permission - - @available(swift 4.2) - @available(macOS 10.14, iOS 12.0, tvOS 12.0, watchOS 5.0, *) - public typealias Role = CKShare_Participant_Role - - @available(swift 4.2) - @available(macOS, deprecated: 10.14, renamed: "CKShare.Participant.Role") - @available(iOS, deprecated: 12.0, renamed: "CKShare.Participant.Role") - @available(tvOS, deprecated: 12.0, renamed: "CKShare.Participant.Role") - @available(watchOS, deprecated: 5.0, renamed: "CKShare.Participant.Role") - public typealias ParticipantType = CKShare_Participant_ParticipantType -} diff --git a/stdlib/public/Darwin/CloudKit/CKSubscription_NotificationInfo.swift b/stdlib/public/Darwin/CloudKit/CKSubscription_NotificationInfo.swift deleted file mode 100644 index 24e85cf7a0bc4..0000000000000 --- a/stdlib/public/Darwin/CloudKit/CKSubscription_NotificationInfo.swift +++ /dev/null @@ -1,134 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CloudKit // Clang module - -#if !os(watchOS) - -/** - The payload of a push notification delivered in the UIApplication `application:didReceiveRemoteNotification:` delegate method contains information about the firing subscription. - - Use `Notification(fromRemoteNotificationDictionary:)` to parse that payload. - On tvOS, alerts, badges, sounds, and categories are not handled in push notifications. However, Subscriptions remain available to help you avoid polling the server. - */ -@nonobjc -@available(macOS 10.10, iOS 8.0, *) @available(watchOS, unavailable) -extension CKSubscription.NotificationInfo { - /// A list of field names to take from the matching record that is used as substitution variables in a formatted alert string. - #if !os(tvOS) - - @available(tvOS, unavailable) - @available(swift 4.2) - public var alertLocalizationArgs: [CKRecord.FieldKey]? { - get { return self.__alertLocalizationArgs } - set { self.__alertLocalizationArgs = newValue } - } - - /// A list of field names to take from the matching record that is used as substitution variables in a formatted title string. - @available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) - @available(swift 4.2) - public var titleLocalizationArgs: [CKRecord.FieldKey]? { - get { return self.__titleLocalizationArgs } - set { self.__titleLocalizationArgs = newValue } - } - - /// A list of field names to take from the matching record that is used as substitution variables in a formatted subtitle string. - @available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) - @available(swift 4.2) - public var subtitleLocalizationArgs: [CKRecord.FieldKey]? { - get { return self.__subtitleLocalizationArgs } - set { self.__subtitleLocalizationArgs = newValue } - } - - #endif // !os(tvOS) - - /** - A list of keys from the matching record to include in the notification payload. - - Only some keys are allowed. The value types associated with those keys on the server must be one of these classes: - - CKRecord.Reference - - CLLocation - - NSDate - - NSNumber - - NSString - */ - @available(swift 4.2) - public var desiredKeys: [CKRecord.FieldKey]? { - get { return self.__desiredKeys } - set { self.__desiredKeys = newValue } - } - - public convenience init(alertBody: String? = nil, - alertLocalizationKey: String? = nil, - alertLocalizationArgs: [CKRecord.FieldKey] = [], - title: String? = nil, - titleLocalizationKey: String? = nil, - titleLocalizationArgs: [CKRecord.FieldKey] = [], - subtitle: String? = nil, - subtitleLocalizationKey: String? = nil, - subtitleLocalizationArgs: [CKRecord.FieldKey] = [], - alertActionLocalizationKey: String? = nil, - alertLaunchImage: String? = nil, - soundName: String? = nil, - desiredKeys: [CKRecord.FieldKey] = [], - shouldBadge: Bool = false, - shouldSendContentAvailable: Bool = false, - shouldSendMutableContent: Bool = false, - category: String? = nil, - collapseIDKey: String? = nil) { - - self.init() - - #if !os(tvOS) - do { - self.alertBody = alertBody - self.alertLocalizationKey = alertLocalizationKey - self.alertLocalizationArgs = alertLocalizationArgs - - if #available(macOS 10.13, iOS 11.0, *) { - self.title = title - self.titleLocalizationKey = titleLocalizationKey - self.titleLocalizationArgs = titleLocalizationArgs - self.subtitle = subtitle - self.subtitleLocalizationKey = subtitleLocalizationKey - self.subtitleLocalizationArgs = subtitleLocalizationArgs - } - - self.alertActionLocalizationKey = alertActionLocalizationKey - self.alertLaunchImage = alertLaunchImage - self.soundName = soundName - } - #endif // !os(tvOS) - - self.desiredKeys = desiredKeys - - if #available(tvOS 10.0, *) { - self.shouldBadge = shouldBadge - } - self.shouldSendContentAvailable = shouldSendContentAvailable - if #available(macOS 10.13, iOS 11.0, tvOS 11.0, *) { - self.shouldSendMutableContent = shouldSendMutableContent - } - #if !os(tvOS) - do { - if #available(macOS 10.11, iOS 9.0, *) { - self.category = category - } - } - #endif // !os(tvOS) - if #available(macOS 10.13, iOS 11.0, tvOS 11.0, *) { - self.collapseIDKey = collapseIDKey - } - } -} - -#endif // !os(watchOS) diff --git a/stdlib/public/Darwin/CloudKit/CMakeLists.txt b/stdlib/public/Darwin/CloudKit/CMakeLists.txt deleted file mode 100644 index 4b48d3c53d18c..0000000000000 --- a/stdlib/public/Darwin/CloudKit/CMakeLists.txt +++ /dev/null @@ -1,38 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftCloudKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - NestedNames.swift - TypealiasStrings.swift - CKError.swift - CKFetchRecordZoneChangesOperation.swift - CKRecord.swift - CKRecordZone_ID.swift - CKRecord_ID.swift - CKRecord_Reference.swift - CKShare.swift - CKShare_Participant.swift - CKSubscription_NotificationInfo.swift - CKRecordValue.swift - DefaultParameters.swift - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR - - SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch IOKit Foundation CoreLocation XPC CoreFoundation ObjectiveC # auto-updated - os XPC - SWIFT_MODULE_DEPENDS_IOS Darwin Dispatch Foundation CoreLocation CoreFoundation ObjectiveC # auto-updated - os - SWIFT_MODULE_DEPENDS_TVOS Darwin Dispatch Foundation CoreLocation CoreFoundation ObjectiveC # auto-updated - os - SWIFT_MODULE_DEPENDS_WATCHOS Darwin Dispatch Foundation CoreLocation CoreFoundation ObjectiveC # auto-updated - os - FRAMEWORK_DEPENDS_WEAK CloudKit - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_CLOUDKIT_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_CLOUDKIT_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_CLOUDKIT_TVOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_CLOUDKIT_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/CloudKit/DefaultParameters.swift b/stdlib/public/Darwin/CloudKit/DefaultParameters.swift deleted file mode 100644 index b4628faa87ab6..0000000000000 --- a/stdlib/public/Darwin/CloudKit/DefaultParameters.swift +++ /dev/null @@ -1,87 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CloudKit // Clang module - -@nonobjc -@available(macOS 10.14, iOS 12.0, tvOS 12.0, watchOS 5.0, *) -extension CKFetchRecordZoneChangesOperation { - @available(swift 4.2) - public convenience init(recordZoneIDs: [CKRecordZone.ID]? = nil, configurationsByRecordZoneID: [CKRecordZone.ID: ZoneConfiguration]? = nil) { - self.init() - self.recordZoneIDs = recordZoneIDs - self.configurationsByRecordZoneID = configurationsByRecordZoneID - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKModifyRecordZonesOperation { - @available(swift 4.2) - public convenience init(recordZonesToSave: [CKRecordZone]? = nil, recordZoneIDsToDelete: [CKRecordZone.ID]? = nil) { - self.init() - self.recordZonesToSave = recordZonesToSave - self.recordZoneIDsToDelete = recordZoneIDsToDelete - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKModifyRecordsOperation { - @available(swift 4.2) - public convenience init(recordsToSave: [CKRecord]? = nil, recordIDsToDelete: [CKRecord.ID]? = nil) { - self.init() - self.recordsToSave = recordsToSave - self.recordIDsToDelete = recordIDsToDelete - } -} - -#if !os(watchOS) - -@nonobjc -@available(macOS 10.10, iOS 8.0, *) @available(watchOS, unavailable) -extension CKModifySubscriptionsOperation { - @available(swift 4.2) - public convenience init(subscriptionsToSave: [CKSubscription]? = nil, subscriptionIDsToDelete: [CKSubscription.ID]? = nil) { - self.init() - self.subscriptionsToSave = subscriptionsToSave - self.__subscriptionIDsToDelete = subscriptionIDsToDelete - } -} - -#endif // os(watchOS) - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKRecord { - @available(swift, introduced: 4.2, deprecated: 4.2, message: "Use init(recordType:recordID:) + CKRecord.ID(zoneID:) instead") - public convenience init(recordType: CKRecord.RecordType, zoneID: CKRecordZone.ID) { - self.init(recordType: recordType, recordID: CKRecord.ID(zoneID: zoneID)) - } - @available(swift 4.2) - public convenience init(recordType: CKRecord.RecordType, recordID: CKRecord.ID = CKRecord.ID()) { - self.init(__recordType: recordType, recordID: recordID) - } -} - -#if !os(watchOS) - -@nonobjc -@available(macOS 10.12, iOS 10.0, tvOS 10.0, *) @available(watchOS, unavailable) -extension CKQuerySubscription { - @available(swift 4.2) - public convenience init(recordType: CKRecord.RecordType, predicate: NSPredicate, subscriptionID: CKSubscription.ID = UUID().uuidString, options querySubscriptionOptions: CKQuerySubscription.Options = []) { - self.init(__recordType: recordType, predicate: predicate, subscriptionID: subscriptionID, options: querySubscriptionOptions) - } -} - -#endif // !os(watchOS) diff --git a/stdlib/public/Darwin/CloudKit/NestedNames.swift b/stdlib/public/Darwin/CloudKit/NestedNames.swift deleted file mode 100644 index dd83f245ed28c..0000000000000 --- a/stdlib/public/Darwin/CloudKit/NestedNames.swift +++ /dev/null @@ -1,46 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CloudKit // Clang module - -// Work arounds for 39295365, 39261783 - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKContainer { - @available(swift 4.2) - public enum Application { - public typealias Permissions = CKContainer_Application_Permissions - public typealias PermissionStatus = CKContainer_Application_PermissionStatus - public typealias PermissionBlock = CKContainer_Application_PermissionBlock - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKOperation { - @available(swift 4.2) - public typealias ID = String -} - -#if os(watchOS) - -@available(watchOS 3.0, *) -public enum CKSubscription {} - -#endif // os(watchOS) - -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKSubscription { - @available(swift 4.2) - public typealias ID = String -} diff --git a/stdlib/public/Darwin/CloudKit/TypealiasStrings.swift b/stdlib/public/Darwin/CloudKit/TypealiasStrings.swift deleted file mode 100644 index 8995cdbb07054..0000000000000 --- a/stdlib/public/Darwin/CloudKit/TypealiasStrings.swift +++ /dev/null @@ -1,336 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CloudKit // Clang module - -@nonobjc -@available(macOS 10.12, iOS 9.3, tvOS 9.2, watchOS 3.0, *) -extension CKContainer { - /** - If a long lived operation is cancelled or finishes completely it is no longer returned by this call. - */ - @available(swift 4.2) - public func fetchAllLongLivedOperationIDs(completionHandler: @escaping ([CKOperation.ID]?, Error?) -> Void) { - self.__fetchAllLongLivedOperationIDs(completionHandler: completionHandler) - } - /** - Long lived CKOperations returned by this call must be started on an operation queue. - Remember to set the callback blocks before starting the operation. - If an operation has already completed against the server, and is subsequently resumed, that operation will replay all of its callbacks from the start of the operation, but the request will not be re-sent to the server. - If a long lived operation is cancelled or finishes completely it is no longer returned by this call. - */ - @available(swift 4.2) - public func fetchLongLivedOperation(withID operationID: CKOperation.ID, completionHandler: @escaping (CKOperation?, Error?) -> Void) { - self.__fetchLongLivedOperation(withID: operationID, completionHandler: completionHandler) - } -} - -@nonobjc -@available(macOS 10.12, iOS 9.3, tvOS 9.2, watchOS 3.0, *) -extension CKOperation { - /** This is an identifier unique to this CKOperation. - - This value is chosen by the system, and will be unique to this instance of a CKOperation. This identifier will be sent to Apple's servers, and can be used to identify any server-side logging associated with this operation. - */ - @available(swift 4.2) - public var operationID: CKOperation.ID { - get { return self.__operationID } - } -} - -#if !os(watchOS) - -@nonobjc -@available(macOS 10.10, iOS 8.0, *) @available(watchOS, unavailable) -extension CKModifySubscriptionsOperation { - @available(swift 4.2) - public var subscriptionIDsToDelete: [CKSubscription.ID]? { - get { return self.__subscriptionIDsToDelete } - set { self.__subscriptionIDsToDelete = newValue } - } - /** This block is called when the operation completes. - - The Operation.completionBlock will also be called if both are set. - If the error is `CKErrorPartialFailure`, the error's userInfo dictionary contains a dictionary of subscriptionIDs to errors keyed off of `CKPartialErrorsByItemIDKey`. - */ - @available(swift 4.2) - public var modifySubscriptionsCompletionBlock: (([CKSubscription]?, [CKSubscription.ID]?, Error?) -> Void)? { - get { return self.__modifySubscriptionsCompletionBlock } - set { self.__modifySubscriptionsCompletionBlock = newValue } - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, *) @available(watchOS, unavailable) -extension CKFetchSubscriptionsOperation { - @available(swift 4.2) - public convenience init(subscriptionIDs: [CKSubscription.ID]) { - self.init(__subscriptionIDs: subscriptionIDs) - } - - @available(swift 4.2) - public var subscriptionIDs: [CKSubscription.ID]? { - get { return self.__subscriptionIDs } - set { self.__subscriptionIDs = newValue } - } - /** This block is called when the operation completes. - - The Operation.completionBlock will also be called if both are set. - If the error is `CKErrorPartialFailure`, the error's userInfo dictionary contains a dictionary of subscriptionID to errors keyed off of `CKPartialErrorsByItemIDKey`. - */ - @available(swift 4.2) - public var fetchSubscriptionCompletionBlock: (([CKSubscription.ID : CKSubscription]?, Error?) -> Void)? { - get { return self.__fetchSubscriptionCompletionBlock } - set { self.__fetchSubscriptionCompletionBlock = newValue } - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, *) @available(watchOS, unavailable) -extension CKDatabase { - @available(swift 4.2) - public func fetch(withSubscriptionID subscriptionID: CKSubscription.ID, completionHandler: @escaping (CKSubscription?, Error?) -> Void) { - self.__fetch(withSubscriptionID: subscriptionID, completionHandler: completionHandler) - } - @available(swift 4.2) - public func delete(withSubscriptionID subscriptionID: CKSubscription.ID, completionHandler: @escaping (String?, Error?) -> Void) { - self.__delete(withSubscriptionID: subscriptionID, completionHandler: completionHandler) - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, *) @available(watchOS, unavailable) -extension CKSubscription { - @available(swift 4.2) - public var subscriptionID: CKSubscription.ID { - get { return self.__subscriptionID } - } -} - -@nonobjc -@available(macOS 10.12, iOS 10.0, tvOS 10.0, *) @available(watchOS, unavailable) -extension CKQuerySubscription { - /// The record type that this subscription watches - @available(swift 4.2) - public var recordType: CKRecord.RecordType? { - get { return self.__recordType } - } -} - -@nonobjc -@available(macOS 10.12, iOS 10.0, tvOS 10.0, *) @available(watchOS, unavailable) -extension CKRecordZoneSubscription { - @available(swift 4.2) - public convenience init(zoneID: CKRecordZone.ID, subscriptionID: CKSubscription.ID) { - self.init(__zoneID: zoneID, subscriptionID: subscriptionID) - } - /// Optional property. If set, a zone subscription is scoped to record changes for this record type - @available(swift 4.2) - public var recordType: CKRecord.RecordType? { - get { return self.__recordType } - set { self.__recordType = newValue } - } -} - -@nonobjc -@available(macOS 10.12, iOS 10.0, tvOS 10.0, *) @available(watchOS, unavailable) -extension CKDatabaseSubscription { - @available(swift 4.2) - public convenience init(subscriptionID: CKSubscription.ID) { - self.init(__subscriptionID: subscriptionID) - } - /// Optional property. If set, a database subscription is scoped to record changes for this record type - @available(swift 4.2) - public var recordType: CKRecord.RecordType? { - get { return self.__recordType } - set { self.__recordType = newValue } - } -} - -#endif // !os(watchOS) - -@nonobjc -@available(macOS 10.11, iOS 9.0, watchOS 3.0, *) -extension CKNotification { - /// The ID of the subscription that caused this notification to fire - @available(swift 4.2) - public var subscriptionID: CKSubscription.ID? { - get { return self.__subscriptionID } - } -} - -@nonobjc -@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) -extension CKFetchRecordZoneChangesOperation { - @available(swift 4.2) - public var recordWithIDWasDeletedBlock: ((CKRecord.ID, CKRecord.RecordType) -> Void)? { - get { return self.__recordWithIDWasDeletedBlock } - set { self.__recordWithIDWasDeletedBlock = newValue } - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKQuery { - /// Use `NSPredicate(value: true)` if you want to query for all records of a given type. - @available(swift 4.2) - public convenience init(recordType: CKRecord.RecordType, predicate: NSPredicate) { - self.init(__recordType: recordType, predicate: predicate) - } - @available(swift 4.2) - public var recordType: CKRecord.RecordType { - get { return self.__recordType } - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKRecord { - @available(swift 4.2) - public var recordType: CKRecord.RecordType { - get { return self.__recordType } - } - /** In addition to `object(forKey:)` and `setObject(_:forKey:)`, dictionary-style subscripting (`record[key]` and `record[key] = value`) can be used to get and set values. - Acceptable value object classes are: - - String - - Date - - Data - - Bool - - Int - - UInt - - Float - - Double - - [U]Int8 et al - - CKReference / Record.Reference - - CKAsset - - CLLocation - - NSData - - NSDate - - NSNumber - - NSString - - Array and/or NSArray containing objects of any of the types above - - Any other classes will result in an exception with name `NSInvalidArgumentException`. - - Field keys starting with '_' are reserved. Attempting to set a key prefixed with a '_' will result in an error. - - Key names roughly match C variable name restrictions. They must begin with an ASCII letter and can contain ASCII letters and numbers and the underscore character. - The maximum key length is 255 characters. - */ - @available(swift 4.2) - public func object(forKey key: CKRecord.FieldKey) -> __CKRecordObjCValue? { - return self.__object(forKey: key) - } - @available(swift 4.2) - public func setObject(_ object: __CKRecordObjCValue?, forKey key: CKRecord.FieldKey) { - self.__setObject(object, forKey: key) - } - @available(swift 4.2) - public subscript(key: CKRecord.FieldKey) -> __CKRecordObjCValue? { - get { return self.object(forKey: key) } - set { self.setObject(newValue, forKey: key) } - } - @available(swift 4.2) - public func allKeys() -> [CKRecord.FieldKey] { - return self.__allKeys() - } - /// A list of keys that have been modified on the local CKRecord instance - @available(swift 4.2) - public func changedKeys() -> [CKRecord.FieldKey] { - return self.__changedKeys() - } -} - -@nonobjc -@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) -extension CKFetchShareMetadataOperation { - /** Declares which user-defined keys should be fetched and added to the resulting `rootRecord`. - - Only consulted if `shouldFetchRootRecord` is YES. - If nil, declares the entire root record should be downloaded. If set to an empty array, declares that no user fields should be downloaded. - Defaults to nil. - */ - @available(swift 4.2) - public var rootRecordDesiredKeys: [CKRecord.FieldKey]? { - get { return self.__rootRecordDesiredKeys } - set { self.__rootRecordDesiredKeys = newValue } - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKFetchRecordsOperation { - /** Declares which user-defined keys should be fetched and added to the resulting CKRecords. - - If nil, declares the entire record should be downloaded. If set to an empty array, declares that no user fields should be downloaded. - Defaults to nil. - */ - @available(swift 4.2) - public var desiredKeys: [CKRecord.FieldKey]? { - get { return self.__desiredKeys } - set { self.__desiredKeys = newValue } - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -extension CKQueryOperation { - /** Declares which user-defined keys should be fetched and added to the resulting CKRecords. - - If nil, declares the entire record should be downloaded. If set to an empty array, declares that no user fields should be downloaded. - Defaults to nil. - */ - @available(swift 4.2) - public var desiredKeys: [CKRecord.FieldKey]? { - get { return self.__desiredKeys } - set { self.__desiredKeys = newValue } - } -} - -@nonobjc -@available(macOS 10.10, iOS 8.0, watchOS 3.0, *) -@available(swift, obsoleted: 4.2, renamed: "CKRecord.SystemType.userRecord") -public let CKRecordTypeUserRecord: String = __CKRecordTypeUserRecord - -@nonobjc -@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) -@available(swift, obsoleted: 4.2, renamed: "CKRecord.SystemFieldKey.parent") -public let CKRecordParentKey: String = __CKRecordParentKey - -@nonobjc -@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) -@available(swift, obsoleted: 4.2, renamed: "CKRecord.SystemFieldKey.share") -public let CKRecordShareKey: String = __CKRecordShareKey - - - -@nonobjc -@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) -@available(swift, obsoleted: 4.2, renamed: "CKRecord.SystemType.share") -public let CKRecordTypeShare: String = __CKRecordTypeShare - -@nonobjc -@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) -@available(swift, obsoleted: 4.2, renamed: "CKShare.SystemFieldKey.title") -public let CKShareTitleKey: String = __CKShareTitleKey - -@nonobjc -@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) -@available(swift, obsoleted: 4.2, renamed: "CKShare.SystemFieldKey.thumbnailImageData") -public let CKShareThumbnailImageDataKey: String = __CKShareThumbnailImageDataKey - -@nonobjc -@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) -@available(swift, obsoleted: 4.2, renamed: "CKShare.SystemFieldKey.shareType") -public let CKShareTypeKey: String = __CKShareTypeKey - - diff --git a/stdlib/public/Darwin/Compression/CMakeLists.txt b/stdlib/public/Darwin/Compression/CMakeLists.txt deleted file mode 100644 index f9447f6fadedf..0000000000000 --- a/stdlib/public/Darwin/Compression/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftCompression ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - Compression.swift - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" "-lcompression" - SWIFT_MODULE_DEPENDS_OSX Darwin # auto-updated - Foundation # Imported in Swift - SWIFT_MODULE_DEPENDS_IOS Darwin # auto-updated - Foundation # Imported in Swift - SWIFT_MODULE_DEPENDS_TVOS Darwin # auto-updated - Foundation # Imported in Swift - SWIFT_MODULE_DEPENDS_WATCHOS Darwin # auto-updated - Foundation # Imported in Swift - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_COMPRESSION_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_COMPRESSION_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_COMPRESSION_TVOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_COMPRESSION_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/Compression/Compression.swift b/stdlib/public/Darwin/Compression/Compression.swift deleted file mode 100644 index 9e6799aaf712f..0000000000000 --- a/stdlib/public/Darwin/Compression/Compression.swift +++ /dev/null @@ -1,394 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -import Darwin -import Foundation -@_exported import Compression - -/// Compression algorithms, wraps the C API constants. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) -public enum Algorithm: CaseIterable, RawRepresentable { - - /// LZFSE - case lzfse - - /// Deflate (conforming to RFC 1951) - case zlib - - /// LZ4 with simple frame encapsulation - case lz4 - - /// LZMA in a XZ container - case lzma - - public init?(rawValue: compression_algorithm) { - switch rawValue { - case COMPRESSION_LZFSE: self = .lzfse - case COMPRESSION_ZLIB: self = .zlib - case COMPRESSION_LZ4: self = .lz4 - case COMPRESSION_LZMA: self = .lzma - default: return nil - } - } - - public var rawValue: compression_algorithm { - switch self { - case .lzfse: return COMPRESSION_LZFSE - case .zlib: return COMPRESSION_ZLIB - case .lz4: return COMPRESSION_LZ4 - case .lzma: return COMPRESSION_LZMA - } - } -} - -/// Compression filter direction of operation, compress/decompress -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) -public enum FilterOperation: RawRepresentable { - - /// Compress raw data to a compressed payload - case compress - - /// Decompress a compressed payload to raw data - case decompress - - public init?(rawValue: compression_stream_operation) { - switch rawValue { - case COMPRESSION_STREAM_ENCODE: self = .compress - case COMPRESSION_STREAM_DECODE: self = .decompress - default: return nil - } - } - - public var rawValue: compression_stream_operation { - switch self { - case .compress: return COMPRESSION_STREAM_ENCODE - case .decompress: return COMPRESSION_STREAM_DECODE - } - } -} - -/// Compression errors -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) -public enum FilterError: Error { - - /// Filter failed to initialize, - /// or invalid internal state, - /// or invalid parameters - case invalidState - - /// Invalid data in a call to compression_stream_process, - /// or non-empty write after an output filter has been finalized - case invalidData -} - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) -extension compression_stream { - - /// Initialize a compression_stream struct - /// - /// - Parameter operation: direction of operation - /// - Parameter algorithm: compression algorithm - /// - /// - Throws: `FilterError.invalidState` if `algorithm` is not supported - /// by the Compression stream API - /// - internal init(operation: FilterOperation, algorithm: Algorithm) throws { - self.init(dst_ptr: UnsafeMutablePointer(bitPattern: -1)!, - dst_size: 0, - src_ptr: UnsafeMutablePointer(bitPattern: -1)!, - src_size: 0, - state: nil) - let status = compression_stream_init(&self, operation.rawValue, algorithm.rawValue) - guard status == COMPRESSION_STATUS_OK else { throw FilterError.invalidState } - } -} - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) -public class OutputFilter { - private var _stream: compression_stream - private var _buf: UnsafeMutablePointer - private let _bufCapacity: Int - private let _writeFunc: (Data?) throws -> Void - private var _finalized: Bool = false - - /// Initialize an output filter - /// - /// - Parameters: - /// - operation: direction of operation - /// - algorithm: compression algorithm - /// - bufferCapacity: capacity of the internal data buffer - /// - writeFunc: called to write the processed data - /// - /// - Throws: `FilterError.invalidState` if stream initialization failed - public init( - _ operation: FilterOperation, - using algorithm: Algorithm, - bufferCapacity: Int = 65536, - writingTo writeFunc: @escaping (Data?) throws -> Void - ) throws { - _stream = try compression_stream(operation: operation, algorithm: algorithm) - _buf = UnsafeMutablePointer.allocate(capacity: bufferCapacity) - _bufCapacity = bufferCapacity - _writeFunc = writeFunc - } - - /// Send data to output filter - /// - /// Processed output will be sent to the output closure. - /// A call with empty/nil data is interpreted as finalize(). - /// Writing non empty/nil data to a finalized stream is an error. - /// - /// - Parameter data: data to process - /// - /// - Throws: - /// `FilterError.invalidData` if an error occurs during processing, - /// or if `data` is not empty/nil, and the filter is the finalized state - public func write(_ data: D?) throws { - // Finalize if data is empty/nil - if data == nil || data!.isEmpty { try finalize() ; return } - - // Fail if already finalized - if _finalized { throw FilterError.invalidData } - - // Process all incoming data - for region in data!.regions { - try region.withUnsafeBytes { (raw_src_ptr: UnsafeRawBufferPointer) in - _stream.src_size = region.count - _stream.src_ptr = raw_src_ptr.baseAddress!.assumingMemoryBound(to: UInt8.self) - while (_stream.src_size > 0) { _ = try _process(finalizing: false) } - } - } - } - - /// Finalize the stream, i.e. flush all data remaining in the stream - /// - /// Processed output will be sent to the output closure. - /// When all output has been sent, the writingTo closure is called one last time with nil data. - /// Once the stream is finalized, writing non empty/nil data to the stream will throw an exception. - /// - /// - Throws: `FilterError.invalidData` if an error occurs during processing - public func finalize() throws { - // Do nothing if already finalized - if _finalized { return } - - // Finalize stream - _stream.src_size = 0 - var status = COMPRESSION_STATUS_OK - while (status != COMPRESSION_STATUS_END) { status = try _process(finalizing: true) } - - // Update state - _finalized = true - - // Notify end of stream - try _writeFunc(nil) - } - - // Cleanup resources. The filter is finalized now if it was not finalized yet. - deinit { - // Finalize now if not done earlier - try? finalize() - - // Cleanup - _buf.deallocate() - compression_stream_destroy(&_stream) - } - - // Call compression_stream_process with current src, and dst set to _buf, then write output to the closure - // Return status - private func _process(finalizing finalize: Bool) throws -> compression_status { - // Process current input, and write to buf - _stream.dst_ptr = _buf - _stream.dst_size = _bufCapacity - - let status = compression_stream_process(&_stream, (finalize ? Int32(COMPRESSION_STREAM_FINALIZE.rawValue) : 0)) - guard status != COMPRESSION_STATUS_ERROR else { throw FilterError.invalidData } - - // Number of bytes written to buf - let writtenBytes = _bufCapacity - _stream.dst_size - - // Write output - if writtenBytes > 0 { - let outData = Data(bytesNoCopy: _buf, count: writtenBytes, deallocator: .none) - try _writeFunc(outData) - } - - return status - } - -} - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) -public class InputFilter { - - // Internal buffer to read bytes from a DataProtocol implementation - private class InputFilterBuffer { - private var _data: D // current input data - private var _remaining: Int // total bytes remaining to process in _data - private var _regionIndex: D.Regions.Index // region being read in _data - private var _regionRemaining: Int // remaining bytes to read in region being read in _data - - public init(_ data: D) throws { - _data = data - _remaining = _data.count - _regionRemaining = 0 - _regionIndex = _data.regions.startIndex - if _regionIndex != _data.regions.endIndex { _regionRemaining = _data.regions[_regionIndex].count } - // Advance to first non-zero region - try advance(by: 0) - } - - // Return number of remaining bytes - public func remaining() -> Int { return _remaining } - - // Call f with a buffer to the remaining bytes of the current contiguous region - public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R? { - if _remaining == 0 { - return try body(UnsafeRawBufferPointer(start: nil, count: 0)) - } else { - let r = _data.regions[_regionIndex] - return try r.withUnsafeBytes { (region_buf: UnsafeRawBufferPointer) in - let src_buf = UnsafeRawBufferPointer( - start: region_buf.baseAddress!.assumingMemoryBound(to: UInt8.self) + region_buf.count - _regionRemaining, - count: _regionRemaining) - return try body(src_buf) - } - } - } - - // Consume n bytes in the current region (n can be 0, up to _regionRemaining), and move to next non-empty region if needed - // post-condition: _remaining == 0 || _regionRemaining > 0 - public func advance(by n: Int) throws { - - // Sanity checks - if n > _regionRemaining { throw FilterError.invalidState } // invalid n - - // Update counters - _regionRemaining -= n - _remaining -= n - - // Move to next non-empty region if we are done with the current one - let r = _data.regions - while _regionRemaining == 0 { - r.formIndex(after: &_regionIndex) - if _regionIndex == r.endIndex { break } - _regionRemaining = r[_regionIndex].count - } - - // Sanity checks - if _remaining != 0 && _regionRemaining == 0 { throw FilterError.invalidState } - } - } - - private let _readCapacity: Int // size to use when calling _readFunc - private let _readFunc: (Int) throws -> D? // caller-provided read function - private var _stream: compression_stream - private var _buf: InputFilterBuffer? = nil // input - private var _eofReached: Bool = false // did we read end-of-file from the input? - private var _endReached: Bool = false // did we reach end-of-file from the decoder stream? - - /// Initialize an input filter - /// - /// - Parameters: - /// - operation: direction of operation - /// - algorithm: compression algorithm - /// - bufferCapacity: capacity of the internal data buffer - /// - readFunc: called to read the input data - /// - /// - Throws: `FilterError.invalidState` if filter initialization failed - public init( - _ operation: FilterOperation, - using algorithm: Algorithm, - bufferCapacity: Int = 65536, - readingFrom readFunc: @escaping (Int) throws -> D? - ) throws { - _stream = try compression_stream(operation: operation, algorithm: algorithm) - _readCapacity = bufferCapacity - _readFunc = readFunc - } - - /// Read processed data from the filter - /// - /// Input data, when needed, is obtained from the input closure - /// When the input closure returns a nil or empty Data object, the filter will be - /// finalized, and after all processed data has been read, readData will return nil - /// to signal end of input - /// - /// - Parameter count: max number of bytes to read from the filter - /// - /// - Returns: a new Data object containing at most `count` output bytes, or nil if no more data is available - /// - /// - Throws: - /// `FilterError.invalidData` if an error occurs during processing - public func readData(ofLength count: Int) throws -> Data? { - // Sanity check - precondition(count > 0, "number of bytes to read can't be 0") - - // End reached, return early, nothing to do - if _endReached { return nil } - - // Allocate result - var result = Data(count: count) - - try result.withUnsafeMutableBytes { (dst_ptr: UnsafeMutablePointer) in - - // Write to result until full, or end reached - _stream.dst_size = count - _stream.dst_ptr = dst_ptr - - while _stream.dst_size > 0 && !_endReached { - - // Refill _buf if needed, and EOF was not yet read - if (_buf?.remaining() ?? 0) == 0 && !_eofReached { - let data = try _readFunc(_readCapacity) // may be nil, or empty - if data?.count ?? 0 == 0 { // nil or empty -> EOF - _eofReached = true - _buf = nil - } else { - _buf = try InputFilterBuffer(data!) - } - } - - // Process some data - if let buf = _buf { - try buf.withUnsafeBytes { (src_buf: UnsafeRawBufferPointer) in - // Point to buffer - _stream.src_ptr = src_buf.baseAddress!.assumingMemoryBound(to: UInt8.self) - _stream.src_size = src_buf.count - let status = compression_stream_process(&_stream, (_eofReached ? Int32(COMPRESSION_STREAM_FINALIZE.rawValue) : 0)) - guard status != COMPRESSION_STATUS_ERROR else { throw FilterError.invalidData } - if status == COMPRESSION_STATUS_END { _endReached = true } - // Advance by the number of consumed bytes - let consumed = src_buf.count - _stream.src_size - try buf.advance(by: consumed) - } - } else { - // No data available, process until END reached - let status = compression_stream_process(&_stream, (_eofReached ? Int32(COMPRESSION_STREAM_FINALIZE.rawValue) : 0)) - guard status != COMPRESSION_STATUS_ERROR else { throw FilterError.invalidData } - if status == COMPRESSION_STATUS_END { _endReached = true } - } - - } // _stream.dst_size > 0 && !_endReached - - } // result.withUnsafeMutableBytes - - // Update actual size - result.count = count - _stream.dst_size - return result - } - - // Cleanup resources - deinit { - compression_stream_destroy(&_stream) - } - -} diff --git a/stdlib/public/Darwin/Contacts/CMakeLists.txt b/stdlib/public/Darwin/Contacts/CMakeLists.txt deleted file mode 100644 index a642d91383ebe..0000000000000 --- a/stdlib/public/Darwin/Contacts/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftContacts ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - CNError.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch IOKit Foundation XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_WATCHOS Darwin Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS_WEAK Contacts - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_CONTACTS_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_CONTACTS_IOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_CONTACTS_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/Contacts/CNError.swift b/stdlib/public/Darwin/Contacts/CNError.swift deleted file mode 100644 index ad0b71dcd020b..0000000000000 --- a/stdlib/public/Darwin/Contacts/CNError.swift +++ /dev/null @@ -1,35 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Contacts -import Foundation - -@available(macOS 10.11, iOS 9.0, *) -extension CNError { - /// One or more CNContact, CNGroup or CNContainer objects for which - /// the error applies. - public var affectedRecords: [AnyObject]? { - return userInfo[CNErrorUserInfoAffectedRecordsKey] as? [AnyObject] - } - - /// The record identifiers to which this error applies. - public var affectedRecordIdentifiers: [String]? { - return userInfo[CNErrorUserInfoAffectedRecordIdentifiersKey] as? [String] - } - - /// The key paths associated with a given error. For validation - /// errors this will contain key paths to specific object - /// properties. - public var keyPaths: [String]? { - return userInfo[CNErrorUserInfoKeyPathsKey] as? [String] - } -} diff --git a/stdlib/public/Darwin/CoreAudio/CMakeLists.txt b/stdlib/public/Darwin/CoreAudio/CMakeLists.txt deleted file mode 100644 index 5e725ee15a597..0000000000000 --- a/stdlib/public/Darwin/CoreAudio/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftCoreAudio ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - CoreAudio.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin Dispatch CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin Dispatch CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin Dispatch CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_WATCHOS Darwin Dispatch CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS CoreAudio - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_COREAUDIO_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_COREAUDIO_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_COREAUDIO_TVOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_COREAUDIO_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/CoreAudio/CoreAudio.swift b/stdlib/public/Darwin/CoreAudio/CoreAudio.swift deleted file mode 100644 index afab53f9b6e07..0000000000000 --- a/stdlib/public/Darwin/CoreAudio/CoreAudio.swift +++ /dev/null @@ -1,168 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CoreAudio // Clang module - -extension UnsafeBufferPointer { - /// Initialize an `UnsafeBufferPointer` from an `AudioBuffer`. - /// Binds the buffer's memory type to `Element`. - public init(_ audioBuffer: AudioBuffer) { - let count = Int(audioBuffer.mDataByteSize) / MemoryLayout.stride - let elementPtr = audioBuffer.mData?.bindMemory( - to: Element.self, capacity: count) - self.init(start: elementPtr, count: count) - } -} - -extension UnsafeMutableBufferPointer { - /// Initialize an `UnsafeMutableBufferPointer` from an - /// `AudioBuffer`. - public init(_ audioBuffer: AudioBuffer) { - let count = Int(audioBuffer.mDataByteSize) / MemoryLayout.stride - let elementPtr = audioBuffer.mData?.bindMemory( - to: Element.self, capacity: count) - self.init(start: elementPtr, count: count) - } -} - -extension AudioBuffer { - /// Initialize an `AudioBuffer` from an - /// `UnsafeMutableBufferPointer`. - public init( - _ typedBuffer: UnsafeMutableBufferPointer, - numberOfChannels: Int - ) { - let byteSize = typedBuffer.count * MemoryLayout.stride - self.init(mNumberChannels: UInt32(numberOfChannels), - mDataByteSize: UInt32(byteSize), - mData: UnsafeMutableRawPointer(typedBuffer.baseAddress)) - } -} - -extension AudioBufferList { - /// - Returns: the size in bytes of an `AudioBufferList` that can hold up to - /// `maximumBuffers` `AudioBuffer`s. - public static func sizeInBytes(maximumBuffers: Int) -> Int { - precondition(maximumBuffers >= 1, - "AudioBufferList should contain at least one AudioBuffer") - return MemoryLayout.size + - (maximumBuffers - 1) * MemoryLayout.stride - } - - /// Allocate an `AudioBufferList` with a capacity for the specified number of - /// `AudioBuffer`s. - /// - /// The `count` property of the new `AudioBufferList` is initialized to - /// `maximumBuffers`. - /// - /// The memory should be freed with `free()`. - public static func allocate(maximumBuffers: Int) - -> UnsafeMutableAudioBufferListPointer { - let byteSize = sizeInBytes(maximumBuffers: maximumBuffers) - let ablMemory = calloc(byteSize, 1) - precondition(ablMemory != nil, - "failed to allocate memory for an AudioBufferList") - - let listPtr = ablMemory!.bindMemory(to: AudioBufferList.self, capacity: 1) - (ablMemory! + MemoryLayout.stride).bindMemory( - to: AudioBuffer.self, capacity: maximumBuffers) - let abl = UnsafeMutableAudioBufferListPointer(listPtr) - abl.count = maximumBuffers - return abl - } -} - -/// A wrapper for a pointer to an `AudioBufferList`. -/// -/// Like `UnsafeMutablePointer`, this type provides no automated memory -/// management and the user must therefore take care to allocate and free -/// memory appropriately. -public struct UnsafeMutableAudioBufferListPointer { - /// Construct from an `AudioBufferList` pointer. - public init(_ p: UnsafeMutablePointer) { - unsafeMutablePointer = p - } - - /// Construct from an `AudioBufferList` pointer. - public init?(_ p: UnsafeMutablePointer?) { - guard let unwrapped = p else { return nil } - self.init(unwrapped) - } - - /// The number of `AudioBuffer`s in the `AudioBufferList` - /// (`mNumberBuffers`). - public var count: Int { - get { - return Int(unsafeMutablePointer.pointee.mNumberBuffers) - } - nonmutating set(newValue) { - unsafeMutablePointer.pointee.mNumberBuffers = UInt32(newValue) - } - } - - /// The pointer to the first `AudioBuffer` in this `AudioBufferList`. - internal var _audioBuffersPointer: UnsafeMutablePointer { - // AudioBufferList has one AudioBuffer in a "flexible array member". - // Position the pointer after that, and skip one AudioBuffer back. This - // brings us to the start of AudioBuffer array. - let rawPtr = UnsafeMutableRawPointer(unsafeMutablePointer + 1) - return rawPtr.assumingMemoryBound(to: AudioBuffer.self) - 1 - } - - // FIXME: the properties 'unsafePointer' and 'unsafeMutablePointer' should be - // initializers on UnsafePointer and UnsafeMutablePointer, but we don't want - // to allow any UnsafePointer to be initializable from an - // UnsafeMutableAudioBufferListPointer, only UnsafePointer. - // We need constrained extensions for that. rdar://17821143 - - /// The pointer to the wrapped `AudioBufferList`. - public var unsafePointer: UnsafePointer { - return UnsafePointer(unsafeMutablePointer) - } - - /// The pointer to the wrapped `AudioBufferList`. - public var unsafeMutablePointer: UnsafeMutablePointer -} - -extension UnsafeMutableAudioBufferListPointer - : MutableCollection, RandomAccessCollection { - - public typealias Element = AudioBuffer - public typealias Index = Int - public typealias Indices = Range - - /// Always zero, which is the index of the first `AudioBuffer`. - public var startIndex: Int { - return 0 - } - - /// The "past the end" position; always identical to `count`. - public var endIndex: Int { - return count - } - - /// Access an indexed `AudioBuffer` (`mBuffers[i]`). - @_borrowed - public subscript(index: Index) -> Element { - _read { - precondition(index >= 0 && index < self.count, - "subscript index out of range") - yield ((_audioBuffersPointer + index).pointee) - } - nonmutating _modify { - precondition(index >= 0 && index < self.count, - "subscript index out of range") - yield (&(_audioBuffersPointer + index).pointee) - } - } -} - diff --git a/stdlib/public/Darwin/CoreData/CMakeLists.txt b/stdlib/public/Darwin/CoreData/CMakeLists.txt deleted file mode 100644 index ad6f6ba7703a1..0000000000000 --- a/stdlib/public/Darwin/CoreData/CMakeLists.txt +++ /dev/null @@ -1,24 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftCoreData ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - CocoaError.swift - NSManagedObjectContext.swift - CoreData.mm - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch IOKit Foundation XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_WATCHOS Darwin Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS CoreData - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_COREDATA_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_COREDATA_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_COREDATA_TVOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_COREDATA_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/CoreData/CocoaError.swift b/stdlib/public/Darwin/CoreData/CocoaError.swift deleted file mode 100644 index 0f4126c3b05bd..0000000000000 --- a/stdlib/public/Darwin/CoreData/CocoaError.swift +++ /dev/null @@ -1,829 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CoreData -import Foundation - -// Code constants -extension CocoaError.Code { - public static var managedObjectValidation: CocoaError.Code { - return CocoaError.Code(rawValue: 1550) - } - public static var validationMultipleErrors: CocoaError.Code { - return CocoaError.Code(rawValue: 1560) - } - public static var validationMissingMandatoryProperty: CocoaError.Code { - return CocoaError.Code(rawValue: 1570) - } - public static var validationRelationshipLacksMinimumCount: CocoaError.Code { - return CocoaError.Code(rawValue: 1580) - } - public static var validationRelationshipExceedsMaximumCount: CocoaError.Code { - return CocoaError.Code(rawValue: 1590) - } - public static var validationRelationshipDeniedDelete: CocoaError.Code { - return CocoaError.Code(rawValue: 1600) - } - public static var validationNumberTooLarge: CocoaError.Code { - return CocoaError.Code(rawValue: 1610) - } - public static var validationNumberTooSmall: CocoaError.Code { - return CocoaError.Code(rawValue: 1620) - } - public static var validationDateTooLate: CocoaError.Code { - return CocoaError.Code(rawValue: 1630) - } - public static var validationDateTooSoon: CocoaError.Code { - return CocoaError.Code(rawValue: 1640) - } - public static var validationInvalidDate: CocoaError.Code { - return CocoaError.Code(rawValue: 1650) - } - public static var validationStringTooLong: CocoaError.Code { - return CocoaError.Code(rawValue: 1660) - } - public static var validationStringTooShort: CocoaError.Code { - return CocoaError.Code(rawValue: 1670) - } - public static var validationStringPatternMatching: CocoaError.Code { - return CocoaError.Code(rawValue: 1680) - } - public static var managedObjectContextLocking: CocoaError.Code { - return CocoaError.Code(rawValue: 132000) - } - public static var persistentStoreCoordinatorLocking: CocoaError.Code { - return CocoaError.Code(rawValue: 132010) - } - public static var managedObjectReferentialIntegrity: CocoaError.Code { - return CocoaError.Code(rawValue: 133000) - } - public static var managedObjectExternalRelationship: CocoaError.Code { - return CocoaError.Code(rawValue: 133010) - } - public static var managedObjectMerge: CocoaError.Code { - return CocoaError.Code(rawValue: 133020) - } - public static var managedObjectConstraintMerge: CocoaError.Code { - return CocoaError.Code(rawValue: 133021) - } - public static var persistentStoreInvalidType: CocoaError.Code { - return CocoaError.Code(rawValue: 134000) - } - public static var persistentStoreTypeMismatch: CocoaError.Code { - return CocoaError.Code(rawValue: 134010) - } - public static var persistentStoreIncompatibleSchema: CocoaError.Code { - return CocoaError.Code(rawValue: 134020) - } - public static var persistentStoreSave: CocoaError.Code { - return CocoaError.Code(rawValue: 134030) - } - public static var persistentStoreIncompleteSave: CocoaError.Code { - return CocoaError.Code(rawValue: 134040) - } - public static var persistentStoreSaveConflicts: CocoaError.Code { - return CocoaError.Code(rawValue: 134050) - } - public static var coreData: CocoaError.Code { - return CocoaError.Code(rawValue: 134060) - } - public static var persistentStoreOperation: CocoaError.Code { - return CocoaError.Code(rawValue: 134070) - } - public static var persistentStoreOpen: CocoaError.Code { - return CocoaError.Code(rawValue: 134080) - } - public static var persistentStoreTimeout: CocoaError.Code { - return CocoaError.Code(rawValue: 134090) - } - public static var persistentStoreUnsupportedRequestType: CocoaError.Code { - return CocoaError.Code(rawValue: 134091) - } - public static var persistentStoreIncompatibleVersionHash: CocoaError.Code { - return CocoaError.Code(rawValue: 134100) - } - public static var migration: CocoaError.Code { - return CocoaError.Code(rawValue: 134110) - } - public static var migrationCancelled: CocoaError.Code { - return CocoaError.Code(rawValue: 134120) - } - public static var migrationMissingSourceModel: CocoaError.Code { - return CocoaError.Code(rawValue: 134130) - } - public static var migrationMissingMappingModel: CocoaError.Code { - return CocoaError.Code(rawValue: 134140) - } - public static var migrationManagerSourceStore: CocoaError.Code { - return CocoaError.Code(rawValue: 134150) - } - public static var migrationManagerDestinationStore: CocoaError.Code { - return CocoaError.Code(rawValue: 134160) - } - public static var entityMigrationPolicy: CocoaError.Code { - return CocoaError.Code(rawValue: 134170) - } - public static var sqlite: CocoaError.Code { - return CocoaError.Code(rawValue: 134180) - } - public static var inferredMappingModel: CocoaError.Code { - return CocoaError.Code(rawValue: 134190) - } - public static var externalRecordImport: CocoaError.Code { - return CocoaError.Code(rawValue: 134200) - } -} - -// Code constants with names deprecated late in Swift 3 -extension CocoaError.Code { - @available(*, deprecated, renamed: "managedObjectValidation") - public static var managedObjectValidationError: CocoaError.Code { - return CocoaError.Code(rawValue: 1550) - } - @available(*, deprecated, renamed: "validationMultipleErrors") - public static var validationMultipleErrorsError: CocoaError.Code { - return CocoaError.Code(rawValue: 1560) - } - @available(*, deprecated, renamed: "validationMissingMandatoryProperty") - public static var validationMissingMandatoryPropertyError: CocoaError.Code { - return CocoaError.Code(rawValue: 1570) - } - @available(*, deprecated, renamed: "validationRelationshipLacksMinimumCount") - public static var validationRelationshipLacksMinimumCountError: CocoaError.Code { - return CocoaError.Code(rawValue: 1580) - } - @available(*, deprecated, renamed: "validationRelationshipExceedsMaximumCount") - public static var validationRelationshipExceedsMaximumCountError: CocoaError.Code { - return CocoaError.Code(rawValue: 1590) - } - @available(*, deprecated, renamed: "validationRelationshipDeniedDelete") - public static var validationRelationshipDeniedDeleteError: CocoaError.Code { - return CocoaError.Code(rawValue: 1600) - } - @available(*, deprecated, renamed: "validationNumberTooLarge") - public static var validationNumberTooLargeError: CocoaError.Code { - return CocoaError.Code(rawValue: 1610) - } - @available(*, deprecated, renamed: "validationNumberTooSmall") - public static var validationNumberTooSmallError: CocoaError.Code { - return CocoaError.Code(rawValue: 1620) - } - @available(*, deprecated, renamed: "validationDateTooLate") - public static var validationDateTooLateError: CocoaError.Code { - return CocoaError.Code(rawValue: 1630) - } - @available(*, deprecated, renamed: "validationDateTooSoon") - public static var validationDateTooSoonError: CocoaError.Code { - return CocoaError.Code(rawValue: 1640) - } - @available(*, deprecated, renamed: "validationInvalidDate") - public static var validationInvalidDateError: CocoaError.Code { - return CocoaError.Code(rawValue: 1650) - } - @available(*, deprecated, renamed: "validationStringTooLong") - public static var validationStringTooLongError: CocoaError.Code { - return CocoaError.Code(rawValue: 1660) - } - @available(*, deprecated, renamed: "validationStringTooShort") - public static var validationStringTooShortError: CocoaError.Code { - return CocoaError.Code(rawValue: 1670) - } - @available(*, deprecated, renamed: "validationStringPatternMatching") - public static var validationStringPatternMatchingError: CocoaError.Code { - return CocoaError.Code(rawValue: 1680) - } - @available(*, deprecated, renamed: "managedObjectContextLocking") - public static var managedObjectContextLockingError: CocoaError.Code { - return CocoaError.Code(rawValue: 132000) - } - @available(*, deprecated, renamed: "persistentStoreCoordinatorLocking") - public static var persistentStoreCoordinatorLockingError: CocoaError.Code { - return CocoaError.Code(rawValue: 132010) - } - @available(*, deprecated, renamed: "managedObjectReferentialIntegrity") - public static var managedObjectReferentialIntegrityError: CocoaError.Code { - return CocoaError.Code(rawValue: 133000) - } - @available(*, deprecated, renamed: "managedObjectExternalRelationship") - public static var managedObjectExternalRelationshipError: CocoaError.Code { - return CocoaError.Code(rawValue: 133010) - } - @available(*, deprecated, renamed: "managedObjectMerge") - public static var managedObjectMergeError: CocoaError.Code { - return CocoaError.Code(rawValue: 133020) - } - @available(*, deprecated, renamed: "managedObjectConstraintMerge") - public static var managedObjectConstraintMergeError: CocoaError.Code { - return CocoaError.Code(rawValue: 133021) - } - @available(*, deprecated, renamed: "persistentStoreInvalidType") - public static var persistentStoreInvalidTypeError: CocoaError.Code { - return CocoaError.Code(rawValue: 134000) - } - @available(*, deprecated, renamed: "persistentStoreTypeMismatch") - public static var persistentStoreTypeMismatchError: CocoaError.Code { - return CocoaError.Code(rawValue: 134010) - } - @available(*, deprecated, renamed: "persistentStoreIncompatibleSchema") - public static var persistentStoreIncompatibleSchemaError: CocoaError.Code { - return CocoaError.Code(rawValue: 134020) - } - @available(*, deprecated, renamed: "persistentStoreSave") - public static var persistentStoreSaveError: CocoaError.Code { - return CocoaError.Code(rawValue: 134030) - } - @available(*, deprecated, renamed: "persistentStoreIncompleteSave") - public static var persistentStoreIncompleteSaveError: CocoaError.Code { - return CocoaError.Code(rawValue: 134040) - } - @available(*, deprecated, renamed: "persistentStoreSaveConflicts") - public static var persistentStoreSaveConflictsError: CocoaError.Code { - return CocoaError.Code(rawValue: 134050) - } - @available(*, deprecated, renamed: "coreData") - public static var coreDataError: CocoaError.Code { - return CocoaError.Code(rawValue: 134060) - } - @available(*, deprecated, renamed: "persistentStoreOperation") - public static var persistentStoreOperationError: CocoaError.Code { - return CocoaError.Code(rawValue: 134070) - } - @available(*, deprecated, renamed: "persistentStoreOpen") - public static var persistentStoreOpenError: CocoaError.Code { - return CocoaError.Code(rawValue: 134080) - } - @available(*, deprecated, renamed: "persistentStoreTimeout") - public static var persistentStoreTimeoutError: CocoaError.Code { - return CocoaError.Code(rawValue: 134090) - } - @available(*, deprecated, renamed: "persistentStoreUnsupportedRequestType") - public static var persistentStoreUnsupportedRequestTypeError: CocoaError.Code { - return CocoaError.Code(rawValue: 134091) - } - @available(*, deprecated, renamed: "persistentStoreIncompatibleVersionHash") - public static var persistentStoreIncompatibleVersionHashError: CocoaError.Code { - return CocoaError.Code(rawValue: 134100) - } - @available(*, deprecated, renamed: "migration") - public static var migrationError: CocoaError.Code { - return CocoaError.Code(rawValue: 134110) - } - @available(*, deprecated, renamed: "migrationCancelled") - public static var migrationCancelledError: CocoaError.Code { - return CocoaError.Code(rawValue: 134120) - } - @available(*, deprecated, renamed: "migrationMissingSourceModel") - public static var migrationMissingSourceModelError: CocoaError.Code { - return CocoaError.Code(rawValue: 134130) - } - @available(*, deprecated, renamed: "migrationMissingMappingModel") - public static var migrationMissingMappingModelError: CocoaError.Code { - return CocoaError.Code(rawValue: 134140) - } - @available(*, deprecated, renamed: "migrationManagerSourceStore") - public static var migrationManagerSourceStoreError: CocoaError.Code { - return CocoaError.Code(rawValue: 134150) - } - @available(*, deprecated, renamed: "migrationManagerDestinationStore") - public static var migrationManagerDestinationStoreError: CocoaError.Code { - return CocoaError.Code(rawValue: 134160) - } - @available(*, deprecated, renamed: "entityMigrationPolicy") - public static var entityMigrationPolicyError: CocoaError.Code { - return CocoaError.Code(rawValue: 134170) - } - @available(*, deprecated, renamed: "sqlite") - public static var sqliteError: CocoaError.Code { - return CocoaError.Code(rawValue: 134180) - } - @available(*, deprecated, renamed: "inferredMappingModel") - public static var inferredMappingModelError: CocoaError.Code { - return CocoaError.Code(rawValue: 134190) - } - @available(*, deprecated, renamed: "externalRecordImport") - public static var externalRecordImportError: CocoaError.Code { - return CocoaError.Code(rawValue: 134200) - } -} - -// Code constants -extension CocoaError { - public static var managedObjectValidation: CocoaError.Code { - return CocoaError.Code(rawValue: 1550) - } - public static var validationMultipleErrors: CocoaError.Code { - return CocoaError.Code(rawValue: 1560) - } - public static var validationMissingMandatoryProperty: CocoaError.Code { - return CocoaError.Code(rawValue: 1570) - } - public static var validationRelationshipLacksMinimumCount: CocoaError.Code { - return CocoaError.Code(rawValue: 1580) - } - public static var validationRelationshipExceedsMaximumCount: CocoaError.Code { - return CocoaError.Code(rawValue: 1590) - } - public static var validationRelationshipDeniedDelete: CocoaError.Code { - return CocoaError.Code(rawValue: 1600) - } - public static var validationNumberTooLarge: CocoaError.Code { - return CocoaError.Code(rawValue: 1610) - } - public static var validationNumberTooSmall: CocoaError.Code { - return CocoaError.Code(rawValue: 1620) - } - public static var validationDateTooLate: CocoaError.Code { - return CocoaError.Code(rawValue: 1630) - } - public static var validationDateTooSoon: CocoaError.Code { - return CocoaError.Code(rawValue: 1640) - } - public static var validationInvalidDate: CocoaError.Code { - return CocoaError.Code(rawValue: 1650) - } - public static var validationStringTooLong: CocoaError.Code { - return CocoaError.Code(rawValue: 1660) - } - public static var validationStringTooShort: CocoaError.Code { - return CocoaError.Code(rawValue: 1670) - } - public static var validationStringPatternMatching: CocoaError.Code { - return CocoaError.Code(rawValue: 1680) - } - public static var managedObjectContextLocking: CocoaError.Code { - return CocoaError.Code(rawValue: 132000) - } - public static var persistentStoreCoordinatorLocking: CocoaError.Code { - return CocoaError.Code(rawValue: 132010) - } - public static var managedObjectReferentialIntegrity: CocoaError.Code { - return CocoaError.Code(rawValue: 133000) - } - public static var managedObjectExternalRelationship: CocoaError.Code { - return CocoaError.Code(rawValue: 133010) - } - public static var managedObjectMerge: CocoaError.Code { - return CocoaError.Code(rawValue: 133020) - } - public static var managedObjectConstraintMerge: CocoaError.Code { - return CocoaError.Code(rawValue: 133021) - } - public static var persistentStoreInvalidType: CocoaError.Code { - return CocoaError.Code(rawValue: 134000) - } - public static var persistentStoreTypeMismatch: CocoaError.Code { - return CocoaError.Code(rawValue: 134010) - } - public static var persistentStoreIncompatibleSchema: CocoaError.Code { - return CocoaError.Code(rawValue: 134020) - } - public static var persistentStoreSave: CocoaError.Code { - return CocoaError.Code(rawValue: 134030) - } - public static var persistentStoreIncompleteSave: CocoaError.Code { - return CocoaError.Code(rawValue: 134040) - } - public static var persistentStoreSaveConflicts: CocoaError.Code { - return CocoaError.Code(rawValue: 134050) - } - public static var coreData: CocoaError.Code { - return CocoaError.Code(rawValue: 134060) - } - public static var persistentStoreOperation: CocoaError.Code { - return CocoaError.Code(rawValue: 134070) - } - public static var persistentStoreOpen: CocoaError.Code { - return CocoaError.Code(rawValue: 134080) - } - public static var persistentStoreTimeout: CocoaError.Code { - return CocoaError.Code(rawValue: 134090) - } - public static var persistentStoreUnsupportedRequestType: CocoaError.Code { - return CocoaError.Code(rawValue: 134091) - } - public static var persistentStoreIncompatibleVersionHash: CocoaError.Code { - return CocoaError.Code(rawValue: 134100) - } - public static var migration: CocoaError.Code { - return CocoaError.Code(rawValue: 134110) - } - public static var migrationCancelled: CocoaError.Code { - return CocoaError.Code(rawValue: 134120) - } - public static var migrationMissingSourceModel: CocoaError.Code { - return CocoaError.Code(rawValue: 134130) - } - public static var migrationMissingMappingModel: CocoaError.Code { - return CocoaError.Code(rawValue: 134140) - } - public static var migrationManagerSourceStore: CocoaError.Code { - return CocoaError.Code(rawValue: 134150) - } - public static var migrationManagerDestinationStore: CocoaError.Code { - return CocoaError.Code(rawValue: 134160) - } - public static var entityMigrationPolicy: CocoaError.Code { - return CocoaError.Code(rawValue: 134170) - } - public static var sqlite: CocoaError.Code { - return CocoaError.Code(rawValue: 134180) - } - public static var inferredMappingModel: CocoaError.Code { - return CocoaError.Code(rawValue: 134190) - } - public static var externalRecordImport: CocoaError.Code { - return CocoaError.Code(rawValue: 134200) - } -} - -// Code constants with names deprecated late in Swift 3 -extension CocoaError { - @available(*, deprecated, renamed: "managedObjectValidation") - public static var managedObjectValidationError: CocoaError.Code { - return CocoaError.Code(rawValue: 1550) - } - @available(*, deprecated, renamed: "validationMultipleErrors") - public static var validationMultipleErrorsError: CocoaError.Code { - return CocoaError.Code(rawValue: 1560) - } - @available(*, deprecated, renamed: "validationMissingMandatoryProperty") - public static var validationMissingMandatoryPropertyError: CocoaError.Code { - return CocoaError.Code(rawValue: 1570) - } - @available(*, deprecated, renamed: "validationRelationshipLacksMinimumCount") - public static var validationRelationshipLacksMinimumCountError: CocoaError.Code { - return CocoaError.Code(rawValue: 1580) - } - @available(*, deprecated, renamed: "validationRelationshipExceedsMaximumCount") - public static var validationRelationshipExceedsMaximumCountError: CocoaError.Code { - return CocoaError.Code(rawValue: 1590) - } - @available(*, deprecated, renamed: "validationRelationshipDeniedDelete") - public static var validationRelationshipDeniedDeleteError: CocoaError.Code { - return CocoaError.Code(rawValue: 1600) - } - @available(*, deprecated, renamed: "validationNumberTooLarge") - public static var validationNumberTooLargeError: CocoaError.Code { - return CocoaError.Code(rawValue: 1610) - } - @available(*, deprecated, renamed: "validationNumberTooSmall") - public static var validationNumberTooSmallError: CocoaError.Code { - return CocoaError.Code(rawValue: 1620) - } - @available(*, deprecated, renamed: "validationDateTooLate") - public static var validationDateTooLateError: CocoaError.Code { - return CocoaError.Code(rawValue: 1630) - } - @available(*, deprecated, renamed: "validationDateTooSoon") - public static var validationDateTooSoonError: CocoaError.Code { - return CocoaError.Code(rawValue: 1640) - } - @available(*, deprecated, renamed: "validationInvalidDate") - public static var validationInvalidDateError: CocoaError.Code { - return CocoaError.Code(rawValue: 1650) - } - @available(*, deprecated, renamed: "validationStringTooLong") - public static var validationStringTooLongError: CocoaError.Code { - return CocoaError.Code(rawValue: 1660) - } - @available(*, deprecated, renamed: "validationStringTooShort") - public static var validationStringTooShortError: CocoaError.Code { - return CocoaError.Code(rawValue: 1670) - } - @available(*, deprecated, renamed: "validationStringPatternMatching") - public static var validationStringPatternMatchingError: CocoaError.Code { - return CocoaError.Code(rawValue: 1680) - } - @available(*, deprecated, renamed: "managedObjectContextLocking") - public static var managedObjectContextLockingError: CocoaError.Code { - return CocoaError.Code(rawValue: 132000) - } - @available(*, deprecated, renamed: "persistentStoreCoordinatorLocking") - public static var persistentStoreCoordinatorLockingError: CocoaError.Code { - return CocoaError.Code(rawValue: 132010) - } - @available(*, deprecated, renamed: "managedObjectReferentialIntegrity") - public static var managedObjectReferentialIntegrityError: CocoaError.Code { - return CocoaError.Code(rawValue: 133000) - } - @available(*, deprecated, renamed: "managedObjectExternalRelationship") - public static var managedObjectExternalRelationshipError: CocoaError.Code { - return CocoaError.Code(rawValue: 133010) - } - @available(*, deprecated, renamed: "managedObjectMerge") - public static var managedObjectMergeError: CocoaError.Code { - return CocoaError.Code(rawValue: 133020) - } - @available(*, deprecated, renamed: "managedObjectConstraintMerge") - public static var managedObjectConstraintMergeError: CocoaError.Code { - return CocoaError.Code(rawValue: 133021) - } - @available(*, deprecated, renamed: "persistentStoreInvalidType") - public static var persistentStoreInvalidTypeError: CocoaError.Code { - return CocoaError.Code(rawValue: 134000) - } - @available(*, deprecated, renamed: "persistentStoreTypeMismatch") - public static var persistentStoreTypeMismatchError: CocoaError.Code { - return CocoaError.Code(rawValue: 134010) - } - @available(*, deprecated, renamed: "persistentStoreIncompatibleSchema") - public static var persistentStoreIncompatibleSchemaError: CocoaError.Code { - return CocoaError.Code(rawValue: 134020) - } - @available(*, deprecated, renamed: "persistentStoreSave") - public static var persistentStoreSaveError: CocoaError.Code { - return CocoaError.Code(rawValue: 134030) - } - @available(*, deprecated, renamed: "persistentStoreIncompleteSave") - public static var persistentStoreIncompleteSaveError: CocoaError.Code { - return CocoaError.Code(rawValue: 134040) - } - @available(*, deprecated, renamed: "persistentStoreSaveConflicts") - public static var persistentStoreSaveConflictsError: CocoaError.Code { - return CocoaError.Code(rawValue: 134050) - } - @available(*, deprecated, renamed: "coreData") - public static var coreDataError: CocoaError.Code { - return CocoaError.Code(rawValue: 134060) - } - @available(*, deprecated, renamed: "persistentStoreOperation") - public static var persistentStoreOperationError: CocoaError.Code { - return CocoaError.Code(rawValue: 134070) - } - @available(*, deprecated, renamed: "persistentStoreOpen") - public static var persistentStoreOpenError: CocoaError.Code { - return CocoaError.Code(rawValue: 134080) - } - @available(*, deprecated, renamed: "persistentStoreTimeout") - public static var persistentStoreTimeoutError: CocoaError.Code { - return CocoaError.Code(rawValue: 134090) - } - @available(*, deprecated, renamed: "persistentStoreUnsupportedRequestType") - public static var persistentStoreUnsupportedRequestTypeError: CocoaError.Code { - return CocoaError.Code(rawValue: 134091) - } - @available(*, deprecated, renamed: "persistentStoreIncompatibleVersionHash") - public static var persistentStoreIncompatibleVersionHashError: CocoaError.Code { - return CocoaError.Code(rawValue: 134100) - } - @available(*, deprecated, renamed: "migration") - public static var migrationError: CocoaError.Code { - return CocoaError.Code(rawValue: 134110) - } - @available(*, deprecated, renamed: "migrationCancelled") - public static var migrationCancelledError: CocoaError.Code { - return CocoaError.Code(rawValue: 134120) - } - @available(*, deprecated, renamed: "migrationMissingSourceModel") - public static var migrationMissingSourceModelError: CocoaError.Code { - return CocoaError.Code(rawValue: 134130) - } - @available(*, deprecated, renamed: "migrationMissingMappingModel") - public static var migrationMissingMappingModelError: CocoaError.Code { - return CocoaError.Code(rawValue: 134140) - } - @available(*, deprecated, renamed: "migrationManagerSourceStore") - public static var migrationManagerSourceStoreError: CocoaError.Code { - return CocoaError.Code(rawValue: 134150) - } - @available(*, deprecated, renamed: "migrationManagerDestinationStore") - public static var migrationManagerDestinationStoreError: CocoaError.Code { - return CocoaError.Code(rawValue: 134160) - } - @available(*, deprecated, renamed: "entityMigrationPolicy") - public static var entityMigrationPolicyError: CocoaError.Code { - return CocoaError.Code(rawValue: 134170) - } - @available(*, deprecated, renamed: "sqlite") - public static var sqliteError: CocoaError.Code { - return CocoaError.Code(rawValue: 134180) - } - @available(*, deprecated, renamed: "inferredMappingModel") - public static var inferredMappingModelError: CocoaError.Code { - return CocoaError.Code(rawValue: 134190) - } - @available(*, deprecated, renamed: "externalRecordImport") - public static var externalRecordImportError: CocoaError.Code { - return CocoaError.Code(rawValue: 134200) - } -} - -extension CocoaError { - /// Object that failed to validate for a validation error. - public var validationObject: Any? { - return userInfo[NSValidationObjectErrorKey] - } - - /// Key that failed to validate for a validation error. - public var validationKey: String? { - return userInfo[NSValidationKeyErrorKey] as? String - } - - /// For predicate-based validation, the predicate for the condition - /// that failed to validate. - public var validationPredicate: NSPredicate? { - return userInfo[NSValidationPredicateErrorKey] as? NSPredicate - } - - /// The value for the key that failed to validate for a validation - /// error. - public var validationValue: Any? { - return userInfo[NSValidationValueErrorKey] - } - - /// Stores prompting an error. - public var affectedStores: [AnyObject]? { - return userInfo[NSAffectedStoresErrorKey] as? [AnyObject] - } - - /// Objects prompting an error. - public var affectedObjects: [AnyObject]? { - return userInfo[NSAffectedObjectsErrorKey] as? [AnyObject] - } - - /// The conflicts that arise from a persistent store. - public var persistentStoreSaveConflicts: [NSMergeConflict]? { - return userInfo[NSPersistentStoreSaveConflictsErrorKey] as? [NSMergeConflict] - } -} - -// Swift 2 names of code constants, removed from Swift 3 -extension CocoaError { - @available(*, unavailable, renamed: "managedObjectValidation") - public static var ManagedObjectValidationError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "validationMultipleErrors") - public static var ValidationMultipleErrorsError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "validationMissingMandatoryProperty") - public static var ValidationMissingMandatoryPropertyError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "validationRelationshipLacksMinimumCount") - public static var ValidationRelationshipLacksMinimumCountError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "validationRelationshipExceedsMaximumCount") - public static var ValidationRelationshipExceedsMaximumCountError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "validationRelationshipDeniedDelete") - public static var ValidationRelationshipDeniedDeleteError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "validationNumberTooLarge") - public static var ValidationNumberTooLargeError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "validationNumberTooSmall") - public static var ValidationNumberTooSmallError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "validationDateTooLate") - public static var ValidationDateTooLateError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "validationDateTooSoon") - public static var ValidationDateTooSoonError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "validationInvalidDate") - public static var ValidationInvalidDateError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "validationStringTooLong") - public static var ValidationStringTooLongError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "validationStringTooShort") - public static var ValidationStringTooShortError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "validationStringPatternMatching") - public static var ValidationStringPatternMatchingError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "managedObjectContextLocking") - public static var ManagedObjectContextLockingError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "persistentStoreCoordinatorLocking") - public static var PersistentStoreCoordinatorLockingError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "managedObjectReferentialIntegrity") - public static var ManagedObjectReferentialIntegrityError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "managedObjectExternalRelationship") - public static var ManagedObjectExternalRelationshipError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "managedObjectMerge") - public static var ManagedObjectMergeError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "managedObjectConstraintMerge") - public static var ManagedObjectConstraintMergeError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "persistentStoreInvalidType") - public static var PersistentStoreInvalidTypeError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "persistentStoreTypeMismatch") - public static var PersistentStoreTypeMismatchError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "persistentStoreIncompatibleSchema") - public static var PersistentStoreIncompatibleSchemaError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "persistentStoreSave") - public static var PersistentStoreSaveError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "persistentStoreIncompleteSave") - public static var PersistentStoreIncompleteSaveError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "persistentStoreSaveConflicts") - public static var PersistentStoreSaveConflictsError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "coreData") - public static var CoreDataError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "persistentStoreOperation") - public static var PersistentStoreOperationError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "persistentStoreOpen") - public static var PersistentStoreOpenError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "persistentStoreTimeout") - public static var PersistentStoreTimeoutError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "persistentStoreUnsupportedRequestType") - public static var PersistentStoreUnsupportedRequestTypeError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "persistentStoreIncompatibleVersionHash") - public static var PersistentStoreIncompatibleVersionHashError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "migration") - public static var MigrationError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "migrationCancelled") - public static var MigrationCancelledError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "migrationMissingSourceModel") - public static var MigrationMissingSourceModelError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "migrationMissingMappingModel") - public static var MigrationMissingMappingModelError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "migrationManagerSourceStore") - public static var MigrationManagerSourceStoreError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "migrationManagerDestinationStore") - public static var MigrationManagerDestinationStoreError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "entityMigrationPolicy") - public static var EntityMigrationPolicyError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "sqlite") - public static var SQLiteError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "inferredMappingModel") - public static var InferredMappingModelError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } - @available(*, unavailable, renamed: "externalRecordImport") - public static var ExternalRecordImportError: CocoaError.Code { - fatalError("unavailable accessor can't be called") - } -} diff --git a/stdlib/public/Darwin/CoreData/CoreData.mm b/stdlib/public/Darwin/CoreData/CoreData.mm deleted file mode 100644 index 44397674b8798..0000000000000 --- a/stdlib/public/Darwin/CoreData/CoreData.mm +++ /dev/null @@ -1,28 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -#import - -// Make sure -conformsToProtocol: checks succeed even on older OSs. -// This only works because NSFetchRequestResult doesn't have any method -// requirements. - -#define CONFORMS_TO_NSFETCHREQUESTRESULT(TYPE) \ -@interface TYPE (_SwiftNSFetchRequestResult) \ -@end \ -@implementation TYPE (_SwiftNSFetchRequestResult) \ -@end - -CONFORMS_TO_NSFETCHREQUESTRESULT(NSNumber) -CONFORMS_TO_NSFETCHREQUESTRESULT(NSDictionary) -CONFORMS_TO_NSFETCHREQUESTRESULT(NSManagedObject) -CONFORMS_TO_NSFETCHREQUESTRESULT(NSManagedObjectID) diff --git a/stdlib/public/Darwin/CoreData/NSManagedObjectContext.swift b/stdlib/public/Darwin/CoreData/NSManagedObjectContext.swift deleted file mode 100644 index e37c0609f7850..0000000000000 --- a/stdlib/public/Darwin/CoreData/NSManagedObjectContext.swift +++ /dev/null @@ -1,24 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CoreData -import Foundation - -extension NSManagedObjectContext { - public func fetch(_ request: NSFetchRequest) throws -> [T] { - return try fetch(unsafeDowncast(request, to: NSFetchRequest.self)) as! [T] - } - - public func count(for request: NSFetchRequest) throws -> Int { - return try count(for: unsafeDowncast(request, to: NSFetchRequest.self)) - } -} diff --git a/stdlib/public/Darwin/CoreGraphics/CMakeLists.txt b/stdlib/public/Darwin/CoreGraphics/CMakeLists.txt index 9a6c20b10662a..a424ca4218150 100644 --- a/stdlib/public/Darwin/CoreGraphics/CMakeLists.txt +++ b/stdlib/public/Darwin/CoreGraphics/CMakeLists.txt @@ -12,7 +12,7 @@ add_swift_target_library(swiftCoreGraphics ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYP SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - SWIFT_MODULE_DEPENDS_OSX Darwin Dispatch IOKit CoreFoundation ObjectiveC # auto-updated + SWIFT_MODULE_DEPENDS_OSX Darwin Dispatch CoreFoundation ObjectiveC # auto-updated SWIFT_MODULE_DEPENDS_IOS Darwin Dispatch CoreFoundation ObjectiveC # auto-updated SWIFT_MODULE_DEPENDS_TVOS Darwin Dispatch CoreFoundation ObjectiveC # auto-updated SWIFT_MODULE_DEPENDS_WATCHOS Darwin Dispatch CoreFoundation ObjectiveC # auto-updated diff --git a/stdlib/public/Darwin/CoreImage/CMakeLists.txt b/stdlib/public/Darwin/CoreImage/CMakeLists.txt deleted file mode 100644 index 39d7f0d54b97a..0000000000000 --- a/stdlib/public/Darwin/CoreImage/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftCoreImage ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - CoreImage.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Metal Dispatch IOKit Foundation XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics Metal Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreGraphics Metal Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS_OSX QuartzCore - FRAMEWORK_DEPENDS_IOS_TVOS CoreImage - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_COREIMAGE_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_COREIMAGE_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_COREIMAGE_TVOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/CoreImage/CoreImage.swift b/stdlib/public/Darwin/CoreImage/CoreImage.swift deleted file mode 100644 index 7f9bfa6599300..0000000000000 --- a/stdlib/public/Darwin/CoreImage/CoreImage.swift +++ /dev/null @@ -1,60 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -import Foundation -@_exported import CoreImage // Clang module - -extension CIFilter { -#if os(macOS) - // - (CIImage *)apply:(CIKernel *)k, ... - // @objc(apply:arguments:options:) - // func apply(_ k: CIKernel, - // arguments args: [AnyObject]?, - // options dict: Dictionary?) -> CIImage? - func apply(_ k: CIKernel, args: [AnyObject], options: (String, AnyObject)...) -> CIImage? { - var dict = [String : AnyObject](minimumCapacity: options.count) - for (key, value) in options { - dict[key] = value - } - return self.apply(k, arguments: args, options: dict) - } -#endif - - @available(iOS, introduced: 8.0) - @available(macOS, introduced: 10.10) - convenience init?( - name: String, elements: (String, AnyObject)... - ) { - var dict = [String : AnyObject](minimumCapacity: elements.count) - for (key, value) in elements { - dict[key] = value - } - self.init(name: name, parameters: dict) - } -} - -#if os(macOS) -extension CISampler { - // - (id)initWithImage:(CIImage *)im keysAndValues:key0, ...; - convenience init(im: CIImage, elements: (String, Any)...) { - var dict = [AnyHashable : Any](minimumCapacity: elements.count) - for (key, value) in elements { - dict[key] = value - } - - // @objc(initWithImage:options:) - // init(image im: CIImage, - // options dict: NSDictionary?) - self.init(image: im, options: dict) - } -} -#endif diff --git a/stdlib/public/Darwin/CoreLocation/CLError.swift b/stdlib/public/Darwin/CoreLocation/CLError.swift deleted file mode 100644 index cd96095f0660b..0000000000000 --- a/stdlib/public/Darwin/CoreLocation/CLError.swift +++ /dev/null @@ -1,24 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CoreLocation -import Foundation - -#if os(iOS) -extension CLError { - /// In a regionMonitoringResponseDelayed error, the region that the - /// location services can more effectively monitor. - public var alternateRegion: CLRegion? { - return userInfo[kCLErrorUserInfoAlternateRegionKey] as? CLRegion - } -} -#endif diff --git a/stdlib/public/Darwin/CoreLocation/CMakeLists.txt b/stdlib/public/Darwin/CoreLocation/CMakeLists.txt deleted file mode 100644 index 82fbc9b451a43..0000000000000 --- a/stdlib/public/Darwin/CoreLocation/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftCoreLocation ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - CLError.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - GYB_SOURCES - NSValue.swift.gyb - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch IOKit Foundation XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_WATCHOS Darwin Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS CoreLocation - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_CORELOCATION_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_CORELOCATION_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_CORELOCATION_TVOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_CORELOCATION_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/CoreLocation/NSValue.swift.gyb b/stdlib/public/Darwin/CoreLocation/NSValue.swift.gyb deleted file mode 100644 index a0170bff414ee..0000000000000 --- a/stdlib/public/Darwin/CoreLocation/NSValue.swift.gyb +++ /dev/null @@ -1,38 +0,0 @@ -@_exported import CoreLocation -import Foundation - -%{ -from gyb_foundation_support import \ - ObjectiveCBridgeableImplementationForNSValueWithCategoryMethods -}% - -// Get the ObjC type used by -[NSValue valueWithMKCoordinate:] -// to instantiate the resulting NSValue objects, in case these get changed -// in the future. This is extra tricky because MapKit *might not be loaded*, -// in which case we need to fall back to the static @encode string. -private let CLLocationCoordinate2DInNSValueObjCType: UnsafePointer = { - let factorySel = Selector(("valueWithMKCoordinate:")) - guard let opaqueFactoryMethod = NSValue.method(for: factorySel) else { - return _getObjCTypeEncoding(CLLocationCoordinate2D.self) - } - typealias FactoryMethodType = - @convention(c) (AnyClass, Selector, CLLocationCoordinate2D) -> NSValue - let factoryMethod = - unsafeBitCast(opaqueFactoryMethod, to: FactoryMethodType.self) - return factoryMethod(NSValue.self, factorySel, .init()).objCType -}() - -${ ObjectiveCBridgeableImplementationForNSValueWithCategoryMethods( - Type="CLLocationCoordinate2D", - initializer="""{ - var addressableValue = $0 - return NSValue(bytes: &addressableValue, - objCType: CLLocationCoordinate2DInNSValueObjCType) - }""", - getter="""{ - var result = CLLocationCoordinate2D() - $0.getValue(&result) - return result - }""", - objCType="{ _ in CLLocationCoordinate2DInNSValueObjCType }", -) } diff --git a/stdlib/public/Darwin/CoreMedia/CMTime.swift b/stdlib/public/Darwin/CoreMedia/CMTime.swift deleted file mode 100644 index bf515ae4649f0..0000000000000 --- a/stdlib/public/Darwin/CoreMedia/CMTime.swift +++ /dev/null @@ -1,134 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CoreMedia // Clang module - -extension CMTime { - public init(seconds: Double, preferredTimescale: CMTimeScale) { - self = CMTimeMakeWithSeconds(seconds, preferredTimescale: preferredTimescale) - } - - public init(value: CMTimeValue, timescale: CMTimeScale) { - self = CMTimeMake(value: value, timescale: timescale) - } -} - -// CMTIME_IS_VALID -// CMTIME_IS_INVALID -// CMTIME_IS_POSITIVEINFINITY -// CMTIME_IS_NEGATIVEINFINITY -// CMTIME_IS_INDEFINITE -// CMTIME_IS_NUMERIC -// CMTIME_HAS_BEEN_ROUNDED -// CMTimeGetSeconds -// CMTimeConvertScale -extension CMTime { - public var isValid: Bool { - return self.flags.contains(.valid) - } - - public var isPositiveInfinity: Bool { - return self.isValid && - self.flags.contains(.positiveInfinity) - } - - public var isNegativeInfinity: Bool { - return self.isValid && - self.flags.contains(.negativeInfinity) - } - - public var isIndefinite: Bool { - return self.isValid && - self.flags.contains(.indefinite) - } - - public var isNumeric: Bool { - return - self.flags.intersection([.valid, .impliedValueFlagsMask]) == .valid - } - - public var hasBeenRounded: Bool { - return self.isNumeric && - self.flags.contains(.hasBeenRounded) - } - - public var seconds: Double { - return CMTimeGetSeconds(self) - } - - public func convertScale(_ newTimescale: Int32, method: CMTimeRoundingMethod) - -> CMTime { - return CMTimeConvertScale(self, timescale: newTimescale, method: method) - } -} - -public func CMTIME_IS_VALID(_ time: CMTime) -> Bool { - return time.isValid -} - -public func CMTIME_IS_INVALID(_ time: CMTime) -> Bool { - return !time.isValid -} - -public func CMTIME_IS_POSITIVEINFINITY(_ time: CMTime) -> Bool { - return time.isPositiveInfinity -} - -public func CMTIME_IS_NEGATIVEINFINITY(_ time: CMTime) -> Bool { - return time.isNegativeInfinity -} - -public func CMTIME_IS_INDEFINITE(_ time: CMTime) -> Bool { - return time.isIndefinite -} - -public func CMTIME_IS_NUMERIC(_ time: CMTime) -> Bool { - return time.isNumeric -} - -public func CMTIME_HAS_BEEN_ROUNDED(_ time: CMTime) -> Bool { - return time.hasBeenRounded -} - -extension CMTime { - // CMTimeAdd - public static func + (addend1: CMTime, addend2: CMTime) -> CMTime { - return CMTimeAdd(addend1, addend2) - } - - // CMTimeSubtract - public static func - (minuend: CMTime, subtrahend: CMTime) -> CMTime { - return CMTimeSubtract(minuend, subtrahend) - } -} - -// CMTimeCompare -extension CMTime : Equatable, Comparable { - public static func < (time1: CMTime, time2: CMTime) -> Bool { - return CMTimeCompare(time1, time2) < 0 - } - public static func <= (time1: CMTime, time2: CMTime) -> Bool { - return CMTimeCompare(time1, time2) <= 0 - } - public static func > (time1: CMTime, time2: CMTime) -> Bool { - return CMTimeCompare(time1, time2) > 0 - } - public static func >= (time1: CMTime, time2: CMTime) -> Bool { - return CMTimeCompare(time1, time2) >= 0 - } - public static func == (time1: CMTime, time2: CMTime) -> Bool { - return CMTimeCompare(time1, time2) == 0 - } - public static func != (time1: CMTime, time2: CMTime) -> Bool { - return CMTimeCompare(time1, time2) != 0 - } -} diff --git a/stdlib/public/Darwin/CoreMedia/CMTimeRange.swift b/stdlib/public/Darwin/CoreMedia/CMTimeRange.swift deleted file mode 100644 index 66ffb62265fbe..0000000000000 --- a/stdlib/public/Darwin/CoreMedia/CMTimeRange.swift +++ /dev/null @@ -1,86 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CoreMedia // Clang module - -// CMTIMERANGE_IS_VALID -// CMTIMERANGE_IS_INVALID -// CMTIMERANGE_IS_INDEFINITE -// CMTIMERANGE_IS_EMPTY -// CMTimeRangeGetEnd -// CMTimeRangeGetUnion -// CMTimeRangeGetIntersection -// CMTimeRangeContainsTime -// CMTimeRangeContainsTimeRange -// CMTimeRangeFromTimeToTime -extension CMTimeRange { - public init(start: CMTime, end: CMTime) { - self = CMTimeRangeFromTimeToTime(start: start, end: end) - } - - public var isValid: Bool { - return self.start.isValid && - self.duration.isValid && - (self.duration.epoch == 0) && - (self.duration.value >= 0) - } - - public var isIndefinite: Bool { - return self.isValid && - (self.start.isIndefinite || self.duration.isIndefinite) - } - - public var isEmpty: Bool { - return self.isValid && (self.duration == .zero) - } - - public var end: CMTime { - return CMTimeRangeGetEnd(self) - } - - public func union(_ otherRange: CMTimeRange) -> CMTimeRange { - return CMTimeRangeGetUnion(self, otherRange: otherRange) - } - public func intersection(_ otherRange: CMTimeRange) -> CMTimeRange { - return CMTimeRangeGetIntersection(self, otherRange: otherRange) - } - public func containsTime(_ time: CMTime) -> Bool { - return CMTimeRangeContainsTime(self, time: time) - } - public func containsTimeRange(_ range: CMTimeRange) -> Bool { - return CMTimeRangeContainsTimeRange(self, otherRange: range) - } -} - -public func CMTIMERANGE_IS_VALID (_ range: CMTimeRange) -> Bool { - return range.isValid -} -public func CMTIMERANGE_IS_INVALID (_ range: CMTimeRange) -> Bool { - return !range.isValid -} -public func CMTIMERANGE_IS_INDEFINITE (_ range: CMTimeRange) -> Bool { - return range.isIndefinite -} -public func CMTIMERANGE_IS_EMPTY (_ range: CMTimeRange) -> Bool { - return range.isEmpty -} - -// CMTimeRangeEqual -extension CMTimeRange : Equatable { - public static func == (range1: CMTimeRange, range2: CMTimeRange) -> Bool { - return CMTimeRangeEqual(range1, range2) - } - - public static func != (range1: CMTimeRange, range2: CMTimeRange) -> Bool { - return !CMTimeRangeEqual(range1, range2) - } -} diff --git a/stdlib/public/Darwin/CoreMedia/CMakeLists.txt b/stdlib/public/Darwin/CoreMedia/CMakeLists.txt deleted file mode 100644 index 1b9e50c1f0d2d..0000000000000 --- a/stdlib/public/Darwin/CoreMedia/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftCoreMedia ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - CMTime.swift - CMTimeRange.swift - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Metal Dispatch IOKit Foundation XPC CoreFoundation CoreAudio ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics Metal Dispatch Foundation CoreFoundation CoreAudio ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreGraphics Metal Dispatch Foundation CoreFoundation CoreAudio ObjectiveC # auto-updated - FRAMEWORK_DEPENDS CoreMedia - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_COREMEDIA_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_COREMEDIA_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_COREMEDIA_TVOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/CryptoTokenKit/CMakeLists.txt b/stdlib/public/Darwin/CryptoTokenKit/CMakeLists.txt deleted file mode 100644 index 779d2968ff1ab..0000000000000 --- a/stdlib/public/Darwin/CryptoTokenKit/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftCryptoTokenKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - TKSmartCard.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX - SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch IOKit Foundation XPC CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS CryptoTokenKit - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_CRYPTOTOKENKIT_OSX} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/CryptoTokenKit/TKSmartCard.swift b/stdlib/public/Darwin/CryptoTokenKit/TKSmartCard.swift deleted file mode 100644 index d6756b81b65e0..0000000000000 --- a/stdlib/public/Darwin/CryptoTokenKit/TKSmartCard.swift +++ /dev/null @@ -1,54 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import CryptoTokenKit - -import Foundation - -@available(macOS 10.10, *) -extension TKSmartCard { - public func send(ins: UInt8, p1: UInt8, p2: UInt8, data: Data? = nil, - le: Int? = nil, reply: @escaping (Data?, UInt16, Error?) -> Void) { - - self.__sendIns(ins, p1: p1, p2: p2, data: data, - le: le.map { NSNumber(value: $0) }, reply: reply) - } - - @available(macOS 10.12, *) - public func send(ins: UInt8, p1: UInt8, p2: UInt8, data: Data? = nil, - le: Int? = nil) throws -> (sw: UInt16, response: Data) { - - var sw: UInt16 = 0 - let response = try self.__sendIns(ins, p1: p1, p2: p2, data: data, - le: le.map { NSNumber(value: $0) }, sw: &sw) - return (sw: sw, response: response) - } - - @available(macOS 10.12, *) - public func withSession(_ body: @escaping () throws -> T) throws -> T { - var result: T? - try self.__inSession(executeBlock: { - (errorPointer: NSErrorPointer) -> Bool in - do { - result = try body() - return true - } catch let error as NSError { - errorPointer?.pointee = error - return false - } - }) - - // it is safe to force unwrap the result here, as the self.__inSession - // function rethrows the errors which happened inside the block - return result! - } -} diff --git a/stdlib/public/Darwin/Foundation/CMakeLists.txt b/stdlib/public/Darwin/Foundation/CMakeLists.txt index 8f19f213dc525..4b489d06a297e 100644 --- a/stdlib/public/Darwin/Foundation/CMakeLists.txt +++ b/stdlib/public/Darwin/Foundation/CMakeLists.txt @@ -83,7 +83,7 @@ add_swift_target_library(swiftFoundation ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}" "-Xllvm" "-sil-inline-generics" "-Xllvm" "-sil-partial-specialization" "${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS}" LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch IOKit XPC CoreFoundation ObjectiveC # auto-updated + SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch CoreFoundation ObjectiveC # auto-updated CoreGraphics # imported in Swift SWIFT_MODULE_DEPENDS_IOS Darwin Dispatch CoreFoundation ObjectiveC # auto-updated CoreGraphics # imported in Swift diff --git a/stdlib/public/Darwin/GLKit/CMakeLists.txt b/stdlib/public/Darwin/GLKit/CMakeLists.txt deleted file mode 100644 index 52561c9158b08..0000000000000 --- a/stdlib/public/Darwin/GLKit/CMakeLists.txt +++ /dev/null @@ -1,24 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftGLKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - GYB_SOURCES - GLKMath.swift.gyb - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin CoreImage CoreGraphics Metal Dispatch IOKit simd Foundation CoreData QuartzCore AppKit ModelIO XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch simd Foundation QuartzCore ModelIO CoreFoundation ObjectiveC # auto-updated - os - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch simd Foundation QuartzCore ModelIO CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS GLKit - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_GLKIT_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_GLKIT_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_GLKIT_TVOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/GLKit/GLKMath.swift.gyb b/stdlib/public/Darwin/GLKit/GLKMath.swift.gyb deleted file mode 100644 index da60e05f527db..0000000000000 --- a/stdlib/public/Darwin/GLKit/GLKMath.swift.gyb +++ /dev/null @@ -1,64 +0,0 @@ -//===----------------------------------------------------------*- swift -*-===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// -// GLKit overlays for Swift -//===----------------------------------------------------------------------===// - -@_exported import GLKit // Clang module - -// The GLKit headers provide a fairly complete set of types and operations -// that Swift's importer is now able to present in Swift. However, Swift -// still doesn't know yet how to natively expose the elements of these types. -// This overlay generates Swift accessors for the GLKit matrix and vector -// types. - -// Do dirty pointer manipulations to index an opaque struct like an array. -@inlinable // FIXME(inline-always) -@inline(__always) -public func _indexHomogeneousValue(_ aggregate: UnsafePointer, - _ index: Int) -> T { - return UnsafeRawPointer(aggregate).load( - fromByteOffset: index * MemoryLayout.stride, as: T.self) -} - -%{ -def defineSubscript(Type, limit): - return """ - @inlinable // FIXME(inline-always) - public subscript(i: Int) -> Float {{ - @inline(__always) - get {{ - precondition(i >= 0, "Negative {0} index out of range") - precondition(i < {1}, "{0} index out of range") - - // We can't derive an UnsafePointer from a let binding. Lame. - var clone = self - return _indexHomogeneousValue(&clone, i) - }} - }} - """.format(Type, limit) -}% - -% for size in [2, 3, 4]: - -extension GLKMatrix${size} { - ${ defineSubscript("GLKMatrix" + str(size), size * size) } -} - -extension GLKVector${size} { - ${ defineSubscript("GLKVector" + str(size), size) } -} - -% end - -extension GLKQuaternion { - ${ defineSubscript("GLKQuaternion", 4) } -} diff --git a/stdlib/public/Darwin/GameplayKit/CMakeLists.txt b/stdlib/public/Darwin/GameplayKit/CMakeLists.txt deleted file mode 100644 index 5cfd0e1b1498e..0000000000000 --- a/stdlib/public/Darwin/GameplayKit/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftGameplayKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - GameplayKit.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin CoreImage CoreGraphics Metal Dispatch IOKit GLKit SceneKit simd Foundation CoreData SpriteKit QuartzCore AppKit ModelIO XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch GLKit SceneKit simd Foundation SpriteKit QuartzCore ModelIO CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch GLKit SceneKit simd Foundation SpriteKit QuartzCore ModelIO CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS_WEAK GameplayKit - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_GAMEPLAYKIT_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_GAMEPLAYKIT_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_GAMEPLAYKIT_TVOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/GameplayKit/GameplayKit.swift b/stdlib/public/Darwin/GameplayKit/GameplayKit.swift deleted file mode 100644 index 5fcf3d65aa684..0000000000000 --- a/stdlib/public/Darwin/GameplayKit/GameplayKit.swift +++ /dev/null @@ -1,94 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import GameplayKit // Clang module -import CoreGraphics -import simd - - -@available(iOS, introduced: 9.0) -@available(macOS, introduced: 10.11) -@available(tvOS, introduced: 9.0) -extension GKPath { - /// Creates a path from an array of points - /// - Parameter points: an array of SIMD2 points to make a path from - /// - Parameter radius: radius of the path to create - /// - Parameter cyclical: if the path is of a cycle that loops back on itself - public convenience init(points: [SIMD2], radius: Float, cyclical: Bool) { - var variablePoints = points - self.init(__points: &variablePoints, count: points.count, radius: radius, cyclical: cyclical) - } -} - - -@available(iOS, introduced: 10.0) -@available(macOS, introduced: 10.12) -@available(tvOS, introduced: 10.0) -extension GKPath { - /// Creates a path from an array of points - /// - Parameter points: an array of SIMD3 points to make a path from - /// - Parameter radius: the radius of the path to create - /// - Parameter cyclical: if the path is of a cycle that loops back on itself - public convenience init(points: [SIMD3], radius: Float, cyclical: Bool) { - var variablePoints = points - self.init(__float3Points: &variablePoints, count: points.count, radius: radius, cyclical: cyclical) - } -} - -@available(iOS, introduced: 9.0) -@available(macOS, introduced: 10.11) -@available(tvOS, introduced: 9.0) -extension GKPolygonObstacle { - /// Creates a polygon obstacle with an array of points. - /// - Parameter points: array of points in counter-clockwise order that are the vertices of a convex polygon - public convenience init(points: [SIMD2]) { - var variablePoints = points - self.init(__points: &variablePoints, count: points.count) - } -} - -@available(iOS, introduced: 9.0) -@available(macOS, introduced: 10.11) -@available(tvOS, introduced: 9.0) -extension GKEntity { - /// Gets the component of the indicated class. Returns nil if entity does not have this component - /// - Parameter ofType: the type of the component you want to get - public func component(ofType componentClass: ComponentType.Type) -> ComponentType? { - return self.__component(for: componentClass) as? ComponentType - } - /// Removes the component of the indicates class from this entity - /// - Parameter ofType: the type of component you want to remove - public func removeComponent(ofType componentClass: ComponentType.Type) { - self.__removeComponent(for: componentClass) - } -} - -@objc -internal protocol _SwiftGKStateMachineLike { - @objc(stateForClass:) - func state(forClass: AnyClass) -> AnyObject? -} - -@available(iOS, introduced: 9.0) -@available(macOS, introduced: 10.11) -@available(tvOS, introduced: 9.0) -extension GKStateMachine { - /// Gets the state of the indicated class. Returns nil if the state machine does not have this state. - /// - Parameter forClass: the type of the state you want to get - public func state( - forClass stateClass: StateType.Type) -> StateType? { - // FIXME: GameplayKit marked state(forClass:) unavailable, which means we - // can't use it from SwiftPrivate. Bounce through perform(_:with:) instead. - return self.perform(#selector(_SwiftGKStateMachineLike.state(forClass:)), with: stateClass)?.takeUnretainedValue() as! StateType? - } -} - diff --git a/stdlib/public/Darwin/HomeKit/CMakeLists.txt b/stdlib/public/Darwin/HomeKit/CMakeLists.txt deleted file mode 100644 index ede6485160dfd..0000000000000 --- a/stdlib/public/Darwin/HomeKit/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftHomeKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - HomeKit.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR - SWIFT_MODULE_DEPENDS_IOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch Foundation QuartzCore CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch Foundation QuartzCore CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreGraphics Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - UIKit # required in some configurations but not found by tool - FRAMEWORK_DEPENDS_WEAK HomeKit - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_HOMEKIT_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_HOMEKIT_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_HOMEKIT_TVOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_HOMEKIT_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/HomeKit/HomeKit.swift b/stdlib/public/Darwin/HomeKit/HomeKit.swift deleted file mode 100644 index 4123dde3c116c..0000000000000 --- a/stdlib/public/Darwin/HomeKit/HomeKit.swift +++ /dev/null @@ -1,17 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import HomeKit -import Foundation - -@available(iOS 8.0, watchOS 2.0, tvOS 10.0, *) -public let HMCharacteristicPropertySupportsEventNotification = Notification.Name.HMCharacteristicPropertySupportsEvent.rawValue diff --git a/stdlib/public/Darwin/IOKit/CMakeLists.txt b/stdlib/public/Darwin/IOKit/CMakeLists.txt deleted file mode 100644 index 65bad41b37b72..0000000000000 --- a/stdlib/public/Darwin/IOKit/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftIOKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - IOReturn.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX - SWIFT_MODULE_DEPENDS_OSX Darwin Dispatch CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS IOKit - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_IOKIT_OSX} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/IOKit/IOReturn.swift b/stdlib/public/Darwin/IOKit/IOReturn.swift deleted file mode 100644 index 3c3eeb64f7fe1..0000000000000 --- a/stdlib/public/Darwin/IOKit/IOReturn.swift +++ /dev/null @@ -1,125 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import IOKit - -/// General error -public var kIOReturnError: IOReturn { return iokit_common_err(0x2bc) } -/// Can't allocate memory -public var kIOReturnNoMemory: IOReturn { return iokit_common_err(0x2bd) } -/// Resource shortage -public var kIOReturnNoResources: IOReturn { return iokit_common_err(0x2be) } -/// Error during IPC -public var kIOReturnIPCError: IOReturn { return iokit_common_err(0x2bf) } -/// No such device -public var kIOReturnNoDevice: IOReturn { return iokit_common_err(0x2c0) } -/// Privilege violation -public var kIOReturnNotPrivileged: IOReturn { return iokit_common_err(0x2c1) } -/// Invalid argument -public var kIOReturnBadArgument: IOReturn { return iokit_common_err(0x2c2) } -/// Device read locked -public var kIOReturnLockedRead: IOReturn { return iokit_common_err(0x2c3) } -/// Device write locked -public var kIOReturnLockedWrite: IOReturn { return iokit_common_err(0x2c4) } -/// Exclusive access and device already open -public var kIOReturnExclusiveAccess: IOReturn { return iokit_common_err(0x2c5) } -/// Sent/received messages had different msg_id -public var kIOReturnBadMessageID: IOReturn { return iokit_common_err(0x2c6) } -/// Unsupported function -public var kIOReturnUnsupported: IOReturn { return iokit_common_err(0x2c7) } -/// Misc. VM failure -public var kIOReturnVMError: IOReturn { return iokit_common_err(0x2c8) } -/// Internal error -public var kIOReturnInternalError: IOReturn { return iokit_common_err(0x2c9) } -/// General I/O error -public var kIOReturnIOError: IOReturn { return iokit_common_err(0x2ca) } -/// Can't acquire lock -public var kIOReturnCannotLock: IOReturn { return iokit_common_err(0x2cc) } -/// Device not open -public var kIOReturnNotOpen: IOReturn { return iokit_common_err(0x2cd) } -/// Read not supported -public var kIOReturnNotReadable: IOReturn { return iokit_common_err(0x2ce) } -/// Write not supported -public var kIOReturnNotWritable: IOReturn { return iokit_common_err(0x2cf) } -/// Alignment error -public var kIOReturnNotAligned: IOReturn { return iokit_common_err(0x2d0) } -/// Media error -public var kIOReturnBadMedia: IOReturn { return iokit_common_err(0x2d1) } -/// Device(s) still open -public var kIOReturnStillOpen: IOReturn { return iokit_common_err(0x2d2) } -/// RLD failure -public var kIOReturnRLDError: IOReturn { return iokit_common_err(0x2d3) } -/// DMA failure -public var kIOReturnDMAError: IOReturn { return iokit_common_err(0x2d4) } -/// Device busy -public var kIOReturnBusy: IOReturn { return iokit_common_err(0x2d5) } -/// I/O timeout -public var kIOReturnTimeout: IOReturn { return iokit_common_err(0x2d6) } -/// Device offline -public var kIOReturnOffline: IOReturn { return iokit_common_err(0x2d7) } -/// Not ready -public var kIOReturnNotReady: IOReturn { return iokit_common_err(0x2d8) } -/// Device not attached -public var kIOReturnNotAttached: IOReturn { return iokit_common_err(0x2d9) } -/// No DMA channels left -public var kIOReturnNoChannels: IOReturn { return iokit_common_err(0x2da) } -/// No space for data -public var kIOReturnNoSpace: IOReturn { return iokit_common_err(0x2db) } -/// Port already exists -public var kIOReturnPortExists: IOReturn { return iokit_common_err(0x2dd) } -/// Can't wire down physical memory -public var kIOReturnCannotWire: IOReturn { return iokit_common_err(0x2de) } -/// No interrupt attached -public var kIOReturnNoInterrupt: IOReturn { return iokit_common_err(0x2df) } -/// No DMA frames enqueued -public var kIOReturnNoFrames: IOReturn { return iokit_common_err(0x2e0) } -/// Oversized msg received on interrupt port -public var kIOReturnMessageTooLarge: IOReturn { return iokit_common_err(0x2e1) } -/// Not permitted -public var kIOReturnNotPermitted: IOReturn { return iokit_common_err(0x2e2) } -/// No power to device -public var kIOReturnNoPower: IOReturn { return iokit_common_err(0x2e3) } -/// Media not present -public var kIOReturnNoMedia: IOReturn { return iokit_common_err(0x2e4) } -/// media not formatted -public var kIOReturnUnformattedMedia: IOReturn { return iokit_common_err(0x2e5) } -/// No such mode -public var kIOReturnUnsupportedMode: IOReturn { return iokit_common_err(0x2e6) } -/// Data underrun -public var kIOReturnUnderrun: IOReturn { return iokit_common_err(0x2e7) } -/// Data overrun -public var kIOReturnOverrun: IOReturn { return iokit_common_err(0x2e8) } -/// The device is not working properly -public var kIOReturnDeviceError: IOReturn { return iokit_common_err(0x2e9) } -/// A completion routine is required -public var kIOReturnNoCompletion: IOReturn { return iokit_common_err(0x2ea) } -/// Operation aborted -public var kIOReturnAborted: IOReturn { return iokit_common_err(0x2eb) } -/// Bus bandwidth would be exceeded -public var kIOReturnNoBandwidth: IOReturn { return iokit_common_err(0x2ec) } -/// Device not responding -public var kIOReturnNotResponding: IOReturn { return iokit_common_err(0x2ed) } -/// Isochronous I/O request for distant past -public var kIOReturnIsoTooOld: IOReturn { return iokit_common_err(0x2ee) } -/// Isochronous I/O request for distant future -public var kIOReturnIsoTooNew: IOReturn { return iokit_common_err(0x2ef) } -/// Data was not found -public var kIOReturnNotFound: IOReturn { return iokit_common_err(0x2f0) } -/// Should never be seen -public var kIOReturnInvalid: IOReturn { return iokit_common_err(0x1) } - -internal let SYS_IOKIT = UInt32((0x38 & 0x3f) << 26) -internal let SUB_IOKIT_COMMON = UInt32((0 & 0xfff) << 14) - -internal func iokit_common_err(_ value: UInt32) -> IOReturn { - return IOReturn(bitPattern: SYS_IOKIT | SUB_IOKIT_COMMON | value) -} diff --git a/stdlib/public/Darwin/Intents/CMakeLists.txt b/stdlib/public/Darwin/Intents/CMakeLists.txt deleted file mode 100644 index 6ad05a3529033..0000000000000 --- a/stdlib/public/Darwin/Intents/CMakeLists.txt +++ /dev/null @@ -1,44 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftIntents ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - INBooleanResolutionResult.swift - INCallRecord.swift - INDoubleResolutionResult.swift - INGetCarLockStatusIntentResponse.swift - INGetCarPowerLevelStatusIntentResponse.swift - INIntegerResolutionResult.swift - INIntent.swift - INNotebookItemTypeResolutionResult.swift - INParameter.swift - INPlayMediaIntent.swift - INRequestRideIntent.swift - INRideOption.swift - INSaveProfileInCarIntent.swift - INSearchCallHistoryIntent.swift - INSearchForPhotosIntentResponse.swift - INSetCarLockStatusIntent.swift - INSetClimateSettingsInCarIntent.swift - INSetDefrosterSettingsInCarIntent.swift - INSetProfileInCarIntent.swift - INSetRadioStationIntent.swift - INSetSeatSettingsInCarIntent.swift - INShortcut.swift - INStartPhotoPlaybackIntentResponse.swift - INStartWorkoutIntent.swift - NSStringIntents.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch IOKit Foundation CoreLocation XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin Dispatch Foundation CoreLocation CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_WATCHOS Darwin Dispatch Foundation CoreLocation CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS_WEAK Intents - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_INTENTS_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_INTENTS_IOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/Intents/INBooleanResolutionResult.swift b/stdlib/public/Darwin/Intents/INBooleanResolutionResult.swift deleted file mode 100644 index 14abcfc6a3c24..0000000000000 --- a/stdlib/public/Darwin/Intents/INBooleanResolutionResult.swift +++ /dev/null @@ -1,26 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) -@available(iOS 10.0, watchOS 3.2, *) -extension INBooleanResolutionResult { - @nonobjc public - static func confirmationRequired(with valueToConfirm: Bool?) -> Self { - let number = valueToConfirm.map { NSNumber(value: $0) } - return __confirmationRequiredWithValue(toConfirm: number) - } -} -#endif - diff --git a/stdlib/public/Darwin/Intents/INCallRecord.swift b/stdlib/public/Darwin/Intents/INCallRecord.swift deleted file mode 100644 index f26d7ee16bc1f..0000000000000 --- a/stdlib/public/Darwin/Intents/INCallRecord.swift +++ /dev/null @@ -1,48 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) -@available(iOS 11.0, watchOS 4.0, *) -extension INCallRecord { - @nonobjc - public convenience init( - identifier: String, - dateCreated: Date? = nil, - caller: INPerson? = nil, - callRecordType: INCallRecordType, - callCapability: INCallCapability, - callDuration: Double? = nil, - unseen: Bool? = nil - ) { - self.init(__identifier: identifier, - dateCreated: dateCreated, - caller: caller, - callRecordType: callRecordType, - callCapability: callCapability, - callDuration: callDuration.map { NSNumber(value: $0) }, - unseen: unseen.map { NSNumber(value: $0) }) - } - - @nonobjc - public final var callDuration: Double? { - return __callDuration?.doubleValue - } - - @nonobjc - public final var unseen: Bool? { - return __unseen?.boolValue - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INDoubleResolutionResult.swift b/stdlib/public/Darwin/Intents/INDoubleResolutionResult.swift deleted file mode 100644 index c8d37293eb4d5..0000000000000 --- a/stdlib/public/Darwin/Intents/INDoubleResolutionResult.swift +++ /dev/null @@ -1,25 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) -@available(iOS 10.0, watchOS 3.2, *) -extension INDoubleResolutionResult { - @nonobjc public - static func confirmationRequired(with valueToConfirm: Double?) -> Self { - let number = valueToConfirm.map { NSNumber(value: $0) } - return __confirmationRequiredWithValue(toConfirm: number) - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INGetCarLockStatusIntentResponse.swift b/stdlib/public/Darwin/Intents/INGetCarLockStatusIntentResponse.swift deleted file mode 100644 index 3e8df8e831a9d..0000000000000 --- a/stdlib/public/Darwin/Intents/INGetCarLockStatusIntentResponse.swift +++ /dev/null @@ -1,29 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) -@available(iOS 10.3, watchOS 3.2, *) -extension INGetCarLockStatusIntentResponse { - @nonobjc - public final var locked: Bool? { - get { - return __locked?.boolValue - } - set(newLocked) { - __locked = newLocked.map { NSNumber(value: $0) } - } - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INGetCarPowerLevelStatusIntentResponse.swift b/stdlib/public/Darwin/Intents/INGetCarPowerLevelStatusIntentResponse.swift deleted file mode 100644 index 0d1f3a1cbb558..0000000000000 --- a/stdlib/public/Darwin/Intents/INGetCarPowerLevelStatusIntentResponse.swift +++ /dev/null @@ -1,61 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) -@available(iOS 10.3, watchOS 3.2, *) -extension INGetCarPowerLevelStatusIntentResponse { - @nonobjc - public final var fuelPercentRemaining: Float? { - get { - return __fuelPercentRemaining?.floatValue - } - set(newPercent) { - __fuelPercentRemaining = newPercent.map { NSNumber(value: $0) } - } - } - - @nonobjc - public final var chargePercentRemaining: Float? { - get { - return __chargePercentRemaining?.floatValue - } - set(newPercent) { - __chargePercentRemaining = newPercent.map { NSNumber(value: $0) } - } - } - - @nonobjc - @available(iOS 12.0, watchOS 5.0, *) - public final var charging: Bool? { - get { - return __charging?.boolValue - } - set(newCharging) { - __charging = newCharging.map { NSNumber(value: $0) } - } - } - - @nonobjc - @available(iOS 12.0, watchOS 5.0, *) - public final var minutesToFull: Int? { - get { - return __minutesToFull?.intValue - } - set(newMinutesToFull) { - __minutesToFull = newMinutesToFull.map { NSNumber(value: $0) } - } - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INIntegerResolutionResult.swift b/stdlib/public/Darwin/Intents/INIntegerResolutionResult.swift deleted file mode 100644 index c28e3ae8482da..0000000000000 --- a/stdlib/public/Darwin/Intents/INIntegerResolutionResult.swift +++ /dev/null @@ -1,25 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) -@available(iOS 10.0, watchOS 3.2, *) -extension INIntegerResolutionResult { - @nonobjc public - static func confirmationRequired(with valueToConfirm: Int?) -> Self { - let number = valueToConfirm.map { NSNumber(value: $0) } - return __confirmationRequiredWithValue(toConfirm: number) - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INIntent.swift b/stdlib/public/Darwin/Intents/INIntent.swift deleted file mode 100644 index a93c1c7bb478b..0000000000000 --- a/stdlib/public/Darwin/Intents/INIntent.swift +++ /dev/null @@ -1,42 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) - -public protocol _INIntentSetImageKeyPath { } - -extension _INIntentSetImageKeyPath { - - @available(iOS 12.0, watchOS 5.0, *) - public func setImage(_ image: INImage?, forParameterNamed parameterName: KeyPath) { - if let keyPathString = parameterName._kvcKeyPathString { - (self as! INIntent).__setImage(image, forParameterNamed: keyPathString) - } - } - - @available(iOS 12.0, watchOS 5.0, *) - public func image(forParameterNamed parameterName: KeyPath) -> INImage? { - if let keyPathString = parameterName._kvcKeyPathString { - return (self as! INIntent).__image(forParameterNamed: keyPathString) - } else { - return nil - } - } -} - -@available(iOS 10.0, watchOS 3.2, *) -extension INIntent : _INIntentSetImageKeyPath { } - -#endif diff --git a/stdlib/public/Darwin/Intents/INNotebookItemTypeResolutionResult.swift b/stdlib/public/Darwin/Intents/INNotebookItemTypeResolutionResult.swift deleted file mode 100644 index f5df3d2235439..0000000000000 --- a/stdlib/public/Darwin/Intents/INNotebookItemTypeResolutionResult.swift +++ /dev/null @@ -1,26 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) -@available(iOS 11.0, watchOS 4.0, *) -extension INNotebookItemTypeResolutionResult { - @nonobjc public - static func disambiguation(with notebookItemTypesToDisambiguate: [INNotebookItemType]) -> Self { - let numbers = notebookItemTypesToDisambiguate.map { NSNumber(value: $0.rawValue) } - return __disambiguationWithNotebookItemTypes(toDisambiguate: numbers) - } -} -#endif - diff --git a/stdlib/public/Darwin/Intents/INParameter.swift b/stdlib/public/Darwin/Intents/INParameter.swift deleted file mode 100644 index 123426b8eeef9..0000000000000 --- a/stdlib/public/Darwin/Intents/INParameter.swift +++ /dev/null @@ -1,29 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) -@available(iOS 11.0, *) -extension INParameter { - @nonobjc - public convenience init?(keyPath: KeyPath) { - if let aClass = Root.self as? AnyClass, - let keyPathString = keyPath._kvcKeyPathString { - self.init(for: aClass, keyPath: keyPathString) - } else { - return nil - } - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INPlayMediaIntent.swift b/stdlib/public/Darwin/Intents/INPlayMediaIntent.swift deleted file mode 100644 index e9e010d8d27fc..0000000000000 --- a/stdlib/public/Darwin/Intents/INPlayMediaIntent.swift +++ /dev/null @@ -1,44 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) -@available(iOS 12.0, watchOS 5.0, *) -extension INPlayMediaIntent { - @nonobjc - public convenience init( - mediaItems: [INMediaItem]? = nil, - mediaContainer: INMediaItem? = nil, - playShuffled: Bool? = nil, - playbackRepeatMode: INPlaybackRepeatMode = .unknown, - resumePlayback: Bool? = nil - ) { - self.init(__mediaItems: mediaItems, - mediaContainer: mediaContainer, - playShuffled: playShuffled.map { NSNumber(value: $0) }, - playbackRepeatMode: playbackRepeatMode, - resumePlayback: resumePlayback.map { NSNumber(value: $0) }) - } - - @nonobjc - public final var playShuffled: Bool? { - return __playShuffled?.boolValue - } - - @nonobjc - public final var resumePlayback: Bool? { - return __resumePlayback?.boolValue - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INRequestRideIntent.swift b/stdlib/public/Darwin/Intents/INRequestRideIntent.swift deleted file mode 100644 index 7819d03415dfc..0000000000000 --- a/stdlib/public/Darwin/Intents/INRequestRideIntent.swift +++ /dev/null @@ -1,53 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) -@available(iOS 10.0, watchOS 3.2, *) -extension INRequestRideIntent { - @nonobjc - public convenience init( - pickupLocation: CLPlacemark? = nil, - dropOffLocation: CLPlacemark? = nil, - rideOptionName: INSpeakableString? = nil, - partySize: Int? = nil, - paymentMethod: INPaymentMethod? = nil, - scheduledPickupTime: INDateComponentsRange? = nil - ) { - if #available(iOS 10.3, *) { - self.init(__pickupLocation: pickupLocation, - dropOffLocation: dropOffLocation, - rideOptionName: rideOptionName, - partySize: partySize.map { NSNumber(value: $0) }, - paymentMethod: paymentMethod, - scheduledPickupTime: scheduledPickupTime) - } else { -#if os(iOS) - self.init(__pickupLocation: pickupLocation, - dropOffLocation: dropOffLocation, - rideOptionName: rideOptionName, - partySize: partySize.map { NSNumber(value: $0) }, - paymentMethod: paymentMethod) -#else - fatalError("The initializer is not available") -#endif - } - } - - @nonobjc - public final var partySize: Int? { - return __partySize?.intValue - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INRideOption.swift b/stdlib/public/Darwin/Intents/INRideOption.swift deleted file mode 100644 index 194756d173cef..0000000000000 --- a/stdlib/public/Darwin/Intents/INRideOption.swift +++ /dev/null @@ -1,45 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) - -@available(iOS 10.0, watchOS 3.2, *) -extension INRideOption { - @available(iOS 10.0, watchOS 3.2, *) - @available(swift, obsoleted: 4) - @nonobjc - public var usesMeteredFare: NSNumber? { - get { - return __usesMeteredFare - } - set(newUsesMeteredFare) { - __usesMeteredFare = newUsesMeteredFare - } - } - - @available(iOS 10.0, watchOS 3.2, *) - @available(swift, introduced: 4.0) - @nonobjc - public var usesMeteredFare: Bool? { - get { - return __usesMeteredFare?.boolValue - } - set(newUsesMeteredFare) { - __usesMeteredFare = newUsesMeteredFare.map { NSNumber(value: $0) } - } - } -} - -#endif diff --git a/stdlib/public/Darwin/Intents/INSaveProfileInCarIntent.swift b/stdlib/public/Darwin/Intents/INSaveProfileInCarIntent.swift deleted file mode 100644 index d55103a64afd3..0000000000000 --- a/stdlib/public/Darwin/Intents/INSaveProfileInCarIntent.swift +++ /dev/null @@ -1,32 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) -@available(iOS 10.0, *) -extension INSaveProfileInCarIntent { - @nonobjc - public convenience init( - profileNumber: Int? = nil, profileLabel: String? = nil - ) { - self.init(__profileNumber: profileNumber.map { NSNumber(value: $0) }, - profileLabel: profileLabel) - } - - @nonobjc - public final var profileNumber: Int? { - return __profileNumber?.intValue - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INSearchCallHistoryIntent.swift b/stdlib/public/Darwin/Intents/INSearchCallHistoryIntent.swift deleted file mode 100644 index cc34ede9a219d..0000000000000 --- a/stdlib/public/Darwin/Intents/INSearchCallHistoryIntent.swift +++ /dev/null @@ -1,41 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) -@available(iOS 10.0, watchOS 3.2, *) -extension INSearchCallHistoryIntent { - @available(iOS 11.0, watchOS 4.0, *) - @nonobjc - public convenience init( - dateCreated: INDateComponentsRange? = nil, - recipient: INPerson? = nil, - callCapabilities: INCallCapabilityOptions, - callTypes: INCallRecordTypeOptions, - unseen: Bool? = nil - ) { - self.init(__dateCreated: dateCreated, - recipient: recipient, - callCapabilities: callCapabilities, - callTypes: callTypes, - unseen: unseen.map { NSNumber(value: $0) }) - } - - @available(iOS 11.0, watchOS 4.0, *) - @nonobjc - public final var unseen: Bool? { - return __unseen?.boolValue - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INSearchForPhotosIntentResponse.swift b/stdlib/public/Darwin/Intents/INSearchForPhotosIntentResponse.swift deleted file mode 100644 index 64328219dabf7..0000000000000 --- a/stdlib/public/Darwin/Intents/INSearchForPhotosIntentResponse.swift +++ /dev/null @@ -1,29 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) -@available(iOS 10.0, watchOS 3.2, *) -extension INSearchForPhotosIntentResponse { - @nonobjc - public final var searchResultsCount: Int? { - get { - return __searchResultsCount?.intValue - } - set { - __searchResultsCount = newValue.map { NSNumber(value: $0) } - } - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INSetCarLockStatusIntent.swift b/stdlib/public/Darwin/Intents/INSetCarLockStatusIntent.swift deleted file mode 100644 index 39f7645edd5f4..0000000000000 --- a/stdlib/public/Darwin/Intents/INSetCarLockStatusIntent.swift +++ /dev/null @@ -1,29 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) -@available(iOS 10.3, watchOS 3.2, *) -extension INSetCarLockStatusIntent { - @nonobjc - public convenience init(locked: Bool?, carName: INSpeakableString?) { - self.init(__locked:locked as NSNumber?, carName:carName) - } - - @nonobjc - public final var locked: Bool? { - return __locked?.boolValue - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INSetClimateSettingsInCarIntent.swift b/stdlib/public/Darwin/Intents/INSetClimateSettingsInCarIntent.swift deleted file mode 100644 index 06d678435d426..0000000000000 --- a/stdlib/public/Darwin/Intents/INSetClimateSettingsInCarIntent.swift +++ /dev/null @@ -1,106 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) -@available(iOS 10.0, *) -extension INSetClimateSettingsInCarIntent { - - @nonobjc - @available(iOS 12.0, *) - public convenience init( - enableFan: Bool? = nil, - enableAirConditioner: Bool? = nil, - enableClimateControl: Bool? = nil, - enableAutoMode: Bool? = nil, - airCirculationMode: INCarAirCirculationMode = .unknown, - fanSpeedIndex: Int? = nil, - fanSpeedPercentage: Double? = nil, - relativeFanSpeedSetting: INRelativeSetting = .unknown, - temperature: Measurement? = nil, - relativeTemperatureSetting: INRelativeSetting = .unknown, - climateZone: INCarSeat = .unknown, - carName: INSpeakableString? = nil) { - self.init(__enableFan: enableFan.map { NSNumber(value: $0) }, - enableAirConditioner: enableAirConditioner.map { NSNumber(value: $0) }, - enableClimateControl: enableClimateControl.map { NSNumber(value: $0) }, - enableAutoMode: enableAutoMode.map { NSNumber(value: $0) }, - airCirculationMode: airCirculationMode, - fanSpeedIndex: fanSpeedIndex.map { NSNumber(value: $0) }, - fanSpeedPercentage: fanSpeedPercentage.map { NSNumber(value: $0) }, - relativeFanSpeedSetting: relativeFanSpeedSetting, - temperature: temperature, - relativeTemperatureSetting: relativeTemperatureSetting, - climateZone: climateZone, - carName: carName) - } - - @nonobjc - @available(iOS, obsoleted: 12.0) - public convenience init( - enableFan: Bool? = nil, - enableAirConditioner: Bool? = nil, - enableClimateControl: Bool? = nil, - enableAutoMode: Bool? = nil, - airCirculationMode: INCarAirCirculationMode = .unknown, - fanSpeedIndex: Int? = nil, - fanSpeedPercentage: Double? = nil, - relativeFanSpeedSetting: INRelativeSetting = .unknown, - temperature: Measurement? = nil, - relativeTemperatureSetting: INRelativeSetting = .unknown, - climateZone: INCarSeat = .unknown) { - self.init(__enableFan: enableFan.map { NSNumber(value: $0) }, - enableAirConditioner: enableAirConditioner.map { NSNumber(value: $0) }, - enableClimateControl: enableClimateControl.map { NSNumber(value: $0) }, - enableAutoMode: enableAutoMode.map { NSNumber(value: $0) }, - airCirculationMode: airCirculationMode, - fanSpeedIndex: fanSpeedIndex.map { NSNumber(value: $0) }, - fanSpeedPercentage: fanSpeedPercentage.map { NSNumber(value: $0) }, - relativeFanSpeedSetting: relativeFanSpeedSetting, - temperature: temperature, - relativeTemperatureSetting: relativeTemperatureSetting, - climateZone: climateZone) - } - - @nonobjc - public final var enableFan: Bool? { - return __enableFan?.boolValue - } - - @nonobjc - public final var enableAirConditioner: Bool? { - return __enableAirConditioner?.boolValue - } - - @nonobjc - public final var enableClimateControl: Bool? { - return __enableClimateControl?.boolValue - } - - @nonobjc - public final var enableAutoMode: Bool? { - return __enableAutoMode?.boolValue - } - - @nonobjc - public final var fanSpeedIndex: Int? { - return __fanSpeedIndex?.intValue - } - - @nonobjc - public final var fanSpeedPercentage: Double? { - return __fanSpeedPercentage?.doubleValue - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INSetDefrosterSettingsInCarIntent.swift b/stdlib/public/Darwin/Intents/INSetDefrosterSettingsInCarIntent.swift deleted file mode 100644 index 8eaa1a42bc162..0000000000000 --- a/stdlib/public/Darwin/Intents/INSetDefrosterSettingsInCarIntent.swift +++ /dev/null @@ -1,44 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) -@available(iOS 10.0, *) -extension INSetDefrosterSettingsInCarIntent { - - @nonobjc - @available(iOS 12.0, *) - public convenience init( - enable: Bool? = nil, defroster: INCarDefroster = .unknown, carName: INSpeakableString? = nil - ) { - self.init(__enable: enable.map { NSNumber(value: $0) }, - defroster: defroster, - carName: carName) - } - - @nonobjc - @available(iOS, obsoleted: 12.0) - public convenience init( - enable: Bool? = nil, defroster: INCarDefroster = .unknown - ) { - self.init(__enable: enable.map { NSNumber(value: $0) }, - defroster: defroster) - } - - @nonobjc - public final var enable: Bool? { - return __enable?.boolValue - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INSetProfileInCarIntent.swift b/stdlib/public/Darwin/Intents/INSetProfileInCarIntent.swift deleted file mode 100644 index 06525e7993838..0000000000000 --- a/stdlib/public/Darwin/Intents/INSetProfileInCarIntent.swift +++ /dev/null @@ -1,147 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) -@nonobjc -@available(iOS 10.0, *) -extension INSetProfileInCarIntent { - - @available(iOS 12.0, *) - public convenience init(profileNumber: Int? = nil, profileName: String? = nil, isDefaultProfile: Bool? = nil, carName: INSpeakableString? = nil) { - self.init(__profileNumber: profileNumber.map { NSNumber(value: $0) }, profileName: profileName, defaultProfile: isDefaultProfile.map { NSNumber(value: $0) }, carName: carName) - } - - @available(iOS, introduced: 11.0, obsoleted: 12.0) - public convenience init(profileNumber: Int? = nil, profileName: String? = nil, isDefaultProfile: Bool? = nil) { - self.init(__profileNumber: profileNumber.map { NSNumber(value: $0) }, profileName: profileName, defaultProfile: isDefaultProfile.map { NSNumber(value: $0) }) - } - - @available(iOS, deprecated: 11.0, renamed: "init(profileNumber:profileName:isDefaultProfile:)") - public convenience init(defaultProfile: Int?) { - if #available(iOS 10.3, *) { - self.init(__profileNumber: nil, profileName: nil, defaultProfile: defaultProfile.map { NSNumber(value: $0) }) - } - else { - self.init(__profileNumber: nil, profileLabel: nil, defaultProfile: defaultProfile.map { NSNumber(value: $0) }) - } - } - - @available(iOS, deprecated: 11.0, renamed: "init(profileNumber:profileName:isDefaultProfile:)") - public convenience init(profileLabel: String?) { - if #available(iOS 10.3, *) { - self.init(__profileNumber: nil, profileName: profileLabel, defaultProfile: nil) - } - else { - self.init(__profileNumber: nil, profileLabel: profileLabel, defaultProfile: nil) - } - } - - @available(iOS, deprecated: 11.0, renamed: "init(profileNumber:profileName:isDefaultProfile:)") - public convenience init(profileLabel: String?, defaultProfile: Int?) { - if #available(iOS 10.3, *) { - self.init(__profileNumber: nil, profileName: profileLabel, defaultProfile: defaultProfile.map { NSNumber(value: $0) }) - } - else { - self.init(__profileNumber: nil, profileLabel: profileLabel, defaultProfile: defaultProfile.map { NSNumber(value: $0) }) - } - } - - @available(iOS, deprecated: 11.0, renamed: "init(profileNumber:profileName:isDefaultProfile:)") - public convenience init(profileLabel: String?, isDefaultProfile: Bool?) { - if #available(iOS 10.3, *) { - self.init(__profileNumber: nil, profileName: profileLabel, defaultProfile: isDefaultProfile.map { NSNumber(value: $0) }) - } - else { - self.init(__profileNumber: nil, profileLabel: profileLabel, defaultProfile: isDefaultProfile.map { NSNumber(value: $0) }) - } - } - - @available(iOS, deprecated: 11.0, renamed: "init(profileNumber:profileName:isDefaultProfile:)") - public convenience init(profileName: String?, defaultProfile: Int?) { - if #available(iOS 10.3, *) { - self.init(__profileNumber: nil, profileName: profileName, defaultProfile: defaultProfile.map { NSNumber(value: $0) }) - } - else { - self.init(__profileNumber: nil, profileLabel: profileName, defaultProfile: defaultProfile.map { NSNumber(value: $0) }) - } - } - - @available(iOS, deprecated: 11.0, renamed: "init(profileNumber:profileName:isDefaultProfile:)") - public convenience init(profileNumber: Int?, defaultProfile: Int?) { - if #available(iOS 10.3, *) { - self.init(__profileNumber: profileNumber.map { NSNumber(value: $0) }, profileName: nil, defaultProfile: defaultProfile.map { NSNumber(value: $0) }) - } - else { - self.init(__profileNumber: profileNumber.map { NSNumber(value: $0) }, profileLabel: nil, defaultProfile: defaultProfile.map { NSNumber(value: $0) }) - } - } - - @available(iOS, deprecated: 11.0, renamed: "init(profileNumber:profileName:isDefaultProfile:)") - public convenience init(profileNumber: Int?, profileLabel: String?) { - if #available(iOS 10.3, *) { - self.init(__profileNumber: profileNumber.map { NSNumber(value: $0) }, profileName: profileLabel, defaultProfile: nil) - } - else { - self.init(__profileNumber: profileNumber.map { NSNumber(value: $0) }, profileLabel: profileLabel, defaultProfile: nil) - } - } - - @available(iOS, deprecated: 11.0, renamed: "init(profileNumber:profileName:isDefaultProfile:)") - public convenience init(profileNumber: Int?, profileLabel: String?, defaultProfile: Int?) { - if #available(iOS 10.3, *) { - self.init(__profileNumber: profileNumber.map { NSNumber(value: $0) }, profileName: profileLabel, defaultProfile: defaultProfile.map { NSNumber(value: $0) }) - } - else { - self.init(__profileNumber: profileNumber.map { NSNumber(value: $0) }, profileLabel: profileLabel, defaultProfile: defaultProfile.map { NSNumber(value: $0) }) - } - } - - @available(iOS, deprecated: 11.0, renamed: "init(profileNumber:profileName:isDefaultProfile:)") - public convenience init(profileNumber: Int?, profileLabel: String?, isDefaultProfile: Bool?) { - if #available(iOS 10.3, *) { - self.init(__profileNumber: profileNumber.map { NSNumber(value: $0) }, profileName: profileLabel, defaultProfile: isDefaultProfile.map { NSNumber(value: $0) }) - } - else { - self.init(__profileNumber: profileNumber.map { NSNumber(value: $0) }, profileLabel: profileLabel, defaultProfile: isDefaultProfile.map { NSNumber(value: $0) }) - } - } - - @available(iOS, deprecated: 11.0, renamed: "init(profileNumber:profileName:isDefaultProfile:)") - public convenience init(profileNumber: Int?, profileName: String?, defaultProfile: Int?) { - if #available(iOS 10.3, *) { - self.init(__profileNumber: profileNumber.map { NSNumber(value: $0) }, profileName: profileName, defaultProfile: defaultProfile.map { NSNumber(value: $0) }) - } - else { - self.init(__profileNumber: profileNumber.map { NSNumber(value: $0) }, profileLabel: profileName, defaultProfile: defaultProfile.map { NSNumber(value: $0) }) - } - } - - @available(iOS 10.0, *) - public var isDefaultProfile: Bool? { - return __defaultProfile?.boolValue - } - - @available(swift, deprecated: 3.2, obsoleted: 4.0, - message: "Please use isDefaultProfile instead") - public var defaultProfile: Int? { - return __defaultProfile?.intValue - } - - @available(iOS 10.0, *) - public final var profileNumber: Int? { - return __profileNumber?.intValue - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INSetRadioStationIntent.swift b/stdlib/public/Darwin/Intents/INSetRadioStationIntent.swift deleted file mode 100644 index bfdab48951930..0000000000000 --- a/stdlib/public/Darwin/Intents/INSetRadioStationIntent.swift +++ /dev/null @@ -1,46 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) -@available(iOS 10.0, *) -extension INSetRadioStationIntent { - @nonobjc - public convenience init( - radioType: INRadioType = .unknown, - frequency: Double? = nil, - stationName: String? = nil, - channel: String? = nil, - presetNumber: Int? = nil - ) { - self.init(__radioType: radioType, - frequency: frequency.map { NSNumber(value: $0) }, - stationName: stationName, - channel: channel, - presetNumber: presetNumber.map { NSNumber(value: $0) }) - } - - @nonobjc - public final var frequency: Double? { - return __frequency?.doubleValue - } - - @nonobjc - public final var presetNumber: Int? { - return __presetNumber?.intValue - } - -} - -#endif diff --git a/stdlib/public/Darwin/Intents/INSetSeatSettingsInCarIntent.swift b/stdlib/public/Darwin/Intents/INSetSeatSettingsInCarIntent.swift deleted file mode 100644 index d694d33bfe948..0000000000000 --- a/stdlib/public/Darwin/Intents/INSetSeatSettingsInCarIntent.swift +++ /dev/null @@ -1,78 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) -@available(iOS 10.0, *) -extension INSetSeatSettingsInCarIntent { - - @nonobjc - @available(iOS 12.0, *) - public convenience init( - enableHeating: Bool? = nil, - enableCooling: Bool? = nil, - enableMassage: Bool? = nil, - seat: INCarSeat = .unknown, - level: Int? = nil, - relativeLevel: INRelativeSetting = .unknown, - carName: INSpeakableString? = nil - ) { - self.init(__enableHeating: enableHeating.map { NSNumber(value: $0) }, - enableCooling: enableCooling.map { NSNumber(value: $0) }, - enableMassage: enableMassage.map { NSNumber(value: $0) }, - seat: seat, - level: level.map { NSNumber(value: $0) }, - relativeLevel: relativeLevel, - carName: carName) - } - - @nonobjc - @available(iOS, obsoleted: 12.0) - public convenience init( - enableHeating: Bool? = nil, - enableCooling: Bool? = nil, - enableMassage: Bool? = nil, - seat: INCarSeat = .unknown, - level: Int? = nil, - relativeLevel: INRelativeSetting = .unknown - ) { - self.init(__enableHeating: enableHeating.map { NSNumber(value: $0) }, - enableCooling: enableCooling.map { NSNumber(value: $0) }, - enableMassage: enableMassage.map { NSNumber(value: $0) }, - seat: seat, - level: level.map { NSNumber(value: $0) }, - relativeLevel: relativeLevel) - } - - @nonobjc - public final var enableHeating: Bool? { - return __enableHeating?.boolValue - } - - @nonobjc - public final var enableCooling: Bool? { - return __enableCooling?.boolValue - } - - @nonobjc - public final var enableMassage: Bool? { - return __enableMassage?.boolValue - } - - @nonobjc - public final var level: Int? { - return __level?.intValue - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INShortcut.swift b/stdlib/public/Darwin/Intents/INShortcut.swift deleted file mode 100644 index 069ac3db154ff..0000000000000 --- a/stdlib/public/Darwin/Intents/INShortcut.swift +++ /dev/null @@ -1,123 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) - -@available(iOS 12.0, watchOS 5.0, *) -public enum INShortcut : ReferenceConvertible { - public typealias ReferenceType = INShortcutReference - - case intent(INIntent) - case userActivity(NSUserActivity) - - init(from objcShortcut: INShortcutReference) { - if let intent = objcShortcut.intent { - self = .intent(intent) - } else if let userActivity = objcShortcut.userActivity { - self = .userActivity(userActivity) - } else { - fatalError("INShortcutReference object must have either intent or userActivity") - } - } -} - -// Convenience initializers, to mimic the ObjC initializer API -@available(iOS 12.0, watchOS 5.0, *) -extension INShortcut { - public init?(intent: INIntent) { - // use the ObjC initializer, to re-use its validation of the intent - guard let ref = INShortcutReference(intent: intent) else { return nil } - self.init(from: ref) - } - public init(userActivity: NSUserActivity) { - self = .userActivity(userActivity) - } -} - -// Convenience properties, to mimic the ObjC API -@available(iOS 12.0, watchOS 5.0, *) -extension INShortcut { - public var intent: INIntent? { - guard case let .intent(intent) = self else { return nil } - return intent - } - public var userActivity: NSUserActivity? { - guard case let .userActivity(userActivity) = self else { return nil } - return userActivity - } -} - -@available(iOS 12.0, watchOS 5.0, *) -extension INShortcut : CustomStringConvertible { - public var description: String { - return reference.description - } -} - -@available(iOS 12.0, watchOS 5.0, *) -extension INShortcut : CustomDebugStringConvertible { - public var debugDescription: String { - return reference.debugDescription - } -} - -@available(iOS 12.0, watchOS 5.0, *) -extension INShortcut : Hashable { - public func hash(into hasher: inout Hasher) { - reference.hash(into: &hasher) - } -} - -@available(iOS 12.0, watchOS 5.0, *) -extension INShortcut : Equatable {} - -@available(iOS 12.0, watchOS 5.0, *) -extension INShortcut { - fileprivate var reference: INShortcutReference { - switch self { - case .intent(let intent): - return INShortcutReference(intent: intent)! - case .userActivity(let userActivity): - return INShortcutReference(userActivity: userActivity) - } - } -} - -@available(iOS 12.0, watchOS 5.0, *) -extension INShortcut : _ObjectiveCBridgeable { - @_semantics("convertToObjectiveC") - public func _bridgeToObjectiveC() -> INShortcutReference { - return self.reference - } - - public static func _forceBridgeFromObjectiveC(_ source: INShortcutReference, result: inout INShortcut?) { - if !_conditionallyBridgeFromObjectiveC(source, result: &result) { - fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)") - } - } - - public static func _conditionallyBridgeFromObjectiveC(_ source: INShortcutReference, result: inout INShortcut?) -> Bool { - result = INShortcut(from: source) - return true - } - - @_effects(readonly) - public static func _unconditionallyBridgeFromObjectiveC(_ source: INShortcutReference?) -> INShortcut { - guard let src = source else { fatalError("Missing source") } - return INShortcut(from: src) - } -} - -#endif diff --git a/stdlib/public/Darwin/Intents/INStartPhotoPlaybackIntentResponse.swift b/stdlib/public/Darwin/Intents/INStartPhotoPlaybackIntentResponse.swift deleted file mode 100644 index e6b417fdefe62..0000000000000 --- a/stdlib/public/Darwin/Intents/INStartPhotoPlaybackIntentResponse.swift +++ /dev/null @@ -1,29 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) -@available(iOS 10.0, watchOS 3.2, *) -extension INStartPhotoPlaybackIntentResponse { - @nonobjc - public final var searchResultsCount: Int? { - get { - return __searchResultsCount?.intValue - } - set { - __searchResultsCount = newValue.map { NSNumber(value: $0) } - } - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/INStartWorkoutIntent.swift b/stdlib/public/Darwin/Intents/INStartWorkoutIntent.swift deleted file mode 100644 index 3434eb060ae5e..0000000000000 --- a/stdlib/public/Darwin/Intents/INStartWorkoutIntent.swift +++ /dev/null @@ -1,44 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -#if os(iOS) || os(watchOS) -@available(iOS 10.0, watchOS 3.2, *) -extension INStartWorkoutIntent { - @nonobjc - public convenience init( - workoutName: INSpeakableString? = nil, - goalValue: Double? = nil, - workoutGoalUnitType: INWorkoutGoalUnitType = .unknown, - workoutLocationType: INWorkoutLocationType = .unknown, - isOpenEnded: Bool? = nil - ) { - self.init(__workoutName: workoutName, - goalValue: goalValue.map { NSNumber(value: $0) }, - workoutGoalUnitType: workoutGoalUnitType, - workoutLocationType: workoutLocationType, - isOpenEnded: isOpenEnded.map { NSNumber(value: $0) }) - } - - @nonobjc - public final var goalValue: Double? { - return __goalValue?.doubleValue - } - - @nonobjc - public final var isOpenEnded: Bool? { - return __isOpenEnded?.boolValue - } -} -#endif diff --git a/stdlib/public/Darwin/Intents/NSStringIntents.swift b/stdlib/public/Darwin/Intents/NSStringIntents.swift deleted file mode 100644 index 9d6d00e9daa50..0000000000000 --- a/stdlib/public/Darwin/Intents/NSStringIntents.swift +++ /dev/null @@ -1,35 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Intents -import Foundation - -extension NSString { - @available(OSX 10.14, iOS 12.0, watchOS 5.0, *) - public class func deferredLocalizedIntentsString(with format: String, _ args: CVarArg...) -> NSString { - return withVaList(args) { - self.__deferredLocalizedIntentsString(withFormat: format, fromTable: nil, arguments: $0) as NSString - } - } - - @available(OSX 10.14, iOS 12.0, watchOS 5.0, *) - public class func deferredLocalizedIntentsString(with format: String, table: String, _ args: CVarArg...) -> NSString { - return withVaList(args) { - self.__deferredLocalizedIntentsString(withFormat: format, fromTable: table, arguments: $0) as NSString - } - } - - @available(OSX 10.14, iOS 12.0, watchOS 5.0, *) - public class func deferredLocalizedIntentsString(with format: String, table: String, arguments: CVaListPointer) -> NSString { - return self.__deferredLocalizedIntentsString(withFormat: format, fromTable: table, arguments: arguments) as NSString - } -} diff --git a/stdlib/public/Darwin/MapKit/CMakeLists.txt b/stdlib/public/Darwin/MapKit/CMakeLists.txt deleted file mode 100644 index 8b1ffc99bda59..0000000000000 --- a/stdlib/public/Darwin/MapKit/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftMapKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - - GYB_SOURCES - NSValue.swift.gyb - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - SWIFT_MODULE_DEPENDS_OSX Darwin CoreImage CoreGraphics Metal Dispatch IOKit Foundation CoreData CoreLocation QuartzCore AppKit XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch Foundation CoreLocation QuartzCore CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch Foundation CoreLocation QuartzCore CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreGraphics UIKit Dispatch Foundation CoreLocation CoreFoundation ObjectiveC # auto-updated - UIKit # required in some configurations but not found by tool - FRAMEWORK_DEPENDS MapKit - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_MAPKIT_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_MAPKIT_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_MAPKIT_TVOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_MAPKIT_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/MapKit/NSValue.swift.gyb b/stdlib/public/Darwin/MapKit/NSValue.swift.gyb deleted file mode 100644 index d6ec015102584..0000000000000 --- a/stdlib/public/Darwin/MapKit/NSValue.swift.gyb +++ /dev/null @@ -1,36 +0,0 @@ -@_exported import MapKit // Clang module -import Foundation - -%{ -from gyb_foundation_support import \ - ObjectiveCBridgeableImplementationForNSValueWithCategoryMethods -}% - -// Get the ObjC type used by -[NSValue valueWithMKCoordinateSpan:] -// to instantiate the resulting NSValue objects, in case these get changed -// in the future. -@available(tvOS 9.2, *) -private let MKCoordinateSpanInNSValueObjCType = - NSValue(mkCoordinateSpan: .init()).objCType - -${ ObjectiveCBridgeableImplementationForNSValueWithCategoryMethods( - Type="MKCoordinateSpan", - initializer="""{ - guard #available(tvOS 9.2, *) else { - fatalError("MKCoordinateSpan is not supported on tvOS before tvOS 9.2") - } - return NSValue(mkCoordinateSpan: $0) - }""", - getter="""{ - guard #available(tvOS 9.2, *) else { - fatalError("MKCoordinateSpan is not supported on tvOS before tvOS 9.2") - } - return $0.mkCoordinateSpanValue - }""", - objCType="""{ _ in - guard #available(tvOS 9.2, *) else { - fatalError("MKCoordinateSpan is not supported on tvOS before tvOS 9.2") - } - return MKCoordinateSpanInNSValueObjCType - }""", -) } diff --git a/stdlib/public/Darwin/MediaPlayer/CMakeLists.txt b/stdlib/public/Darwin/MediaPlayer/CMakeLists.txt deleted file mode 100644 index 0700ae75b0d6b..0000000000000 --- a/stdlib/public/Darwin/MediaPlayer/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftMediaPlayer ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - MPMusicPlayerPlayParameters.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" "-L${sdk}/usr/lib/swift/" - TARGET_SDKS IOS IOS_SIMULATOR - - SWIFT_MODULE_DEPENDS_IOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch simd Foundation AVFoundation CoreMedia QuartzCore CoreFoundation CoreAudio ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_FROM_SDK CoreMIDI - FRAMEWORK_DEPENDS_WEAK MediaPlayer - - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_MEDIAPLAYER_IOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/MediaPlayer/MPMusicPlayerPlayParameters.swift b/stdlib/public/Darwin/MediaPlayer/MPMusicPlayerPlayParameters.swift deleted file mode 100644 index 566e769ab6a7c..0000000000000 --- a/stdlib/public/Darwin/MediaPlayer/MPMusicPlayerPlayParameters.swift +++ /dev/null @@ -1,69 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import MediaPlayer -import Foundation - -@available(iOS 11.0, *) -extension MPMusicPlayerPlayParameters: Codable { - public required convenience init(from decoder: Decoder) throws { - var playParametersDictionary: [String: Any] = [:] - let values = try decoder.container(keyedBy: CodingKeys.self) - - if let id = try values.decodeIfPresent(String.self, forKey: .id) { - playParametersDictionary[CodingKeys.id.rawValue] = id - } - else if let id = try values.decodeIfPresent(Int64.self, forKey: .id) { - playParametersDictionary[CodingKeys.id.rawValue] = NSNumber(value: id) - } - - if let kind = try values.decodeIfPresent(String.self, forKey: .kind) { - playParametersDictionary[CodingKeys.kind.rawValue] = kind - } - - if let isLibrary = try values.decodeIfPresent(Bool.self, forKey: .isLibrary) { - playParametersDictionary[CodingKeys.isLibrary.rawValue] = NSNumber(value: isLibrary) - } - - guard MPMusicPlayerPlayParameters(dictionary: playParametersDictionary) != nil else { - throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, - debugDescription: "Attempted to decode MPMusicPlayerPlayParameters from invalid playParams dictionary.")) - } - self.init(dictionary: playParametersDictionary)! - } - - public func encode(to encoder: Encoder) throws { - let playParametersDictionary = self.dictionary - var values = encoder.container(keyedBy: CodingKeys.self) - - if let id = playParametersDictionary[CodingKeys.id.rawValue] as? String { - try values.encode(id, forKey: .id) - } - else if let id = playParametersDictionary[CodingKeys.id.rawValue] as? Int64 { - try values.encode(id, forKey: .id) - } - - if let kind = playParametersDictionary[CodingKeys.kind.rawValue] as? String { - try values.encode(kind, forKey: .kind) - } - - if let isLibrary = playParametersDictionary[CodingKeys.isLibrary.rawValue] as? Bool { - try values.encode(isLibrary, forKey: .isLibrary) - } - } - - internal enum CodingKeys: String, CodingKey { - case id - case kind - case isLibrary - } -} diff --git a/stdlib/public/Darwin/Metal/CMakeLists.txt b/stdlib/public/Darwin/Metal/CMakeLists.txt deleted file mode 100644 index eba6b8c1b7077..0000000000000 --- a/stdlib/public/Darwin/Metal/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftMetal ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - Metal.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch IOKit Foundation XPC CoreFoundation ObjectiveC # auto-updated - os - SWIFT_MODULE_DEPENDS_IOS Darwin Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - os - SWIFT_MODULE_DEPENDS_TVOS Darwin Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - os - - FRAMEWORK_DEPENDS_WEAK Metal - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_METAL_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_METAL_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_METAL_TVOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/Metal/Metal.swift b/stdlib/public/Darwin/Metal/Metal.swift deleted file mode 100644 index c1dd0847c693c..0000000000000 --- a/stdlib/public/Darwin/Metal/Metal.swift +++ /dev/null @@ -1,282 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Metal // Clang module - -@available(macOS 10.11, iOS 8.0, tvOS 8.0, *) -extension MTLBlitCommandEncoder { - - public func fill(buffer: MTLBuffer, range: Range, value: UInt8) { - __fill(buffer, range: NSRange(location: range.lowerBound, length: range.count), value: value) - } - - @available(macOS 10.14, iOS 12.0, tvOS 12.0, *) - public func resetCommandsInBuffer(_ buffer: MTLIndirectCommandBuffer, range: Range) { - __resetCommands(in: buffer, with: NSRange(location: range.lowerBound, length: range.count)) - } - - @available(macOS 10.14, iOS 12.0, tvOS 12.0, *) - public func copyIndirectCommandBuffer (_ buffer: MTLIndirectCommandBuffer, sourceRange: Range, destination: MTLIndirectCommandBuffer, destinationIndex: Int) { - __copy (buffer, sourceRange: NSRange(location: sourceRange.lowerBound, length: sourceRange.count),destination: destination, destinationIndex: destinationIndex) - } - @available(macOS 10.14, iOS 12.0, tvOS 12.0, *) - public func optimizeIndirectCommandBuffer (_ buffer: MTLIndirectCommandBuffer, range: Range) { - __optimizeIndirectCommandBuffer(buffer, with: NSRange(location: range.lowerBound, length: range.count)) - } -} - -@available(macOS 10.11, iOS 8.0, tvOS 8.0, *) -extension MTLBuffer { - -#if os(macOS) - @available(macOS, introduced: 10.11) - public func didModifyRange(_ range: Range) { - __didModifyRange(NSRange(location: range.lowerBound, length: range.count)) - } -#endif - - @available(macOS 10.12, iOS 10.0, tvOS 10.0, *) - public func addDebugMarker(_ marker: String, range: Range) { - __addDebugMarker(marker, range: NSRange(location: range.lowerBound, length: range.count)) - } -} - -@available(macOS 10.11, iOS 8.0, tvOS 8.0, *) -extension MTLComputeCommandEncoder { - - @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) - public func useResources(_ resources: [MTLResource], usage: MTLResourceUsage) { - __use(resources, count: resources.count, usage: usage) - } - - @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) - public func useHeaps(_ heaps: [MTLHeap]) { - __use(heaps, count: heaps.count) - } - - public func setBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range) { - __setBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) - } - - public func setTextures(_ textures: [MTLTexture?], range: Range) { - __setTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) - } - - public func setSamplerStates(_ samplers: [MTLSamplerState?], range: Range) { - __setSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) - } - - public func setSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range) { - __setSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) - } - - @available(macOS 10.14, iOS 12.0, tvOS 12.0, *) - public func memoryBarrier(resources:[MTLResource]) { - __memoryBarrier(resources: resources, count: resources.count) - } -} - -@available(macOS 10.11, iOS 8.0, tvOS 8.0, *) -extension MTLDevice { - - @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) - public func getDefaultSamplePositions(sampleCount: Int) -> [MTLSamplePosition] { - return [MTLSamplePosition](unsafeUninitializedCapacity: sampleCount) { buf, initializedCount in - __getDefaultSamplePositions(buf.baseAddress!, count: sampleCount) - initializedCount = sampleCount - } - } -} - -#if os(macOS) -@available(swift 4) -@available(macOS 10.13, *) -public func MTLCopyAllDevicesWithObserver(handler: @escaping MTLDeviceNotificationHandler) -> (devices:[MTLDevice], observer:NSObject) { - var observer: NSObjectProtocol? - let devices = __MTLCopyAllDevicesWithObserver(&observer, handler) - // FIXME: The force cast here isn't great – ideally we would return the - // observer as an NSObjectProtocol. - return (devices, observer as! NSObject) -} -#endif - -@available(macOS 10.12, iOS 10.0, tvOS 10.0, *) -extension MTLFunctionConstantValues { - - public func setConstantValues(_ values: UnsafeRawPointer, type: MTLDataType, range: Range) { - __setConstantValues(values, type: type, with: NSRange(location: range.lowerBound, length: range.count)) - } - -} - -@available(macOS 10.13, iOS 11.0, tvOS 11.0, *) -extension MTLArgumentEncoder { - - public func setBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range) { - __setBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) - } - - public func setTextures(_ textures: [MTLTexture?], range: Range) { - __setTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) - } - - public func setSamplerStates(_ samplers: [MTLSamplerState?], range: Range) { - __setSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) - } - - #if os(macOS) - @available(macOS 10.14, *) - public func setRenderPipelineStates(_ pipelines: [MTLRenderPipelineState?], range: Range) { - __setRenderPipelineStates(pipelines, with: NSRange(location: range.lowerBound, length: range.count)) - } - #endif - - @available(macOS 10.14, iOS 12.0, tvOS 12.0, *) - public func setIndirectCommandBuffers(_ buffers: [MTLIndirectCommandBuffer?], range: Range) { - __setIndirectCommandBuffers(buffers, with: NSRange(location: range.lowerBound, length: range.count)) - } -} - -@available(macOS 10.11, iOS 8.0, tvOS 8.0, *) -extension MTLRenderCommandEncoder { - - @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) - public func useResources(_ resources: [MTLResource], usage: MTLResourceUsage) { - __use(resources, count: resources.count, usage: usage) - } - - @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) - public func useHeaps(_ heaps: [MTLHeap]) { - __use(heaps, count: heaps.count) - } - -#if os(macOS) || os(iOS) - @available(macOS 10.13, iOS 12.0, *) - public func setViewports(_ viewports: [MTLViewport]) { - __setViewports(viewports, count: viewports.count) - } - - @available(macOS 10.13, iOS 12.0, *) - public func setScissorRects(_ scissorRects: [MTLScissorRect]) { - __setScissorRects(scissorRects, count: scissorRects.count) - } -#endif - - public func setVertexBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range) { - __setVertexBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) - } - - public func setVertexTextures(_ textures: [MTLTexture?], range: Range) { - __setVertexTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) - } - - public func setVertexSamplerStates(_ samplers: [MTLSamplerState?], range: Range) { - __setVertexSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) - } - - public func setVertexSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range) { - __setVertexSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) - } - - public func setFragmentBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range) { - __setFragmentBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) - } - - public func setFragmentTextures(_ textures: [MTLTexture?], range: Range) { - __setFragmentTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) - } - - public func setFragmentSamplerStates(_ samplers: [MTLSamplerState?], range: Range) { - __setFragmentSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) - } - - public func setFragmentSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range) { - __setFragmentSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) - } - -#if os(iOS) - - @available(iOS 11.0, *) - public func setTileBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range) { - __setTileBuffers(buffers, offsets: offsets, with: NSRange(location: range.lowerBound, length: range.count)) - } - - @available(iOS 11.0, *) - public func setTileTextures(_ textures: [MTLTexture?], range: Range) { - __setTileTextures(textures, with: NSRange(location: range.lowerBound, length: range.count)) - } - - @available(iOS 11.0, *) - public func setTileSamplerStates(_ samplers: [MTLSamplerState?], range: Range) { - __setTileSamplerStates(samplers, with: NSRange(location: range.lowerBound, length: range.count)) - } - - @available(iOS 11.0, *) - public func setTileSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range) { - __setTileSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSRange(location: range.lowerBound, length: range.count)) - } -#endif - -#if os(macOS) - @available(macOS 10.14, *) - public func memoryBarrier(resources: [MTLResource], after: MTLRenderStages, before: MTLRenderStages) { - __memoryBarrier(resources: resources, count: resources.count, after: after, before: before) - } -#endif - - @available(macOS 10.14, iOS 12.0, tvOS 12.0, *) - public func executeCommandsInBuffer(_ buffer: MTLIndirectCommandBuffer, range: Range) { - __executeCommands(in: buffer, with: NSRange(location: range.lowerBound, length: range.count)) - } - - #if os(macOS) - @available(macOS 10.14, *) - public func executeCommandsInBuffer(_ buffer: MTLIndirectCommandBuffer, indirectBuffer indirectRangeBuffer: MTLBuffer, offset: Int) { - __executeCommands(in: buffer, indirectBuffer: indirectRangeBuffer, indirectBufferOffset: offset) - } - #endif -} - -@available(macOS 10.14, iOS 12.0, tvOS 12.0, *) -extension MTLIndirectCommandBuffer { - public func reset(_ range: Range) { - __reset(with: NSRange(location: range.lowerBound, length: range.count)) - } -} - -@available(macOS 10.11, iOS 8.0, tvOS 8.0, *) -extension MTLRenderPassDescriptor { - - @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) - public func setSamplePositions(_ positions: [MTLSamplePosition]) { - __setSamplePositions(positions, count: positions.count) - } - - @available(macOS 10.13, iOS 11.0, tvOS 11.0, *) - public func getSamplePositions() -> [MTLSamplePosition] { - let numPositions = __getSamplePositions(nil, count: 0) - return [MTLSamplePosition](unsafeUninitializedCapacity: numPositions) { buf, initializedCount in - __getSamplePositions(buf.baseAddress!, count: numPositions) - initializedCount = numPositions - } - } - -} - -@available(macOS 10.11, iOS 8.0, tvOS 8.0, *) -extension MTLTexture { - - @available(macOS 10.11, iOS 9.0, tvOS 9.0, *) - public func makeTextureView(pixelFormat: MTLPixelFormat, textureType: MTLTextureType, levels levelRange: Range, slices sliceRange: Range) -> MTLTexture? { - return __newTextureView(with: pixelFormat, textureType: textureType, levels: NSRange(location: levelRange.lowerBound, length: levelRange.count), slices: NSRange(location: sliceRange.lowerBound, length: sliceRange.count)) - } -} diff --git a/stdlib/public/Darwin/MetalKit/CMakeLists.txt b/stdlib/public/Darwin/MetalKit/CMakeLists.txt deleted file mode 100644 index 652b592738132..0000000000000 --- a/stdlib/public/Darwin/MetalKit/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftMetalKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - MetalKit.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin CoreImage CoreGraphics Metal Dispatch IOKit simd Foundation CoreData QuartzCore AppKit ModelIO XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch simd Foundation QuartzCore ModelIO CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch simd Foundation QuartzCore ModelIO CoreFoundation ObjectiveC # auto-updated - - FRAMEWORK_DEPENDS_WEAK MetalKit - FRAMEWORK_DEPENDS_WEAK Metal - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_METALKIT_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_METALKIT_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_METALKIT_TVOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/MetalKit/MetalKit.swift b/stdlib/public/Darwin/MetalKit/MetalKit.swift deleted file mode 100644 index 285302b0b64f9..0000000000000 --- a/stdlib/public/Darwin/MetalKit/MetalKit.swift +++ /dev/null @@ -1,44 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import MetalKit // Clang module - -@available(macOS 10.11, iOS 9.0, tvOS 9.0, *) -extension MTKMesh { - public class func newMeshes(asset: MDLAsset, device: MTLDevice) throws -> (modelIOMeshes: [MDLMesh], metalKitMeshes: [MTKMesh]) { - var modelIOMeshes: NSArray? - let metalKitMeshes = try MTKMesh.__newMeshes(from: asset, device: device, sourceMeshes: &modelIOMeshes) - return (modelIOMeshes: modelIOMeshes as! [MDLMesh], metalKitMeshes: metalKitMeshes) - } -} - -@available(swift 4) -@available(macOS 10.12, iOS 10.0, tvOS 10.0, *) -public func MTKModelIOVertexDescriptorFromMetalWithError(_ metalDescriptor: MTLVertexDescriptor) throws -> MDLVertexDescriptor { - var error: NSError? = nil - let result = __MTKModelIOVertexDescriptorFromMetalWithError(metalDescriptor, &error) - if let error = error { - throw error - } - return result -} - -@available(swift 4) -@available(macOS 10.12, iOS 10.0, tvOS 10.0, *) -public func MTKMetalVertexDescriptorFromModelIOWithError(_ modelIODescriptor: MDLVertexDescriptor) throws -> MTLVertexDescriptor? { - var error: NSError? = nil - let result = __MTKMetalVertexDescriptorFromModelIOWithError(modelIODescriptor, &error) - if let error = error { - throw error - } - return result -} diff --git a/stdlib/public/Darwin/ModelIO/CMakeLists.txt b/stdlib/public/Darwin/ModelIO/CMakeLists.txt deleted file mode 100644 index b85d0e225e741..0000000000000 --- a/stdlib/public/Darwin/ModelIO/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftModelIO ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - ModelIO.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR - - SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch IOKit simd Foundation XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics Dispatch simd Foundation CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreGraphics Dispatch simd Foundation CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS_WEAK ModelIO - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/ModelIO/ModelIO.swift b/stdlib/public/Darwin/ModelIO/ModelIO.swift deleted file mode 100644 index 908f85214ee36..0000000000000 --- a/stdlib/public/Darwin/ModelIO/ModelIO.swift +++ /dev/null @@ -1,368 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import ModelIO -import simd - -extension Array { - fileprivate init( - unsafeUninitializedCount count: Int, - initializedWith initializer: (UnsafeMutablePointer) -> Void - ) { - self.init(unsafeUninitializedCapacity: count) { buffer, initializedCount in - initializer(buffer.baseAddress!) - initializedCount = count - } - } -} - -@available(macOS, introduced: 10.13) -@available(iOS, introduced: 11.0) -@available(tvOS, introduced: 11.0) -extension MDLMatrix4x4Array { - @nonobjc public var float4x4Array: [float4x4] { - get { - let count = elementCount - return [float4x4](unsafeUninitializedCount: count) { ptr in - __getFloat4x4Array(ptr, maxCount: count) - } - } - set(array) { - __setFloat4x4(array, count: array.count) - } - } - - @nonobjc public var double4x4Array: [double4x4] { - get { - let count = elementCount - return [double4x4](unsafeUninitializedCount: count) { ptr in - __getDouble4x4Array(ptr, maxCount: count) - } - } - set(array) { - __setDouble4x4(array, count: array.count) - } - } -} - - - -@available(macOS, introduced: 10.13) -@available(iOS, introduced: 11.0) -@available(tvOS, introduced: 11.0) -extension MDLAnimatedValue { - @nonobjc public var times: [TimeInterval] { - get { - return [TimeInterval](unsafeUninitializedCount: timeSampleCount) { ptr in - __getTimes(ptr, maxCount: timeSampleCount) - } - } - } -} - -@available(macOS, introduced: 10.13) -@available(iOS, introduced: 11.0) -@available(tvOS, introduced: 11.0) -extension MDLAnimatedScalarArray { - @nonobjc public func set(floatArray array:[Float], atTime time: TimeInterval){ - __setFloat(array, count: array.count, atTime: time) - } - - @nonobjc public func set(doubleArray array:[Double], atTime time: TimeInterval){ - __setDouble(array, count: array.count, atTime: time) - } - - @nonobjc public func floatArray(atTime time: TimeInterval) -> [Float] { - return [Float](unsafeUninitializedCount: elementCount) { ptr in - __getFloat(ptr, maxCount: elementCount, atTime: time) - } - } - - @nonobjc public func doubleArray(atTime time: TimeInterval) -> [Double] { - return [Double](unsafeUninitializedCount: elementCount) { ptr in - __getDouble(ptr, maxCount: elementCount, atTime: time) - } - } - - @nonobjc public func reset(floatArray array:[Float], atTimes times: [TimeInterval]){ - __reset(with: array, count: array.count, atTimes: times, count: times.count) - } - - @nonobjc public func reset(doubleArray array:[Double], atTimes times: [TimeInterval]){ - __reset(with: array, count: array.count, atTimes: times, count: times.count) - } - - @nonobjc public var floatArray: [Float] { - get { - let count = elementCount * timeSampleCount - return [Float](unsafeUninitializedCount: count) { ptr in - __getFloat(ptr, maxCount: count) - } - } - } - - @nonobjc public var doubleArray: [Double] { - get { - let count = elementCount * timeSampleCount - return [Double](unsafeUninitializedCount: count) { ptr in - __getDouble(ptr, maxCount: count) - } - } - } -} - -@available(macOS, introduced: 10.13) -@available(iOS, introduced: 11.0) -@available(tvOS, introduced: 11.0) -extension MDLAnimatedVector3Array { - @nonobjc public func set(float3Array array:[SIMD3], atTime time: TimeInterval){ - __setFloat3(array, count: array.count, atTime: time) - } - - @nonobjc public func set(double3Array array:[SIMD3], atTime time: TimeInterval){ - __setDouble3(array, count: array.count, atTime: time) - } - - @nonobjc public func float3Array(atTime time: TimeInterval) -> [SIMD3] { - return [SIMD3](unsafeUninitializedCount: elementCount) { ptr in - __getFloat3Array(ptr, maxCount: elementCount, atTime: time) - } - } - - @nonobjc public func double3Array(atTime time: TimeInterval) -> [SIMD3] { - return [SIMD3](unsafeUninitializedCount: elementCount) { ptr in - __getDouble3Array(ptr, maxCount: elementCount, atTime: time) - } - } - - @nonobjc public func reset(float3Array array:[SIMD3], atTimes times: [TimeInterval]){ - __reset(withFloat3Array: array, count: array.count, atTimes: times, count: times.count) - } - - @nonobjc public func reset(double3Array array:[SIMD3], atTimes times: [TimeInterval]){ - __reset(withDouble3Array: array, count: array.count, atTimes: times, count: times.count) - } - - @nonobjc public var float3Array: [SIMD3] { - get { - let count = elementCount * timeSampleCount - return [SIMD3](unsafeUninitializedCount: count) { ptr in - __getFloat3Array(ptr, maxCount: count) - } - } - } - - @nonobjc public var double3Array: [SIMD3] { - get { - let count = elementCount * timeSampleCount - return [SIMD3](unsafeUninitializedCount: count) { ptr in - __getDouble3Array(ptr, maxCount: count) - } - } - } -} - -@available(macOS, introduced: 10.13) -@available(iOS, introduced: 11.0) -@available(tvOS, introduced: 11.0) -extension MDLAnimatedQuaternionArray { - @nonobjc public func set(floatQuaternionArray array:[simd_quatf], atTime time: TimeInterval){ - __setFloat(array, count: array.count, atTime: time) - } - - @nonobjc public func set(doubleQuaternionArray array:[simd_quatd], atTime time: TimeInterval){ - __setDouble(array, count: array.count, atTime: time) - } - - @nonobjc public func floatQuaternionArray(atTime time: TimeInterval) -> [simd_quatf] { - return [simd_quatf](unsafeUninitializedCount: elementCount) { ptr in - __getFloat(ptr, maxCount: elementCount, atTime: time) - } - } - - @nonobjc public func doubleQuaternionArray(atTime time: TimeInterval) -> [simd_quatd] { - return [simd_quatd](unsafeUninitializedCount: elementCount) { ptr in - __getDouble(ptr, maxCount: elementCount, atTime: time) - } - } - - @nonobjc public func reset(floatQuaternionArray array:[simd_quatf], atTimes times: [TimeInterval]){ - __reset(withFloat: array, count: array.count, atTimes: times, count: times.count) - } - - @nonobjc public func reset(doubleQuaternionArray array:[simd_quatd], atTimes times: [TimeInterval]){ - __reset(withDouble: array, count: array.count, atTimes: times, count: times.count) - } - - @nonobjc public var floatQuaternionArray : [simd_quatf] { - get { - let count = elementCount * timeSampleCount - return [simd_quatf](unsafeUninitializedCount: count) { ptr in - __getFloat(ptr, maxCount: count) - } - } - } - - @nonobjc public var doubleQuaternionArray: [simd_quatd] { - get { - let count = elementCount * timeSampleCount - return [simd_quatd](unsafeUninitializedCount: count) { ptr in - __getDouble(ptr, maxCount: count) - } - } - } -} - -@available(macOS, introduced: 10.13) -@available(iOS, introduced: 11.0) -@available(tvOS, introduced: 11.0) -extension MDLAnimatedScalar { - @nonobjc public func reset(floatArray array:[Float], atTimes times: [TimeInterval]){ - __reset(withFloatArray: array, atTimes: times, count: times.count) - } - - @nonobjc public func reset(doubleArray array:[Double], atTimes times: [TimeInterval]){ - __reset(withDoubleArray: array, atTimes: times, count: times.count) - } - - @nonobjc public var floatArray: [Float] { - get { - return [Float](unsafeUninitializedCount: timeSampleCount) { ptr in - __getFloatArray(ptr, maxCount: timeSampleCount) - } - } - } - - @nonobjc public var doubleArray: [Double] { - get { - return [Double](unsafeUninitializedCount: timeSampleCount) { ptr in - __getDoubleArray(ptr, maxCount: timeSampleCount) - } - } - } -} - -@available(macOS, introduced: 10.13) -@available(iOS, introduced: 11.0) -@available(tvOS, introduced: 11.0) -extension MDLAnimatedVector2 { - @nonobjc public func reset(float2Array array:[SIMD2], atTimes times: [TimeInterval]){ - __reset(withFloat2Array: array, atTimes: times, count: times.count) - } - - @nonobjc public func reset(double2Array array:[SIMD2], atTimes times: [TimeInterval]){ - __reset(withDouble2Array: array, atTimes: times, count: times.count) - } - - @nonobjc public var float2Array: [SIMD2] { - get { - return [SIMD2](unsafeUninitializedCount: timeSampleCount) { ptr in - __getFloat2Array(ptr, maxCount: timeSampleCount) - } - } - } - - @nonobjc public var double2Array: [SIMD2] { - get { - return [SIMD2](unsafeUninitializedCount: timeSampleCount) { ptr in - __getDouble2Array(ptr, maxCount: timeSampleCount) - } - } - } -} - -@available(macOS, introduced: 10.13) -@available(iOS, introduced: 11.0) -@available(tvOS, introduced: 11.0) -extension MDLAnimatedVector3 { - @nonobjc public func reset(float3Array array:[SIMD3], atTimes times: [TimeInterval]){ - __reset(withFloat3Array: array, atTimes: times, count: times.count) - } - - @nonobjc public func reset(double3Array array:[SIMD3], atTimes times: [TimeInterval]){ - __reset(withDouble3Array: array, atTimes: times, count: times.count) - } - - @nonobjc public var float3Array: [SIMD3] { - get { - return [SIMD3](unsafeUninitializedCount: timeSampleCount) { ptr in - __getFloat3Array(ptr, maxCount: timeSampleCount) - } - } - } - - @nonobjc public var double3Array: [SIMD3] { - get { - return [SIMD3](unsafeUninitializedCount: timeSampleCount) { ptr in - __getDouble3Array(ptr, maxCount: timeSampleCount) - } - } - } -} - -@available(macOS, introduced: 10.13) -@available(iOS, introduced: 11.0) -@available(tvOS, introduced: 11.0) -extension MDLAnimatedVector4 { - @nonobjc public func reset(float4Array array:[SIMD4], atTimes times: [TimeInterval]){ - __reset(withFloat4Array: array, atTimes: times, count: times.count) - } - - @nonobjc public func reset(double4Array array:[SIMD4], atTimes times: [TimeInterval]){ - __reset(withDouble4Array: array, atTimes: times, count: times.count) - } - - @nonobjc public var float4Array: [SIMD4] { - get { - return [SIMD4](unsafeUninitializedCount: timeSampleCount) { ptr in - __getFloat4Array(ptr, maxCount: timeSampleCount) - } - } - } - - @nonobjc public var double4Array: [SIMD4] { - get { - return [SIMD4](unsafeUninitializedCount: timeSampleCount) { ptr in - __getDouble4Array(ptr, maxCount: timeSampleCount) - } - } - } -} - -@available(macOS, introduced: 10.13) -@available(iOS, introduced: 11.0) -@available(tvOS, introduced: 11.0) -extension MDLAnimatedMatrix4x4 { - @nonobjc public func reset(float4x4Array array:[float4x4], atTimes times: [TimeInterval]){ - __reset(withFloat4x4Array: array, atTimes: times, count: times.count) - } - - @nonobjc public func reset(double4Array array:[double4x4], atTimes times: [TimeInterval]){ - __reset(withDouble4x4Array: array, atTimes: times, count: times.count) - } - - @nonobjc public var float4x4Array: [float4x4] { - get { - return [float4x4](unsafeUninitializedCount: timeSampleCount) { ptr in - __getFloat4x4Array(ptr, maxCount: timeSampleCount) - } - } - } - - @nonobjc public var double4x4Array: [double4x4] { - get { - return [double4x4](unsafeUninitializedCount: timeSampleCount) { ptr in - __getDouble4x4Array(ptr, maxCount: timeSampleCount) - } - } - } -} diff --git a/stdlib/public/Darwin/NaturalLanguage/CMakeLists.txt b/stdlib/public/Darwin/NaturalLanguage/CMakeLists.txt deleted file mode 100644 index 47a1729894a0a..0000000000000 --- a/stdlib/public/Darwin/NaturalLanguage/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftNaturalLanguage ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - NLLanguageRecognizer.swift - NLTagger.swift - NLTokenizer.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch IOKit Foundation XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_WATCHOS Darwin Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - - FRAMEWORK_DEPENDS_WEAK NaturalLanguage - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_NATURALLANGUAGE_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_NATURALLANGUAGE_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_NATURALLANGUAGE_TVOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_NATURALLANGUAGE_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/NaturalLanguage/NLLanguageRecognizer.swift b/stdlib/public/Darwin/NaturalLanguage/NLLanguageRecognizer.swift deleted file mode 100644 index 1ff503b9dbe48..0000000000000 --- a/stdlib/public/Darwin/NaturalLanguage/NLLanguageRecognizer.swift +++ /dev/null @@ -1,32 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import NaturalLanguage -import Foundation - -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -extension NLLanguageRecognizer { - @nonobjc - public var languageHints: [NLLanguage : Double] { - get { - return self.__languageHints.mapValues { $0.doubleValue } - } - set(newHints) { - self.__languageHints = newHints.mapValues { NSNumber(value: $0) } - } - } - - @nonobjc - public func languageHypotheses(withMaximum maxHypotheses: Int) -> [NLLanguage : Double] { - return self.__languageHypotheses(withMaximum: maxHypotheses).mapValues { $0.doubleValue } - } -} diff --git a/stdlib/public/Darwin/NaturalLanguage/NLTagger.swift b/stdlib/public/Darwin/NaturalLanguage/NLTagger.swift deleted file mode 100644 index 138d448ae0c4d..0000000000000 --- a/stdlib/public/Darwin/NaturalLanguage/NLTagger.swift +++ /dev/null @@ -1,75 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import NaturalLanguage -import Foundation - -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -extension NLTagger { - @nonobjc - public func tokenRange(at index: String.Index, unit: NLTokenUnit) -> Range { - let str = self.string ?? "" - let characterIndex = index.utf16Offset(in: str) - let nsrange = self.__tokenRange(at: characterIndex, unit: unit) - return Range(nsrange, in: str)! - } - - @nonobjc - public func tag(at index: String.Index, unit: NLTokenUnit, scheme: NLTagScheme) -> (NLTag?, Range) { - let str = self.string ?? "" - let characterIndex = index.utf16Offset(in: str) - let rangePointer = NSRangePointer.allocate(capacity: 1) - rangePointer.initialize(to: NSMakeRange(0, 0)) - let tag = self.__tag(at: characterIndex, unit: unit, scheme: scheme, tokenRange: rangePointer) - let range = Range(rangePointer.pointee, in: str)! - rangePointer.deallocate() - return (tag, range) - } - - @nonobjc - public func enumerateTags(in range: Range, unit: NLTokenUnit, scheme: NLTagScheme, options: NLTagger.Options = [], using block: (NLTag?, Range) -> Bool) { - guard let str = self.string else { return } - let nsrange = NSRange(range, in:str) - self.__enumerateTags(in: nsrange, unit: unit, scheme: scheme, options: options) { (tag, tokenNSRange, stop) in - if let tokenRange = Range(tokenNSRange, in: str) { - let keepGoing = block(tag, tokenRange) - if (!keepGoing) { - stop.pointee = true - } - } - } - } - - @nonobjc - public func tags(in range: Range, unit: NLTokenUnit, scheme: NLTagScheme, options: NLTagger.Options = []) -> [(NLTag?, Range)] { - var array:[(NLTag?, Range)] = [] - self.enumerateTags(in: range, unit: unit, scheme: scheme, options: options) { (tag, tokenRange) -> Bool in - array.append((tag, tokenRange)) - return true - } - return array - } - - @nonobjc - public func setLanguage(_ language: NLLanguage, range: Range) { - guard let str = self.string else { return } - let nsrange = NSRange(range, in: str) - self.__setLanguage(language, range: nsrange) - } - - @nonobjc - public func setOrthography(_ orthography: NSOrthography, range: Range) { - guard let str = self.string else { return } - let nsrange = NSRange(range, in: str) - self.__setOrthography(orthography, range: nsrange) - } -} diff --git a/stdlib/public/Darwin/NaturalLanguage/NLTokenizer.swift b/stdlib/public/Darwin/NaturalLanguage/NLTokenizer.swift deleted file mode 100644 index ca8b337e31d3a..0000000000000 --- a/stdlib/public/Darwin/NaturalLanguage/NLTokenizer.swift +++ /dev/null @@ -1,49 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import NaturalLanguage -import Foundation - -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -extension NLTokenizer { - @nonobjc - public func tokenRange(at index: String.Index) -> Range { - let str = self.string ?? "" - let characterIndex = index.utf16Offset(in: str) - let nsrange = self.__tokenRange(at:characterIndex) - return Range(nsrange, in: str)! - } - - @nonobjc - public func enumerateTokens(in range: Range, using block: (Range, NLTokenizer.Attributes) -> Bool) { - guard let str = self.string else { return } - let nsrange = NSRange(range, in: str) - self.__enumerateTokens(in: nsrange) { (tokenNSRange, attrs, stop) in - if let tokenRange = Range(tokenNSRange, in:str) { - let keepGoing = block(tokenRange, attrs) - if (!keepGoing) { - stop.pointee = true - } - } - } - } - - @nonobjc - public func tokens(for range: Range) -> [Range] { - var array:[Range] = [] - self.enumerateTokens(in: range) { (tokenRange, attrs) -> Bool in - array.append(tokenRange) - return true - } - return array - } -} diff --git a/stdlib/public/Darwin/Network/CMakeLists.txt b/stdlib/public/Darwin/Network/CMakeLists.txt deleted file mode 100644 index 07d5e4daeb427..0000000000000 --- a/stdlib/public/Darwin/Network/CMakeLists.txt +++ /dev/null @@ -1,38 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftNetwork ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - Network.swift - NWConnection.swift - NWEndpoint.swift - NWError.swift - NWListener.swift - NWParameters.swift - NWPath.swift - NWProtocolIP.swift - NWProtocol.swift - NWProtocolTCP.swift - NWProtocolTLS.swift - NWProtocolUDP.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR # WATCHOS WATCHOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin Dispatch CoreFoundation ObjectiveC # auto-updated - Foundation # Imported in Swift - SWIFT_MODULE_DEPENDS_IOS Darwin Dispatch CoreFoundation ObjectiveC # auto-updated - Foundation # Imported in Swift - SWIFT_MODULE_DEPENDS_TVOS Darwin Dispatch CoreFoundation ObjectiveC # auto-updated - Foundation # Imported in Swift - # SWIFT_MODULE_DEPENDS_WATCHOS Darwin Dispatch Foundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS_WEAK Network - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_NETWORK_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_NETWORK_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_NETWORK_TVOS} - # DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_NETWORK_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/Network/NWConnection.swift b/stdlib/public/Darwin/Network/NWConnection.swift deleted file mode 100644 index c0f2f7e8c9686..0000000000000 --- a/stdlib/public/Darwin/Network/NWConnection.swift +++ /dev/null @@ -1,573 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -import Dispatch -import Foundation -@_implementationOnly import _SwiftNetworkOverlayShims - -/// An NWConnection is an object that represents a bi-directional data pipe between -/// a local endpoint and a remote endpoint. -/// -/// A connection handles establishment of any transport, security, or application-level protocols -/// required to transmit and receive user data. Multiple protocol instances may be attempted during -/// the establishment phase of the connection. -// NOTE: older overlays had Network.NWConnection as the ObjC name. -// The two must coexist, so it was renamed. The old name must not be -// used in the new runtime. _TtC7Network13_NWConnection is the -// mangled name for Network._NWConnection. -@_objcRuntimeName(_TtC7Network13_NWConnection) -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public final class NWConnection : CustomDebugStringConvertible { - - public var debugDescription: String { - return String("\(self.nw)") - } - - /// States a connection may be in - public enum State : Equatable { - /// The initial state prior to start - case setup - /// Waiting connections have not yet been started, or do not have a viable network - case waiting(NWError) - /// Preparing connections are actively establishing the connection - case preparing - /// Ready connections can send and receive data - case ready - /// Failed connections are disconnected and can no longer send or receive data - case failed(NWError) - /// Cancelled connections have been invalidated by the client and will send no more events - case cancelled - - internal init(_ nw: nw_connection_state_t, _ err: nw_error_t?) { - switch nw { - case Network.nw_connection_state_invalid: - self = .setup - case Network.nw_connection_state_waiting: - if let error = NWError(err) { - self = .waiting(error) - } else { - self = .waiting(NWError.posix(.ENETDOWN)) - } - case Network.nw_connection_state_preparing: - self = .preparing - case Network.nw_connection_state_ready: - self = .ready - case Network.nw_connection_state_failed: - if let error = NWError(err) { - self = .failed(error) - } else { - self = .failed(NWError.posix(.EINVAL)) - } - case Network.nw_connection_state_cancelled: - self = .cancelled - default: - self = .cancelled - } - } - } - - internal let nw : nw_connection_t - - private var _state = NWConnection.State.setup - - /// Access the current state of the connection - public var state: NWConnection.State { - return _state - } - - private var _stateUpdateHandler: ((_ state: NWConnection.State) -> Void)? - - /// Set a block to be called when the connection's state changes, which may be called - /// multiple times until the connection is cancelled. - public var stateUpdateHandler: ((_ state: NWConnection.State) -> Void)? { - set { - self._stateUpdateHandler = newValue - if let newValue = newValue { - nw_connection_set_state_changed_handler(self.nw) { (state, error) in - self._state = NWConnection.State(state, error) - newValue(self._state) - } - } else { - nw_connection_set_state_changed_handler(self.nw) { (state, error) in - self._state = NWConnection.State(state, error) - } - } - } - get { - return self._stateUpdateHandler - } - } - - /// Retrieve the maximum datagram size that can be sent - /// on the connection. Any datagrams sent should be less - /// than or equal to this size. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public var maximumDatagramSize: Int { - get { - return Int(nw_connection_get_maximum_datagram_size(self.nw)) - } - } - - private var _currentPath: NWPath? = nil - - /// Current path for the connection, which can be used to extract interface and effective endpoint information - public var currentPath: NWPath? { - get { - if let path = nw_connection_copy_current_path(self.nw) { - return NWPath(path) - } - return nil - } - } - - private var _pathUpdateHandler: ((_ newPath: NWPath) -> Void)? - - /// Set a block to be called when the connection's path has changed, which may be called - /// multiple times until the connection is cancelled. - public var pathUpdateHandler: ((_ newPath: NWPath) -> Void)? { - set { - self._pathUpdateHandler = newValue - if let newValue = newValue { - nw_connection_set_path_changed_handler(self.nw) { (nwPath) in - let newPath = NWPath(nwPath) - self._currentPath = newPath - newValue(newPath) - } - } else { - nw_connection_set_path_changed_handler(self.nw, nil) - } - - } - get { - return self._pathUpdateHandler - } - } - - private var _viabilityUpdateHandler: ((_ isViable: Bool) -> Void)? - - /// Set a block to be called when the connection's viability changes, which may be called - /// multiple times until the connection is cancelled. - /// - /// Connections that are not currently viable do not have a route, and packets will not be - /// sent or received. There is a possibility that the connection will become viable - /// again when network connectivity changes. - public var viabilityUpdateHandler: ((_ isViable: Bool) -> Void)? { - set { - self._viabilityUpdateHandler = newValue - if let newValue = newValue { - nw_connection_set_viability_changed_handler(self.nw) { (isViable) in - newValue(isViable) - } - } else { - nw_connection_set_viability_changed_handler(self.nw, nil) - } - - } - get { - return self._viabilityUpdateHandler - } - } - - private var _betterPathUpdateHandler: ((_ betterPathAvailable: Bool) -> Void)? - - /// A better path being available indicates that the system thinks there is a preferred path or - /// interface to use, compared to the one this connection is actively using. As an example, the - /// connection is established over an expensive cellular interface and an unmetered Wi-Fi interface - /// is now available. - /// - /// Set a block to be called when a better path becomes available or unavailable, which may be called - /// multiple times until the connection is cancelled. - /// - /// When a better path is available, if it is possible to migrate work from this connection to a new connection, - /// create a new connection to the endpoint. Continue doing work on this connection until the new connection is - /// ready. Once ready, transition work to the new connection and cancel this one. - public var betterPathUpdateHandler: ((_ betterPathAvailable: Bool) -> Void)? { - set { - self._betterPathUpdateHandler = newValue - if let newValue = newValue { - nw_connection_set_better_path_available_handler(self.nw) { (betterPathAvailable) in - newValue(betterPathAvailable) - } - } else { - nw_connection_set_better_path_available_handler(self.nw, nil) - } - - } - get { - return self._betterPathUpdateHandler - } - } - - /// The remote endpoint of the connection - public let endpoint: NWEndpoint - - /// The set of parameters with which the connection was created - public let parameters: NWParameters - - private init(to: NWEndpoint, using: NWParameters, connection: nw_connection_t) { - self.endpoint = to - self.parameters = using - self.nw = connection - nw_connection_set_state_changed_handler(self.nw) { (state, error) in - self._state = NWConnection.State(state, error) - } - } - - convenience internal init?(using: NWParameters, inbound: nw_connection_t) { - guard let peer = NWEndpoint(nw_connection_copy_endpoint(inbound)) else { - return nil - } - self.init(to: peer, using: using, connection: inbound) - } - - /// Create a new outbound connection to an endpoint, with parameters. - /// The parameters determine the protocols to be used for the connection, and their options. - /// - /// - Parameter to: The remote endpoint to which to connect. - /// - Parameter using: The parameters define which protocols and path to use. - public init(to: NWEndpoint, using: NWParameters) { - self.endpoint = to - self.parameters = using - self.nw = nw_connection_create(to.nw!, using.nw) - nw_connection_set_state_changed_handler(self.nw) { (state, error) in - self._state = NWConnection.State(state, error) - } - } - - /// Create a new outbound connection to a hostname and port, with parameters. - /// The parameters determine the protocols to be used for the connection, and their options. - /// - /// - Parameter host: The remote hostname to which to connect. - /// - Parameter port: The remote port to which to connect. - /// - Parameter using: The parameters define which protocols and path to use. - public convenience init(host: NWEndpoint.Host, port: NWEndpoint.Port, using: NWParameters) { - self.init(to: .hostPort(host: host, port: port), using: using) - } - - /// Start the connection and provide a dispatch queue for callback blocks. - /// - /// Starts the connection, which will cause the connection to evaluate its path, do resolution and try to become - /// ready (connected). NWConnection establishment is asynchronous. A stateUpdateHandler may be used to determine - /// when the state changes. If the connection can not be established, the state will transition to waiting with - /// an associated error describing the reason. If an unrecoverable error is encountered, the state will - /// transition to failed with an associated NWError value. If the connection is established, the state will - /// transition to ready. - /// - /// Start should only be called once on a connection, and multiple calls to start will - /// be ignored. - public func start(queue: DispatchQueue) { - self._queue = queue - nw_connection_set_queue(self.nw, queue) - nw_connection_start(self.nw) - } - - private var _queue: DispatchQueue? - - /// Get queue used for delivering block handlers, such as stateUpdateHandler, pathUpdateHandler, - /// viabilityUpdateHandler, betterPathUpdateHandler, and completions for send and receive. - /// If the connection has not yet been started, the queue will be nil. Once the connection has been - /// started, the queue will be valid. - public var queue: DispatchQueue? { - get { - return self._queue - } - } - - /// Cancel the connection, and cause all update handlers to be cancelled. - /// - /// Cancel is asynchronous. The last callback will be to the stateUpdateHandler with the cancelled state. After - /// the stateUpdateHandlers are called with the cancelled state, all blocks are released to break retain cycles. - /// - /// Calls to cancel after the first one are ignored. - public func cancel() { - nw_connection_cancel(self.nw) - } - - /// A variant of cancel that performs non-graceful closure of the transport. - public func forceCancel() { - nw_connection_force_cancel(self.nw) - } - - /// Cancel the currently connected endpoint, causing the connection to fall through to the next endpoint if - /// available, or to go to the waiting state if no more endpoints are available. - public func cancelCurrentEndpoint() { - nw_connection_cancel_current_endpoint(self.nw) - } - - /// NWConnections will normally re-attempt on network changes. This function causes a connection that is in - /// the waiting state to re-attempt even without a network change. - public func restart() { - nw_connection_restart(self.nw) - } - - /// Content Context controls options for how data is sent, and access for metadata to send or receive. - /// All properties of Content Context are valid for sending. For received Content Context, only the protocolMetadata - /// values will be set. - // Set the ObjC name of this class to be nested in the customized ObjC name of NWConnection. - @_objcRuntimeName(_TtCC7Network13_NWConnection14ContentContext) - public class ContentContext { - internal let nw: nw_content_context_t - - /// A string description of the content, used for logging and debugging. - public let identifier: String - - /// An expiration in milliseconds after scheduling a send, after which the content may be dropped. - /// Defaults to 0, which implies no expiration. Used only when sending. - public let expirationMilliseconds: UInt64 - - /// A numeric value between 0.0 and 1.0 to specify priority of this data/message. Defaults to 0.5. - /// Used only when sending. - public let relativePriority: Double - - /// Any content marked as an antecedent must be sent prior to this content being sent. Defaults to nil. - /// Used only when sending. - public let antecedent: NWConnection.ContentContext? - - /// A boolean indicating if this context is the final context in a given direction on this connection. Defaults to false. - public let isFinal: Bool - - /// An array of protocol metadata to send (to inform the protocols of per-data options) or receive (to receive per-data options or statistics). - public var protocolMetadata: [NWProtocolMetadata] { - get { - var metadataArray: [NWProtocolMetadata] = [] - nw_content_context_foreach_protocol_metadata(self.nw) { (definition, metadata) in - if nw_protocol_metadata_is_tcp(metadata) { - metadataArray.append(NWProtocolTCP.Metadata(metadata)) - } else if nw_protocol_metadata_is_udp(metadata) { - metadataArray.append(NWProtocolUDP.Metadata(metadata)) - } else if nw_protocol_metadata_is_ip(metadata) { - metadataArray.append(NWProtocolIP.Metadata(metadata)) - } else if nw_protocol_metadata_is_tls(metadata) { - metadataArray.append(NWProtocolTLS.Metadata(metadata)) - } - } - return metadataArray - } - } - - /// Access the metadata for a specific protocol from a context. The metadata may be nil. - public func protocolMetadata(definition: NWProtocolDefinition) -> NWProtocolMetadata? { - if let metadata = nw_content_context_copy_protocol_metadata(self.nw, definition.nw) { - if nw_protocol_metadata_is_tcp(metadata) { - return NWProtocolTCP.Metadata(metadata) - } else if nw_protocol_metadata_is_udp(metadata) { - return NWProtocolUDP.Metadata(metadata) - } else if nw_protocol_metadata_is_ip(metadata) { - return NWProtocolIP.Metadata(metadata) - } else if nw_protocol_metadata_is_tls(metadata) { - return NWProtocolTLS.Metadata(metadata) - } - } - return nil - } - - /// Create a context for sending, that optionally can set expiration (default 0), - /// priority (default 0.5), antecedent (default nil), and protocol metadata (default []]). - public init(identifier: String, expiration: UInt64 = 0, priority: Double = 0.5, isFinal: Bool = false, antecedent: NWConnection.ContentContext? = nil, metadata: [NWProtocolMetadata]? = []) { - self.nw = nw_content_context_create(identifier) - - self.identifier = identifier - - self.expirationMilliseconds = expiration - nw_content_context_set_expiration_milliseconds(self.nw, expiration) - - self.relativePriority = priority - nw_content_context_set_relative_priority(self.nw, priority) - - self.isFinal = isFinal - nw_content_context_set_is_final(self.nw, isFinal) - - self.antecedent = antecedent - if let otherContext = antecedent { - nw_content_context_set_antecedent(self.nw, otherContext.nw) - } - - if let metadataArray = metadata { - for singleMetadata in metadataArray { - nw_content_context_set_metadata_for_protocol(self.nw, singleMetadata.nw) - } - } - } - - /// Use the default message context to send content with all default properties: - /// default priority, no expiration, and not the final message. Marking this context - /// as complete with a send indicates that the message content is now complete and any - /// other messages that were blocked may be scheduled, but will not close the underlying - /// connection. Use this context for any lightweight sends of datagrams or messages on - /// top of a stream that do not require special properties. - /// This context does not support overriding any properties. - public static let defaultMessage : NWConnection.ContentContext = NWConnection.ContentContext(_swift_nw_content_context_default_message())! - - /// Use the final message context to indicate that no more sends are expected - /// once this context is complete. Like .defaultMessage, all properties are default. - /// Marking a send as complete when using this context will close the sending side of the - /// underlying connection. This is the equivalent of sending a FIN on a TCP stream. - /// This context does not support overriding any properties. - public static let finalMessage : NWConnection.ContentContext = NWConnection.ContentContext(_swift_nw_content_context_final_message())! - - /// Use the default stream context to indicate that this sending context is - /// the one that represents the entire connection. All context properties are default. - /// This context behaves in the same way as .finalMessage, such that marking the - /// context complete by sending isComplete will close the sending side of the - /// underlying connection (a FIN for a TCP stream). - /// Note that this context is a convenience for sending a single, final context. - /// If the protocol used by the connection is a stream (such as TCP), the caller - /// may still use .defaultMessage, .finalMessage, or a custom context with priorities - /// and metadata to set properties of a particular chunk of stream data relative - /// to other data on the stream. - /// This context does not support overriding any properties. - public static let defaultStream : NWConnection.ContentContext = NWConnection.ContentContext(_swift_nw_content_context_default_stream())! - - internal init?(_ nw: nw_content_context_t?) { - guard let nw = nw else { - return nil - } - - self.nw = nw - - // Received content context doesn't have expiration, priority, or antecedents - self.expirationMilliseconds = 0 - self.relativePriority = 0 - self.antecedent = nil - self.isFinal = nw_content_context_get_is_final(nw) - self.identifier = String(cString: nw_content_context_get_identifier(nw)) - } - } - - /// Receive data from a connection. This may be called before the connection - /// is ready, in which case the receive request will be queued until the - /// connection is ready. The completion handler will be invoked exactly - /// once for each call, so the client must call this function multiple - /// times to receive multiple chunks of data. For protocols that - /// support flow control, such as TCP, calling receive opens the receive - /// window. If the client stops calling receive, the receive window will - /// fill up and the remote peer will stop sending. - /// - Parameter minimumIncompleteLength: The minimum length to receive from the connection, - /// until the content is complete. - /// - Parameter maximumLength: The maximum length to receive from the connection in a single completion. - /// - Parameter completion: A receive completion is invoked exactly once for a call to receive(...). - /// The completion indicates that the requested content has been received (in which case - /// the content is delivered), or else an error has occurred. Parameters to the completion are: - /// - /// - content: The received content, as constrained by the minimum and maximum length. This may - /// be nil if the message or stream is complete (without any more data to deliver), or if - /// an error was encountered. - /// - /// - contentContext: Content context describing the received content. This includes protocol metadata - /// that lets the caller introspect information about the received content (such as flags on a packet). - /// - /// - isComplete: An indication that this context (a message or stream, for example) is now complete. For - /// protocols such as TCP, this will be marked when the entire stream has be closed in the - /// reading direction. For protocols such as UDP, this will be marked when the end of a - /// datagram has been reached. - /// - /// - error: An error will be sent if the receive was terminated before completing. There may still - /// be content delivered along with the error, but this content may be shorter than the requested - /// ranges. An error will be sent for any outstanding receives when the connection is cancelled. - public func receive(minimumIncompleteLength: Int, maximumLength: Int, - completion: @escaping (_ content: Data?, - _ contentContext: NWConnection.ContentContext?, - _ isComplete: Bool, _ error: NWError?) -> Void) { - nw_connection_receive(self.nw, UInt32(minimumIncompleteLength), UInt32(maximumLength)) { - (content, context, complete, nwError) in - completion(NWCreateNSDataFromDispatchData(content), ContentContext(context), complete, NWError(nwError)); - } - } - - /// Receive complete message content from the connection, waiting for the content to be marked complete - /// (or encounter an error) before delivering the callback. This is useful for datagram or message-based - /// protocols like UDP. See receive(minimumIncompleteLength:, maximumLength:, completion:) for a description - /// of the completion handler. - public func receiveMessage(completion: @escaping (_ completeContent: Data?, - _ contentContext: NWConnection.ContentContext?, - _ isComplete: Bool, _ error: NWError?) -> Void) { - nw_connection_receive_message(self.nw) { (content, context, complete, nwError) in - completion(NWCreateNSDataFromDispatchData(content), ContentContext(context), complete, NWError(nwError)) - } - } - - /// A type representing a wrapped completion handler invoked when send content has been consumed by the protocol stack, or the lack of a completion handler because the content is idempotent. - public enum SendCompletion { - /// Completion handler to be invoked when send content has been successfully processed, or failed to send due to an error. - /// Note that this does not guarantee that the data was sent out over the network, or acknowledge, but only that - /// it has been consumed by the protocol stack. - case contentProcessed((_ error: NWError?) -> Void) - /// Idempotent content may be sent multiple times when opening up a 0-RTT connection, so there is no completion block - case idempotent - } - - /// Send data on a connection. This may be called before the connection is ready, - /// in which case the send will be enqueued until the connection is ready to send. - /// This is an asynchronous send and the completion block can be used to - /// determine when the send is complete. There is nothing preventing a client - /// from issuing an excessive number of outstanding sends. To minimize memory - /// footprint and excessive latency as a consequence of buffer bloat, it is - /// advisable to keep a low number of outstanding sends. The completion block - /// can be used to pace subsequent sends. - /// - Parameter content: The data to send on the connection. May be nil if this send marks its context as complete, such - /// as by sending .finalMessage as the context and marking isComplete to send a write-close. - /// - Parameter contentContext: The context associated with the content, which represents a logical message - /// to be sent on the connection. All content sent within a single context will - /// be sent as an in-order unit, up until the point that the context is marked - /// complete (see isComplete). Once a context is marked complete, it may be re-used - /// as a new logical message. Protocols like TCP that cannot send multiple - /// independent messages at once (serial streams) will only start processing a new - /// context once the prior context has been marked complete. Defaults to .defaultMessage. - /// - Parameter isComplete: A flag indicating if the caller's sending context (logical message) is now complete. - /// Until a context is marked complete, content sent for other contexts may not - /// be sent immediately (if the protocol requires sending bytes serially, like TCP). - /// For datagram protocols, like UDP, isComplete indicates that the content represents - /// a complete datagram. - /// When sending using streaming protocols like TCP, isComplete can be used to mark the end - /// of a single message on the stream, of which there may be many. However, it can also - /// indicate that the connection should send a "write close" (a TCP FIN) if the sending - /// context is the final context on the connection. Specifically, to send a "write close", - /// pass .finalMessage or .defaultStream for the context (or create a custom context and - /// set .isFinal), and pass true for isComplete. - /// - Parameter completion: A completion handler (.contentProcessed) to notify the caller when content has been processed by - /// the connection, or a marker that this data is idempotent (.idempotent) and may be sent multiple times as fast open data. - public func send(content: Data?, contentContext: NWConnection.ContentContext = .defaultMessage, isComplete: Bool = true, completion: SendCompletion) { - switch completion { - case .idempotent: - _swift_nw_connection_send_idempotent(self.nw, NWCreateDispatchDataFromNSData(content), contentContext.nw, isComplete) - case .contentProcessed(let handler): - _swift_nw_connection_send(self.nw, NWCreateDispatchDataFromNSData(content), contentContext.nw, isComplete) { (error) in - handler(NWError(error)) - } - } - } - - /// Batching allows multiple send or receive calls provides a hint to the connection that the operations - /// should be coalesced to improve efficiency. Calls other than send and receive will not be affected. - public func batch(_ block: () -> Void) { - nw_connection_batch(self.nw, block) - } - - /// Access connection-wide protocol metadata on the connection. This allows access to state for protocols - /// like TCP and TLS that have long-term state. - public func metadata(definition: NWProtocolDefinition) -> NWProtocolMetadata? { - if let metadata = nw_connection_copy_protocol_metadata(self.nw, definition.nw) { - if nw_protocol_metadata_is_tcp(metadata) { - return NWProtocolTCP.Metadata(metadata) - } else if nw_protocol_metadata_is_udp(metadata) { - return NWProtocolUDP.Metadata(metadata) - } else if nw_protocol_metadata_is_ip(metadata) { - return NWProtocolIP.Metadata(metadata) - } else if nw_protocol_metadata_is_tls(metadata) { - return NWProtocolTLS.Metadata(metadata) - } - return NWProtocolMetadata(metadata) - } else { - return nil - } - } -} diff --git a/stdlib/public/Darwin/Network/NWEndpoint.swift b/stdlib/public/Darwin/Network/NWEndpoint.swift deleted file mode 100644 index 6249c30a73ab6..0000000000000 --- a/stdlib/public/Darwin/Network/NWEndpoint.swift +++ /dev/null @@ -1,737 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -import Darwin -import Foundation -@_implementationOnly import _SwiftNetworkOverlayShims - -internal extension sockaddr_in { - init(_ address:in_addr, _ port: in_port_t) { - self.init(sin_len: UInt8(MemoryLayout.size), sin_family: sa_family_t(AF_INET), sin_port: port, - sin_addr: address, sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) - } - - func withSockAddr(_ body: (_ sa: UnsafePointer) throws -> ReturnType) rethrows -> ReturnType { - // We need to create a mutable copy of `self` so that we can pass it to `withUnsafePointer(to:_:)`. - var sin = self - return try withUnsafePointer(to: &sin) { - try $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { - try body($0) - } - } - } -} - -internal extension sockaddr_in6 { - init(_ address:in6_addr, _ port: in_port_t, flow: UInt32 = 0, scope: UInt32 = 0) { - self.init(sin6_len: UInt8(MemoryLayout.size), sin6_family: sa_family_t(AF_INET6), sin6_port: port, - sin6_flowinfo: flow, sin6_addr: address, sin6_scope_id: scope) - } - - func withSockAddr(_ body: (_ sa: UnsafePointer) throws -> ReturnType) rethrows -> ReturnType { - // We need to create a mutable copy of `self` so that we can pass it to `withUnsafePointer(to:_:)`. - var sin6 = self - return try withUnsafePointer(to: &sin6) { - try $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { - try body($0) - } - } - } -} - -internal extension in_addr { - init(address: UInt32) { - self.init() - self.s_addr = address.bigEndian - } -} - -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -private func getaddrinfo_numeric(_ string: String, family: Int32 = 0) -> NWEndpoint.Host? { - // Determine if this string has an interface scope specified "127.0.0.1%lo0" or "fe80::1%lo0" - var string = string - var interface : NWInterface? = nil - if let range = string.range(of: "%", options: String.CompareOptions.backwards) { - interface = NWInterface(String(string[range.upperBound...])) - if interface != nil { - string.removeSubrange(range.lowerBound...) - } - } - - // call getaddrinfo - var hints = addrinfo(ai_flags: AI_NUMERICHOST, ai_family: family, ai_socktype: SOCK_STREAM, ai_protocol: 0, - ai_addrlen: 0, ai_canonname: nil, ai_addr: nil, ai_next: nil) - var resolved : UnsafeMutablePointer? = nil - // After this point we must ensure we free addrinfo before we return - guard getaddrinfo(string, nil, &hints, &resolved) == 0, let addrinfo = resolved else { - return nil - } - - var result: NWEndpoint.Host? = nil - - if let sa = addrinfo.pointee.ai_addr { - if sa.pointee.sa_family == AF_INET { - sa.withMemoryRebound(to: sockaddr_in.self, capacity: 1, { (sin) -> Void in - result = NWEndpoint.Host.ipv4(IPv4Address(sin.pointee.sin_addr, interface)) - }) - } else if sa.pointee.sa_family == AF_INET6 { - sa.withMemoryRebound(to: sockaddr_in6.self, capacity: 1, { (sin6) -> Void in - if sin6.pointee.sin6_scope_id != 0 { - interface = NWInterface(Int(sin6.pointee.sin6_scope_id)) - } - let ipv6 = IPv6Address(sin6.pointee.sin6_addr, interface); - if ipv6.isIPv4Mapped && family == AF_UNSPEC, let ipv4 = ipv6.asIPv4 { - // Treat IPv4 mapped as IPv4 - result = NWEndpoint.Host.ipv4(ipv4) - } else { - result = NWEndpoint.Host.ipv6(ipv6) - } - }) - } - } - freeaddrinfo(addrinfo) - return result -} - -private func getnameinfo_numeric(address: UnsafeRawPointer) -> String { - let sa = address.assumingMemoryBound(to: sockaddr.self) - var result : String? = nil - let maxLen = socklen_t(100) - let storage = UnsafeMutablePointer.allocate(capacity: Int(maxLen)) - if getnameinfo(sa, socklen_t(sa.pointee.sa_len), storage, maxLen, nil, 0, NI_NUMERICHOST) == 0 { - result = String(cString: storage) - } - storage.deallocate() - return result ?? "?" -} - -/// An IP address -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public protocol IPAddress { - - /// Fetch the raw address as data - var rawValue: Data { get } - - /// Create an IP address from data. The length of the data must - /// match the expected length of addresses in the address family - /// (four bytes for IPv4, and sixteen bytes for IPv6) - init?(_ rawValue: Data, _ interface: NWInterface?) - - /// Create an IP address from an address literal string. - /// If the string contains '%' to indicate an interface, the interface will be - /// associated with the address, such as "::1%lo0" being associated with the loopback - /// interface. - /// This function does not perform host name to address resolution. This is the same as calling getaddrinfo - /// and using AI_NUMERICHOST. - init?(_ string: String) - - /// The interface the address is scoped to, if any. - var interface: NWInterface? { get } - - /// Indicates if this address is loopback - var isLoopback : Bool { get } - - /// Indicates if this address is link-local - var isLinkLocal : Bool { get } - - /// Indicates if this address is multicast - var isMulticast : Bool { get } -} - -/// IPv4Address -/// Base type to hold an IPv4 address and convert between strings and raw bytes. -/// Note that an IPv4 address may be scoped to an interface. -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public struct IPv4Address: IPAddress, Hashable, CustomDebugStringConvertible { - - /// The IPv4 any address used for listening - public static let any = IPv4Address(in_addr(address: INADDR_ANY), nil) - - /// The IPv4 broadcast address used to broadcast to all hosts - public static let broadcast = IPv4Address(in_addr(address: INADDR_BROADCAST), nil) - - /// The IPv4 loopback address - public static let loopback = IPv4Address(in_addr(address: INADDR_LOOPBACK), nil) - - /// The IPv4 all hosts multicast group - public static let allHostsGroup = IPv4Address(in_addr(address: INADDR_ALLHOSTS_GROUP), nil) - - /// The IPv4 all routers multicast group - public static let allRoutersGroup = IPv4Address(in_addr(address: INADDR_ALLRTRS_GROUP), nil) - - /// The IPv4 all reports multicast group for ICMPv3 membership reports - public static let allReportsGroup = IPv4Address(in_addr(address: INADDR_ALLRPTS_GROUP), nil) - - /// The IPv4 multicast DNS group. (Note: Use the dns_sd APIs instead of creating your own responder/resolver) - public static let mdnsGroup = IPv4Address(in_addr(address: INADDR_ALLMDNS_GROUP), nil) - - /// Indicates if this IPv4 address is loopback (127.0.0.1) - public var isLoopback : Bool { - return self == IPv4Address.loopback - } - - /// Indicates if this IPv4 address is link-local - public var isLinkLocal : Bool { - let linkLocalMask: UInt32 = IN_CLASSB_NET - let linkLocalCompare: UInt32 = IN_LINKLOCALNETNUM - return (self.address.s_addr & linkLocalMask.bigEndian) == linkLocalCompare.bigEndian - } - - /// Indicates if this IPv4 address is multicast - public var isMulticast : Bool { - let multicastMask: UInt32 = IN_CLASSD_NET - let multicastCompare: UInt32 = INADDR_UNSPEC_GROUP - return (self.address.s_addr & multicastMask.bigEndian) == multicastCompare.bigEndian - } - - /// Fetch the raw address (four bytes) - public var rawValue: Data { - var temporary = self.address - return withUnsafeBytes(of: &temporary) { (bytes) -> Data in - Data(bytes) - } - } - - internal init(_ address: in_addr, _ interface: NWInterface?) { - self.address = address - self.interface = interface - } - - /// Create an IPv4 address from a 4-byte data. Optionally specify an interface. - /// - /// - Parameter rawValue: The raw bytes of the IPv4 address, must be exactly 4 bytes or init will fail. - /// - Parameter interface: An optional network interface to scope the address to. Defaults to nil. - /// - Returns: An IPv4Address or nil if the Data parameter did not contain an IPv4 address. - public init?(_ rawValue: Data, _ interface: NWInterface? = nil) { - if rawValue.count != MemoryLayout.size { - return nil - } - let v4 = rawValue.withUnsafeBytes { $0.load(as: in_addr.self) } - self.init(v4, interface) - } - - /// Create an IPv4 address from an address literal string. - /// - /// This function does not perform host name to address resolution. This is the same as calling getaddrinfo - /// and using AI_NUMERICHOST. - /// - /// - Parameter string: An IPv4 address literal string such as "127.0.0.1", "169.254.8.8%en0". - /// - Returns: An IPv4Address or nil if the string parameter did not - /// contain an IPv4 address literal. - public init?(_ string: String) { - guard let result = getaddrinfo_numeric(string, family: AF_INET) else { - return nil - } - guard case .ipv4(let address) = result else { - return nil - } - self = address - } - - fileprivate let address : in_addr - - /// The interface the address is scoped to, if any. - public let interface: NWInterface? - - // Hashable - public static func == (lhs: IPv4Address, rhs: IPv4Address) -> Bool { - return lhs.address.s_addr == rhs.address.s_addr && lhs.interface == rhs.interface - } - - public func hash(into hasher: inout Hasher) { - hasher.combine(self.address.s_addr) - hasher.combine(self.interface) - } - - // CustomDebugStringConvertible - public var debugDescription: String { - var sin = sockaddr_in(self.address, 0) - let addressString = getnameinfo_numeric(address: &sin) - if let interface = self.interface { - return String("\(addressString)%\(interface)") - } else { - return addressString - } - } -} - -/// IPv6Address -/// Base type to hold an IPv6 address and convert between strings and raw bytes. -/// Note that an IPv6 address may be scoped to an interface. -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public struct IPv6Address: IPAddress, Hashable, CustomDebugStringConvertible { - - /// IPv6 any address - public static let any = IPv6Address(in6addr_any, nil) - - /// IPv6 broadcast address - public static let broadcast = IPv6Address(in6addr_any, nil) - - /// IPv6 loopback address - public static let loopback = IPv6Address(in6addr_loopback, nil) - - /// IPv6 all node local nodes multicast - public static let nodeLocalNodes = IPv6Address(in6addr_nodelocal_allnodes, nil) - - /// IPv6 all link local nodes multicast - public static let linkLocalNodes = IPv6Address(in6addr_linklocal_allnodes, nil) - - /// IPv6 all link local routers multicast - public static let linkLocalRouters = IPv6Address(in6addr_linklocal_allrouters, nil) - - public enum Scope: UInt8 { - case nodeLocal = 1 - case linkLocal = 2 - case siteLocal = 5 - case organizationLocal = 8 - case global = 0x0e - } - - /// Is the Any address "::0" - public var isAny : Bool { - return self.address.__u6_addr.__u6_addr32.0 == 0 && - self.address.__u6_addr.__u6_addr32.1 == 0 && - self.address.__u6_addr.__u6_addr32.2 == 0 && - self.address.__u6_addr.__u6_addr32.3 == 0 - } - - /// Is the looback address "::1" - public var isLoopback : Bool { - return self.address.__u6_addr.__u6_addr32.0 == 0 && - self.address.__u6_addr.__u6_addr32.1 == 0 && - self.address.__u6_addr.__u6_addr32.2 == 0 && - self.address.__u6_addr.__u6_addr32.3 != 0 && - self.address.__u6_addr.__u6_addr32.3 == UInt32(1).bigEndian - } - - /// Is an IPv4 compatible address - public var isIPv4Compatabile : Bool { - return self.address.__u6_addr.__u6_addr32.0 == 0 && - self.address.__u6_addr.__u6_addr32.1 == 0 && - self.address.__u6_addr.__u6_addr32.2 == 0 && - self.address.__u6_addr.__u6_addr32.3 != 0 && - self.address.__u6_addr.__u6_addr32.3 != UInt32(1).bigEndian - } - - /// Is an IPv4 mapped address such as "::ffff:1.2.3.4" - public var isIPv4Mapped : Bool { - return self.address.__u6_addr.__u6_addr32.0 == 0 && - self.address.__u6_addr.__u6_addr32.1 == 0 && - self.address.__u6_addr.__u6_addr32.2 == UInt32(0x0000ffff).bigEndian - } - - /// For IPv6 addresses that are IPv4 mapped, returns the IPv4 address - /// - /// - Returns: nil unless the IPv6 address was mapped or compatible, in which case the IPv4 address is - /// returned. - public var asIPv4 : IPv4Address? { - guard self.isIPv4Mapped || self.isIPv4Compatabile else { - return nil - } - return IPv4Address(in_addr(address: self.address.__u6_addr.__u6_addr32.3.bigEndian), - self.interface) - } - - /// Is a 6to4 IPv6 address - public var is6to4 : Bool { - return self.address.__u6_addr.__u6_addr16.0 == UInt16(0x2002).bigEndian - } - - /// Is a link-local address - public var isLinkLocal : Bool { - return self.address.__u6_addr.__u6_addr8.0 == UInt8(0xfe) && - (self.address.__u6_addr.__u6_addr8.1 & 0xc0) == 0x80 - } - - /// Is multicast - public var isMulticast : Bool { - return self.address.__u6_addr.__u6_addr8.0 == 0xff - } - - /// Returns the multicast scope - public var multicastScope : IPv6Address.Scope? { - if (self.isMulticast) { - return IPv6Address.Scope(rawValue: self.address.__u6_addr.__u6_addr8.1 & 0x0f) - } - return nil - } - - internal init(_ ip6: in6_addr, _ interface: NWInterface?) { - self.address = ip6 - self.interface = interface - } - - /// Create an IPv6 from a raw 16 byte value and optional interface - /// - /// - Parameter rawValue: A 16 byte IPv6 address - /// - Parameter interface: An optional interface the address is scoped to. Defaults to nil. - /// - Returns: nil unless the raw data contained an IPv6 address - public init?(_ rawValue: Data, _ interface: NWInterface? = nil) { - if rawValue.count != MemoryLayout.size { - return nil - } - let v6 = rawValue.withUnsafeBytes { $0.load(as: in6_addr.self) } - self.init(v6, interface) - } - - /// Create an IPv6 address from a string literal such as "fe80::1%lo0" or "2001:DB8::5" - /// - /// This function does not perform hostname resolution. This is similar to calling getaddrinfo with - /// AI_NUMERICHOST. - /// - /// - Parameter string: An IPv6 address literal string. - /// - Returns: nil unless the string contained an IPv6 literal - public init?(_ string: String) { - guard let result = getaddrinfo_numeric(string, family: AF_INET6) else { - return nil - } - guard case .ipv6(let address) = result else { - return nil - } - self = address - } - - fileprivate let address: in6_addr - - /// The interface the address is scoped to, if any. - public let interface: NWInterface? - - /// Fetch the raw address (sixteen bytes) - public var rawValue: Data { - var temporary = self.address - return withUnsafeBytes(of: &temporary) { (bytes) -> Data in - Data(bytes) - } - } - - // Hashable - public static func ==(lhs: IPv6Address, rhs: IPv6Address) -> Bool { - return lhs.address.__u6_addr.__u6_addr32.0 == rhs.address.__u6_addr.__u6_addr32.0 && - lhs.address.__u6_addr.__u6_addr32.1 == rhs.address.__u6_addr.__u6_addr32.1 && - lhs.address.__u6_addr.__u6_addr32.2 == rhs.address.__u6_addr.__u6_addr32.2 && - lhs.address.__u6_addr.__u6_addr32.3 == rhs.address.__u6_addr.__u6_addr32.3 && - lhs.interface == rhs.interface - } - - public func hash(into hasher: inout Hasher) { - hasher.combine(self.address.__u6_addr.__u6_addr32.0) - hasher.combine(self.address.__u6_addr.__u6_addr32.1) - hasher.combine(self.address.__u6_addr.__u6_addr32.2) - hasher.combine(self.address.__u6_addr.__u6_addr32.3) - hasher.combine(self.interface) - } - - // CustomDebugStringConvertible - public var debugDescription: String { - var sin6 = sockaddr_in6(self.address, 0) - let addressString = getnameinfo_numeric(address: &sin6) - if let interface = self.interface { - return String("\(addressString)%\(interface)") - } else { - return addressString - } - } -} - -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -/// NWEndpoint represents something that can be connected to. -public enum NWEndpoint: Hashable, CustomDebugStringConvertible { - // Depends on non-exhaustive enum support for forward compatibility - in the event we need to add - // a new case in the future - // https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md - - /// A host port endpoint represents an endpoint defined by the host and port. - case hostPort(host: NWEndpoint.Host, port: NWEndpoint.Port) - - /// A service endpoint represents a Bonjour service - case service(name: String, type: String, domain: String, interface: NWInterface?) - - /// A unix endpoint represents a path that supports connections using AF_UNIX domain sockets. - case unix(path: String) - - /// A Host is a name or address - public enum Host: Hashable, CustomDebugStringConvertible, ExpressibleByStringLiteral { - public typealias StringLiteralType = String - - public func hash(into hasher: inout Hasher) { - switch self { - case .name(let hostName, let hostInterface): - hasher.combine(hostInterface) - hasher.combine(hostName) - case .ipv4(let v4Address): - hasher.combine(v4Address) - case .ipv6(let v6Address): - hasher.combine(v6Address) - } - } - - /// A host specified as a name and optional interface scope - case name(String, NWInterface?) - - /// A host specified as an IPv4 address - case ipv4(IPv4Address) - - /// A host specified an an IPv6 address - case ipv6(IPv6Address) - - public init(stringLiteral: StringLiteralType) { - self.init(stringLiteral) - } - - /// Create a host from a string. - /// - /// This is the preferred way to create a host. If the string is an IPv4 address literal ("198.51.100.2"), an - /// IPv4 host will be created. If the string is an IPv6 address literal ("2001:DB8::2", "fe80::1%lo", etc), an IPv6 - /// host will be created. If the string is an IPv4 mapped IPv6 address literal ("::ffff:198.51.100.2") an IPv4 - /// host will be created. Otherwise, a named host will be created. - /// - /// - Parameter string: An IPv4 address literal, an IPv6 address literal, or a hostname. - /// - Returns: A Host object - public init(_ string: String) { - if let result = getaddrinfo_numeric(string) { - self = result - } else { - if let range = string.range(of: "%", options: String.CompareOptions.backwards), - let interface = NWInterface(String(string[range.upperBound...])){ - self = .name(String(string[..? = nil - if getaddrinfo(nil, service, &hints, &resolved) != 0 { - return nil - } - - // Check that it didn't return NULL. - guard let addrinfo = resolved else { - return nil - } - - // After this point we must ensure we free addrinfo before we return - guard let sa = addrinfo.pointee.ai_addr, sa.pointee.sa_family == AF_INET6 else { - freeaddrinfo(addrinfo) - return nil - } - - self.port = sa.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) {sin6 in - return sin6.pointee.sin6_port.bigEndian - } - - freeaddrinfo(addrinfo) - } - - public init(integerLiteral value: IntegerLiteralType) { - self.port = value - } - - public init?(rawValue: UInt16) { - self.port = rawValue - } - - internal init(_ value: UInt16) { - self.init(integerLiteral: value) - } - - public var debugDescription: String { - return String(port) - } - } - - /// Returns the interface the endpoint is scoped to if any - public var interface : NWInterface? { - switch self { - case .hostPort(host: let host, port: _): - return host.interface - case .service(name: _, type: _, domain: _, interface: let interface): - return interface - case .unix(_): - return nil - } - } - - internal init?(_ nw: nw_endpoint_t?) { - guard let nw = nw else { - return nil - } - var interface: NWInterface? = nil - if let nwinterface = nw_endpoint_copy_interface(nw) { - interface = NWInterface(nwinterface) - } - if nw_endpoint_get_type(nw) == Network.nw_endpoint_type_host { - let host = NWEndpoint.Host.name(String(cString: nw_endpoint_get_hostname(nw)), interface) - self = .hostPort(host: host, port: NWEndpoint.Port(nw_endpoint_get_port(nw))) - } else if nw_endpoint_get_type(nw) == Network.nw_endpoint_type_address { - let port = NWEndpoint.Port(nw_endpoint_get_port(nw)) - let address = nw_endpoint_get_address(nw) - if address.pointee.sa_family == AF_INET && address.pointee.sa_len == MemoryLayout.size { - let host = address.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { - (sin: UnsafePointer) -> NWEndpoint.Host in - return NWEndpoint.Host.ipv4(IPv4Address(sin.pointee.sin_addr, interface)) - } - self = .hostPort(host: host, port: port) - } else if address.pointee.sa_family == AF_INET6 && - address.pointee.sa_len == MemoryLayout.size { - let host = address.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) { - (sin6) -> NWEndpoint.Host in - if interface == nil && sin6.pointee.sin6_scope_id != 0 { - interface = NWInterface(Int(sin6.pointee.sin6_scope_id)) - } - return NWEndpoint.Host.ipv6(IPv6Address(sin6.pointee.sin6_addr, - interface)) - } - self = .hostPort(host: host, port: port) - } else if address.pointee.sa_family == AF_UNIX { - // sockaddr_un is very difficult to deal with in swift. Fortunately, nw_endpoint_copy_address_string - // already does exactly what we need. - let path = nw_endpoint_copy_address_string(nw) - self = .unix(path: String(cString: path)) - path.deallocate() - } else { - return nil - } - } else if nw_endpoint_get_type(nw) == Network.nw_endpoint_type_bonjour_service { - self = .service(name: String(cString: nw_endpoint_get_bonjour_service_name(nw)), - type: String(cString: nw_endpoint_get_bonjour_service_type(nw)), - domain: String(cString: nw_endpoint_get_bonjour_service_domain(nw)), - interface: interface) - } else { - return nil - } - } - - public func hash(into hasher: inout Hasher) { - switch self { - case .hostPort(host: let host, port: let port): - hasher.combine(host) - hasher.combine(port) - case .service(name: let name, type: let type, domain: let domain, interface: let interface): - hasher.combine(name) - hasher.combine(type) - hasher.combine(domain) - hasher.combine(interface) - case .unix(let path): - hasher.combine(path) - } - } - - public var debugDescription: String { - switch self { - case .hostPort(host: let host, port: let port): - var separator = ":" - if case .ipv6 = host { - separator = "." - } - return String("\(host)\(separator)\(port)") - case .service(name: let name, type: let type, domain: let domain, interface: let interface): - if let interface = interface { - return String("\(name).\(type)\(domain)%\(interface)") - } - return String("\(name).\(type)\(domain)") - case .unix(let path): - return path - } - } - - internal var nw: nw_endpoint_t? { - var endpoint: nw_endpoint_t? = nil - var interface: NWInterface? = nil - switch self { - case .hostPort(host: let host, port: let port): - switch host { - case .ipv4(let ipv4): - let sin = sockaddr_in(ipv4.address, port.port.bigEndian) - endpoint = sin.withSockAddr { (sa) -> nw_endpoint_t in - nw_endpoint_create_address(sa) - } - interface = ipv4.interface - case .ipv6(let ipv6): - let sin6 = sockaddr_in6(ipv6.address, port.port.bigEndian) - endpoint = sin6.withSockAddr { (sa) -> nw_endpoint_t? in - nw_endpoint_create_address(sa) - } - interface = ipv6.interface - case .name(let host, let hostInterface): - endpoint = nw_endpoint_create_host(host, port.debugDescription) - interface = hostInterface - } - case .service(name: let name, type: let type, domain: let domain, interface: let bonjourInterface): - endpoint = nw_endpoint_create_bonjour_service(name, type, domain) - interface = bonjourInterface - case .unix(let path): - endpoint = nw_endpoint_create_unix(path) - } - if interface != nil && endpoint != nil { - nw_endpoint_set_interface(endpoint!, interface!.nw) - } - return endpoint - } -} diff --git a/stdlib/public/Darwin/Network/NWError.swift b/stdlib/public/Darwin/Network/NWError.swift deleted file mode 100644 index eb26c780fdbd9..0000000000000 --- a/stdlib/public/Darwin/Network/NWError.swift +++ /dev/null @@ -1,73 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -import Darwin -import Security -@_implementationOnly import _SwiftNetworkOverlayShims - -/// NWError is a type to deliver error codes relevant to NWConnection and NWListener objects. -/// Generic connectivity errors will be delivered in the posix domain, resolution errors will -/// be delivered in the dns domain, and security errors will be delivered in the tls domain. -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public enum NWError: Error, CustomDebugStringConvertible, Equatable { - - /// The error code will be a POSIX error as defined in - case posix(POSIXErrorCode) - - /// The error code will be a DNSServiceErrorType error as defined in - case dns(DNSServiceErrorType) - - /// The error code will be a TLS error as defined in - case tls(OSStatus) - - internal init(_ nw: nw_error_t) { - switch nw_error_get_error_domain(nw) { - case Network.nw_error_domain_posix: - if let errorCode = POSIXErrorCode(rawValue: nw_error_get_error_code(nw)) { - self = .posix(errorCode) - } else { - self = .posix(.EINVAL) - } - case Network.nw_error_domain_dns: - self = .dns(DNSServiceErrorType(nw_error_get_error_code(nw))) - case Network.nw_error_domain_tls: - self = .tls(OSStatus(nw_error_get_error_code(nw))) - default: - self = .posix(.EINVAL) - } - } - - internal init?(_ nw: nw_error_t?) { - guard let nw = nw else { - return nil - } - self.init(nw) - } - - public var debugDescription: String { - switch self { - case .posix(let posixError): - let maxLen = 128 - let storage = UnsafeMutablePointer.allocate(capacity: maxLen) - var asString = "Unknown" - if strerror_r(posixError.rawValue, storage, maxLen) == 0 { - asString = String(cString: storage) - } - storage.deallocate() - return String("\(posixError): \(asString)") - case .dns(let dnsError): - return String("\(dnsError): \(String(cString: nwlog_get_string_for_dns_service_error(Int32(dnsError))))") - case .tls(let tlsError): - return String("\(tlsError): \(String(describing: SecCopyErrorMessageString(Int32(tlsError), nil)))") - } - } -} diff --git a/stdlib/public/Darwin/Network/NWListener.swift b/stdlib/public/Darwin/Network/NWListener.swift deleted file mode 100644 index 054fdee0a89db..0000000000000 --- a/stdlib/public/Darwin/Network/NWListener.swift +++ /dev/null @@ -1,321 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -import Darwin -import Dispatch -import Foundation - -/// An NWListener is an object that is able to receive incoming NWConnection -/// objects by binding to a local endpoint. A listener will accept connections based -/// on the protocols defined in its stack. For transport listeners (such as TCP and UDP), -/// accepted connections will represent new local and remote address and port tuples. -/// For listeners that include higher-level protocols that support multiplexing, -/// accepted connections will represent multiplexed streams on a new or existing transport -/// binding. - -// NOTE: older overlays had Network.NWListener as the ObjC name. -// The two must coexist, so it was renamed. The old name must not be -// used in the new runtime. _TtC7Network11_NWListener is the -// mangled name for Network._NWListener. -@_objcRuntimeName(_TtC7Network11_NWListener) -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public final class NWListener: CustomDebugStringConvertible { - public var debugDescription: String { - return String("\(self.nw)") - } - - /// Defines a service to advertise - public struct Service : Equatable, CustomDebugStringConvertible { - public var debugDescription: String { - var description = "" - if let name = self.name { - description = String("\(name).\(type)") - } else { - description = String("*.\(type)") - } - if let domain = self.domain { - description = String("\(description).\(domain)") - } else { - description = String("\(description).*") - } - if let txtRecord = txtRecord, !txtRecord.isEmpty { - description = String("\(description) <\(txtRecord.count) bytes of txt>") - } - return description - } - - /// Bonjour service name - if nil the system name will be used - public let name: String? - - /// Bonjour service type - public let type: String - - /// Bonjour service domain - if nil the system will register in all appropriate domains - public let domain: String? - - /// Bonjour txtRecord - metadata for the service. Update the txtRecord by setting the - /// service on the listener with the same name/type/domain and a new txtRecord. - public let txtRecord: Data? - - /// Create a Service to advertise for the listener. Name, domain, and txtRecord all default to nil. - public init(name: String? = nil, type: String, domain: String? = nil, txtRecord: Data? = nil) { - self.name = name - self.type = type - self.domain = domain - self.txtRecord = txtRecord - } - - internal var nw: nw_advertise_descriptor_t { - get { - let descriptor = nw_advertise_descriptor_create_bonjour_service(name, type, domain) - if let txtRecord = txtRecord { - txtRecord.withUnsafeBytes({ (ptr: UnsafePointer) -> Void in - nw_advertise_descriptor_set_txt_record(descriptor!, ptr, txtRecord.count) - }) - } - return descriptor! - } - } - } - - public enum State: Equatable { - /// Prior to start, the listener will be in the setup state - case setup - - /// Waiting listeners do not have a viable network - case waiting(NWError) - - /// Ready listeners are able to receive incoming connections - /// Bonjour service may not yet be registered - case ready - - /// Failed listeners are no longer able to receive incoming connections - case failed(NWError) - - /// Cancelled listeners have been invalidated by the client and will send no more events - case cancelled - - internal init(_ nw: nw_listener_state_t, _ err: nw_error_t?) { - switch nw { - case Network.nw_listener_state_invalid: - self = .setup - case Network.nw_listener_state_waiting: - if let error = NWError(err) { - self = .waiting(error) - } else { - self = .waiting(NWError.posix(.ENETDOWN)) - } - case Network.nw_listener_state_ready: - self = .ready - case Network.nw_listener_state_failed: - if let error = NWError(err) { - self = .failed(error) - } else { - self = .failed(NWError.posix(.EINVAL)) - } - case Network.nw_listener_state_cancelled: - self = .cancelled - default: - self = .cancelled - } - } - } - - private var _newConnectionHandler: ((_ connection: NWConnection) -> Void)? - - /// Block to be called for new inbound connections - public var newConnectionHandler: ((_ connection: NWConnection) -> Void)? { - set { - self._newConnectionHandler = newValue - if let newValue = newValue { - nw_listener_set_new_connection_handler(self.nw) { (nwConnection) in - guard let newConnection = NWConnection(using: self.parameters, inbound: nwConnection) else { - return; - } - newValue(newConnection) - } - } else { - nw_listener_set_state_changed_handler(self.nw, nil) - } - } - get { - return self._newConnectionHandler - } - } - - private var _state : State = .setup - private let nw: nw_listener_t - - private var _stateUpdateHandler: ((_ state: NWListener.State) -> Void)? - - /// Set a block to be called when the listener's state changes, which may be called - /// multiple times until the listener is cancelled. - public var stateUpdateHandler: ((_ state: NWListener.State) -> Void)? { - set { - self._stateUpdateHandler = newValue - if let newValue = newValue { - nw_listener_set_state_changed_handler(self.nw) { (state, error) in - self._state = NWListener.State(state, error) - newValue(self._state) - } - } else { - nw_listener_set_state_changed_handler(self.nw, nil) - } - } - get { - return self._stateUpdateHandler - } - } - - /// NWParameters used to create the listener - public let parameters : NWParameters - - private var _service : NWListener.Service? - - /// Optional Bonjour service to advertise with the listener - /// May be modified on the fly to update the TXT record or - /// change the advertised service. - public var service: NWListener.Service? { - get { - return _service - } - set { - _service = newValue - if let service = _service { - nw_listener_set_advertise_descriptor(nw, service.nw) - } else { - nw_listener_set_advertise_descriptor(nw, nil) - } - } - } - - /// The current port the listener is bound to, if any. The port is only valid when the listener is in the ready - /// state. - public var port: NWEndpoint.Port? { - return NWEndpoint.Port(nw_listener_get_port(self.nw)) - } - - public enum ServiceRegistrationChange { - /// An event when a Bonjour service has been registered, with the endpoint being advertised - case add(NWEndpoint) - - /// An event when a Bonjour service has been unregistered, with the endpoint being removed - case remove(NWEndpoint) - } - - private var _serviceRegistrationUpdateHandler: ((_ change: NWListener.ServiceRegistrationChange) -> Void)? - - /// Set a block to be called when the listener has added or removed a - /// registered service. This may be called multiple times until the listener - /// is cancelled. - public var serviceRegistrationUpdateHandler: ((_ change: NWListener.ServiceRegistrationChange) -> Void)? { - set { - self._serviceRegistrationUpdateHandler = newValue - if let newValue = newValue { - nw_listener_set_advertised_endpoint_changed_handler(self.nw) { (endpoint, added) in - if let changedEndpoint = NWEndpoint(endpoint) { - if added { - newValue(NWListener.ServiceRegistrationChange.add(changedEndpoint)) - } else { - newValue(NWListener.ServiceRegistrationChange.remove(changedEndpoint)) - } - } - } - } else { - nw_listener_set_advertised_endpoint_changed_handler(self.nw, nil) - } - } - get { - return self._serviceRegistrationUpdateHandler - } - } - - internal init(_ listener: nw_listener_t, _ parameters: NWParameters) { - self.parameters = parameters; - self.nw = listener - } - - /// Creates a networking listener. The listener will be assigned a random - /// port to listen on unless otherwise specified. - /// - /// - Parameter using: The parameters to use for the listener, which include the protocols to use for the - /// listener. The parameters requiredLocalEndpoint may be used to specify the local address and port to listen on. - /// - Parameter on: The port to listen on. Defaults to .any which will cause a random unused port to be assigned. - /// Specifying a port that is already in use will cause the listener to fail after starting. - /// - Returns: Returns a listener object that may be set up and started or throws an error if the parameters are - /// not compatible with the provided port. - public init(using: NWParameters, on: NWEndpoint.Port = .any) throws { - if on != .any { - guard let listener = nw_listener_create_with_port("\(on)", using.nw) else { - throw NWError.posix(.EINVAL) - } - self.parameters = using - self.nw = listener - } else { - guard let listener = nw_listener_create(using.nw) else { - throw NWError.posix(.EINVAL) - } - self.parameters = using - self.nw = listener - } - } - - /// Creates a networking listener based on an existing - /// multiplexing connection. If there are multiple protocols - /// in the connection that support listening for incoming flows, - /// the listener will be hooked up the highest in the stack - /// (the closest to the reading and writing of the client data). - /// - /// - Parameter withConnection: An existing connection that has a multiplexing protocol - /// that supports receiving new connections. - /// - Parameter parameters: The parameters to use for the listener. The protocol stack - /// defined in the parameters must be able to join a protocol - /// in the connection that supports listening protocols. - convenience internal init?(connection: NWConnection, parameters: NWParameters) { - guard let listener = nw_listener_create_with_connection(connection.nw, parameters.nw) else { - return nil - } - self.init(listener, parameters) - } - - /// Start the listener and provide a queue on which callback handlers will be executed. - /// When the listener state moves to ready, the listener is registered with the system - /// and can receive incoming connections. - /// Start should only be called once on a listener, and multiple calls to start will - /// be ignored. - public func start(queue: DispatchQueue) { - self._queue = queue - nw_listener_set_queue(self.nw, queue) - nw_listener_start(self.nw) - } - - private var _queue : DispatchQueue? = nil - - /// Get queue used for delivering block handlers, such as stateUpdateHandler, - /// serviceRegistrationUpdateHandler, and newConnectionHandler. - /// If the listener has not yet been started, the queue will be nil. Once the listener has been - /// started, the queue will be valid. - public var queue: DispatchQueue? { - get { - return _queue - } - } - - /// Cancel the listener. - /// - /// The cancel is asynchronous and the state will eventually transition to cancelled. Subsequent calls to - /// cancel are ignored. - public func cancel() { - nw_listener_cancel(self.nw) - } -} - diff --git a/stdlib/public/Darwin/Network/NWParameters.swift b/stdlib/public/Darwin/Network/NWParameters.swift deleted file mode 100644 index face2df7c8989..0000000000000 --- a/stdlib/public/Darwin/Network/NWParameters.swift +++ /dev/null @@ -1,505 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -/// An NWParameters object contains the parameters necessary to create -/// a network connection or listener. NWParameters include any preferences for -/// network paths (such as required, prohibited, and preferred networks, and local -/// endpoint requirements); preferences for data transfer and quality of service; -/// and the protocols to be used for a connection along with any protocol-specific -/// options. -// NOTE: older overlays had Network.NWParameters as the ObjC name. -// The two must coexist, so it was renamed. The old name must not be -// used in the new runtime. _TtC7Network13_NWParameters is the -// mangled name for Network._NWParameters. -@_objcRuntimeName(_TtC7Network13_NWParameters) -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public final class NWParameters : CustomDebugStringConvertible { - public var debugDescription: String { - return String("\(self.nw)") - } - - internal let nw : nw_parameters_t - - /// Creates a parameters object that is configured for TLS and TCP. The caller can use - /// the default configuration for TLS and TCP, or set specific options for each protocol, - /// or disable TLS. - /// - /// - Parameter tls: TLS options or nil for no TLS - /// - Parameter tcp: TCP options. Defaults to NWProtocolTCP.Options() with no options overridden. - /// - Returns: NWParameters object that can be used for creating a connection or listener - public convenience init(tls: NWProtocolTLS.Options?, tcp: NWProtocolTCP.Options = NWProtocolTCP.Options()) { - self.init() - let protocolStack = self.defaultProtocolStack - protocolStack.transportProtocol = tcp - if let tls = tls { - protocolStack.applicationProtocols = [tls] - } else { - protocolStack.applicationProtocols = [] - } - } - - /// Creates a parameters object that is configured for DTLS and UDP. The caller can use - /// the default configuration for DTLS and UDP, or set specific options for each protocol, - /// or disable TLS. - /// - /// - Parameter dtls: DTLS options or nil for no DTLS - /// - Parameter udp: UDP options. Defaults to NWProtocolUDP.Options() with no options overridden. - /// - Returns: NWParameters object that can be used for create a connection or listener - public convenience init(dtls: NWProtocolTLS.Options?, udp: NWProtocolUDP.Options = NWProtocolUDP.Options()) { - self.init() - let protocolStack = self.defaultProtocolStack - protocolStack.transportProtocol = udp - if let dtls = dtls { - protocolStack.applicationProtocols = [dtls] - } else { - protocolStack.applicationProtocols = [] - } - } - - /// Creates a generic NWParameters object. Note that in order to use parameters - /// with a NWConnection or a NetworkListener, the parameters must have protocols - /// added into the defaultProtocolStack. Clients using standard protocol - /// configurations should use init(tls:tcp:) or init(dtls:udp:). - public init() { - self.nw = nw_parameters_create() - } - - private init(nw: nw_parameters_t) { - self.nw = nw - } - - /// Default set of parameters for TLS over TCP - /// This is equivalent to calling init(tls:NWProtocolTLS.Options(), tcp:NWProtocolTCP.Options()) - public class var tls: NWParameters { - return NWParameters(tls:NWProtocolTLS.Options()) - } - - /// Default set of parameters for DTLS over UDP - /// This is equivalent to calling init(dtls:NWProtocolTLS.Options(), udp:NWProtocolUDP.Options()) - public class var dtls: NWParameters { - return NWParameters(dtls:NWProtocolTLS.Options()) - } - - /// Default set of parameters for TCP - /// This is equivalent to calling init(tls:nil, tcp:NWProtocolTCP.Options()) - public class var tcp: NWParameters { - return NWParameters(tls:nil) - } - - /// Default set of parameters for UDP - /// This is equivalent to calling init(dtls:nil, udp:NWProtocolUDP.Options()) - public class var udp: NWParameters { - return NWParameters(dtls:nil) - } - - /// Require a connection to use a specific interface, or fail if not available - public var requiredInterface: NWInterface? { - set { - if let interface = newValue { - nw_parameters_require_interface(self.nw, interface.nw) - } else { - nw_parameters_require_interface(self.nw, nil) - } - } - get { - if let interface = nw_parameters_copy_required_interface(self.nw) { - return NWInterface(interface) - } else { - return nil - } - } - } - - /// Require a connection to use a specific interface type, or fail if not available - public var requiredInterfaceType: NWInterface.InterfaceType { - set { - nw_parameters_set_required_interface_type(self.nw, newValue.nw) - } - get { - return NWInterface.InterfaceType(nw_parameters_get_required_interface_type(self.nw)) - } - } - - /// Define one or more interfaces that a connection will not be allowed to use - public var prohibitedInterfaces: [NWInterface]? { - set { - nw_parameters_clear_prohibited_interfaces(self.nw) - if let prohibitedInterfaces = newValue { - for prohibitedInterface in prohibitedInterfaces { - nw_parameters_prohibit_interface(self.nw, prohibitedInterface.nw) - } - } - } - get { - var interfaces = [NWInterface]() - nw_parameters_iterate_prohibited_interfaces(self.nw) { (interface) in - interfaces.append(NWInterface(interface)) - return true - } - return interfaces - } - } - - /// Define one or more interface types that a connection will not be allowed to use - public var prohibitedInterfaceTypes: [NWInterface.InterfaceType]? { - set { - nw_parameters_clear_prohibited_interface_types(self.nw) - if let prohibitedInterfaceTypes = newValue { - for prohibitedInterfaceType in prohibitedInterfaceTypes { - nw_parameters_prohibit_interface_type(self.nw, prohibitedInterfaceType.nw) - } - } - } - get { - var interfaceTypes = [NWInterface.InterfaceType]() - nw_parameters_iterate_prohibited_interface_types(self.nw) { (interfaceType) in - interfaceTypes.append(NWInterface.InterfaceType(interfaceType)) - return true - } - return interfaceTypes - } - } - - /// Disallow connection from using interfaces considered expensive - public var prohibitExpensivePaths: Bool { - set { - nw_parameters_set_prohibit_expensive(self.nw, newValue) - } - get { - return nw_parameters_get_prohibit_expensive(self.nw) - } - } - - /// If true, a direct connection will be attempted first even if proxies are configured. If the direct connection - /// fails, connecting through the proxies will still be attempted. - public var preferNoProxies: Bool { - set { - nw_parameters_set_prefer_no_proxy(self.nw, newValue) - } - get { - return nw_parameters_get_prefer_no_proxy(self.nw) - } - } - - /// Force a specific local address to be used. This value is nil by - /// default, in which case the system selects the most appropriate - /// local address and selects a local port. - public var requiredLocalEndpoint: NWEndpoint? { - set { - if let endpoint = newValue { - nw_parameters_set_local_endpoint(self.nw, endpoint.nw) - } else { - nw_parameters_set_local_endpoint(self.nw, nil) - } - } - get { - if let endpoint = nw_parameters_copy_local_endpoint(self.nw) { - return NWEndpoint(endpoint) - } else { - return nil - } - } - } - - /// Allow multiple connections to use the same local address and port - /// (SO_REUSEADDR and SO_REUSEPORT). - public var allowLocalEndpointReuse: Bool { - set { - nw_parameters_set_reuse_local_address(self.nw, newValue) - } - get { - return nw_parameters_get_reuse_local_address(self.nw) - } - } - - /// Cause an NWListener to only advertise services on the local link, - /// and only accept connections from the local link. - public var acceptLocalOnly: Bool { - set { - nw_parameters_set_local_only(self.nw, newValue) - } - get { - return nw_parameters_get_local_only(self.nw) - } - } - - /// Allow the inclusion of peer-to-peer interfaces when - /// listening or establishing outbound connections. This parameter - /// will not take effect if a specific interface is required. - /// This parameter is applicable when advertising a Bonjour service - /// on a listener, or connecting to a Bonjour service. - public var includePeerToPeer: Bool { - set { - nw_parameters_set_include_peer_to_peer(self.nw, newValue) - } - get { - return nw_parameters_get_include_peer_to_peer(self.nw) - } - } - - /// The ServiceClass represents the network queuing priority to use - /// for traffic generated by a NWConnection. - public enum ServiceClass { - /// Default priority traffic - case bestEffort - /// Bulk traffic, or traffic that can be de-prioritized behind foreground traffic - case background - /// Interactive video traffic - case interactiveVideo - /// Interactive voice traffic - case interactiveVoice - /// Responsive data - case responsiveData - /// Signaling - case signaling - - internal var nw: nw_service_class_t { - switch self { - case .bestEffort: - return Network.nw_service_class_best_effort - case .background: - return Network.nw_service_class_background - case .interactiveVideo: - return Network.nw_service_class_interactive_video - case .interactiveVoice: - return Network.nw_service_class_interactive_voice - case .responsiveData: - return Network.nw_service_class_responsive_data - case .signaling: - return Network.nw_service_class_signaling - } - } - - internal init(_ nw: nw_service_class_t) { - switch nw { - case Network.nw_service_class_best_effort: - self = .bestEffort - case Network.nw_service_class_background: - self = .background - case Network.nw_service_class_interactive_video: - self = .interactiveVideo - case Network.nw_service_class_interactive_voice: - self = .interactiveVoice - case Network.nw_service_class_responsive_data: - self = .responsiveData - case Network.nw_service_class_signaling: - self = .signaling - default: - self = .bestEffort - } - } - } - public var serviceClass: NWParameters.ServiceClass { - set { - nw_parameters_set_service_class(self.nw, newValue.nw) - } - get { - return NWParameters.ServiceClass(nw_parameters_get_service_class(self.nw)) - } - } - - /// Multipath services represent the modes of multipath usage that are - /// allowed for connections. - public enum MultipathServiceType { - /// No multipath transport will be attempted - case disabled - /// Only use the expensive interface when the when the primary one is not available - case handover - /// Use the expensive interface more aggressively to reduce latency - case interactive - /// Use all available interfaces to provide the highest throughput and lowest latency - case aggregate - - internal var nw: nw_multipath_service_t { - switch self { - case .disabled: - return Network.nw_multipath_service_disabled - case .handover: - return Network.nw_multipath_service_handover - case .interactive: - return Network.nw_multipath_service_interactive - case .aggregate: - return Network.nw_multipath_service_aggregate - } - } - - internal init(_ nw: nw_multipath_service_t) { - switch nw { - case Network.nw_multipath_service_disabled: - self = .disabled - case Network.nw_multipath_service_handover: - self = .handover - case Network.nw_multipath_service_interactive: - self = .interactive - case Network.nw_multipath_service_aggregate: - self = .aggregate - default: - self = .disabled - } - } - } - public var multipathServiceType: NWParameters.MultipathServiceType { - set { - nw_parameters_set_multipath_service(self.nw, newValue.nw) - } - get { - return NWParameters.MultipathServiceType(nw_parameters_get_multipath_service(self.nw)) - } - } - - /// Use fast open for an outbound NWConnection, which may be done at any - /// protocol level. Use of fast open requires that the caller send - /// idempotent data on the connection before the connection may move - /// into ready state. As a side effect, this may implicitly enable - /// fast open for protocols in the stack, even if they did not have - /// fast open explicitly enabled on them (such as the option to enable - /// TCP Fast Open). - public var allowFastOpen: Bool { - set { - nw_parameters_set_fast_open_enabled(self.nw, newValue) - } - get { - return nw_parameters_get_fast_open_enabled(self.nw) - } - } - - /// Allow or prohibit the use of expired DNS answers during connection establishment. - /// If allowed, a DNS answer that was previously returned may be re-used for new - /// connections even after the answers are considered expired. A query for fresh answers - /// will be sent in parallel, and the fresh answers will be used as alternate addresses - /// in case the expired answers do not result in successful connections. - /// By default, this value is .systemDefault, which allows the system to determine - /// if it is appropriate to use expired answers. - public enum ExpiredDNSBehavior { - /// Let the system determine whether or not to allow expired DNS answers - case systemDefault - /// Explicitly allow the use of expired DNS answers - case allow - /// Explicitly prohibit the use of expired DNS answers - case prohibit - - internal var nw: nw_parameters_expired_dns_behavior_t { - switch self { - case .systemDefault: - return Network.nw_parameters_expired_dns_behavior_default - case .allow: - return Network.nw_parameters_expired_dns_behavior_allow - case .prohibit: - return Network.nw_parameters_expired_dns_behavior_prohibit - } - } - - internal init(_ nw: nw_parameters_expired_dns_behavior_t) { - switch nw { - case Network.nw_parameters_expired_dns_behavior_default: - self = .systemDefault - case Network.nw_parameters_expired_dns_behavior_allow: - self = .allow - case Network.nw_parameters_expired_dns_behavior_prohibit: - self = .prohibit - default: - self = .systemDefault - } - } - } - public var expiredDNSBehavior: NWParameters.ExpiredDNSBehavior { - set { - nw_parameters_set_expired_dns_behavior(self.nw, newValue.nw) - } - get { - return NWParameters.ExpiredDNSBehavior(nw_parameters_get_expired_dns_behavior(self.nw)) - } - } - - /// A ProtocolStack contains a list of protocols to use for a connection. - /// The members of the protocol stack are NWProtocolOptions objects, each - /// defining which protocol to use within the stack along with any protocol-specific - /// options. Each stack includes an array of application-level protocols, a single - /// transport-level protocol, and an optional internet-level protocol. If the internet- - /// level protocol is not specified, any available and applicable IP address family - /// may be used. - // Set the ObjC name of this class to be nested in the customized ObjC - // name of NWParameters. - @_objcRuntimeName(_TtCC7Network13_NWParameters13ProtocolStack) - public class ProtocolStack { - public var applicationProtocols: [NWProtocolOptions] { - set { - nw_protocol_stack_clear_application_protocols(self.nw) - for applicationProtocol in newValue.reversed() { - nw_protocol_stack_prepend_application_protocol(self.nw, applicationProtocol.nw) - } - } - get { - var applicationProtocols = [NWProtocolOptions]() - nw_protocol_stack_iterate_application_protocols(self.nw) { (protocolOptions) in - let applicationDefinition = nw_protocol_options_copy_definition(protocolOptions) - if (nw_protocol_definition_is_equal(applicationDefinition, NWProtocolTLS.definition.nw)) { - applicationProtocols.append(NWProtocolTLS.Options(protocolOptions)) - } - } - return applicationProtocols - } - } - - public var transportProtocol: NWProtocolOptions? { - set { - if let transport = newValue { - nw_protocol_stack_set_transport_protocol(self.nw, transport.nw) - } - } - get { - if let transport = nw_protocol_stack_copy_transport_protocol(nw) { - let transportDefinition = nw_protocol_options_copy_definition(transport) - if (nw_protocol_definition_is_equal(transportDefinition, NWProtocolTCP.definition.nw)) { - return NWProtocolTCP.Options(transport) - } else if (nw_protocol_definition_is_equal(transportDefinition, NWProtocolUDP.definition.nw)) { - return NWProtocolUDP.Options(transport) - } - } - return nil - } - } - - public var internetProtocol: NWProtocolOptions? { - set { - // Not currently allowed - return - } - get { - if let ip = nw_protocol_stack_copy_internet_protocol(nw) { - if (nw_protocol_definition_is_equal(nw_protocol_options_copy_definition(ip), NWProtocolIP.definition.nw)) { - return NWProtocolIP.Options(ip) - } - } - return nil - } - } - - internal let nw: nw_protocol_stack_t - - internal init(_ nw: nw_protocol_stack_t) { - self.nw = nw - } - } - - /// Every NWParameters has a default protocol stack, although it may start out empty. - public var defaultProtocolStack: NWParameters.ProtocolStack { - get { - return NWParameters.ProtocolStack(nw_parameters_copy_default_protocol_stack(self.nw)) - } - } - - /// Perform a deep copy of parameters - public func copy() -> NWParameters { - return NWParameters(nw: nw_parameters_copy(self.nw)) - } -} diff --git a/stdlib/public/Darwin/Network/NWPath.swift b/stdlib/public/Darwin/Network/NWPath.swift deleted file mode 100644 index 37df6b6841a6b..0000000000000 --- a/stdlib/public/Darwin/Network/NWPath.swift +++ /dev/null @@ -1,302 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -import Foundation -@_implementationOnly import _SwiftNetworkOverlayShims - -/// An NWInterface object represents an instance of a network interface of a specific -/// type, such as a Wi-Fi or Cellular interface. -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public struct NWInterface : Hashable, CustomDebugStringConvertible { - - public var debugDescription: String { - return self.name - } - - public static func ==(lhs: NWInterface, rhs: NWInterface) -> Bool { - return lhs.index == rhs.index && lhs.name == rhs.name - } - - public func hash(into hasher: inout Hasher) { - hasher.combine(self.index) - hasher.combine(self.name) - } - - /// Interface types represent the underlying media for a network link - public enum InterfaceType { - /// A virtual or otherwise unknown interface type - case other - /// A Wi-Fi link - case wifi - /// A Cellular link - case cellular - /// A Wired Ethernet link - case wiredEthernet - /// The Loopback Interface - case loopback - - internal var nw : nw_interface_type_t { - switch self { - case .wifi: - return Network.nw_interface_type_wifi - case .cellular: - return Network.nw_interface_type_cellular - case .wiredEthernet: - return Network.nw_interface_type_wired - case .loopback: - return Network.nw_interface_type_loopback - case .other: - return Network.nw_interface_type_other - } - } - - internal init(_ nw: nw_interface_type_t) { - switch nw { - case Network.nw_interface_type_wifi: - self = .wifi - case Network.nw_interface_type_cellular: - self = .cellular - case Network.nw_interface_type_wired: - self = .wiredEthernet - case Network.nw_interface_type_loopback: - self = .loopback - default: - self = .other - } - } - } - - /// The interface type. - public let type: InterfaceType - - /// The name of the interface, such as "en0" - public let name: String - - /// The kernel index of the interface - public let index: Int - - internal let nw: nw_interface_t - - internal init(_ nw: nw_interface_t) { - self.nw = nw - self.type = NWInterface.InterfaceType(nw_interface_get_type(nw)) - self.name = String(cString: nw_interface_get_name(nw)) - self.index = Int(nw_interface_get_index(nw)) - } - - internal init?(_ index: Int) { - guard let nw = nw_interface_create_with_index(UInt32(index)) else { - return nil - } - self.init(nw) - } - - internal init?(_ name: String) { - guard let nw = nw_interface_create_with_name(name) else { - return nil - } - self.init(nw) - } -} - -/// An NWPath object represents a snapshot of network path state. This state -/// represents the known information about the local interface and routes that may -/// be used to send and receive data. If the network path for a connection changes -/// due to interface characteristics, addresses, or other attributes, a new NWPath -/// object will be generated. Note that the differences in the path attributes may not -/// be visible through public accessors, and these changes should be treated merely -/// as an indication that something about the network has changed. -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public struct NWPath : Equatable, CustomDebugStringConvertible { - - public var debugDescription: String { - return String(describing: self.nw) - } - - /// An NWPath status indicates if there is a usable route available upon which to send and receive data. - public enum Status { - /// The path has a usable route upon which to send and receive data - case satisfied - /// The path does not have a usable route. This may be due to a network interface being down, or due to system policy. - case unsatisfied - /// The path does not currently have a usable route, but a connection attempt will trigger network attachment. - case requiresConnection - } - - public let status: NWPath.Status - - /// A list of all interfaces currently available to this path - public let availableInterfaces: [NWInterface] - - /// Checks if the path uses an NWInterface that is considered to be expensive - /// - /// Cellular interfaces are considered expensive. WiFi hotspots from an iOS device are considered expensive. Other - /// interfaces may appear as expensive in the future. - public let isExpensive : Bool - public let supportsIPv4 : Bool - public let supportsIPv6 : Bool - public let supportsDNS : Bool - - /// Check the local endpoint set on a path. This will be nil for paths - /// from an NWPathMonitor. For paths from an NWConnection, this will - /// be set to the local address and port in use by the connection. - public let localEndpoint: NWEndpoint? - - /// Check the remote endpoint set on a path. This will be nil for paths - /// from an NWPathMonitor. For paths from an NWConnection, this will - /// be set to the remote address and port in use by the connection. - public let remoteEndpoint: NWEndpoint? - - /// Checks if the path uses an NWInterface with the specified type - public func usesInterfaceType(_ type: NWInterface.InterfaceType) -> Bool { - if let path = self.nw { - return nw_path_uses_interface_type(path, type.nw) - } - return false - } - - internal let nw: nw_path_t? - - internal init(_ path: nw_path_t?) { - var interfaces = [NWInterface]() - var local: NWEndpoint? = nil - var remote: NWEndpoint? = nil - if let path = path { - let nwstatus = nw_path_get_status(path) - switch (nwstatus) { - case Network.nw_path_status_satisfied: - self.status = .satisfied - case Network.nw_path_status_satisfiable: - self.status = .requiresConnection - default: - self.status = .unsatisfied - } - self.isExpensive = nw_path_is_expensive(path) - self.supportsDNS = nw_path_has_dns(path) - self.supportsIPv4 = nw_path_has_ipv4(path) - self.supportsIPv6 = nw_path_has_ipv6(path) - - nw_path_enumerate_interfaces(path, { (interface) in - interfaces.append(NWInterface(interface)) - return true - }) - - if let nwlocal = nw_path_copy_effective_local_endpoint(path) { - local = NWEndpoint(nwlocal) - } - if let nwremote = nw_path_copy_effective_remote_endpoint(path) { - remote = NWEndpoint(nwremote) - } - } else { - self.status = .unsatisfied - self.isExpensive = false - self.supportsDNS = false - self.supportsIPv4 = false - self.supportsIPv6 = false - } - self.availableInterfaces = interfaces - self.nw = path - self.localEndpoint = local - self.remoteEndpoint = remote - } - - public static func ==(lhs: NWPath, rhs: NWPath) -> Bool { - if let lnw = lhs.nw, let rnw = rhs.nw { - return nw_path_is_equal(lnw, rnw) - } - return lhs.nw == nil && rhs.nw == nil - } -} - -/// The NWPathMonitor allows the caller to fetch the current global path (or -/// a path restricted to a specific network interface type). The path for the monitor -/// is an observable property that will be updated upon each network change. -/// Paths generated by a path monitor are not specific to a given endpoint, and -/// will not have the localEndpoint or remoteEndpoint properties set. -/// The paths will watch the state of multiple interfaces, and allows the -/// application to enumerate the available interfaces for use in creating connections -/// or listeners bound to specific interfaces. -// NOTE: older overlays had Network.NWPathMonitor as the ObjC name. -// The two must coexist, so it was renamed. The old name must not be -// used in the new runtime. _TtC7Network14_NWPathMonitor is the -// mangled name for Network._NWPathMonitor. -@_objcRuntimeName(_TtC7Network14_NWPathMonitor) -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public final class NWPathMonitor { - - /// Access the current network path tracked by the monitor - public var currentPath = NWPath(nil) - fileprivate let nw : nw_path_monitor_t - - /// Set a block to be called when the network path changes - private var _pathUpdateHandler: ((_ newPath: NWPath) -> Void)? - public var pathUpdateHandler: ((_ newPath: NWPath) -> Void)? { - set { - self._pathUpdateHandler = newValue - } - get { - return self._pathUpdateHandler - } - } - - /// Start the path monitor and set a queue on which path updates - /// will be delivered. - /// Start should only be called once on a monitor, and multiple calls to start will - /// be ignored. - public func start(queue: DispatchQueue) { - self._queue = queue - nw_path_monitor_set_queue(self.nw, queue) - nw_path_monitor_start(self.nw) - } - - /// Cancel the path monitor, after which point no more path updates will - /// be delivered. - public func cancel() { - nw_path_monitor_cancel(self.nw) - } - - private var _queue: DispatchQueue? - - /// Get queue used for delivering the pathUpdateHandler block. - /// If the path monitor has not yet been started, the queue will be nil. Once the - /// path monitor has been started, the queue will be valid. - public var queue: DispatchQueue? { - get { - return self._queue - } - } - - - /// Create a network path monitor to monitor overall network state for the - /// system. This allows enumeration of all interfaces that are available for - /// general use by the application. - public init() { - self.nw = nw_path_monitor_create() - nw_path_monitor_set_update_handler(self.nw) { (newPath) in - self.currentPath = NWPath(newPath) - if let handler = self._pathUpdateHandler { - handler(self.currentPath) - } - } - } - - /// Create a network path monitor that watches a single interface type. - public init(requiredInterfaceType: NWInterface.InterfaceType) { - self.nw = nw_path_monitor_create_with_type(requiredInterfaceType.nw) - nw_path_monitor_set_update_handler(self.nw) { (newPath) in - self.currentPath = NWPath(newPath) - if let handler = self._pathUpdateHandler { - handler(self.currentPath) - } - } - } -} diff --git a/stdlib/public/Darwin/Network/NWProtocol.swift b/stdlib/public/Darwin/Network/NWProtocol.swift deleted file mode 100644 index f05e30cf6c91b..0000000000000 --- a/stdlib/public/Darwin/Network/NWProtocol.swift +++ /dev/null @@ -1,86 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -/// NWProtocolDefinition is an abstract superclass that represents the identifier of a -/// protocol that can be used with connections and listeners, such as TCP. -// NOTE: older overlays had Network.NWProtocolDefinition as the ObjC name. -// The two must coexist, so it was renamed. The old name must not be -// used in the new runtime. _TtC7Network21_NWProtocolDefinition is the -// mangled name for Network._NWProtocolDefinition. -@_objcRuntimeName(_TtC7Network21_NWProtocolDefinition) -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public class NWProtocolDefinition : Equatable, CustomDebugStringConvertible { - public static func == (lhs: NWProtocolDefinition, rhs: NWProtocolDefinition) -> Bool { - return nw_protocol_definition_is_equal(lhs.nw, rhs.nw) - } - - /// The name of the protocol, such as "TCP" or "UDP" - public let name: String - internal let nw: nw_protocol_definition_t - - internal init(_ nw: nw_protocol_definition_t, _ name: String) { - self.name = name - self.nw = nw - } - - public var debugDescription: String { - return self.name - } -} - -/// NWProtocolOptions is an abstract superclass that represents a configuration options -/// that can be used to add a protocol into an NWParameters.ProtocolStack. These options -/// configure the behavior of a protocol and cannot be changed after starting a connection. -// NOTE: older overlays had Network.NWProtocolOptions as the ObjC name. -// The two must coexist, so it was renamed. The old name must not be -// used in the new runtime. _TtC7Network18_NWProtocolOptions is the -// mangled name for Network._NWProtocolOptions. -@_objcRuntimeName(_TtC7Network18_NWProtocolOptions) -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public class NWProtocolOptions { - internal let nw: nw_protocol_options_t - - - internal init(_ nw: nw_protocol_options_t) { - self.nw = nw - } -} - -/// NWProtocolMetadata is an abstract superclass. An instance of metadata holds a set of -/// protocol-specific metadata. This metadata allows clients to pass down protocol requirements -/// specific to some content being sent; as well as to retrieve metadata specific to some -/// content that was received. Each protocol is responsible for defining its own accessor -/// functions to set and get metadata. -// NOTE: older overlays had Network.NWProtocolMetadata as the ObjC name. -// The two must coexist, so it was renamed. The old name must not be -// used in the new runtime. _TtC7Network19_NWProtocolMetadata is the -// mangled name for Network._NWProtocolMetadata. -@_objcRuntimeName(_TtC7Network19_NWProtocolMetadata) -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public class NWProtocolMetadata { - internal let nw: nw_protocol_metadata_t - - internal init(_ nw: nw_protocol_metadata_t) { - self.nw = nw - } -} - -/// NWProtocol is an abstract superclass to which protocol implementations conform. -// NOTE: older overlays had Network.NWProtocol as the ObjC name. -// The two must coexist, so it was renamed. The old name must not be -// used in the new runtime. _TtC7Network11_NWProtocol is the -// mangled name for Network._NWProtocol. -@_objcRuntimeName(_TtC7Network11_NWProtocol) -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public class NWProtocol { - -} diff --git a/stdlib/public/Darwin/Network/NWProtocolIP.swift b/stdlib/public/Darwin/Network/NWProtocolIP.swift deleted file mode 100644 index 1e585bb95e5b9..0000000000000 --- a/stdlib/public/Darwin/Network/NWProtocolIP.swift +++ /dev/null @@ -1,225 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -// NOTE: older overlays had Network.NWProtocolIP as the ObjC name. -// The two must coexist, so it was renamed. The old name must not be -// used in the new runtime. _TtC7Network13_NWProtocolIP is the -// mangled name for Network._NWProtocolIP. -@_objcRuntimeName(_TtC7Network13_NWProtocolIP) -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public class NWProtocolIP : NWProtocol { - public static let definition: NWProtocolDefinition = { - NWProtocolDefinition(nw_protocol_copy_ip_definition(), "ip") - }() - - // Set the ObjC name of this class to be nested in the customized ObjC - // name of NWProtocolIP. - @_objcRuntimeName(_TtCC7Network13_NWProtocolIP7Options) - public class Options : NWProtocolOptions { - public enum Version { - /// Allow any IP version - case any - /// Use only IP version 4 (IPv4) - case v4 - /// Use only IP version 6 (IPv6) - case v6 - - internal var nw: nw_ip_version_t { - switch self { - case .v4: - return Network.nw_ip_version_4 - case .v6: - return Network.nw_ip_version_6 - default: - return Network.nw_ip_version_any - } - } - - internal init(_ nw: nw_ip_version_t) { - switch nw { - case Network.nw_ip_version_4: - self = .v4 - case Network.nw_ip_version_6: - self = .v6 - default: - self = .any - } - } - } - - private var _version: Version = .any - - /// Specify a single version of the Internet NWProtocol to allow. - /// Setting this value will constrain which address endpoints can - /// be used, and will filter DNS results during connection establishment. - public var version: Version { - set { - self._version = newValue - nw_ip_options_set_version(self.nw, newValue.nw) - } - get { - return self._version - } - } - - private var _hopLimit: UInt8 = 0 - - /// Configure the IP hop limit, equivalent to IP_TTL for IPv4 - /// and IPV6_HOPLIMIT for IPv6. - public var hopLimit: UInt8 { - set { - self._hopLimit = newValue - nw_ip_options_set_hop_limit(self.nw, newValue) - } - get { - return self._hopLimit - } - } - - private var _useMinimumMTU: Bool = false - - /// Configure IP to use the minimum MTU value, which - /// is 1280 bytes for IPv6 (IPV6_USE_MIN_MTU). This value has - /// no effect for IPv4. - public var useMinimumMTU: Bool { - set { - self._useMinimumMTU = newValue - nw_ip_options_set_use_minimum_mtu(self.nw, newValue) - } - get { - return self._useMinimumMTU - } - } - - private var _disableFragmentation: Bool = false - - /// Configure IP to disable fragmentation on outgoing - /// packets (IPV6_DONTFRAG). This value has no effect - /// for IPv4. - public var disableFragmentation: Bool { - set { - self._disableFragmentation = newValue - nw_ip_options_set_disable_fragmentation(self.nw, newValue) - } - get { - return self._disableFragmentation - } - } - - private var _shouldCalculateReceiveTime: Bool = false - - /// Configure IP to calculate receive time for inbound - /// packets. - public var shouldCalculateReceiveTime: Bool { - set { - self._shouldCalculateReceiveTime = newValue - nw_ip_options_set_calculate_receive_time(self.nw, newValue) - } - get { - return self._shouldCalculateReceiveTime - } - } - - override internal init(_ nw: nw_protocol_options_t) { - super.init(nw) - } - } - - /// Values for Explicit Congestion Notification flags - public enum ECN { - /// Non ECN-Capable Transport - case nonECT - /// ECN Capable Transport (0) - case ect0 - /// ECN Capable Transport (1) - case ect1 - /// Congestion Experienced - case ce - - fileprivate init(_ nw: nw_ip_ecn_flag_t) { - switch nw { - case Network.nw_ip_ecn_flag_non_ect: - self = .nonECT - case Network.nw_ip_ecn_flag_ect_0: - self = .ect0 - case Network.nw_ip_ecn_flag_ect_1: - self = .ect1 - case Network.nw_ip_ecn_flag_ce: - self = .ce - default: - self = .nonECT - } - } - - fileprivate var nw : nw_ip_ecn_flag_t { - switch self { - case .nonECT: - return Network.nw_ip_ecn_flag_non_ect - case .ect0: - return Network.nw_ip_ecn_flag_ect_0 - case .ect1: - return Network.nw_ip_ecn_flag_ect_1 - case .ce: - return Network.nw_ip_ecn_flag_ce - } - } - } - - /// IP Metadata can be sent or received as part of ContentContext - // Set the ObjC name of this class to be nested in the customized ObjC - // name of NWProtocolIP. - @_objcRuntimeName(_TtCC7Network13_NWProtocolIP8Metadata) - public class Metadata: NWProtocolMetadata { - /// Set ECN flags to be sent on a packet, or get ECN flags - /// received on a packet. These flags will not take effect - /// for protocols such as TCP that deliver data without accounting - /// for packet boundaries. - public var ecn: ECN { - set { - nw_ip_metadata_set_ecn_flag(nw, newValue.nw) - } - get { - return ECN(nw_ip_metadata_get_ecn_flag(nw)) - } - } - - /// Set the network service class to be sent on a packet. The per-packet - /// service class will not take effect for protocols such as TCP that deliver - /// data without accounting for packet boundaries. If you need to set - /// service class for TCP, use the serviceClass property of NWParameters. - public var serviceClass : NWParameters.ServiceClass { - set { - nw_ip_metadata_set_service_class(nw, newValue.nw) - } - get { - return NWParameters.ServiceClass(nw_ip_metadata_get_service_class(nw)) - } - } - - /// The time at which a packet was received, in nanoseconds. - /// Equivalent to timestamps returned by CLOCK_MONOTONIC_RAW. - public var receiveTime: UInt64 { - get { - return nw_ip_metadata_get_receive_time(nw) - } - } - - override internal init(_ nw: nw_protocol_metadata_t) { - super.init(nw) - } - - /// Create an empty IP metadata to send with ContentContext - public init() { - super.init(nw_ip_create_metadata()) - } - } -} diff --git a/stdlib/public/Darwin/Network/NWProtocolTCP.swift b/stdlib/public/Darwin/Network/NWProtocolTCP.swift deleted file mode 100644 index f7968eb767644..0000000000000 --- a/stdlib/public/Darwin/Network/NWProtocolTCP.swift +++ /dev/null @@ -1,277 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -// NOTE: older overlays had Network.NWProtocolTCP as the ObjC name. -// The two must coexist, so it was renamed. The old name must not be -// used in the new runtime. _TtC7Network14_NWProtocolTCP is the -// mangled name for Network._NWProtocolTCP. -@_objcRuntimeName(_TtC7Network14_NWProtocolTCP) -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public class NWProtocolTCP : NWProtocol { - public static let definition: NWProtocolDefinition = { - NWProtocolDefinition(nw_protocol_copy_tcp_definition(), "tcp") - }() - - // Set the ObjC name of this class to be nested in the customized ObjC - // name of NWProtocolTCP. - @_objcRuntimeName(_TtCC7Network14_NWProtocolTCP7Options) - public class Options : NWProtocolOptions { - - private var _noDelay: Bool = false - - /// A boolean indicating that TCP should disable - /// Nagle's algorithm (TCP_NODELAY). - public var noDelay: Bool { - set { - self._noDelay = newValue - nw_tcp_options_set_no_delay(self.nw, newValue) - } - get { - return self._noDelay - } - } - - private var _noPush: Bool = false - - /// A boolean indicating that TCP should be set into - /// no-push mode (TCP_NOPUSH). - public var noPush: Bool { - set { - self._noPush = newValue - nw_tcp_options_set_no_push(self.nw, newValue) - } - get { - return self._noPush - } - } - - private var _noOptions: Bool = false - - /// A boolean indicating that TCP should be set into - /// no-options mode (TCP_NOOPT). - public var noOptions: Bool { - set { - self._noOptions = newValue - nw_tcp_options_set_no_options(self.nw, newValue) - } - get { - return self._noOptions - } - } - - private var _enableKeepalive: Bool = false - - /// A boolean indicating that TCP should send keepalives - /// (SO_KEEPALIVE). - public var enableKeepalive: Bool { - set { - self._enableKeepalive = newValue - nw_tcp_options_set_enable_keepalive(self.nw, newValue) - } - get { - return self._enableKeepalive - } - } - - private var _keepaliveCount: Int = 0 - - /// The number of keepalive probes to send before terminating - /// the connection (TCP_KEEPCNT). - public var keepaliveCount : Int { - set { - self._keepaliveCount = newValue - nw_tcp_options_set_keepalive_count(self.nw, UInt32(newValue)) - } - get { - return self._keepaliveCount - } - } - - private var _keepaliveIdle: Int = 0 - - /// The number of seconds of idleness to wait before keepalive - /// probes are sent by TCP (TCP_KEEPALIVE). - public var keepaliveIdle : Int { - set { - self._keepaliveIdle = newValue - nw_tcp_options_set_keepalive_idle_time(self.nw, UInt32(newValue)) - } - get { - return self._keepaliveIdle - } - } - - private var _keepaliveInterval: Int = 0 - - /// The number of seconds of to wait before resending TCP - /// keepalive probes (TCP_KEEPINTVL). - public var keepaliveInterval : Int { - set { - self._keepaliveInterval = newValue - nw_tcp_options_set_keepalive_interval(self.nw, UInt32(newValue)) - } - get { - return self._keepaliveInterval - } - } - - private var _maximumSegmentSize: Int = 0 - - /// The maximum segment size in bytes (TCP_MAXSEG). - public var maximumSegmentSize : Int { - set { - self._maximumSegmentSize = newValue - nw_tcp_options_set_maximum_segment_size(self.nw, UInt32(newValue)) - } - get { - return self._maximumSegmentSize - } - } - - private var _connectionTimeout: Int = 0 - - /// A timeout for TCP connection establishment, in seconds - /// (TCP_CONNECTIONTIMEOUT). - public var connectionTimeout : Int { - set { - self._connectionTimeout = newValue - nw_tcp_options_set_connection_timeout(self.nw, UInt32(newValue)) - } - get { - return self._connectionTimeout - } - } - - private var _persistTimeout: Int = 0 - - /// The TCP persist timeout, in seconds (PERSIST_TIMEOUT). - /// See RFC 6429. - public var persistTimeout : Int { - set { - self._persistTimeout = newValue - nw_tcp_options_set_persist_timeout(self.nw, UInt32(newValue)) - } - get { - return self._persistTimeout - } - } - - private var _connectionDropTime: Int = 0 - - /// A timeout for TCP retransmission attempts, in seconds - /// (TCP_RXT_CONNDROPTIME). - public var connectionDropTime : Int { - set { - self._connectionDropTime = newValue - nw_tcp_options_set_retransmit_connection_drop_time(self.nw, UInt32(newValue)) - } - get { - return self._connectionDropTime - } - } - - private var _retransmitFinDrop: Bool = false - - /// A boolean to cause TCP to drop its connection after - /// not receiving an ACK after a FIN (TCP_RXT_FINDROP). - public var retransmitFinDrop: Bool { - set { - self._retransmitFinDrop = newValue - nw_tcp_options_set_retransmit_fin_drop(self.nw, newValue) - } - get { - return self._retransmitFinDrop - } - } - - private var _disableAckStretching: Bool = false - - /// A boolean to cause TCP to disable ACK stretching (TCP_SENDMOREACKS). - public var disableAckStretching: Bool { - set { - self._disableAckStretching = newValue - nw_tcp_options_set_disable_ack_stretching(self.nw, newValue) - } - get { - return self._disableAckStretching - } - } - - private var _enableFastOpen: Bool = false - - /// Configure TCP to enable TCP Fast Open (TFO). This may take effect - /// even when TCP is not the top-level protocol in the protocol stack. - /// For example, if TLS is running over TCP, the Client Hello message - /// may be sent as fast open data. - /// - /// If TCP is the top-level protocol in the stack (the one the application - /// directly interacts with), TFO will be disabled unless the application - /// indicated that it will provide its own fast open data by calling - /// NWParameters.allowFastOpen. - public var enableFastOpen: Bool { - set { - self._enableFastOpen = newValue - nw_tcp_options_set_enable_fast_open(self.nw, newValue) - } - get { - return self._enableFastOpen - } - } - - private var _disableECN: Bool = false - - /// A boolean to disable ECN negotiation in TCP. - public var disableECN: Bool { - set { - self._disableECN = newValue - nw_tcp_options_set_disable_ecn(self.nw, newValue) - } - get { - return self._disableECN - } - } - - /// Create TCP options to set in an NWParameters.ProtocolStack - public init() { - super.init(nw_tcp_create_options()) - } - - override internal init(_ nw: nw_protocol_options_t) { - super.init(nw) - } - } - - /// Access TCP metadata using NWConnection.metadata(protocolDefinition: NWProtocolTCP.definition) - /// or in received ContentContext - // Set the ObjC name of this class to be nested in the customized ObjC - // name of NWProtocolTCP. - @_objcRuntimeName(_TtCC7Network14_NWProtocolTCP8Metadata) - public class Metadata: NWProtocolMetadata { - override internal init(_ nw: nw_protocol_metadata_t) { - super.init(nw) - } - - /// Access the current number of bytes in TCP's receive buffer (SO_NREAD). - public var availableReceiveBuffer: UInt32 { - get { - return nw_tcp_get_available_receive_buffer(self.nw) - } - } - - /// Access the current number of bytes in TCP's send buffer (SO_NWRITE). - public var availableSendBuffer: UInt32 { - get { - return nw_tcp_get_available_send_buffer(self.nw) - } - } - } -} diff --git a/stdlib/public/Darwin/Network/NWProtocolTLS.swift b/stdlib/public/Darwin/Network/NWProtocolTLS.swift deleted file mode 100644 index 0522d8d3f29c4..0000000000000 --- a/stdlib/public/Darwin/Network/NWProtocolTLS.swift +++ /dev/null @@ -1,62 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -// NOTE: older overlays had Network.NWProtocolTLS as the ObjC name. -// The two must coexist, so it was renamed. The old name must not be -// used in the new runtime. _TtC7Network14_NWProtocolTLS is the -// mangled name for Network._NWProtocolTLS. -@_objcRuntimeName(_TtC7Network14_NWProtocolTLS) -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public class NWProtocolTLS : NWProtocol { - public static let definition: NWProtocolDefinition = { - NWProtocolDefinition(nw_protocol_copy_tls_definition(), "tls") - }() - - // Set the ObjC name of this class to be nested in the customized ObjC - // name of NWProtocolTLS. - @_objcRuntimeName(_TtCC7Network14_NWProtocolTLS7Options) - public class Options : NWProtocolOptions { - /// Access the sec_protocol_options_t for a given network protocol - /// options instance. See for functions - /// to further configure security options. - public var securityProtocolOptions: sec_protocol_options_t { - return nw_tls_copy_sec_protocol_options(self.nw) - } - - /// Create TLS options to set in an NWParameters.ProtocolStack - public init() { - super.init(nw_tls_create_options()) - } - - override internal init(_ nw: nw_protocol_options_t) { - super.init(nw) - } - } - - /// Access TLS metadata using NWConnection.metadata(protocolDefinition: NWProtocolTLS.definition) - /// or in received ContentContext - // Set the ObjC name of this class to be nested in the customized ObjC - // name of NWNWProtocolTLSProtocolIP. - @_objcRuntimeName(_TtCC7Network14_NWProtocolTLS8Metadata) - public class Metadata: NWProtocolMetadata { - /// Access the sec_protocol_metadata_t for a given network protocol - /// metadata instance. See for functions - /// to further access security metadata. - public var securityProtocolMetadata: sec_protocol_metadata_t { - return nw_tls_copy_sec_protocol_metadata(self.nw) - } - - override internal init(_ nw: nw_protocol_metadata_t) { - super.init(nw) - } - } -} diff --git a/stdlib/public/Darwin/Network/NWProtocolUDP.swift b/stdlib/public/Darwin/Network/NWProtocolUDP.swift deleted file mode 100644 index 7f345d79d9bd8..0000000000000 --- a/stdlib/public/Darwin/Network/NWProtocolUDP.swift +++ /dev/null @@ -1,66 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -// NOTE: older overlays had Network.NWProtocolUDP as the ObjC name. -// The two must coexist, so it was renamed. The old name must not be -// used in the new runtime. _TtC7Network14_NWProtocolUDP is the -// mangled name for Network._NWProtocolUDP. -@_objcRuntimeName(_TtC7Network14_NWProtocolUDP) -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public class NWProtocolUDP : NWProtocol { - public static let definition: NWProtocolDefinition = { - NWProtocolDefinition(nw_protocol_copy_udp_definition(), "udp") - }() - - // Set the ObjC name of this class to be nested in the customized ObjC - // name of NWProtocolUDP. - @_objcRuntimeName(_TtCC7Network14_NWProtocolUDP7Options) - public class Options : NWProtocolOptions { - - private var _preferNoChecksum: Bool = false - - /// Configure UDP to skip computing checksums when sending. - /// This will only take effect when running over IPv4 (UDP_NOCKSUM). - public var preferNoChecksum: Bool { - set { - self._preferNoChecksum = newValue - nw_udp_options_set_prefer_no_checksum(self.nw, newValue) - } - get { - return self._preferNoChecksum - } - } - - /// Create UDP options to set in an NWParameters.ProtocolStack - public init() { - super.init(nw_udp_create_options()) - } - - override internal init(_ nw: nw_protocol_options_t) { - super.init(nw) - } - } - - // Set the ObjC name of this class to be nested in the customized ObjC - // name of NWProtocolUDP. - @_objcRuntimeName(_TtCC7Network14_NWProtocolUDP8Metadata) - public class Metadata: NWProtocolMetadata { - override internal init(_ nw: nw_protocol_metadata_t) { - super.init(nw) - } - - /// Create an empty UDP metadata to send with ContentContext - public init() { - super.init(nw_udp_create_metadata()) - } - } -} diff --git a/stdlib/public/Darwin/Network/Network.swift b/stdlib/public/Darwin/Network/Network.swift deleted file mode 100644 index 53172f56eb033..0000000000000 --- a/stdlib/public/Darwin/Network/Network.swift +++ /dev/null @@ -1,13 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Network diff --git a/stdlib/public/Darwin/OpenCL/CMakeLists.txt b/stdlib/public/Darwin/OpenCL/CMakeLists.txt deleted file mode 100644 index 6edc70d3398c7..0000000000000 --- a/stdlib/public/Darwin/OpenCL/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftOpenCL ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - OpenCL.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX - SWIFT_MODULE_DEPENDS_OSX Darwin Dispatch ObjectiveC # auto-updated - FRAMEWORK_DEPENDS OpenCL - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_OPENCL_OSX} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/OpenCL/OpenCL.swift b/stdlib/public/Darwin/OpenCL/OpenCL.swift deleted file mode 100644 index f8b9edcb9d055..0000000000000 --- a/stdlib/public/Darwin/OpenCL/OpenCL.swift +++ /dev/null @@ -1,24 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import OpenCL // Clang module - -@available(macOS, introduced: 10.7) -public func clSetKernelArgsListAPPLE( - _ kernel: cl_kernel, _ uint: cl_uint, _ args: CVarArg... -) -> cl_int { - // The variable arguments are num_args arguments that are the following: - // cl_uint arg_indx, - // size_t arg_size, - // const void *arg_value, - return withVaList(args) { clSetKernelArgsVaListAPPLE(kernel, uint, $0) } -} diff --git a/stdlib/public/Darwin/Photos/CMakeLists.txt b/stdlib/public/Darwin/Photos/CMakeLists.txt deleted file mode 100644 index 7d8a8aae1e786..0000000000000 --- a/stdlib/public/Darwin/Photos/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftPhotos ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - PHChange.swift - PHProjectChangeRequest.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" "-L${sdk}/usr/lib/swift/" - TARGET_SDKS IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR OSX - SWIFT_MODULE_DEPENDS_IOS Darwin CoreImage CoreGraphics Metal Dispatch simd Foundation AVFoundation CoreMedia CoreLocation QuartzCore CoreFoundation CoreAudio ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreImage CoreGraphics Metal Dispatch simd Foundation AVFoundation CoreMedia CoreLocation QuartzCore CoreFoundation CoreAudio ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_OSX Darwin CoreImage CoreGraphics Metal Dispatch IOKit simd Foundation AVFoundation CoreMedia CoreLocation QuartzCore XPC CoreFoundation CoreAudio ObjectiveC # auto-updated - - FRAMEWORK_DEPENDS Photos - - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_PHOTOS_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_PHOTOS_TVOS} - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_PHOTOS_OSX} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/Photos/PHChange.swift b/stdlib/public/Darwin/Photos/PHChange.swift deleted file mode 100644 index 3570dd2ba47f7..0000000000000 --- a/stdlib/public/Darwin/Photos/PHChange.swift +++ /dev/null @@ -1,34 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Photos - -// These methods need to be generic, so that the type parameter of the input -// argument is carried through as the type parameter of the return value. -#if os(iOS) || os(tvOS) -@available(iOS 8.0, tvOS 10.0, *) -extension PHChange { - public func changeDetails< - T : PHObject - >(for object: T) -> PHObjectChangeDetails? { - return self.__changeDetails(for: object) as! PHObjectChangeDetails? - } - - public func changeDetails< - T : PHObject - >(for fetchResult: PHFetchResult) -> PHFetchResultChangeDetails? { - return self.__changeDetails( - for: fetchResult as! PHFetchResult - ) as! PHFetchResultChangeDetails? - } -} -#endif diff --git a/stdlib/public/Darwin/Photos/PHProjectChangeRequest.swift b/stdlib/public/Darwin/Photos/PHProjectChangeRequest.swift deleted file mode 100644 index c7b4a92fc4317..0000000000000 --- a/stdlib/public/Darwin/Photos/PHProjectChangeRequest.swift +++ /dev/null @@ -1,29 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Photos - -#if os(macOS) -@available(macOS 10.13, *) -extension PHProjectChangeRequest { - @available(macOS 10.14, *) - public func removeAssets(_ assets: T) where T: Collection, T.Element == PHAsset { - let array = Array(assets) as NSArray - self.__removeAssets(array) - } - - @available(macOS 10.14, *) - public func removeAssets(_ assets: PHFetchResult) { - self.__removeAssets(assets) - } -} -#endif diff --git a/stdlib/public/Darwin/QuartzCore/CMakeLists.txt b/stdlib/public/Darwin/QuartzCore/CMakeLists.txt deleted file mode 100644 index 75fadb1f748d3..0000000000000 --- a/stdlib/public/Darwin/QuartzCore/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftQuartzCore ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - GYB_SOURCES - NSValue.swift.gyb - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin CoreImage CoreGraphics Metal Dispatch IOKit Foundation XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics Metal Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreGraphics Metal Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS QuartzCore - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_QUARTZCORE_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_QUARTZCORE_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_QUARTZCORE_TVOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/QuartzCore/NSValue.swift.gyb b/stdlib/public/Darwin/QuartzCore/NSValue.swift.gyb deleted file mode 100644 index 5e0e4dcda1015..0000000000000 --- a/stdlib/public/Darwin/QuartzCore/NSValue.swift.gyb +++ /dev/null @@ -1,21 +0,0 @@ -//===--- NSValue.swift - Bridging things in NSValue -----------*- swift -*-===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -%{ -from gyb_foundation_support import ObjectiveCBridgeableImplementationForNSValue -}% - -@_exported import QuartzCore // Clang module -import Foundation - -${ ObjectiveCBridgeableImplementationForNSValue("CATransform3D") } - diff --git a/stdlib/public/Darwin/SafariServices/CMakeLists.txt b/stdlib/public/Darwin/SafariServices/CMakeLists.txt deleted file mode 100644 index 6719232fa8d30..0000000000000 --- a/stdlib/public/Darwin/SafariServices/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftSafariServices ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - SafariServices.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX - SWIFT_MODULE_DEPENDS_OSX Darwin CoreImage CoreGraphics Metal Dispatch IOKit Foundation CoreData QuartzCore AppKit XPC CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS_WEAK SafariServices - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_SAFARISERVICES_OSX} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/SafariServices/SafariServices.swift b/stdlib/public/Darwin/SafariServices/SafariServices.swift deleted file mode 100644 index 95b064a908c7b..0000000000000 --- a/stdlib/public/Darwin/SafariServices/SafariServices.swift +++ /dev/null @@ -1,23 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import SafariServices // Clang module -@_implementationOnly import _SwiftSafariServicesOverlayShims - -#if os(macOS) - -@available(macOS, introduced: 10.11) -public func SFSafariServicesAvailable(_ version: SFSafariServicesVersion = SFSafariServicesVersion.version10_0) -> Bool { - return _swift_SafariServices_isSafariServicesAvailable(version) -} - -#endif diff --git a/stdlib/public/Darwin/SceneKit/CMakeLists.txt b/stdlib/public/Darwin/SceneKit/CMakeLists.txt deleted file mode 100644 index 737fc85cc323e..0000000000000 --- a/stdlib/public/Darwin/SceneKit/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftSceneKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - GYB_SOURCES - SceneKit.swift.gyb - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin CoreImage CoreGraphics Metal Dispatch IOKit GLKit simd Foundation CoreData QuartzCore AppKit ModelIO XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch GLKit simd Foundation QuartzCore ModelIO CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch GLKit simd Foundation QuartzCore ModelIO CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreGraphics Dispatch simd Foundation CoreFoundation ObjectiveC # auto-updated - UIKit # required in some configurations but not found by tool - FRAMEWORK_DEPENDS_WEAK SceneKit - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_SCENEKIT_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_SCENEKIT_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_SCENEKIT_TVOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_SCENEKIT_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/SceneKit/SceneKit.swift.gyb b/stdlib/public/Darwin/SceneKit/SceneKit.swift.gyb deleted file mode 100644 index 2c2a3856d8b32..0000000000000 --- a/stdlib/public/Darwin/SceneKit/SceneKit.swift.gyb +++ /dev/null @@ -1,274 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import SceneKit // Clang module -import CoreGraphics -import Foundation -import simd - -%{ -from gyb_foundation_support import \ - ObjectiveCBridgeableImplementationForNSValueWithCategoryMethods -}% - -// MARK: Exposing SCNFloat - -#if os(macOS) -public typealias SCNFloat = CGFloat -#elseif os(iOS) || os(tvOS) || os(watchOS) -public typealias SCNFloat = Float -#endif - -// MARK: Working with SCNVector3 - -extension SCNVector3 { - public init(_ x: Float, _ y: Float, _ z: Float) { - self.init(x: SCNFloat(x), y: SCNFloat(y), z: SCNFloat(z)) - } - public init(_ x: CGFloat, _ y: CGFloat, _ z: CGFloat) { - self.init(x: SCNFloat(x), y: SCNFloat(y), z: SCNFloat(z)) - } - public init(_ x: Double, _ y: Double, _ z: Double) { - self.init(SCNFloat(x), SCNFloat(y), SCNFloat(z)) - } - public init(_ x: Int, _ y: Int, _ z: Int) { - self.init(SCNFloat(x), SCNFloat(y), SCNFloat(z)) - } - public init(_ v: SIMD3) { - self.init(SCNFloat(v.x), SCNFloat(v.y), SCNFloat(v.z)) - } - public init(_ v: SIMD3) { - self.init(SCNFloat(v.x), SCNFloat(v.y), SCNFloat(v.z)) - } -} - -extension SIMD3 where Scalar == Float { - public init(_ v: SCNVector3) { - self.init(Float(v.x), Float(v.y), Float(v.z)) - } -} - -extension SIMD3 where Scalar == Double { - public init(_ v: SCNVector3) { - self.init(Double(v.x), Double(v.y), Double(v.z)) - } -} - -// MARK: Working with SCNVector4 - -extension SCNVector4 { - public init(_ x: Float, _ y: Float, _ z: Float, _ w: Float) { - self.init(x: SCNFloat(x), y: SCNFloat(y), z: SCNFloat(z), w: SCNFloat(w)) - } - public init(_ x: CGFloat, _ y: CGFloat, _ z: CGFloat, _ w: CGFloat) { - self.init(x: SCNFloat(x), y: SCNFloat(y), z: SCNFloat(z), w: SCNFloat(w)) - } - public init(_ x: Double, _ y: Double, _ z: Double, _ w: Double) { - self.init(SCNFloat(x), SCNFloat(y), SCNFloat(z), SCNFloat(w)) - } - public init(_ x: Int, _ y: Int, _ z: Int, _ w: Int) { - self.init(SCNFloat(x), SCNFloat(y), SCNFloat(z), SCNFloat(w)) - } - public init(_ v: SIMD4) { - self.init(SCNFloat(v.x), SCNFloat(v.y), SCNFloat(v.z), SCNFloat(v.w)) - } - public init(_ v: SIMD4) { - self.init(SCNFloat(v.x), SCNFloat(v.y), SCNFloat(v.z), SCNFloat(v.w)) - } -} - -extension SIMD4 where Scalar == Float { - public init(_ v: SCNVector4) { - self.init(Float(v.x), Float(v.y), Float(v.z), Float(v.w)) - } -} - -extension SIMD4 where Scalar == Double { - public init(_ v: SCNVector4) { - self.init(Double(v.x), Double(v.y), Double(v.z), Double(v.w)) - } -} - -// MARK: Working with SCNMatrix4 - -extension SCNMatrix4 { - public init(_ m: float4x4) { - self.init( - m11: SCNFloat(m[0,0]), m12: SCNFloat(m[0,1]), m13: SCNFloat(m[0,2]), m14: SCNFloat(m[0,3]), - m21: SCNFloat(m[1,0]), m22: SCNFloat(m[1,1]), m23: SCNFloat(m[1,2]), m24: SCNFloat(m[1,3]), - m31: SCNFloat(m[2,0]), m32: SCNFloat(m[2,1]), m33: SCNFloat(m[2,2]), m34: SCNFloat(m[2,3]), - m41: SCNFloat(m[3,0]), m42: SCNFloat(m[3,1]), m43: SCNFloat(m[3,2]), m44: SCNFloat(m[3,3])) - } - public init(_ m: double4x4) { - self.init( - m11: SCNFloat(m[0,0]), m12: SCNFloat(m[0,1]), m13: SCNFloat(m[0,2]), m14: SCNFloat(m[0,3]), - m21: SCNFloat(m[1,0]), m22: SCNFloat(m[1,1]), m23: SCNFloat(m[1,2]), m24: SCNFloat(m[1,3]), - m31: SCNFloat(m[2,0]), m32: SCNFloat(m[2,1]), m33: SCNFloat(m[2,2]), m34: SCNFloat(m[2,3]), - m41: SCNFloat(m[3,0]), m42: SCNFloat(m[3,1]), m43: SCNFloat(m[3,2]), m44: SCNFloat(m[3,3])) - } -} - -extension float4x4 { - public init(_ m: SCNMatrix4) { - self.init([ - SIMD4(Float(m.m11), Float(m.m12), Float(m.m13), Float(m.m14)), - SIMD4(Float(m.m21), Float(m.m22), Float(m.m23), Float(m.m24)), - SIMD4(Float(m.m31), Float(m.m32), Float(m.m33), Float(m.m34)), - SIMD4(Float(m.m41), Float(m.m42), Float(m.m43), Float(m.m44)) - ]) - } -} - -extension double4x4 { - public init(_ m: SCNMatrix4) { - self.init([ - SIMD4(Double(m.m11), Double(m.m12), Double(m.m13), Double(m.m14)), - SIMD4(Double(m.m21), Double(m.m22), Double(m.m23), Double(m.m24)), - SIMD4(Double(m.m31), Double(m.m32), Double(m.m33), Double(m.m34)), - SIMD4(Double(m.m41), Double(m.m42), Double(m.m43), Double(m.m44)) - ]) - } -} - -// MARK: Swift Extensions - -@available(iOS, introduced: 8.0) -@available(macOS, introduced: 10.8) -extension SCNGeometryElement { - /// Creates an instance from `indices` for a `primitiveType` - /// that has a constant number of indices per primitive - /// - Precondition: the `primitiveType` must be `.triangles`, `.triangleStrip`, `.line` or `.point` - public convenience init( - indices: [IndexType], primitiveType: SCNGeometryPrimitiveType - ) { - precondition(primitiveType == .triangles || primitiveType == .triangleStrip || primitiveType == .line || primitiveType == .point, "Expected constant number of indices per primitive") - let indexCount = indices.count - let primitiveCount: Int - switch primitiveType { - case .triangles: - primitiveCount = indexCount / 3 - case .triangleStrip: - primitiveCount = indexCount - 2 - case .line: - primitiveCount = indexCount / 2 - case .point: - primitiveCount = indexCount - case .polygon: - fatalError("Expected constant number of indices per primitive") - @unknown default: - fatalError("Unexpected primitive type") - } - self.init( - data: Data(bytes: indices, count: indexCount * MemoryLayout.stride), - primitiveType: primitiveType, - primitiveCount: primitiveCount, - bytesPerIndex: MemoryLayout.stride) - _fixLifetime(indices) - } -} - -@available(iOS, introduced: 8.0) -@available(macOS, introduced: 10.8) -extension SCNGeometrySource { - @nonobjc - public convenience init(vertices: [SCNVector3]) { - self.init(__vertices: vertices, count: vertices.count) - } - @nonobjc - public convenience init(normals: [SCNVector3]) { - self.init(__normals: normals, count: normals.count) - } - @nonobjc - public convenience init(textureCoordinates: [CGPoint]) { - self.init(__textureCoordinates: textureCoordinates, count: textureCoordinates.count) - } -} - -@available(iOS, introduced: 8.0) -@available(macOS, introduced: 10.10) -extension SCNBoundingVolume { - public var boundingBox: (min: SCNVector3, max: SCNVector3) { - get { - var min = SCNVector3Zero - var max = SCNVector3Zero - __getBoundingBoxMin(&min, max: &max) - return (min: min, max: max) - } - set { - var min = newValue.min - var max = newValue.max - __setBoundingBoxMin(&min, max: &max) - } - } - public var boundingSphere: (center: SCNVector3, radius: Float) { - var center = SCNVector3Zero - var radius = CGFloat(0.0) - __getBoundingSphereCenter(¢er, radius: &radius) - return (center: center, radius: Float(radius)) - } -} - -// MARK: APIs refined for Swift - -@available(iOS, introduced: 8.0) -@available(macOS, introduced: 10.8) -extension SCNSceneSource { - public func entryWithIdentifier(_ uid: String, withClass entryClass: T.Type) -> T? { - return self.__entry(withIdentifier: uid, with: entryClass) as! T? - } -} - -// Bridge vector and matrix types to NSValue. -// -// SceneKit implements its categories on NSValue by converting SCNVector3 -// and SCNVector4 to CGRect, and SCNMatrix4 to CATransform3D, and boxing the -// converted struct instead of as the original type. - -// Get the ObjC type used by -[NSValue valueWithSCN{Vector3,Vector4,Matrix4}:] -// to instantiate the resulting NSValue objects, in case these get changed -// in the future. -private let SCNVector3InNSValueObjCType = - NSValue(scnVector3: SCNVector3()).objCType -private let SCNVector4InNSValueObjCType = - NSValue(scnVector4: SCNVector4()).objCType - -${ ObjectiveCBridgeableImplementationForNSValueWithCategoryMethods( - Type="SCNVector3", - initializer="{ NSValue(scnVector3: $0) }", - getter="{ $0.scnVector3Value }", - objCType="{ _ in SCNVector3InNSValueObjCType }", -) } -${ ObjectiveCBridgeableImplementationForNSValueWithCategoryMethods( - Type="SCNVector4", - initializer="{ NSValue(scnVector4: $0) }", - getter="{ $0.scnVector4Value }", - objCType="{ _ in SCNVector4InNSValueObjCType }", -) } - -// On macOS, SCNMatrix4 is a typedef for CATransform3D, which is already made -// NSValue-bridgeable in the QuartzCore overlay. It is a separate struct on -// iOS, watchOS, and tvOS. - -#if os(iOS) || os(tvOS) || os(watchOS) - -private let SCNMatrix4InNSValueObjCType = - NSValue(scnMatrix4: SCNMatrix4()).objCType - -${ ObjectiveCBridgeableImplementationForNSValueWithCategoryMethods( - Type="SCNMatrix4", - initializer="{ NSValue(scnMatrix4: $0) }", - getter="{ $0.scnMatrix4Value }", - objCType="{ _ in SCNMatrix4InNSValueObjCType }", -) } - -#endif - diff --git a/stdlib/public/Darwin/SpriteKit/CMakeLists.txt b/stdlib/public/Darwin/SpriteKit/CMakeLists.txt deleted file mode 100644 index bbda4a68ca501..0000000000000 --- a/stdlib/public/Darwin/SpriteKit/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftSpriteKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - SpriteKit.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - GYB_SOURCES - SpriteKitQuickLooks.swift.gyb - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin CoreImage CoreGraphics Metal Dispatch IOKit GLKit simd Foundation CoreData QuartzCore AppKit ModelIO XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch GLKit simd Foundation QuartzCore ModelIO CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreImage CoreGraphics Metal UIKit Dispatch GLKit simd Foundation QuartzCore ModelIO CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreGraphics UIKit Dispatch simd Foundation CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS SpriteKit - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_SPRITEKIT_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_SPRITEKIT_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_SPRITEKIT_TVOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_SPRITEKIT_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/SpriteKit/SpriteKit.swift b/stdlib/public/Darwin/SpriteKit/SpriteKit.swift deleted file mode 100644 index d723f05b61e88..0000000000000 --- a/stdlib/public/Darwin/SpriteKit/SpriteKit.swift +++ /dev/null @@ -1,89 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import SpriteKit -import simd - -// SpriteKit defines SKColor using a macro. - -#if os(macOS) -public typealias SKColor = NSColor -#elseif os(iOS) || os(tvOS) || os(watchOS) -public typealias SKColor = UIColor -#endif - -// this class only exists to allow AnyObject lookup of _copyImageData -// since that method only exists in a private header in SpriteKit, the lookup -// mechanism by default fails to accept it as a valid AnyObject call -// -// NOTE: older overlays called this _SpriteKitMethodProvider. The two must -// coexist, so it was renamed. The old name must not be used in the new -// runtime. -@objc class __SpriteKitMethodProvider : NSObject { - override init() { preconditionFailure("don't touch me") } - @objc func _copyImageData() -> NSData! { return nil } -} - -@available(iOS, introduced: 10.0) -@available(macOS, introduced: 10.12) -@available(tvOS, introduced: 10.0) -@available(watchOS, introduced: 3.0) -extension SKWarpGeometryGrid { - /// Create a grid of the specified dimensions, source and destination positions. - /// - /// Grid dimensions (columns and rows) refer to the number of faces in each dimension. The - /// number of vertices required for a given dimension is equal to (cols + 1) * (rows + 1). - /// - /// SourcePositions are normalized (0.0 - 1.0) coordinates to determine the source content. - /// - /// DestinationPositions are normalized (0.0 - 1.0) positional coordinates with respect to - /// the node's native size. Values outside the (0.0-1.0) range are perfectly valid and - /// correspond to positions outside of the native undistorted bounds. - /// - /// Source and destination positions are provided in row-major order starting from the top-left. - /// For example the indices for a 2x2 grid would be as follows: - /// - /// [0]---[1]---[2] - /// | | | - /// [3]---[4]---[5] - /// | | | - /// [6]---[7]---[8] - /// - /// - Parameter columns: the number of columns to initialize the SKWarpGeometryGrid with - /// - Parameter rows: the number of rows to initialize the SKWarpGeometryGrid with - /// - Parameter sourcePositions: the source positions for the SKWarpGeometryGrid to warp from - /// - Parameter destinationPositions: the destination positions for SKWarpGeometryGrid to warp to - public convenience init(columns: Int, rows: Int, sourcePositions: [SIMD2] = [SIMD2](), destinationPositions: [SIMD2] = [SIMD2]()) { - let requiredElementsCount = (columns + 1) * (rows + 1) - switch (destinationPositions.count, sourcePositions.count) { - case (0, 0): - self.init(__columns: columns, rows: rows, sourcePositions: nil, destPositions: nil) - case (let dests, 0): - precondition(dests == requiredElementsCount, "Mismatch found between rows/columns and positions.") - self.init(__columns: columns, rows: rows, sourcePositions: nil, destPositions: destinationPositions) - case (0, let sources): - precondition(sources == requiredElementsCount, "Mismatch found between rows/columns and positions.") - self.init(__columns: columns, rows: rows, sourcePositions: sourcePositions, destPositions: nil) - case (let dests, let sources): - precondition(dests == requiredElementsCount && sources == requiredElementsCount, "Mismatch found between rows/columns and positions.") - self.init(__columns: columns, rows: rows, sourcePositions: sourcePositions, destPositions: destinationPositions) - } - } - - public func replacingBySourcePositions(positions source: [SIMD2]) -> SKWarpGeometryGrid { - return self.__replacingSourcePositions(source) - } - - public func replacingByDestinationPositions(positions destination: [SIMD2]) -> SKWarpGeometryGrid { - return self.__replacingDestPositions(destination) - } -} diff --git a/stdlib/public/Darwin/SpriteKit/SpriteKitQuickLooks.swift.gyb b/stdlib/public/Darwin/SpriteKit/SpriteKitQuickLooks.swift.gyb deleted file mode 100644 index 69a7aebf68f31..0000000000000 --- a/stdlib/public/Darwin/SpriteKit/SpriteKitQuickLooks.swift.gyb +++ /dev/null @@ -1,33 +0,0 @@ -//===----------------------------------------------------------*- swift -*-===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -%import gyb - -% for Self in ['SKShapeNode', 'SKSpriteNode', 'SKTextureAtlas', 'SKTexture']: - -extension ${Self} : _CustomPlaygroundQuickLookable { - @available(*, deprecated, message: "${Self}.customPlaygroundQuickLook will be removed in a future Swift version") - public var customPlaygroundQuickLook: PlaygroundQuickLook { - let data = (self as AnyObject)._copyImageData?() as Data? - - // we could send a Raw, but I don't want to make a copy of the - // bytes for no good reason make an NSImage out of them and - // send that -#if os(macOS) - let image = data.flatMap(NSImage.init(data:)) ?? NSImage() -#elseif os(iOS) || os(watchOS) || os(tvOS) - let image = data.flatMap(UIImage.init(data:)) ?? UIImage() -#endif - - return .sprite(image) - } -} diff --git a/stdlib/public/Darwin/UIKit/CMakeLists.txt b/stdlib/public/Darwin/UIKit/CMakeLists.txt deleted file mode 100644 index 637c3589e6696..0000000000000 --- a/stdlib/public/Darwin/UIKit/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftUIKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - DesignatedInitializers.mm - UIKit.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - GYB_SOURCES - UIKit_FoundationExtensions.swift.gyb - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR - SWIFT_MODULE_DEPENDS_IOS Darwin CoreImage CoreGraphics Metal Dispatch Foundation QuartzCore CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreImage CoreGraphics Metal Dispatch Foundation QuartzCore CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreGraphics Dispatch Foundation CoreFoundation ObjectiveC # auto-updated - SWIFT_COMPILE_FLAGS_WATCHOS -Xfrontend -disable-autolink-framework -Xfrontend CoreText - FRAMEWORK_DEPENDS UIKit - - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_UIKIT_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_UIKIT_TVOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_UIKIT_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/UIKit/DesignatedInitializers.mm b/stdlib/public/Darwin/UIKit/DesignatedInitializers.mm deleted file mode 100644 index e7a10640eb662..0000000000000 --- a/stdlib/public/Darwin/UIKit/DesignatedInitializers.mm +++ /dev/null @@ -1,76 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// -// -// This file contains replacements for the designated initializers of some -// UIKit classes that take variadic parameters and thus cannot be used in -// Swift as-is. -// -//===----------------------------------------------------------------------===// - -#import -#include - -#if (!defined(TARGET_OS_WATCH) || !TARGET_OS_WATCH) && \ - (!defined(TARGET_OS_TV) || !TARGET_OS_TV) -@interface UIActionSheet (_SwiftInterop) - -- (instancetype)initWithTitle:(NSString *)title - delegate:(id)delegate - cancelButtonTitle:(NSString *)cancelButtonTitle - destructiveButtonTitle:(NSString *)destructiveButtonTitle; - -@end - -@implementation UIActionSheet (_SwiftInterop) - -- (instancetype)initWithTitle:(NSString *)title - delegate:(id)delegate - cancelButtonTitle:(NSString *)cancelButtonTitle - destructiveButtonTitle:(NSString *)destructiveButtonTitle { - return [self initWithTitle:title - delegate:delegate - cancelButtonTitle:cancelButtonTitle - destructiveButtonTitle:destructiveButtonTitle - otherButtonTitles:nil]; -} - -@end -#endif - - -#if (!defined(TARGET_OS_WATCH) || !TARGET_OS_WATCH) && \ - (!defined(TARGET_OS_TV) || !TARGET_OS_TV) -@interface UIAlertView (_SwiftInterop) - -- (instancetype)initWithTitle:(NSString *)title - message:(NSString *)message - delegate:(id )delegate - cancelButtonTitle:(NSString *)cancelButtonTitle; - -@end - -@implementation UIAlertView (_SwiftInterop) - -- (instancetype)initWithTitle:(NSString *)title - message:(NSString *)message - delegate:(id )delegate - cancelButtonTitle:(NSString *)cancelButtonTitle { - return [self initWithTitle:title - message:message - delegate:delegate - cancelButtonTitle:cancelButtonTitle - otherButtonTitles:nil]; -} - -@end -#endif - diff --git a/stdlib/public/Darwin/UIKit/UIKit.swift b/stdlib/public/Darwin/UIKit/UIKit.swift deleted file mode 100644 index 3253959bf60af..0000000000000 --- a/stdlib/public/Darwin/UIKit/UIKit.swift +++ /dev/null @@ -1,552 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -import Foundation -@_exported import UIKit - -#if os(iOS) || os(tvOS) -@_implementationOnly import _SwiftUIKitOverlayShims -#endif - -//===----------------------------------------------------------------------===// -// UIGeometry -//===----------------------------------------------------------------------===// - -extension UIEdgeInsets : Equatable { - @_transparent // @fragile - public static func == (lhs: UIEdgeInsets, rhs: UIEdgeInsets) -> Bool { - return lhs.top == rhs.top && - lhs.left == rhs.left && - lhs.bottom == rhs.bottom && - lhs.right == rhs.right - } -} - -@available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) -extension NSDirectionalEdgeInsets : Equatable { - @_transparent // @fragile - public static func == (lhs: NSDirectionalEdgeInsets, rhs: NSDirectionalEdgeInsets) -> Bool { - return lhs.top == rhs.top && - lhs.leading == rhs.leading && - lhs.bottom == rhs.bottom && - lhs.trailing == rhs.trailing - } -} - -extension UIOffset : Equatable { - @_transparent // @fragile - public static func == (lhs: UIOffset, rhs: UIOffset) -> Bool { - return lhs.horizontal == rhs.horizontal && - lhs.vertical == rhs.vertical - } -} - -#if os(iOS) || os(tvOS) -extension UIFloatRange : Equatable { - @_transparent // @fragile - public static func == (lhs: UIFloatRange, rhs: UIFloatRange) -> Bool { - return lhs.minimum == rhs.minimum && - lhs.maximum == rhs.maximum - } -} -#endif - -@available(swift, deprecated: 4.2, message:"Use == operator instead.") -public func UIEdgeInsetsEqualToEdgeInsets(_ insets1: UIEdgeInsets, _ insets2: UIEdgeInsets) -> Bool { - return insets1 == insets2 -} - -@available(swift, deprecated: 4.2, message:"Use == operator instead.") -public func UIOffsetEqualToOffset(_ offset1: UIOffset, _ offset2: UIOffset) -> Bool { - return offset1 == offset2 -} - -#if os(iOS) || os(tvOS) -@available(swift, deprecated: 4.2, message:"Use == operator instead.") -public func UIFloatRangeIsEqualToRange(_ range: UIFloatRange, _ otherRange: UIFloatRange) -> Bool { - return range == otherRange -} -#endif - -extension UIEdgeInsets : Codable { - public init(from decoder: Decoder) throws { - var container = try decoder.unkeyedContainer() - let top = try container.decode(CGFloat.self) - let left = try container.decode(CGFloat.self) - let bottom = try container.decode(CGFloat.self) - let right = try container.decode(CGFloat.self) - self.init(top: top, left: left, bottom: bottom, right: right) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.unkeyedContainer() - try container.encode(top) - try container.encode(left) - try container.encode(bottom) - try container.encode(right) - } -} - -@available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) -extension NSDirectionalEdgeInsets : Codable { - public init(from decoder: Decoder) throws { - var container = try decoder.unkeyedContainer() - let top = try container.decode(CGFloat.self) - let leading = try container.decode(CGFloat.self) - let bottom = try container.decode(CGFloat.self) - let trailing = try container.decode(CGFloat.self) - self.init(top: top, leading: leading, bottom: bottom, trailing: trailing) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.unkeyedContainer() - try container.encode(top) - try container.encode(leading) - try container.encode(bottom) - try container.encode(trailing) - } -} - -extension UIOffset : Codable { - public init(from decoder: Decoder) throws { - var container = try decoder.unkeyedContainer() - let horizontal = try container.decode(CGFloat.self) - let vertical = try container.decode(CGFloat.self) - self.init(horizontal: horizontal, vertical: vertical) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.unkeyedContainer() - try container.encode(horizontal) - try container.encode(vertical) - } -} - -#if os(iOS) || os(tvOS) -extension UIFloatRange : Codable { - public init(from decoder: Decoder) throws { - var container = try decoder.unkeyedContainer() - let minimum = try container.decode(CGFloat.self) - let maximum = try container.decode(CGFloat.self) - self.init(minimum: minimum, maximum: maximum) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.unkeyedContainer() - try container.encode(minimum) - try container.encode(maximum) - } -} -#endif - -//===----------------------------------------------------------------------===// -// Numeric backed types -//===----------------------------------------------------------------------===// - -@available(swift 4) -public protocol _UIKitNumericRawRepresentable : RawRepresentable, Comparable where RawValue: Comparable & Numeric {} - -extension _UIKitNumericRawRepresentable { - - public static func <(lhs: Self, rhs: Self) -> Bool { - return lhs.rawValue < rhs.rawValue - } - - public static func +(lhs: Self, rhs: RawValue) -> Self { - return Self(rawValue: lhs.rawValue + rhs)! - } - - public static func +(lhs: RawValue, rhs: Self) -> Self { - return Self(rawValue: lhs + rhs.rawValue)! - } - - public static func -(lhs: Self, rhs: RawValue) -> Self { - return Self(rawValue: lhs.rawValue - rhs)! - } - - public static func -(lhs: Self, rhs: Self) -> RawValue { - return lhs.rawValue - rhs.rawValue - } - - public static func +=(lhs: inout Self, rhs: RawValue) { - lhs = Self(rawValue: lhs.rawValue + rhs)! - } - - public static func -=(lhs: inout Self, rhs: RawValue) { - lhs = Self(rawValue: lhs.rawValue - rhs)! - } -} - -extension UIFont.Weight : _UIKitNumericRawRepresentable {} - -#if !os(watchOS) -extension UILayoutPriority : _UIKitNumericRawRepresentable {} -extension UIWindow.Level : _UIKitNumericRawRepresentable {} -#endif - -// These are un-imported macros in UIKit. - -//===----------------------------------------------------------------------===// -// UIDeviceOrientation -//===----------------------------------------------------------------------===// - -#if !os(watchOS) && !os(tvOS) -@available(swift, obsoleted: 4.2, - renamed: "getter:UIDeviceOrientation.isLandscape(self:)") -public func UIDeviceOrientationIsLandscape( - _ orientation: UIDeviceOrientation -) -> Bool { - return orientation.isLandscape -} - -@available(swift, obsoleted: 4.2, - renamed: "getter:UIDeviceOrientation.isPortrait(self:)") -public func UIDeviceOrientationIsPortrait( - _ orientation: UIDeviceOrientation -) -> Bool { - return orientation.isPortrait -} - -@available(swift, obsoleted: 4.2, - renamed: "getter:UIDeviceOrientation.isValidInterfaceOrientation(self:)") -public func UIDeviceOrientationIsValidInterfaceOrientation( - _ orientation: UIDeviceOrientation -) -> Bool { - return orientation.isValidInterfaceOrientation -} -#endif - -//===----------------------------------------------------------------------===// -// UIInterfaceOrientation -//===----------------------------------------------------------------------===// - -#if !os(watchOS) && !os(tvOS) -@available(swift, obsoleted: 4.2, - renamed: "getter:UIInterfaceOrientation.isPortrait(self:)") -public func UIInterfaceOrientationIsPortrait( - _ orientation: UIInterfaceOrientation -) -> Bool { - return orientation.isPortrait -} - -@available(swift, obsoleted: 4.2, - renamed: "getter:UIInterfaceOrientation.isLandscape(self:)") -public func UIInterfaceOrientationIsLandscape( - _ orientation: UIInterfaceOrientation -) -> Bool { - return orientation.isLandscape -} -#endif - -// Overlays for variadic initializers. - -#if !os(watchOS) && !os(tvOS) -public extension UIActionSheet { - convenience init(title: String?, - delegate: UIActionSheetDelegate?, - cancelButtonTitle: String?, - destructiveButtonTitle: String?, - // Hack around overload ambiguity with non-variadic constructor. - // - otherButtonTitles firstButtonTitle: String, - _ moreButtonTitles: String...) { - self.init(title: title, - delegate: delegate, - cancelButtonTitle: cancelButtonTitle, - destructiveButtonTitle: destructiveButtonTitle) - self.addButton(withTitle: firstButtonTitle) - for buttonTitle in moreButtonTitles { - self.addButton(withTitle: buttonTitle) - } - } -} -#endif - -#if !os(watchOS) && !os(tvOS) -public extension UIAlertView { - convenience init(title: String, - message: String, - delegate: UIAlertViewDelegate?, - cancelButtonTitle: String?, - // Hack around overload ambiguity with non-variadic constructor. - // - otherButtonTitles firstButtonTitle: String, - _ moreButtonTitles: String...) { - self.init(title: title, - message: message, - delegate: delegate, - cancelButtonTitle: cancelButtonTitle) - self.addButton(withTitle: firstButtonTitle) - for buttonTitle in moreButtonTitles { - self.addButton(withTitle: buttonTitle) - } - } -} -#endif - -#if !os(watchOS) -internal struct _UIViewQuickLookState { - static var views = Set() -} - -extension UIView : __DefaultCustomPlaygroundQuickLookable { - @available(*, deprecated, message: "UIView._defaultCustomPlaygroundQuickLook will be removed in a future Swift version") - public var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook { - if _UIViewQuickLookState.views.contains(self) { - return .view(UIImage()) - } else { - _UIViewQuickLookState.views.insert(self) - // in case of an empty rectangle abort the logging - if (bounds.size.width == 0) || (bounds.size.height == 0) { - return .view(UIImage()) - } - - UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0) - // UIKit is about to update this to be optional, so make it work - // with both older and newer SDKs. (In this context it should always - // be present.) - let ctx: CGContext! = UIGraphicsGetCurrentContext() - UIColor(white:1.0, alpha:0.0).set() - ctx.fill(bounds) - layer.render(in: ctx) - - let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext() - - UIGraphicsEndImageContext() - - _UIViewQuickLookState.views.remove(self) - return .view(image) - } - } -} -#endif - -extension UIColor : _ExpressibleByColorLiteral { - @nonobjc public required convenience init(_colorLiteralRed red: Float, - green: Float, - blue: Float, alpha: Float) { - self.init(red: CGFloat(red), green: CGFloat(green), - blue: CGFloat(blue), alpha: CGFloat(alpha)) - } -} - -public typealias _ColorLiteralType = UIColor - -extension UIImage : _ExpressibleByImageLiteral { - private convenience init!(failableImageLiteral name: String) { - self.init(named: name) - } - - public required convenience init(imageLiteralResourceName name: String) { - self.init(failableImageLiteral: name) - } -} - -public typealias _ImageLiteralType = UIImage - -extension UIFont.TextStyle { - @available(iOS 11.0, watchOS 4.0, tvOS 11.0, *) - public var metrics: UIFontMetrics { - return UIFontMetrics(forTextStyle: self) - } -} - -#if !os(watchOS) // UIContentSizeCategory not available on watchOS -extension UIContentSizeCategory { - - @available(iOS 11.0, tvOS 11.0, *) - public var isAccessibilityCategory: Bool { - return __UIContentSizeCategoryIsAccessibilityCategory(self) - } - - @available(iOS 11.0, tvOS 11.0, *) - public static func < (left: UIContentSizeCategory, right: UIContentSizeCategory) -> Bool { - return __UIContentSizeCategoryCompareToCategory(left, right) == .orderedAscending - } - - @available(iOS 11.0, tvOS 11.0, *) - public static func <= (left: UIContentSizeCategory, right: UIContentSizeCategory) -> Bool { - return __UIContentSizeCategoryCompareToCategory(left, right) != .orderedDescending - } - - @available(iOS 11.0, tvOS 11.0, *) - public static func > (left: UIContentSizeCategory, right: UIContentSizeCategory) -> Bool { - return __UIContentSizeCategoryCompareToCategory(left, right) == .orderedDescending - } - - @available(iOS 11.0, tvOS 11.0, *) - public static func >= (left: UIContentSizeCategory, right: UIContentSizeCategory) -> Bool { - return __UIContentSizeCategoryCompareToCategory(left, right) != .orderedAscending - } -} -#endif - -//===----------------------------------------------------------------------===// -// Focus -//===----------------------------------------------------------------------===// - -#if os(iOS) || os(tvOS) -@available(iOS 11.0, tvOS 11.0, *) -extension UIFocusEnvironment { - @available(iOS 11.0, tvOS 11.0, *) - public func contains(_ environment: UIFocusEnvironment) -> Bool { - return _swift_UIKit_UIFocusEnvironmentContainsEnvironment(self, environment) - } -} - -@available(iOS 11.0, tvOS 11.0, *) -extension UIFocusItem { - @available(iOS 11.0, tvOS 11.0, *) - public var isFocused: Bool { - return self === UIScreen.main.focusedItem - } -} -#endif - -//===----------------------------------------------------------------------===// -// NSItemProviderReading/Writing support -//===----------------------------------------------------------------------===// - -#if os(iOS) - -@available(iOS 11.0, *) -extension UIDragDropSession { - @available(iOS 11.0, *) - public func canLoadObjects< - T : _ObjectiveCBridgeable - >(ofClass: T.Type) -> Bool where T._ObjectiveCType : NSItemProviderReading { - return self.canLoadObjects(ofClass: T._ObjectiveCType.self) - } -} - -@available(iOS 11.0, *) -extension UIDropSession { - @available(iOS 11.0, *) - public func loadObjects< - T : _ObjectiveCBridgeable - >( - ofClass: T.Type, - completion: @escaping ([T]) -> Void - ) -> Progress where T._ObjectiveCType : NSItemProviderReading { - return self.loadObjects(ofClass: T._ObjectiveCType.self) { nss in - let natives = nss.map { $0 as! T } - completion(natives) - } - } -} - -@available(iOS 11.0, *) -extension UIPasteConfiguration { - @available(iOS 11.0, *) - public convenience init< - T : _ObjectiveCBridgeable - >(forAccepting _: T.Type) where T._ObjectiveCType : NSItemProviderReading { - self.init(forAccepting: T._ObjectiveCType.self) - } - - @available(iOS 11.0, *) - public func addTypeIdentifiers< - T : _ObjectiveCBridgeable - >(forAccepting aClass: T.Type) - where T._ObjectiveCType : NSItemProviderReading { - self.addTypeIdentifiers(forAccepting: T._ObjectiveCType.self) - } -} - - -extension UIPasteboard { - @available(iOS 11.0, *) - public func setObjects< - T : _ObjectiveCBridgeable - >(_ objects: [T]) where T._ObjectiveCType : NSItemProviderWriting { - // Using a simpler `$0 as! T._ObjectiveCType` triggers and assertion in - // the compiler. - self.setObjects(objects.map { $0._bridgeToObjectiveC() }) - } - - @available(iOS 11.0, *) - public func setObjects< - T : _ObjectiveCBridgeable - >( - _ objects: [T], - localOnly: Bool, - expirationDate: Date? - ) where T._ObjectiveCType : NSItemProviderWriting { - self.setObjects( - // Using a simpler `$0 as! T._ObjectiveCType` triggers and assertion in - // the compiler. - objects.map { $0._bridgeToObjectiveC() }, - localOnly: localOnly, - expirationDate: expirationDate) - } -} - -#endif - -//===----------------------------------------------------------------------===// -// UIPrintError compatibility -//===----------------------------------------------------------------------===// - -#if os(iOS) - -@available(swift, obsoleted: 4.2, renamed:"UIPrintError.Code.notAvailable.rawValue") -public let UIPrintingNotAvailableError = 1 - -@available(swift, obsoleted: 4.2, renamed:"UIPrintError.Code.noContent.rawValue") -public let UIPrintNoContentError = 2 - -@available(swift, obsoleted: 4.2, renamed:"UIPrintError.Code.unknownImageFormat.rawValue") -public let UIPrintUnknownImageFormatError = 3 - -@available(swift, obsoleted: 4.2, renamed:"UIPrintError.Code.jobFailed.rawValue") -public let UIPrintJobFailedError = 4 - -#endif - -//===----------------------------------------------------------------------===// -// UIApplicationMain compatibility -//===----------------------------------------------------------------------===// - -#if !os(watchOS) - -@available(swift, deprecated: 4.2, message: "Use the overload of UIApplicationMain where the type of the second parameter is UnsafeMutablePointer?>, which is the same as the type of CommandLine.unsafeArgv.") -public func UIApplicationMain(_ argc: Int32, _ argv: UnsafeMutablePointer>!, _ principalClassName: String?, _ delegateClassName: String?) -> Int32 { - let reboundArgv = UnsafeMutableRawPointer(argv).bindMemory(to: UnsafeMutablePointer?.self, capacity: Int(argc)) - return UIApplicationMain(argc, reboundArgv, principalClassName, delegateClassName) -} - -#endif - -//===----------------------------------------------------------------------===// -// UIAccessibilityTraits -//===----------------------------------------------------------------------===// - -extension UIAccessibilityTraits: OptionSet {} - -//===----------------------------------------------------------------------===// -// UITextDirection -//===----------------------------------------------------------------------===// - -#if !os(watchOS) - -extension UITextDirection { - - public static func storage(_ direction: UITextStorageDirection) -> UITextDirection { - return UITextDirection(rawValue: direction.rawValue) - } - - public static func layout(_ direction: UITextLayoutDirection) -> UITextDirection { - return UITextDirection(rawValue: direction.rawValue) - } -} - -#endif diff --git a/stdlib/public/Darwin/UIKit/UIKit_FoundationExtensions.swift.gyb b/stdlib/public/Darwin/UIKit/UIKit_FoundationExtensions.swift.gyb deleted file mode 100644 index bf6b6cd7ef6dc..0000000000000 --- a/stdlib/public/Darwin/UIKit/UIKit_FoundationExtensions.swift.gyb +++ /dev/null @@ -1,95 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -import Foundation -@_exported import UIKit - -%{ -from gyb_foundation_support import ObjectiveCBridgeableImplementationForNSValue -}% - -// UITableView extensions -public extension IndexPath { - - /// Initialize for use with `UITableView` or `UICollectionView`. - public init(row: Int, section: Int) { - self.init(indexes: [section, row]) - } - - /// The section of this index path, when used with `UITableView`. - /// - /// - precondition: The index path must have exactly two elements. - public var section: Int { - get { - precondition(count == 2, "Invalid index path for use with UITableView. This index path must contain exactly two indices specifying the section and row.") - return self[0] - } - set { - precondition(count == 2, "Invalid index path for use with UITableView. This index path must contain exactly two indices specifying the section and row.") - self[0] = newValue - } - } - - /// The row of this index path, when used with `UITableView`. - /// - /// - precondition: The index path must have exactly two elements. - public var row: Int { - get { - precondition(count == 2, "Invalid index path for use with UITableView. This index path must contain exactly two indices specifying the section and row.") - return self[1] - } - set { - precondition(count == 2, "Invalid index path for use with UITableView. This index path must contain exactly two indices specifying the section and row.") - self[1] = newValue - } - } -} - -// UICollectionView extensions -public extension IndexPath { - - /// Initialize for use with `UITableView` or `UICollectionView`. - public init(item: Int, section: Int) { - self.init(indexes: [section, item]) - } - - /// The item of this index path, when used with `UICollectionView`. - /// - /// - precondition: The index path must have exactly two elements. - public var item: Int { - get { - precondition(count == 2, "Invalid index path for use with UICollectionView. This index path must contain exactly two indices specifying the section and item.") - return self[1] - } - set { - precondition(count == 2, "Invalid index path for use with UICollectionView. This index path must contain exactly two indices specifying the section and item.") - self[1] = newValue - } - }} - -public extension URLResourceValues { - - /// Returns a dictionary of UIImage objects keyed by size. - @available(iOS 8.0, *) - public var thumbnailDictionary : [URLThumbnailDictionaryItem : UIImage]? { - return allValues[URLResourceKey.thumbnailDictionaryKey] as? [URLThumbnailDictionaryItem : UIImage] - } -} - -// Bridge UIKit structs to NSValue. - -${ ObjectiveCBridgeableImplementationForNSValue("UIEdgeInsets") } - -@available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) -${ ObjectiveCBridgeableImplementationForNSValue("NSDirectionalEdgeInsets") } - -${ ObjectiveCBridgeableImplementationForNSValue("UIOffset") } diff --git a/stdlib/public/Darwin/Vision/CMakeLists.txt b/stdlib/public/Darwin/Vision/CMakeLists.txt deleted file mode 100644 index 5fd9cb4202f1e..0000000000000 --- a/stdlib/public/Darwin/Vision/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftVision ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - Vision.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" "-L${sdk}/usr/lib/swift/" - TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR - SWIFT_MODULE_DEPENDS_OSX Darwin CoreImage CoreGraphics Metal Dispatch IOKit simd Foundation XPC CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin CoreImage CoreGraphics Metal Dispatch simd Foundation CoreFoundation ObjectiveC # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin CoreImage CoreGraphics Metal Dispatch simd Foundation CoreFoundation ObjectiveC # auto-updated - - FRAMEWORK_DEPENDS_WEAK Vision - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_VISION_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_VISION_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_VISION_TVOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/Vision/Vision.swift b/stdlib/public/Darwin/Vision/Vision.swift deleted file mode 100644 index a6e560b241d2a..0000000000000 --- a/stdlib/public/Darwin/Vision/Vision.swift +++ /dev/null @@ -1,42 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import Vision -import Darwin - -//===----------------------------------------------------------------------===// -// VNFaceLandmarkRegion2D -//===----------------------------------------------------------------------===// - -#if !os(watchOS) - -@available(macOS, introduced: 10.13) -@available(iOS, introduced: 11.0) -@available(tvOS, introduced: 11.0) -extension VNFaceLandmarkRegion2D { - @nonobjc - public var normalizedPoints: [CGPoint] { - let pointsBuffer = UnsafeBufferPointer( - start: self.__normalizedPoints, count: Int(self.pointCount)) - return Array(pointsBuffer) - } - - @nonobjc - public func pointsInImage(imageSize: CGSize) -> [CGPoint] { - let pointsBuffer = UnsafeBufferPointer( - start: self.__pointsInImage(imageSize: imageSize), - count: Int(self.pointCount)) - return Array(pointsBuffer) - } -} - -#endif diff --git a/stdlib/public/Darwin/WatchKit/CMakeLists.txt b/stdlib/public/Darwin/WatchKit/CMakeLists.txt deleted file mode 100644 index a4d2684126efb..0000000000000 --- a/stdlib/public/Darwin/WatchKit/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftWatchKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - WKInterfaceController.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" "-L${sdk}/usr/lib/swift/" - TARGET_SDKS WATCHOS WATCHOS_SIMULATOR - SWIFT_MODULE_DEPENDS_WATCHOS Darwin HomeKit CoreGraphics UIKit Dispatch SceneKit simd Foundation MapKit CoreLocation CoreFoundation ObjectiveC # auto-updated - FRAMEWORK_DEPENDS_WEAK WatchKit - SWIFT_COMPILE_FLAGS_WATCHOS -Xfrontend -disable-autolink-framework -Xfrontend CoreText - - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_WATCHKIT_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/WatchKit/WKInterfaceController.swift b/stdlib/public/Darwin/WatchKit/WKInterfaceController.swift deleted file mode 100644 index a8a2d11f8f0dd..0000000000000 --- a/stdlib/public/Darwin/WatchKit/WKInterfaceController.swift +++ /dev/null @@ -1,54 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import WatchKit -import Foundation - -@available(iOS, introduced: 8.2) -extension WKInterfaceController { - @available(*, unavailable, - renamed: "reloadRootControllers(withNamesAndContexts:)") - @nonobjc final public class func reloadRootControllers( - _ namesAndContexts: [(name: String, context: AnyObject)] - ) { - reloadRootControllers(withNamesAndContexts: namesAndContexts) - } - - // Swift convenience type (class) method for - // reloadRootControllersWithNames:contexts: that takes an array of tuples - public class func reloadRootControllers( - withNamesAndContexts namesAndContexts: [(name: String, context: AnyObject)] - ) { - WKInterfaceController.reloadRootControllers( - withNames: namesAndContexts.map { $0.name }, - contexts: namesAndContexts.map { $0.context }) - } - - @available(*, deprecated, - renamed: "presentController(withNamesAndContexts:)") - @nonobjc final public func presentController( - _ namesAndContexts: [(name: String, context: AnyObject)] - ) { - presentController(withNamesAndContexts: namesAndContexts) - } - - // Swift convenience method for presentControllerWithNames:contexts: that - // takes an array of tuples - public func presentController( - withNamesAndContexts namesAndContexts: [(name: String, context: AnyObject)] - ) { - self.presentController( - withNames: namesAndContexts.map { $0.name }, - contexts: namesAndContexts.map { $0.context }) - } -} - diff --git a/stdlib/public/Darwin/XCTest/CMakeLists.txt b/stdlib/public/Darwin/XCTest/CMakeLists.txt index 3728030bd7a77..c2a6cef19ab65 100644 --- a/stdlib/public/Darwin/XCTest/CMakeLists.txt +++ b/stdlib/public/Darwin/XCTest/CMakeLists.txt @@ -18,9 +18,6 @@ add_swift_target_library(swiftXCTest ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR SWIFT_MODULE_DEPENDS ObjectiveC Foundation FRAMEWORK_DEPENDS Foundation XCTest - SWIFT_MODULE_DEPENDS_OSX AppKit - SWIFT_MODULE_DEPENDS_IOS CoreMedia UIKit - SWIFT_MODULE_DEPENDS_TVOS UIKit DONT_EMBED_BITCODE DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_XCTEST_OSX} diff --git a/stdlib/public/Darwin/XPC/CMakeLists.txt b/stdlib/public/Darwin/XPC/CMakeLists.txt deleted file mode 100644 index 06e64e3a6618d..0000000000000 --- a/stdlib/public/Darwin/XPC/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftXPC ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - XPC.swift - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - TARGET_SDKS OSX - SWIFT_MODULE_DEPENDS_OSX Darwin Dispatch ObjectiveC # auto-updated - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_XPC_OSX} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/XPC/XPC.swift b/stdlib/public/Darwin/XPC/XPC.swift deleted file mode 100644 index fcda4fd130fe8..0000000000000 --- a/stdlib/public/Darwin/XPC/XPC.swift +++ /dev/null @@ -1,119 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import XPC -@_implementationOnly import _SwiftXPCOverlayShims - -//===----------------------------------------------------------------------===// -// XPC Types -//===----------------------------------------------------------------------===// -public var XPC_TYPE_CONNECTION: xpc_type_t { - return _swift_xpc_type_CONNECTION() -} - -public var XPC_TYPE_ENDPOINT: xpc_type_t { - return _swift_xpc_type_ENDPOINT() -} - -public var XPC_TYPE_NULL: xpc_type_t { - return _swift_xpc_type_NULL() -} - -public var XPC_TYPE_BOOL: xpc_type_t { - return _swift_xpc_type_BOOL() -} - -public var XPC_TYPE_INT64: xpc_type_t { - return _swift_xpc_type_INT64() -} - -public var XPC_TYPE_UINT64: xpc_type_t { - return _swift_xpc_type_UINT64() -} - -public var XPC_TYPE_DOUBLE: xpc_type_t { - return _swift_xpc_type_DOUBLE() -} - -public var XPC_TYPE_DATE: xpc_type_t { - return _swift_xpc_type_DATE() -} - -public var XPC_TYPE_DATA: xpc_type_t { - return _swift_xpc_type_DATA() -} - -public var XPC_TYPE_STRING: xpc_type_t { - return _swift_xpc_type_STRING() -} - -public var XPC_TYPE_UUID: xpc_type_t { - return _swift_xpc_type_UUID() -} - -public var XPC_TYPE_FD: xpc_type_t { - return _swift_xpc_type_FD() -} - -public var XPC_TYPE_SHMEM: xpc_type_t { - return _swift_xpc_type_SHMEM() -} - -public var XPC_TYPE_ARRAY: xpc_type_t { - return _swift_xpc_type_ARRAY() -} - -public var XPC_TYPE_DICTIONARY: xpc_type_t { - return _swift_xpc_type_DICTIONARY() -} - -public var XPC_TYPE_ERROR: xpc_type_t { - return _swift_xpc_type_ERROR() -} - -public var XPC_TYPE_ACTIVITY: xpc_type_t { - return _swift_xpc_type_ACTIVITY() -} - -//===----------------------------------------------------------------------===// -// Macros -//===----------------------------------------------------------------------===// - -// xpc/xpc.h -public let XPC_ERROR_KEY_DESCRIPTION: UnsafePointer = _xpc_error_key_description -public let XPC_EVENT_KEY_NAME: UnsafePointer = _xpc_event_key_name - -public var XPC_BOOL_TRUE: xpc_object_t { - return _swift_xpc_bool_true() -} - -public var XPC_BOOL_FALSE: xpc_object_t { - return _swift_xpc_bool_false() -} - -public var XPC_ARRAY_APPEND: size_t { - return -1 -} - -// xpc/connection.h - -public var XPC_ERROR_CONNECTION_INTERRUPTED: xpc_object_t { - return _swift_xpc_connection_interrupted() -} - -public var XPC_ERROR_CONNECTION_INVALID: xpc_object_t { - return _swift_xpc_connection_invalid() -} - -public var XPC_ERROR_TERMINATION_IMMINENT: xpc_object_t { - return _swift_xpc_connection_termination_imminent() -} diff --git a/stdlib/public/Darwin/os/CMakeLists.txt b/stdlib/public/Darwin/os/CMakeLists.txt deleted file mode 100644 index 080ad497ebc5a..0000000000000 --- a/stdlib/public/Darwin/os/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftos ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - format.m - os.m - os_log.swift - os_signpost.swift - os_trace_blob.c - thunks.mm - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - SWIFT_MODULE_DEPENDS_OSX Darwin Dispatch ObjectiveC XPC # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin ObjectiveC # auto-updated - Dispatch # required in some configurations but not found by tool - SWIFT_MODULE_DEPENDS_TVOS Darwin ObjectiveC # auto-updated - Dispatch # required in some configurations but not found by tool - SWIFT_MODULE_DEPENDS_WATCHOS Darwin ObjectiveC # auto-updated - Dispatch # required in some configurations but not found by tool - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_OS_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_OS_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_OS_TVOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_OS_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/os/format.h b/stdlib/public/Darwin/os/format.h deleted file mode 100644 index 696154661d261..0000000000000 --- a/stdlib/public/Darwin/os/format.h +++ /dev/null @@ -1,94 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -#ifndef __OS_FORMAT_H__ -#define __OS_FORMAT_H__ - -#include -#include -#include -#include -#include -#include - -#include "os_trace_blob.h" - -#define OS_LOG_FMT_MAX_CMDS 48 -#define OS_LOG_FMT_BUF_SIZE (2 + (2 + 16) * OS_LOG_FMT_MAX_CMDS) - -typedef enum { - T_C_NONE = 0, - T_C_STATIC = 1, - T_C_DYNAMIC = 2, -} os_log_count_type_t; - -enum os_trace_int_types_t { - T_CHAR = -2, - T_SHORT = -1, - T_INT = 0, - T_LONG = 1, - T_LONGLONG = 2, - T_SIZE = 3, - T_INTMAX = 4, - T_PTRDIFF = 5, -}; - -OS_ENUM(os_log_fmt_cmd_flags, uint8_t, - OSLF_CMD_FLAG_PRIVATE = 0x1, - OSLF_CMD_FLAG_PUBLIC = 0x2, -); - -OS_ENUM(os_log_fmt_cmd_type, uint8_t, - OSLF_CMD_TYPE_SCALAR = 0, - OSLF_CMD_TYPE_COUNT = 1, - OSLF_CMD_TYPE_STRING = 2, - OSLF_CMD_TYPE_DATA = 3, - OSLF_CMD_TYPE_OBJECT = 4, - OSLF_CMD_TYPE_WIDE_STRING = 5, - OSLF_CMD_TYPE_ERRNO = 6, -); - -OS_ENUM(os_log_fmt_hdr_flags, uint8_t, - OSLF_HDR_FLAG_HAS_PRIVATE = 0x01, - OSLF_HDR_FLAG_HAS_NON_SCALAR = 0x02, -); - -enum os_log_int_types_t { - OST_CHAR = -2, - OST_SHORT = -1, - OST_INT = 0, - OST_LONG = 1, - OST_LONGLONG = 2, - OST_SIZE = 3, - OST_INTMAX = 4, - OST_PTRDIFF = 5, -}; - -typedef struct { - os_log_fmt_cmd_flags_t cmd_flags : 4; - os_log_fmt_cmd_type_t cmd_type : 4; - uint8_t cmd_size; - uint8_t cmd_data[]; -} os_log_fmt_cmd_s, *os_log_fmt_cmd_t; - -typedef struct os_log_fmt_hdr_s { - os_log_fmt_hdr_flags_t hdr_flags; - uint8_t hdr_cmd_cnt; - uint8_t hdr_data[]; -} os_log_fmt_hdr_s, *os_log_fmt_hdr_t; - -__attribute__((__visibility__("hidden"))) -bool -_os_log_encode(char buf[OS_LOG_FMT_BUF_SIZE], const char *format, va_list args, - int saved_errno, os_trace_blob_t ob); - -#endif // __OS_FORMAT_H__ diff --git a/stdlib/public/Darwin/os/format.m b/stdlib/public/Darwin/os/format.m deleted file mode 100644 index 5ef8a790ddd79..0000000000000 --- a/stdlib/public/Darwin/os/format.m +++ /dev/null @@ -1,306 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -#include -#include -#include "format.h" - -static inline void -_os_log_encode_arg(os_trace_blob_t ob, os_log_fmt_cmd_t cmd, const void *data) -{ - os_trace_blob_add(ob, cmd, sizeof(os_log_fmt_cmd_s)); - os_trace_blob_add(ob, data, cmd->cmd_size); -} - -bool -_os_log_encode(char buf[OS_LOG_FMT_BUF_SIZE], const char *format, va_list args, - int saved_errno, os_trace_blob_t ob) -{ - os_log_fmt_hdr_s hdr = {0}; - os_trace_blob_add(ob, &hdr, sizeof(hdr)); - - const char *percent = strchr(format, '%'); - - while (percent != NULL) { - ++percent; - if (percent[0] != '%') { - os_log_fmt_cmd_s cmd = {0}; - os_log_count_type_t widtht = T_C_NONE; - os_log_count_type_t prect = T_C_NONE; - os_log_fmt_cmd_flags_t flags = 0; - int type = T_INT; - bool long_double = false; - int precision = 0; - char ch; - - if (hdr.hdr_cmd_cnt == OS_LOG_FMT_MAX_CMDS) { - break; - } - - for (bool done = false; !done; percent++) { - switch (ch = percent[0]) { - /* type of types or other */ - case 'l': type++; break; // longer - case 'h': type--; break; // shorter - case 'z': type = T_SIZE; break; - case 'j': type = T_INTMAX; break; - case 't': type = T_PTRDIFF; break; - - case '*': // dynamic width - widtht = T_C_DYNAMIC; - // if the next character is a '.' then increment percent - // and fallthrough to the precision handling code - if (percent[1] != '.') { - break; - } - percent++; - // FALLTHROUGH - case '.': // precision - if ((percent[1]) == '*') { - prect = T_C_DYNAMIC; - percent++; - } else { - while (isdigit(percent[1])) { - precision = 10 * precision + (percent[1] - '0'); - percent++; - } - if (precision > 1024) precision = 1024; - prect = T_C_STATIC; - } - break; - - case '-': // left-align - case '+': // force sign - case ' ': // prefix non-negative with space - case '#': // alternate - case '\'': // group by thousands - break; - - case '{': // annotated symbols - for (const char *curr2 = percent + 1; (ch = (*curr2)) != 0; curr2++) { - if (ch == '}') { - if (strncmp(percent + 1, "private", MIN(curr2 - percent - 1, 7)) == 0) { - hdr.hdr_flags |= OSLF_HDR_FLAG_HAS_PRIVATE; - flags |= OSLF_CMD_FLAG_PRIVATE; - } else if (strncmp(percent + 1, "public", MIN(curr2 - percent - 1, 6)) == 0) { - flags |= OSLF_CMD_FLAG_PUBLIC; - } - percent = curr2; - break; - } - } - break; - -#define encode_width() \ - do { \ - if (widtht == T_C_DYNAMIC) { \ - cmd.cmd_type = OSLF_CMD_TYPE_SCALAR; \ - encode(int, 0); \ - } \ - } while (0) - -// clang inconsistency: static precision counts are still marked with the -// privacy bits of the command they preceed -#define encode_precision(type) \ - do { \ - if (prect != T_C_NONE) { \ - cmd.cmd_type = type; \ - cmd.cmd_size = sizeof(int); \ - if (prect == T_C_STATIC && type == OSLF_CMD_TYPE_COUNT) { \ - cmd.cmd_flags = flags; \ - } else if (prect == T_C_DYNAMIC) { \ - precision = va_arg(args, int); \ - } \ - _os_log_encode_arg(ob, &cmd, &precision); \ - hdr.hdr_cmd_cnt++; \ - prect = T_C_NONE; \ - } \ - } while (0) - -// scalar data types encode their precision as a scalar -#define encode_scalar_preamble() \ - do { \ - encode_width(); \ - if (prect == T_C_DYNAMIC) { \ - encode_precision(OSLF_CMD_TYPE_SCALAR); \ - } \ - } while (0) - -#define encode_pointer_preamble() \ - do { \ - encode_width(); \ - encode_precision(OSLF_CMD_TYPE_COUNT); \ - } while (0) - -#define encode_nsstring(flags) \ - do { \ - NSString *__arg = va_arg(args, NSString *); \ - const char *_Nullable __var = __arg.UTF8String; \ - cmd.cmd_flags = flags; \ - cmd.cmd_size = sizeof(__var); \ - _os_log_encode_arg(ob, &cmd, &__var); \ - hdr.hdr_cmd_cnt++; \ - } while (0) - -#define encode_smallint(ty, flags) \ - do { \ - int __var = va_arg(args, int); \ - cmd.cmd_flags = flags; \ - cmd.cmd_size = sizeof(__var); \ - _os_log_encode_arg(ob, &cmd, &__var); \ - hdr.hdr_cmd_cnt++; \ - } while (0) - -#define encode(ty, flags) \ - do { \ - ty __var = va_arg(args, ty); \ - cmd.cmd_flags = flags; \ - cmd.cmd_size = sizeof(__var); \ - _os_log_encode_arg(ob, &cmd, &__var); \ - hdr.hdr_cmd_cnt++; \ - } while (0) - - /* fixed types */ - case 'c': // char - case 'd': // integer - case 'i': // integer - case 'o': // octal - case 'u': // unsigned - case 'x': // hex - case 'X': // upper-hex - encode_scalar_preamble(); - cmd.cmd_type = OSLF_CMD_TYPE_SCALAR; - switch (type) { - case T_CHAR: - encode_smallint(char, flags); - break; - case T_SHORT: - encode_smallint(short, flags); - break; - case T_INT: - encode(int, flags); - break; - case T_LONG: - encode(long, flags); - break; - case T_LONGLONG: - encode(long long, flags); - break; - case T_SIZE: - encode(size_t, flags); - break; - case T_INTMAX: - encode(intmax_t, flags); - break; - case T_PTRDIFF: - encode(ptrdiff_t, flags); - break; - default: - return false; - } - done = true; - break; - - case 'p': // emit pointers as scalars - cmd.cmd_type = OSLF_CMD_TYPE_SCALAR; - encode(void *, flags); - done = true; - break; - - case 'C': // wchar is treated like %lc - encode_scalar_preamble(); - cmd.cmd_type = OSLF_CMD_TYPE_SCALAR; - encode_smallint(wint_t, flags); - done = true; - break; - - case 'P': // pointer data - encode_pointer_preamble(); - hdr.hdr_flags |= OSLF_HDR_FLAG_HAS_NON_SCALAR; - cmd.cmd_type = OSLF_CMD_TYPE_DATA; - cmd.cmd_size = sizeof(void *); - encode(void *, flags); - done = true; - break; - - case 'L': // long double - long_double = true; - break; - - case 'a': - case 'A': - case 'e': - case 'E': // floating types - case 'f': - case 'F': - case 'g': - case 'G': - encode_scalar_preamble(); - cmd.cmd_type = OSLF_CMD_TYPE_SCALAR; - if (long_double) { - encode(long double, flags); - } else { - encode(double, flags); - } - done = true; - break; - - case 's': // Strings sent from Swift as NSString objects - encode_pointer_preamble(); - hdr.hdr_flags |= OSLF_HDR_FLAG_HAS_NON_SCALAR; - cmd.cmd_type = OSLF_CMD_TYPE_STRING; - encode_nsstring(flags); - done = true; - break; - - case '@': // CFTypeRef aka NSObject * - // %@ does not support precision - encode_width(); - hdr.hdr_flags |= OSLF_HDR_FLAG_HAS_NON_SCALAR; - cmd.cmd_type = OSLF_CMD_TYPE_OBJECT; - encode(void *, flags); - done = true; - break; - - case 'm': - cmd.cmd_type = OSLF_CMD_TYPE_SCALAR; - cmd.cmd_size = sizeof(int); - cmd.cmd_flags = flags; - _os_log_encode_arg(ob, &cmd, &saved_errno); - hdr.hdr_cmd_cnt++; - done = true; - break; - - default: - if (isdigit(ch)) { // [0-9] - continue; - } - done = true; - break; - } - - if (done) { - percent = strchr(percent, '%'); // Find next format - break; - } - } - } else { - percent = strchr(percent+1, '%'); // Find next format after %% - } - } - *(os_log_fmt_hdr_t)buf = hdr; - return true; -} - -#undef encode_nsstring -#undef encode_smallint -#undef encode diff --git a/stdlib/public/Darwin/os/os.m b/stdlib/public/Darwin/os/os.m deleted file mode 100644 index ec3b08c5b3c9c..0000000000000 --- a/stdlib/public/Darwin/os/os.m +++ /dev/null @@ -1,162 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "thunks.h" -#include "format.h" - -#define OST_FORMAT_MAX_STRING_SIZE 1024 - -typedef struct os_log_pack_s { - uint64_t olp_continuous_time; - struct timespec olp_wall_time; - const void *olp_mh; - const void *olp_pc; - const char *olp_format; - uint8_t olp_data[]; -} os_log_pack_s, *os_log_pack_t; - -API_AVAILABLE(macosx(10.12.4), ios(10.3), tvos(10.2), watchos(3.2)) -size_t -_os_log_pack_size(size_t os_log_format_buffer_size); - -API_AVAILABLE(macosx(10.12.4), ios(10.3), tvos(10.2), watchos(3.2)) -uint8_t * -_os_log_pack_fill(os_log_pack_t pack, size_t size, int saved_errno, const void *dso, const char *fmt); - -API_AVAILABLE(macosx(10.14), ios(12.0), tvos(12.0), watchos(5.0)) -uint8_t * -_os_signpost_pack_fill(os_log_pack_t pack, size_t size, - int saved_errno, const void *dso, const char *fmt, - const char *spnm, os_signpost_id_t spid); - -API_AVAILABLE(macosx(10.12.4), ios(10.3), tvos(10.2), watchos(3.2)) -void -os_log_pack_send(os_log_pack_t pack, os_log_t log, os_log_type_t type); - -API_AVAILABLE(macosx(10.14), ios(12.0), tvos(12.0), watchos(5.0)) -void -_os_signpost_pack_send(os_log_pack_t pack, os_log_t h, - os_signpost_type_t spty); - -__attribute__((__visibility__("default"))) -void * -_swift_os_log_return_address(void) -{ - return __builtin_return_address(1); -} - -__attribute__((__visibility__("default"))) -void -_swift_os_log( - const void * _Nullable dso, - const void * _Nullable ra, - os_log_t _Nonnull h, - os_log_type_t type, - const char * _Nonnull fmt, - va_list args) -{ - int saved_errno = errno; // %m - char buf[OS_LOG_FMT_BUF_SIZE]; - os_trace_blob_s ob = { - .ob_s = buf, - .ob_size = OS_LOG_FMT_BUF_SIZE, - .ob_binary = true - }; - - if (_os_log_encode(buf, fmt, args, saved_errno, &ob)) { - if (os_log_pack_send) { - size_t sz = _os_log_pack_size(ob.ob_len); - uint8_t _Alignas(os_log_pack_s) pack[sz]; - os_log_pack_t p = (os_log_pack_t)pack; - /* - * _os_log_encode has already packed `saved_errno` into a - * OSLF_CMD_TYPE_SCALAR command as the OSLF_CMD_TYPE_ERRNO does not - * deploy backwards, so pass zero for errno here. - */ - uint8_t *ptr = _os_log_pack_fill(p, sz, 0, dso, fmt); - p->olp_pc = ra; - memcpy(ptr, buf, ob.ob_len); - os_log_pack_send(p, h, type); - } else { - _os_log_impl((void *)dso, h, type, fmt, (uint8_t *)buf, ob.ob_len); - } - } -} - -API_AVAILABLE(macosx(10.14), ios(12.0), tvos(12.0), watchos(5.0)) -__attribute__((__visibility__("default"))) -void -_swift_os_signpost_with_format( - const void * _Nullable dso, - const void * _Nullable ra, - os_log_t _Nonnull h, - os_signpost_type_t spty, - const char * _Nonnull spnm, - os_signpost_id_t spid, - const char * _Nullable fmt, - va_list args) -{ - int saved_errno = errno; // %m - char buf[OS_LOG_FMT_BUF_SIZE]; - os_trace_blob_s ob = { - .ob_s = buf, - .ob_size = OS_LOG_FMT_BUF_SIZE, - .ob_maxsize = OS_LOG_FMT_BUF_SIZE, - .ob_binary = true - }; - - /* - * Signposts with a signpost name but no message/arguments are valid; - * the underlying encode/pack/decode infrastructure agrees to treat - * these like having an empty format string. - */ - bool encoded = fmt == NULL ? - _os_log_encode(buf, "", args, saved_errno, &ob) : - _os_log_encode(buf, fmt, args, saved_errno, &ob); - if (encoded) { - size_t sz = _os_log_pack_size(ob.ob_len); - uint8_t _Alignas(os_log_pack_s) pack[sz]; - os_log_pack_t p = (os_log_pack_t)pack; - uint8_t *ptr = _os_signpost_pack_fill(p, sz, saved_errno, dso, - fmt, spnm, spid); - p->olp_pc = ra; - memcpy(ptr, buf, ob.ob_len); - _os_signpost_pack_send(p, h, spty); - } -} - -API_AVAILABLE(macosx(10.14), ios(12.0), tvos(12.0), watchos(5.0)) -__attribute__((__visibility__("default"))) -void -_swift_os_signpost( - const void * _Nullable dso, - const void * _Nullable ra, - os_log_t _Nonnull h, - os_signpost_type_t spty, - const char * _Nonnull spnm, - os_signpost_id_t spid) -{ - static va_list x; - _swift_os_signpost_with_format(dso, ra, h, spty, spnm, spid, NULL, x); -} diff --git a/stdlib/public/Darwin/os/os_log.swift b/stdlib/public/Darwin/os/os_log.swift deleted file mode 100644 index 5eeeb75b6d0be..0000000000000 --- a/stdlib/public/Darwin/os/os_log.swift +++ /dev/null @@ -1,118 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import os -@_exported import os.log -@_implementationOnly import _SwiftOSOverlayShims - -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public func os_log( - _ type: OSLogType, - dso: UnsafeRawPointer = #dsohandle, - log: OSLog = .default, - _ message: StaticString, - _ args: CVarArg...) -{ - guard log.isEnabled(type: type) else { return } - let ra = _swift_os_log_return_address() - - message.withUTF8Buffer { (buf: UnsafeBufferPointer) in - // Since dladdr is in libc, it is safe to unsafeBitCast - // the cstring argument type. - buf.baseAddress!.withMemoryRebound( - to: CChar.self, capacity: buf.count - ) { str in - withVaList(args) { valist in - _swift_os_log(dso, ra, log, type, str, valist) - } - } - } -} - -@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) -public func os_log( - _ message: StaticString, - dso: UnsafeRawPointer? = #dsohandle, - log: OSLog = .default, - type: OSLogType = .default, - _ args: CVarArg...) -{ - guard log.isEnabled(type: type) else { return } - let ra = _swift_os_log_return_address() - - message.withUTF8Buffer { (buf: UnsafeBufferPointer) in - // Since dladdr is in libc, it is safe to unsafeBitCast - // the cstring argument type. - buf.baseAddress!.withMemoryRebound( - to: CChar.self, capacity: buf.count - ) { str in - withVaList(args) { valist in - _swift_os_log(dso, ra, log, type, str, valist) - } - } - } -} - -extension OSLogType { - @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) - public static let `default` = __OS_LOG_TYPE_DEFAULT - - @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) - public static let info = __OS_LOG_TYPE_INFO - - @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) - public static let debug = __OS_LOG_TYPE_DEBUG - - @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) - public static let error = __OS_LOG_TYPE_ERROR - - @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) - public static let fault = __OS_LOG_TYPE_FAULT -} - -extension OSLog { - @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) - public static let disabled = _swift_os_log_disabled() - - @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) - public static let `default` = _swift_os_log_default() - - @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) - public convenience init(subsystem: String, category: String) { - self.init(__subsystem: subsystem, category: category) - } -} - -@available(*, unavailable, renamed: "OSLogType.default") -public var OS_LOG_TYPE_DEFAULT: OSLogType { - fatalError() -} - -@available(*, unavailable, renamed: "OSLogType.info") -public var OS_LOG_TYPE_INFO: OSLogType { - fatalError() -} - -@available(*, unavailable, renamed: "OSLogType.debug") -public var OS_LOG_TYPE_DEBUG: OSLogType { - fatalError() -} - -@available(*, unavailable, renamed: "OSLogType.error") -public var OS_LOG_TYPE_ERROR: OSLogType { - fatalError() -} - -@available(*, unavailable, renamed: "OSLogType.fault") -public var OS_LOG_TYPE_FAULT: OSLogType { - fatalError() -} diff --git a/stdlib/public/Darwin/os/os_signpost.swift b/stdlib/public/Darwin/os/os_signpost.swift deleted file mode 100644 index f4b59f3c40276..0000000000000 --- a/stdlib/public/Darwin/os/os_signpost.swift +++ /dev/null @@ -1,133 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -@_exported import os -@_exported import os.signpost -@_implementationOnly import _SwiftOSOverlayShims -import os.log - -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public func os_signpost( - _ type: OSSignpostType, - dso: UnsafeRawPointer = #dsohandle, - log: OSLog, - name: StaticString, - signpostID: OSSignpostID = .exclusive -) { - let hasValidID = signpostID != .invalid && signpostID != .null - guard log.signpostsEnabled && hasValidID else { return } - let ra = _swift_os_log_return_address() - name.withUTF8Buffer { (nameBuf: UnsafeBufferPointer) in - // Since dladdr is in libc, it is safe to unsafeBitCast - // the cstring argument type. - nameBuf.baseAddress!.withMemoryRebound( - to: CChar.self, capacity: nameBuf.count - ) { nameStr in - _swift_os_signpost(dso, ra, log, type, nameStr, signpostID.rawValue) - } - } -} - -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public func os_signpost( - _ type: OSSignpostType, - dso: UnsafeRawPointer = #dsohandle, - log: OSLog, - name: StaticString, - signpostID: OSSignpostID = .exclusive, - _ format: StaticString, - _ arguments: CVarArg... -) { - let hasValidID = signpostID != .invalid && signpostID != .null - guard log.signpostsEnabled && hasValidID else { return } - let ra = _swift_os_log_return_address() - name.withUTF8Buffer { (nameBuf: UnsafeBufferPointer) in - // Since dladdr is in libc, it is safe to unsafeBitCast - // the cstring argument type. - nameBuf.baseAddress!.withMemoryRebound( - to: CChar.self, capacity: nameBuf.count - ) { nameStr in - format.withUTF8Buffer { (formatBuf: UnsafeBufferPointer) in - // Since dladdr is in libc, it is safe to unsafeBitCast - // the cstring argument type. - formatBuf.baseAddress!.withMemoryRebound( - to: CChar.self, capacity: formatBuf.count - ) { formatStr in - withVaList(arguments) { valist in - _swift_os_signpost_with_format(dso, ra, log, type, - nameStr, signpostID.rawValue, formatStr, valist) - } - } - } - } - } -} - -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -extension OSSignpostType { - public static let event = __OS_SIGNPOST_EVENT - public static let begin = __OS_SIGNPOST_INTERVAL_BEGIN - public static let end = __OS_SIGNPOST_INTERVAL_END -} - -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -public struct OSSignpostID { - public let rawValue: os_signpost_id_t - - public static let exclusive = OSSignpostID(_swift_os_signpost_id_exclusive()) - public static let invalid = OSSignpostID(_swift_os_signpost_id_invalid()) - public static let null = OSSignpostID(_swift_os_signpost_id_null()) - - public init(log: OSLog) { - self.rawValue = __os_signpost_id_generate(log) - } - - public init(log: OSLog, object: AnyObject) { - self.rawValue = __os_signpost_id_make_with_pointer(log, - UnsafeRawPointer(Unmanaged.passUnretained(object).toOpaque())) - } - - public init(_ value: UInt64) { - self.rawValue = value - } -} - -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -extension OSSignpostID : Comparable { - public static func < (a: OSSignpostID, b: OSSignpostID) -> Bool { - return a.rawValue < b.rawValue - } - - public static func == (a: OSSignpostID, b: OSSignpostID) -> Bool { - return a.rawValue == b.rawValue - } -} - -@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) -extension OSLog { - public struct Category { - public let rawValue: String - public static let pointsOfInterest = - Category(string: String(cString: _swift_os_signpost_points_of_interest())) - private init(string: String) { - self.rawValue = string - } - } - - public convenience init(subsystem: String, category: Category) { - self.init(__subsystem: subsystem, category: category.rawValue) - } - - public var signpostsEnabled: Bool { - return __os_signpost_enabled(self) - } -} diff --git a/stdlib/public/Darwin/os/os_trace_blob.c b/stdlib/public/Darwin/os/os_trace_blob.c deleted file mode 100644 index 81c86f185ddbe..0000000000000 --- a/stdlib/public/Darwin/os/os_trace_blob.c +++ /dev/null @@ -1,123 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -#include -#include -#include -#include -#include -#if !defined(__linux__) -#include -#endif -#include "os_trace_blob.h" - -OS_NOINLINE -static void -_os_trace_temporary_resource_shortage(void) -{ - sleep(1); -} - -static void * -_os_trace_malloc(size_t size) -{ - void *buf; - while (os_unlikely(!(buf = malloc(size)))) { - _os_trace_temporary_resource_shortage(); - } - return buf; -} - -static void * -_os_trace_memdup(void *ptr, size_t size) -{ - return memcpy(_os_trace_malloc(size), ptr, size); -} - -static void * -_os_trace_realloc(void *ptr, size_t size) -{ - void *buf; - while (os_unlikely(!(buf = realloc(ptr, size)))) { - _os_trace_temporary_resource_shortage(); - } - return buf; -} - -void -os_trace_blob_destroy_slow(os_trace_blob_t ob) -{ - char *s = ob->ob_s; - ob->ob_s = (void *)0xEBADF000; - ob->ob_flags = 0; - free(s); -} - -char * -os_trace_blob_detach(os_trace_blob_t ob, size_t *len) -{ - bool needs_free = ob->ob_flags & OS_TRACE_BLOB_NEEDS_FREE; - char *s = ob->ob_s; - ob->ob_s = (void *)0xEBADF000; - ob->ob_flags = 0; - if (len) *len = ob->ob_len; - if (needs_free) return s; - return _os_trace_memdup(s, ob->ob_len + !ob->ob_binary); -} - -OS_NOINLINE -static uint32_t -os_trace_blob_grow(os_trace_blob_t ob, size_t hint) -{ - uint32_t size, minsize, used = ob->ob_len + !ob->ob_binary; - if (os_add_overflow(used, hint, &minsize)) { - size = ob->ob_maxsize; - } else if (os_mul_overflow(ob->ob_size, 2, &size)) { - size = ob->ob_maxsize; - } else { - size = MIN((uint32_t)ob->ob_maxsize, MAX(minsize, size)); - } - if (size > ob->ob_size) { - if (ob->ob_flags & OS_TRACE_BLOB_NEEDS_FREE) { - ob->ob_s = _os_trace_realloc(ob->ob_s, size); - } else { - char *s = ob->ob_s; - ob->ob_s = _os_trace_malloc(size); - memcpy(ob->ob_s, s, used); - ob->ob_flags |= OS_TRACE_BLOB_NEEDS_FREE; - } - ob->ob_size = size; - } - return size - used; -} - -uint32_t -os_trace_blob_add_slow(os_trace_blob_t ob, const void *ptr, size_t size) -{ - if (os_unlikely(ob->ob_flags & OS_TRACE_BLOB_TRUNCATED)) { - return 0; - } - - uint32_t avail = _os_trace_blob_available(ob); - if (avail < size) { - if (ob->ob_size < ob->ob_maxsize) { - avail = os_trace_blob_grow(ob, size); - } - if (avail < size) { - ob->ob_flags |= OS_TRACE_BLOB_TRUNCATED; - size = avail; - } - } - - memcpy(ob->ob_s + ob->ob_len, ptr, size); - return _os_trace_blob_growlen(ob, size); -} diff --git a/stdlib/public/Darwin/os/os_trace_blob.h b/stdlib/public/Darwin/os/os_trace_blob.h deleted file mode 100644 index ad7bc8b09a365..0000000000000 --- a/stdlib/public/Darwin/os/os_trace_blob.h +++ /dev/null @@ -1,178 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -#ifndef __BLOB_H__ -#define __BLOB_H__ - -#include -#include -#include -#include -#include -#include "thunks.h" - -OS_ENUM(os_trace_blob_flags, uint16_t, - OS_TRACE_BLOB_NEEDS_FREE = 0x0001, - OS_TRACE_BLOB_TRUNCATED = 0x0002, -); - -typedef struct os_trace_blob_s { - union { - uint8_t *ob_b; - void *ob_v; - char *ob_s; - const char *ob_c; - }; - uint32_t ob_len; - uint32_t ob_size; - uint32_t ob_maxsize; - uint16_t ob_flags; - bool ob_binary; -} os_trace_blob_s, *os_trace_blob_t; - -#pragma mark - helpers (not to be used directly) - -OS_ALWAYS_INLINE -static inline uint32_t -_os_trace_blob_available(os_trace_blob_t ob) -{ - return ob->ob_size - !ob->ob_binary - ob->ob_len; -} - -OS_ALWAYS_INLINE -static inline uint32_t -_os_trace_blob_growlen(os_trace_blob_t ob, size_t extra) -{ - ob->ob_len += extra; - if (!ob->ob_binary) ob->ob_s[ob->ob_len] = '\0'; - return (uint32_t)extra; -} - -OS_ALWAYS_INLINE -static inline void -_os_trace_blob_setlen(os_trace_blob_t ob, uint32_t len) -{ - ob->ob_len = len; - if (!ob->ob_binary) ob->ob_s[len] = '\0'; -} - -__attribute__((__visibility__("hidden"))) -void -os_trace_blob_destroy_slow(os_trace_blob_t ob); - -#pragma mark - initialization and simple helpers - -#define os_trace_blob_init_buf(buf, binary) (os_trace_blob_s){ \ - .ob_v = buf, \ - .ob_binary = binary, \ - .ob_size = ({ _Static_assert(sizeof(*buf) == 1, ""); countof(buf); }) \ - } - -OS_ALWAYS_INLINE -static inline uint32_t -os_trace_blob_max_available(os_trace_blob_t ob) -{ - uint32_t used = ob->ob_len + !ob->ob_binary; - if (ob->ob_maxsize) return ob->ob_maxsize - used; - if (ob->ob_size) return ob->ob_size - used; - return 0; -} - -OS_ALWAYS_INLINE -static inline size_t -os_trace_blob_is_empty(os_trace_blob_t ob) -{ - return ob->ob_len == 0; -} - -OS_MALLOC __attribute__((__visibility__("hidden"))) -char * -os_trace_blob_detach(os_trace_blob_t ob, size_t *len); - -OS_ALWAYS_INLINE -static inline void -os_trace_blob_assert_not_allocated(os_trace_blob_t ob) -{ - if (os_unlikely(ob->ob_flags & OS_TRACE_BLOB_NEEDS_FREE)) { - OS_TRACE_INTERNAL_CRASH(0, "Buffer needs free"); - } -} - -OS_ALWAYS_INLINE -static inline void -os_trace_blob_destroy(os_trace_blob_t ob) -{ - if (ob->ob_flags & OS_TRACE_BLOB_NEEDS_FREE) { - return os_trace_blob_destroy_slow(ob); - } -} - -OS_ALWAYS_INLINE -static inline void -os_trace_blob_set_string(os_trace_blob_t ob, const char *s) -{ - if (ob->ob_flags & OS_TRACE_BLOB_NEEDS_FREE) { - free(ob->ob_s); - } - *ob = (os_trace_blob_s){ - .ob_c = s, - .ob_len = (uint32_t)strlen(s), - // not setting the size means "const" - }; -} - -OS_ALWAYS_INLINE -static inline void -os_trace_blob_rtrim(os_trace_blob_t ob) -{ - uint32_t len = ob->ob_len; - while (len > 0 && isspace(ob->ob_s[len - 1])) len--; - _os_trace_blob_setlen(ob, len); -} - -#pragma mark - appending to the blob - -__attribute__((__visibility__("hidden"))) -uint32_t -os_trace_blob_add_slow(os_trace_blob_t ob, const void *ptr, size_t size); - -OS_ALWAYS_INLINE -static inline uint32_t -os_trace_blob_add(os_trace_blob_t ob, const void *ptr, size_t size) -{ - if (os_unlikely(ob->ob_flags & OS_TRACE_BLOB_TRUNCATED)) { - return 0; - } - if (os_unlikely(size > _os_trace_blob_available(ob))) { - return os_trace_blob_add_slow(ob, ptr, size); - } - memcpy(ob->ob_s + ob->ob_len, ptr, size); - return _os_trace_blob_growlen(ob, size); -} - -OS_ALWAYS_INLINE -static inline uint32_t -os_trace_blob_addc(os_trace_blob_t ob, int c) -{ - uint8_t byte = (uint8_t)c; - return os_trace_blob_add(ob, &byte, 1); -} - -OS_ALWAYS_INLINE -static inline uint32_t -os_trace_blob_add_safe_string(os_trace_blob_t ob, const char *s) -{ - // safe means pure ascii no control chars - return os_trace_blob_add(ob, s, strlen(s)); -} - -#endif // !__LIBTRACE_BLOB_INTERNAL_H__ diff --git a/stdlib/public/Darwin/os/thunks.h b/stdlib/public/Darwin/os/thunks.h deleted file mode 100644 index 2546d95e11f97..0000000000000 --- a/stdlib/public/Darwin/os/thunks.h +++ /dev/null @@ -1,62 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -#ifndef __OS_THUNKS_H__ -#define __OS_THUNKS_H__ - -#include - -#ifndef os_fastpath -#define os_fastpath(x) ((__typeof__(x))OS_EXPECT((long)(x), ~0l)) -#endif -#ifndef os_slowpath -#define os_slowpath(x) ((__typeof__(x))OS_EXPECT((long)(x), 0l)) -#endif -#ifndef os_likely -#define os_likely(x) OS_EXPECT(!!(x), 1) -#endif -#ifndef os_unlikely -#define os_unlikely(x) OS_EXPECT(!!(x), 0) -#endif - -#ifndef MIN -#define MIN(a, b) (((a)<(b))?(a):(b)) -#endif - -#ifndef MAX -#define MAX(a, b) (((a)>(b))?(a):(b)) -#endif - -#ifndef OS_TRACE_INTERNAL_CRASH -#define OS_TRACE_INTERNAL_CRASH(_ptr, _message) _swift_os_log_reportError(0, _message) -#endif - -#ifndef os_likely -#define os_likely(x) OS_EXPECT(!!(x), 1) -#endif -#ifndef os_unlikely -#define os_unlikely(x) OS_EXPECT(!!(x), 0) -#endif - -#define os_add_overflow(a, b, res) __builtin_add_overflow((a), (b), (res)) -#define os_sub_overflow(a, b, res) __builtin_sub_overflow((a), (b), (res)) -#define os_mul_overflow(a, b, res) __builtin_mul_overflow((a), (b), (res)) - -__BEGIN_DECLS - -__attribute__((__visibility__("hidden"))) -void -_swift_os_log_reportError(uint32_t flags, const char *message); - -__END_DECLS - -#endif // __OS_THUNKS_H__ diff --git a/stdlib/public/Darwin/os/thunks.mm b/stdlib/public/Darwin/os/thunks.mm deleted file mode 100644 index 332d22990198f..0000000000000 --- a/stdlib/public/Darwin/os/thunks.mm +++ /dev/null @@ -1,20 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -#include -#include "thunks.h" - -extern "C" void -_swift_os_log_reportError(uint32_t flags, const char *message) -{ - swift::swift_reportError(flags, message); -} diff --git a/stdlib/public/Darwin/simd/CMakeLists.txt b/stdlib/public/Darwin/simd/CMakeLists.txt deleted file mode 100644 index de156d5c73252..0000000000000 --- a/stdlib/public/Darwin/simd/CMakeLists.txt +++ /dev/null @@ -1,24 +0,0 @@ -cmake_minimum_required(VERSION 3.4.3) -include("../../../../cmake/modules/StandaloneOverlay.cmake") - -add_swift_target_library(swiftsimd ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY - - "${SWIFT_SOURCE_DIR}/stdlib/linker-support/magic-symbols-for-install-name.c" - - GYB_SOURCES - simd.swift.gyb - Quaternion.swift.gyb - - SWIFT_COMPILE_FLAGS ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} -parse-stdlib ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" - SWIFT_MODULE_DEPENDS_OSX Darwin # auto-updated - SWIFT_MODULE_DEPENDS_IOS Darwin # auto-updated - SWIFT_MODULE_DEPENDS_TVOS Darwin # auto-updated - SWIFT_MODULE_DEPENDS_WATCHOS Darwin # auto-updated - - DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_SIMD_OSX} - DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_SIMD_IOS} - DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_SIMD_TVOS} - DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_SIMD_WATCHOS} - INSTALL_IN_COMPONENT sdk-overlay -) diff --git a/stdlib/public/Darwin/simd/Quaternion.swift.gyb b/stdlib/public/Darwin/simd/Quaternion.swift.gyb deleted file mode 100644 index 45a2e97474559..0000000000000 --- a/stdlib/public/Darwin/simd/Quaternion.swift.gyb +++ /dev/null @@ -1,268 +0,0 @@ -//===----------------------------------------------------------*- swift -*-===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// -// simd module overlays for Swift -//===----------------------------------------------------------------------===// - -import Swift -import Darwin -@_exported import simd - -%for scalar in ['Float','Double']: -% quat = 'simd_quat' + ('f' if scalar == 'Float' else 'd') -% mat3 = 'simd_' + str.lower(scalar) + '3x3' -% mat4 = 'simd_' + str.lower(scalar) + '4x4' - -extension ${quat} { - - /// Construct a quaternion from components. - /// - /// - Parameters: - /// - ix: The x-component of the imaginary (vector) part. - /// - iy: The y-component of the imaginary (vector) part. - /// - iz: The z-component of the imaginary (vector) part. - /// - r: The real (scalar) part. - @_transparent - public init(ix: ${scalar}, iy: ${scalar}, iz: ${scalar}, r: ${scalar}) { - self.init(vector: SIMD4<${scalar}>(ix, iy, iz, r)) - } - - /// Construct a quaternion from real and imaginary parts. - @_transparent - public init(real: ${scalar}, imag: SIMD3<${scalar}>) { - self.init(vector: simd_make_${str.lower(scalar)}4(imag, real)) - } - - /// A quaternion whose action is a rotation by `angle` radians about `axis`. - /// - /// - Parameters: - /// - angle: The angle to rotate by measured in radians. - /// - axis: The axis to rotate around. - @_transparent - public init(angle: ${scalar}, axis: SIMD3<${scalar}>) { - self = simd_quaternion(angle, axis) - } - - /// A quaternion whose action rotates the vector `from` onto the vector `to`. - @_transparent - public init(from: SIMD3<${scalar}>, to: SIMD3<${scalar}>) { - self = simd_quaternion(from, to) - } - - /// Construct a quaternion from `rotationMatrix`. - @_transparent - public init(_ rotationMatrix: ${mat3}) { - self = simd_quaternion(rotationMatrix) - } - - /// Construct a quaternion from `rotationMatrix`. - @_transparent - public init(_ rotationMatrix: ${mat4}) { - self = simd_quaternion(rotationMatrix) - } - - /// The real (scalar) part of `self`. - public var real: ${scalar} { - @_transparent - get { return vector.w } - @_transparent - set { vector.w = newValue } - } - - /// The imaginary (vector) part of `self`. - public var imag: SIMD3<${scalar}> { - @_transparent - get { return simd_make_${str.lower(scalar)}3(vector) } - @_transparent - set { vector = simd_make_${str.lower(scalar)}4(newValue, vector.w) } - } - - /// The angle (in radians) by which `self`'s action rotates. - @_transparent - public var angle: ${scalar} { - return simd_angle(self) - } - - /// The normalized axis about which `self`'s action rotates. - @_transparent - public var axis: SIMD3<${scalar}> { - return simd_axis(self) - } - - /// The conjugate of `self`. - @_transparent - public var conjugate: ${quat} { - return simd_conjugate(self) - } - - /// The inverse of `self`. - @_transparent - public var inverse: ${quat} { - return simd_inverse(self) - } - - /// The unit quaternion obtained by normalizing `self`. - @_transparent - public var normalized: ${quat} { - return simd_normalize(self) - } - - /// The length of the quaternion interpreted as a 4d vector. - @_transparent - public var length: ${scalar} { - return simd_length(self) - } - - /// Applies the rotation represented by a unit quaternion to the vector and - /// returns the result. - @_transparent - public func act(_ vector: SIMD3<${scalar}>) -> SIMD3<${scalar}> { - return simd_act(self, vector) - } -} - -extension ${mat3} { - /// Construct a 3x3 matrix from `quaternion`. - public init(_ quaternion: ${quat}) { - self = simd_matrix3x3(quaternion) - } -} - -extension ${mat4} { - /// Construct a 4x4 matrix from `quaternion`. - public init(_ quaternion: ${quat}) { - self = simd_matrix4x4(quaternion) - } -} - -extension ${quat} : CustomDebugStringConvertible { - public var debugDescription: String { - return "${quat}(real: \(real), imag: \(imag))" - } -} - -extension ${quat} : Equatable { - @_transparent - public static func ==(lhs: ${quat}, rhs: ${quat}) -> Bool { - return lhs.vector == rhs.vector - } -} - -extension ${quat} { - /// The sum of `lhs` and `rhs`. - @_transparent - public static func +(lhs: ${quat}, rhs: ${quat}) -> ${quat} { - return simd_add(lhs, rhs) - } - - /// Add `rhs` to `lhs`. - @_transparent - public static func +=(lhs: inout ${quat}, rhs: ${quat}) { - lhs = lhs + rhs - } - - /// The difference of `lhs` and `rhs`. - @_transparent - public static func -(lhs: ${quat}, rhs: ${quat}) -> ${quat} { - return simd_sub(lhs, rhs) - } - - /// Subtract `rhs` from `lhs`. - @_transparent - public static func -=(lhs: inout ${quat}, rhs: ${quat}) { - lhs = lhs - rhs - } - - /// The negation of `rhs`. - @_transparent - public static prefix func -(rhs: ${quat}) -> ${quat} { - return simd_sub(${quat}(), rhs) - } - - /// The product of `lhs` and `rhs`. - @_transparent - public static func *(lhs: ${quat}, rhs: ${quat}) -> ${quat} { - return simd_mul(lhs, rhs) - } - - /// The product of `lhs` and `rhs`. - @_transparent - public static func *(lhs: ${scalar}, rhs: ${quat}) -> ${quat} { - return simd_mul(lhs, rhs) - } - - /// The product of `lhs` and `rhs`. - @_transparent - public static func *(lhs: ${quat}, rhs: ${scalar}) -> ${quat} { - return simd_mul(lhs, rhs) - } - - /// Multiply `lhs` by `rhs`. - @_transparent - public static func *=(lhs: inout ${quat}, rhs: ${quat}) { - lhs = lhs * rhs - } - - /// Multiply `lhs` by `rhs`. - @_transparent - public static func *=(lhs: inout ${quat}, rhs: ${scalar}) { - lhs = lhs * rhs - } - - /// The quotient of `lhs` and `rhs`. - @_transparent - public static func /(lhs: ${quat}, rhs: ${quat}) -> ${quat} { - return simd_mul(lhs, rhs.inverse) - } - - /// The quotient of `lhs` and `rhs`. - @_transparent - public static func /(lhs: ${quat}, rhs: ${scalar}) -> ${quat} { - return ${quat}(vector: lhs.vector/rhs) - } - - /// Divide `lhs` by `rhs`. - @_transparent - public static func /=(lhs: inout ${quat}, rhs: ${quat}) { - lhs = lhs / rhs - } - - /// Divide `lhs` by `rhs`. - @_transparent - public static func /=(lhs: inout ${quat}, rhs: ${scalar}) { - lhs = lhs / rhs - } -} - -/// The dot product of the quaternions `p` and `q` interpreted as -/// four-dimensional vectors. -@_transparent -public func dot(_ lhs: ${quat}, _ rhs: ${quat}) -> ${scalar} { - return simd_dot(lhs, rhs) -} - -/// Logarithm of the quaternion `q`. -/// -/// We can write a quaternion `q` in the form: `r(cos(t) + sin(t)v)` where -/// `r` is the length of `q`, `t` is an angle, and `v` is a unit 3-vector. -/// The logarithm of `q` is `log(r) + tv`, just like the logarithm of the -/// complex number `r*(cos(t) + i sin(t))` is `log(r) + it`. -public func log(_ q: ${quat}) -> ${quat} { - return __tg_log(q) -} - -/// Inverse function of `log`; the exponential map on quaternions. -@_transparent -public func exp(_ q: ${quat}) -> ${quat} { - return __tg_exp(q) -} - -%end # for scalar diff --git a/stdlib/public/Darwin/simd/simd.swift.gyb b/stdlib/public/Darwin/simd/simd.swift.gyb deleted file mode 100644 index 926701413ab4b..0000000000000 --- a/stdlib/public/Darwin/simd/simd.swift.gyb +++ /dev/null @@ -1,611 +0,0 @@ -//===----------------------------------------------------------*- swift -*-===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// -// simd.h overlays for Swift -//===----------------------------------------------------------------------===// - -import Swift -import Darwin -@_exported import simd - -public extension SIMD { - @available(swift, deprecated:5, renamed: "init(repeating:)") - @_transparent - init(_ scalar: Scalar) { self.init(repeating: scalar) } -} - -internal extension SIMD2 { - var _descriptionAsArray: String { return "[\(x), \(y)]" } -} - -internal extension SIMD3 { - var _descriptionAsArray: String { return "[\(x), \(y), \(z)]" } -} - -internal extension SIMD4 { - var _descriptionAsArray: String { return "[\(x), \(y), \(z), \(w)]" } -} - -public extension SIMD where Scalar : FixedWidthInteger { - @available(swift, deprecated:5, message: "use 0 &- rhs") - @_transparent - static prefix func -(rhs: Self) -> Self { return 0 &- rhs } -} - -%{ -component = ['x','y','z','w'] -scalar_types = ['Float','Double','Int32','UInt32'] -ctype = { 'Float':'float', 'Double':'double', 'Int32':'int', 'UInt32':'uint'} -floating_types = ['Float','Double'] -}% - -%for scalar in scalar_types: -% for count in [2, 3, 4]: -% vectype = "SIMD" + str(count) + "<" + scalar + ">" -% vecsize = (8 if scalar == 'Double' else 4) * (4 if count == 3 else count) -% vecalign = (16 if vecsize > 16 else vecsize) -% is_floating = scalar in floating_types -% is_signed = scalar[0] != 'U' -% wrap = "" if is_floating else "&" - -@available(swift, deprecated: 5.1, message: "Use SIMD${count}<${scalar}>") -public typealias ${ctype[scalar]}${count} = ${vectype} - -% if is_signed: -/// Elementwise absolute value of a vector. The result is a vector of the same -/// length with all elements positive. -@_transparent -public func abs(_ x: ${vectype}) -> ${vectype} { - return simd_abs(x) -} -% end - -/// Elementwise minimum of two vectors. Each component of the result is the -/// smaller of the corresponding component of the inputs. -@_transparent -public func min(_ x: ${vectype}, _ y: ${vectype}) -> ${vectype} { - return simd_min(x, y) -} - -/// Elementwise maximum of two vectors. Each component of the result is the -/// larger of the corresponding component of the inputs. -@_transparent -public func max(_ x: ${vectype}, _ y: ${vectype}) -> ${vectype} { - return simd_max(x, y) -} - -/// Vector-scalar minimum. Each component of the result is the minimum of the -/// corresponding element of the input vector and the scalar. -@_transparent -public func min(_ vector: ${vectype}, _ scalar: ${scalar}) -> ${vectype} { - return min(vector, ${vectype}(repeating: scalar)) -} - -/// Vector-scalar maximum. Each component of the result is the maximum of the -/// corresponding element of the input vector and the scalar. -@_transparent -public func max(_ vector: ${vectype}, _ scalar: ${scalar}) -> ${vectype} { - return max(vector, ${vectype}(repeating: scalar)) -} - -/// Each component of the result is the corresponding element of `x` clamped to -/// the range formed by the corresponding elements of `min` and `max`. Any -/// lanes of `x` that contain NaN will end up with the `min` value. -@_transparent -public func clamp(_ x: ${vectype}, min: ${vectype}, max: ${vectype}) - -> ${vectype} { - return simd.min(simd.max(x, min), max) -} - -/// Clamp each element of `x` to the range [`min`, max]. If any lane of `x` is -/// NaN, the corresponding lane of the result is `min`. -@_transparent -public func clamp(_ x: ${vectype}, min: ${scalar}, max: ${scalar}) - -> ${vectype} { - return simd.min(simd.max(x, min), max) -} - -/// Sum of the elements of the vector. -@_transparent -public func reduce_add(_ x: ${vectype}) -> ${scalar} { - return simd_reduce_add(x) -} - -/// Minimum element of the vector. -@_transparent -public func reduce_min(_ x: ${vectype}) -> ${scalar} { - return simd_reduce_min(x) -} - -/// Maximum element of the vector. -@_transparent -public func reduce_max(_ x: ${vectype}) -> ${scalar} { - return simd_reduce_max(x) -} - -% if is_floating: - -/// Sign of a vector. Each lane contains -1 if the corresponding lane of `x` -/// is less than zero, +1 if the corresponding lane of `x` is greater than -/// zero, and 0 otherwise. -@_transparent -public func sign(_ x: ${vectype}) -> ${vectype} { - return simd_sign(x) -} - -/// Linear interpolation between `x` (at `t=0`) and `y` (at `t=1`). May be -/// used with `t` outside of [0, 1] as well. -@_transparent -public func mix(_ x: ${vectype}, _ y: ${vectype}, t: ${vectype}) -> ${vectype} { - return x + t*(y-x) -} - -/// Linear interpolation between `x` (at `t=0`) and `y` (at `t=1`). May be -/// used with `t` outside of [0, 1] as well. -@_transparent -public func mix(_ x: ${vectype}, _ y: ${vectype}, t: ${scalar}) -> ${vectype} { - return x + t*(y-x) -} - -/// Elementwise reciprocal. -@_transparent -public func recip(_ x: ${vectype}) -> ${vectype} { - return simd_recip(x) -} - -/// Elementwise reciprocal square root. -@_transparent -public func rsqrt(_ x: ${vectype}) -> ${vectype} { - return simd_rsqrt(x) -} - -/// Alternate name for minimum of two floating-point vectors. -@_transparent -public func fmin(_ x: ${vectype}, _ y: ${vectype}) -> ${vectype} { - return min(x, y) -} - -/// Alternate name for maximum of two floating-point vectors. -@_transparent -public func fmax(_ x: ${vectype}, _ y: ${vectype}) -> ${vectype} { - return max(x, y) -} - -/// Each element of the result is the smallest integral value greater than or -/// equal to the corresponding element of the input. -@_transparent -public func ceil(_ x: ${vectype}) -> ${vectype} { - return __tg_ceil(x) -} - -/// Each element of the result is the largest integral value less than or equal -/// to the corresponding element of the input. -@_transparent -public func floor(_ x: ${vectype}) -> ${vectype} { - return __tg_floor(x) -} - -/// Each element of the result is the closest integral value with magnitude -/// less than or equal to that of the corresponding element of the input. -@_transparent -public func trunc(_ x: ${vectype}) -> ${vectype} { - return __tg_trunc(x) -} - -/// `x - floor(x)`, clamped to lie in the range [0,1). Without this clamp step, -/// the result would be 1.0 when `x` is a very small negative number, which may -/// result in out-of-bounds table accesses in common usage. -@_transparent -public func fract(_ x: ${vectype}) -> ${vectype} { - return simd_fract(x) -} - -/// 0.0 if `x < edge`, and 1.0 otherwise. -@_transparent -public func step(_ x: ${vectype}, edge: ${vectype}) -> ${vectype} { - return simd_step(edge, x) -} - -/// 0.0 if `x < edge0`, 1.0 if `x > edge1`, and cubic interpolation between -/// 0 and 1 in the interval [edge0, edge1]. -@_transparent -public func smoothstep(_ x: ${vectype}, edge0: ${vectype}, edge1: ${vectype}) - -> ${vectype} { - return simd_smoothstep(edge0, edge1, x) -} - -/// Dot product of `x` and `y`. -@_transparent -public func dot(_ x: ${vectype}, _ y: ${vectype}) -> ${scalar} { - return reduce_add(x * y) -} - -/// Projection of `x` onto `y`. -@_transparent -public func project(_ x: ${vectype}, _ y: ${vectype}) -> ${vectype} { - return simd_project(x, y) -} - -/// Length of `x`, squared. This is more efficient to compute than the length, -/// so you should use it if you only need to compare lengths to each other. -/// I.e. instead of writing: -/// -/// if (length(x) < length(y)) { ... } -/// -/// use: -/// -/// if (length_squared(x) < length_squared(y)) { ... } -/// -/// Doing it this way avoids one or two square roots, which is a fairly costly -/// operation. -@_transparent -public func length_squared(_ x: ${vectype}) -> ${scalar} { - return dot(x, x) -} - -/// Length (two-norm or "Euclidean norm") of `x`. -@_transparent -public func length(_ x: ${vectype}) -> ${scalar} { - return sqrt(length_squared(x)) -} - -/// The one-norm (or "taxicab norm") of `x`. -@_transparent -public func norm_one(_ x: ${vectype}) -> ${scalar} { - return reduce_add(abs(x)) -} - -/// The infinity-norm (or "sup norm") of `x`. -@_transparent -public func norm_inf(_ x: ${vectype}) -> ${scalar} { - return reduce_max(abs(x)) -} - -/// Distance between `x` and `y`, squared. -@_transparent -public func distance_squared(_ x: ${vectype}, _ y: ${vectype}) -> ${scalar} { - return length_squared(x - y) -} - -/// Distance between `x` and `y`. -@_transparent -public func distance(_ x: ${vectype}, _ y: ${vectype}) -> ${scalar} { - return length(x - y) -} - -/// Unit vector pointing in the same direction as `x`. -@_transparent -public func normalize(_ x: ${vectype}) -> ${vectype} { - return simd_normalize(x) -} - -/// `x` reflected through the hyperplane with unit normal vector `n`, passing -/// through the origin. E.g. if `x` is [1,2,3] and `n` is [0,0,1], the result -/// is [1,2,-3]. -@_transparent -public func reflect(_ x: ${vectype}, n: ${vectype}) -> ${vectype} { - return simd_reflect(x, n) -} - -/// The refraction direction given unit incident vector `x`, unit surface -/// normal `n`, and index of refraction `eta`. If the angle between the -/// incident vector and the surface is so small that total internal reflection -/// occurs, zero is returned. -@_transparent -public func refract(_ x: ${vectype}, n: ${vectype}, eta: ${scalar}) - -> ${vectype} { - return simd_refract(x, n, eta) -} - -% end # if is_floating -% end # for count in [2, 3, 4] -% if is_floating: -// Scalar versions of common operations: - -/// Returns -1 if `x < 0`, +1 if `x > 0`, and 0 otherwise (`sign(NaN)` is 0). -@_transparent -public func sign(_ x: ${scalar}) -> ${scalar} { - return simd_sign(x) -} - -/// Reciprocal. -@_transparent -public func recip(_ x: ${scalar}) -> ${scalar} { - return simd_recip(x) -} - -/// Reciprocal square root. -@_transparent -public func rsqrt(_ x: ${scalar}) -> ${scalar} { - return simd_rsqrt(x) -} - -/// Returns 0.0 if `x < edge`, and 1.0 otherwise. -@_transparent -public func step(_ x: ${scalar}, edge: ${scalar}) -> ${scalar} { - return simd_step(edge, x) -} - -/// Interprets two two-dimensional vectors as three-dimensional vectors in the -/// xy-plane and computes their cross product, which lies along the z-axis. -@_transparent -public func cross(_ x: SIMD2<${scalar}>, _ y: SIMD2<${scalar}>) -> SIMD3<${scalar}> { - return simd_cross(x,y) -} - -/// Cross-product of two three-dimensional vectors. The resulting vector is -/// perpendicular to the plane determined by `x` and `y`, with length equal to -/// the oriented area of the parallelogram they determine. -@_transparent -public func cross(_ x: SIMD3<${scalar}>, _ y: SIMD3<${scalar}>) -> SIMD3<${scalar}> { - return simd_cross(x,y) -} - -% end # is_floating -%end # for scalar in scalar_types - -%for type in floating_types: -% for rows in [2,3,4]: -% for cols in [2,3,4]: -% mattype = 'simd_' + ctype[type] + str(cols) + 'x' + str(rows) -% diagsize = rows if rows < cols else cols -% coltype = "SIMD" + str(rows) + "<" + type + ">" -% rowtype = "SIMD" + str(cols) + "<" + type + ">" -% diagtype = "SIMD" + str(diagsize) + "<" + type + ">" -% transtype = ctype[type] + str(rows) + 'x' + str(cols) - -public typealias ${ctype[type]}${cols}x${rows} = ${mattype} - -extension ${mattype} { - - /// Initialize matrix to have `scalar` on main diagonal, zeros elsewhere. - public init(_ scalar: ${type}) { - self.init(diagonal: ${diagtype}(repeating: scalar)) - } - - /// Initialize matrix to have specified `diagonal`, and zeros elsewhere. - public init(diagonal: ${diagtype}) { - self.init() -% for i in range(diagsize): - self.columns.${i}.${component[i]} = diagonal.${component[i]} -% end - } - - /// Initialize matrix to have specified `columns`. - public init(_ columns: [${coltype}]) { - precondition(columns.count == ${cols}, "Requires array of ${cols} vectors") - self.init() -% for i in range(cols): - self.columns.${i} = columns[${i}] -% end - } - - /// Initialize matrix to have specified `rows`. - public init(rows: [${rowtype}]) { - precondition(rows.count == ${rows}, "Requires array of ${rows} vectors") - self = ${transtype}(rows).transpose - } - - /// Initialize matrix to have specified `columns`. - public init(${', '.join(['_ col' + str(i) + ': ' + coltype - for i in range(cols)])}) { - self.init() -% for i in range(cols): - self.columns.${i} = col${i} -% end - } - - /// Initialize matrix from corresponding C matrix type. - @available(swift, deprecated: 4, message: "This conversion is no longer necessary; use `cmatrix` directly.") - @_transparent - public init(_ cmatrix: ${mattype}) { - self = cmatrix - } - - /// Get the matrix as the corresponding C matrix type. - @available(swift, deprecated: 4, message: "This property is no longer needed; use the matrix itself.") - @_transparent - public var cmatrix: ${mattype} { - return self - } - - /// Access to individual columns. - public subscript(column: Int) -> ${coltype} { - get { - switch(column) { -% for i in range(cols): - case ${i}: return columns.${i} -% end - default: preconditionFailure("Column index out of range") - } - } - set (value) { - switch(column) { -% for i in range(cols): - case ${i}: columns.${i} = value -% end - default: preconditionFailure("Column index out of range") - } - } - } - - /// Access to individual elements. - public subscript(column: Int, row: Int) -> ${type} { - get { return self[column][row] } - set (value) { self[column][row] = value } - } -} - -extension ${mattype} : CustomDebugStringConvertible { - public var debugDescription: String { - return "${mattype}([${', '.join(map(lambda i: \ - '\(columns.' + str(i) + '._descriptionAsArray)', - range(cols)))}])" - } -} - -extension ${mattype} : Equatable { - @_transparent - public static func ==(lhs: ${mattype}, rhs: ${mattype}) -> Bool { - return simd_equal(lhs, rhs) - } -} - -extension ${mattype} { - - /// Transpose of the matrix. - @_transparent - public var transpose: ${transtype} { - return simd_transpose(self) - } - -% if rows == cols: - /// Inverse of the matrix if it exists, otherwise the contents of the - /// resulting matrix are undefined. - @available(macOS 10.10, iOS 8.0, tvOS 10.0, watchOS 3.0, *) - @_transparent - public var inverse: ${mattype} { - return simd_inverse(self) - } - - /// Determinant of the matrix. - @_transparent - public var determinant: ${type} { - return simd_determinant(self) - } -% end - - /// Sum of two matrices. - @_transparent - public static func +(lhs: ${mattype}, rhs: ${mattype}) -> ${mattype} { - return simd_add(lhs, rhs) - } - - /// Negation of a matrix. - @_transparent - public static prefix func -(rhs: ${mattype}) -> ${mattype} { - return ${mattype}() - rhs - } - - /// Difference of two matrices. - @_transparent - public static func -(lhs: ${mattype}, rhs: ${mattype}) -> ${mattype} { - return simd_sub(lhs, rhs) - } - - @_transparent - public static func +=(lhs: inout ${mattype}, rhs: ${mattype}) -> Void { - lhs = lhs + rhs - } - - @_transparent - public static func -=(lhs: inout ${mattype}, rhs: ${mattype}) -> Void { - lhs = lhs - rhs - } - - /// Scalar-Matrix multiplication. - @_transparent - public static func *(lhs: ${type}, rhs: ${mattype}) -> ${mattype} { - return simd_mul(lhs, rhs) - } - - /// Matrix-Scalar multiplication. - @_transparent - public static func *(lhs: ${mattype}, rhs: ${type}) -> ${mattype} { - return rhs*lhs - } - - @_transparent - public static func *=(lhs: inout ${mattype}, rhs: ${type}) -> Void { - lhs = lhs*rhs - } - - /// Matrix-Vector multiplication. Keep in mind that matrix types are named - /// `${type}NxM` where `N` is the number of *columns* and `M` is the number of - /// *rows*, so we multiply a `${type}3x2 * ${type}3` to get a `${type}2`, for - /// example. - @_transparent - public static func *(lhs: ${mattype}, rhs: ${rowtype}) -> ${coltype} { - return simd_mul(lhs, rhs) - } - - /// Vector-Matrix multiplication. - @_transparent - public static func *(lhs: ${coltype}, rhs: ${mattype}) -> ${rowtype} { - return simd_mul(lhs, rhs) - } - -% for k in [2,3,4]: - /// Matrix multiplication (the "usual" matrix product, not the elementwise - /// product). -% restype = ctype[type] + str(k) + 'x' + str(rows) -% rhstype = ctype[type] + str(k) + 'x' + str(cols) - @_transparent - public static func *(lhs: ${mattype}, rhs: ${rhstype}) -> ${restype} { - return simd_mul(lhs, rhs) - } - -% end # for k in [2,3,4] - -% rhstype = ctype[type] + str(cols) + 'x' + str(cols) - /// Matrix multiplication (the "usual" matrix product, not the elementwise - /// product). - @_transparent - public static func *=(lhs: inout ${mattype}, rhs: ${rhstype}) -> Void { - lhs = lhs*rhs - } -} - -// Make old-style C free functions with the `matrix_` prefix available but -// deprecated in Swift 4. - -% if rows == cols: -@available(swift, deprecated: 4, renamed: "${mattype}(diagonal:)") -public func matrix_from_diagonal(_ d: ${diagtype}) -> ${mattype} { - return ${mattype}(diagonal: d) -} - -@available(swift, deprecated: 4, message: "Use the .inverse property instead.") -@available(macOS 10.10, iOS 8.0, tvOS 10.0, watchOS 3.0, *) -public func matrix_invert(_ x: ${mattype}) -> ${mattype} { - return x.inverse -} - -@available(swift, deprecated: 4, message: "Use the .determinant property instead.") -public func matrix_determinant(_ x: ${mattype}) -> ${type} { - return x.determinant -} - -% end # rows == cols -@available(swift, deprecated: 4, renamed: "${mattype}") -public func matrix_from_columns(${', '.join(['_ col' + str(i) + ': ' + coltype - for i in range(cols)])}) -> ${mattype} { - return ${mattype}(${', '.join(['col' + str(i) for i in range(cols)])}) -} - -public func matrix_from_rows(${', '.join(['_ row' + str(i) + ': ' + rowtype - for i in range(rows)])}) -> ${mattype} { - return ${transtype}(${', '.join(['row' + str(i) for i in range(rows)])}).transpose -} - -@available(swift, deprecated: 4, message: "Use the .transpose property instead.") -public func matrix_transpose(_ x: ${mattype}) -> ${transtype} { - return x.transpose -} - -@available(swift, deprecated: 4, renamed: "==") -public func matrix_equal(_ lhs: ${mattype}, _ rhs: ${mattype}) -> Bool { - return lhs == rhs -} - -% end # for cols in [2,3,4] -% end # for rows in [2,3,4] -%end # for type in floating_types diff --git a/stdlib/public/Differentiation/FloatingPointDifferentiation.swift.gyb b/stdlib/public/Differentiation/FloatingPointDifferentiation.swift.gyb index e4d4ab68350a1..80fc680b28471 100644 --- a/stdlib/public/Differentiation/FloatingPointDifferentiation.swift.gyb +++ b/stdlib/public/Differentiation/FloatingPointDifferentiation.swift.gyb @@ -21,7 +21,7 @@ bits = self_type.bits def Availability(bits): if bits == 16: - return '@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)' + return '@available(macOS 10.16, iOS 14.0, tvOS 14.0, watchOS 7.0, *)' return '' }% diff --git a/stdlib/public/SwiftRemoteMirror/SwiftRemoteMirror.cpp b/stdlib/public/SwiftRemoteMirror/SwiftRemoteMirror.cpp index 5b197ef69a727..449ba048c4457 100644 --- a/stdlib/public/SwiftRemoteMirror/SwiftRemoteMirror.cpp +++ b/stdlib/public/SwiftRemoteMirror/SwiftRemoteMirror.cpp @@ -393,6 +393,9 @@ static swift_typeinfo_t convertTypeInfo(const TypeInfo *TI) { } static swift_childinfo_t convertChild(const TypeInfo *TI, unsigned Index) { + if (!TI) + return {}; + const FieldInfo *FieldInfo; if (auto *EnumTI = dyn_cast(TI)) { FieldInfo = &(EnumTI->getCases()[Index]); diff --git a/stdlib/public/core/Availability.swift b/stdlib/public/core/Availability.swift index ecfc7bb4d1287..55da2e8314a77 100644 --- a/stdlib/public/core/Availability.swift +++ b/stdlib/public/core/Availability.swift @@ -42,3 +42,20 @@ public func _stdlib_isOSVersionAtLeast( return false._value #endif } + +#if os(macOS) +// This is a magic entry point known to the compiler. It is called in +// generated code for API availability checking. +@_semantics("availability.osversion") +@_effects(readnone) +public func _stdlib_isOSVersionAtLeastOrVariantVersionAtLeast( + _ major: Builtin.Word, + _ minor: Builtin.Word, + _ patch: Builtin.Word, + _ variantMajor: Builtin.Word, + _ variantMinor: Builtin.Word, + _ variantPatch: Builtin.Word + ) -> Builtin.Int1 { + return _stdlib_isOSVersionAtLeast(major, minor, patch) +} +#endif diff --git a/stdlib/public/core/BidirectionalCollection.swift b/stdlib/public/core/BidirectionalCollection.swift index 98b6cc89029b5..c702e3c5d5530 100644 --- a/stdlib/public/core/BidirectionalCollection.swift +++ b/stdlib/public/core/BidirectionalCollection.swift @@ -342,9 +342,12 @@ extension BidirectionalCollection where SubSequence == Self { public mutating func removeLast(_ k: Int) { if k == 0 { return } _precondition(k >= 0, "Number of elements to remove should be non-negative") - _precondition(count >= k, - "Can't remove more items from a collection than it contains") - self = self[startIndex..", ch.properties.numericValue) + /// print(ch, "-->", ch.asciiValue) /// } /// // a --> 97 /// // --> 32 @@ -125,7 +125,7 @@ extension Character { /// /// let chars: [Character] = ["4", "④", "万", "a"] /// for ch in chars { - /// print(ch, "-->", ch.properties.numericValue) + /// print(ch, "-->", ch.wholeNumberValue) /// } /// // 4 --> 4 /// // ④ --> 4 diff --git a/stdlib/public/core/Codable.swift b/stdlib/public/core/Codable.swift index 4b7fa1abea676..5ba222e39d343 100644 --- a/stdlib/public/core/Codable.swift +++ b/stdlib/public/core/Codable.swift @@ -4730,7 +4730,7 @@ extension RawRepresentable where RawValue == Float, Self: Decodable { } } -@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) +@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) extension Float16: Codable { /// Creates a new instance by decoding from the given decoder. /// diff --git a/stdlib/public/core/Collection.swift b/stdlib/public/core/Collection.swift index 1db572b65d06c..7b91d1b0d2b3e 100644 --- a/stdlib/public/core/Collection.swift +++ b/stdlib/public/core/Collection.swift @@ -491,7 +491,7 @@ public protocol Collection: Sequence { /// /// let horseName = "Silver" /// if horseName.isEmpty { - /// print("I've been through the desert on a horse with no name.") + /// print("My horse has no name.") /// } else { /// print("Hi ho, \(horseName)!") /// } @@ -1070,7 +1070,7 @@ extension Collection { /// /// let horseName = "Silver" /// if horseName.isEmpty { - /// print("I've been through the desert on a horse with no name.") + /// print("My horse has no name.") /// } else { /// print("Hi ho, \(horseName)!") /// } @@ -1664,8 +1664,10 @@ extension Collection where SubSequence == Self { public mutating func removeFirst(_ k: Int) { if k == 0 { return } _precondition(k >= 0, "Number of elements to remove should be non-negative") - _precondition(count >= k, - "Can't remove more items from a collection than it contains") - self = self[index(startIndex, offsetBy: k).. Bool { //===--- Parsing ----------------------------------------------------------===// %if bits == 16: -@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) +@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) %end extension ${Self}: LosslessStringConvertible { /// Creates a new instance from the given string. @@ -134,7 +134,7 @@ extension ${Self}: LosslessStringConvertible { %if bits == 16: self.init(Substring(text)) %else: - if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) { + if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { self.init(Substring(text)) } else { self = 0.0 @@ -164,7 +164,7 @@ extension ${Self}: LosslessStringConvertible { // In particular, we still have to export // _swift_stdlib_strtoXYZ_clocale() // as ABI to support old compiled code that still requires it. - @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) + @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) public init?(_ text: Substring) { self = 0.0 let success = withUnsafeMutablePointer(to: &self) { p -> Bool in diff --git a/stdlib/public/core/FloatingPointTypes.swift.gyb b/stdlib/public/core/FloatingPointTypes.swift.gyb index 844286bfdeddc..ecc20a48814fd 100644 --- a/stdlib/public/core/FloatingPointTypes.swift.gyb +++ b/stdlib/public/core/FloatingPointTypes.swift.gyb @@ -39,7 +39,7 @@ RawSignificand = 'UInt' + str(SignificandSize) def Availability(bits): if bits == 16: - return '@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)' + return '@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)' return '' if Self == 'Float16': diff --git a/stdlib/public/core/IntegerTypes.swift.gyb b/stdlib/public/core/IntegerTypes.swift.gyb index 4cdb3348e9a3d..d5fb2b1bd7feb 100644 --- a/stdlib/public/core/IntegerTypes.swift.gyb +++ b/stdlib/public/core/IntegerTypes.swift.gyb @@ -1152,7 +1152,7 @@ public struct ${Self} /// `source` must be representable in this type after rounding toward /// zero. % if FloatType == 'Float16': - @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) + @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) % end @_transparent public init(_ source: ${FloatType}) { @@ -1182,7 +1182,7 @@ public struct ${Self} /// /// - Parameter source: A floating-point value to convert to an integer. % if FloatType == 'Float16': - @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) + @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) % end @_transparent public init?(exactly source: ${FloatType}) { diff --git a/stdlib/public/core/Misc.swift b/stdlib/public/core/Misc.swift index 83ec946ea64eb..4d3526d7fb320 100644 --- a/stdlib/public/core/Misc.swift +++ b/stdlib/public/core/Misc.swift @@ -78,13 +78,13 @@ func _typeName(_ type: Any.Type, qualified: Bool = true) -> String { UnsafeBufferPointer(start: stringPtr, count: count)).0 } -@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) +@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) @_silgen_name("swift_getMangledTypeName") public func _getMangledTypeName(_ type: Any.Type) -> (UnsafePointer, Int) /// Returns the mangled name for a given type. -@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) +@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) public // SPI func _mangledTypeName(_ type: Any.Type) -> String? { let (stringPtr, count) = _getMangledTypeName(type) diff --git a/stdlib/public/core/RangeReplaceableCollection.swift b/stdlib/public/core/RangeReplaceableCollection.swift index ff520598bbde8..e535f76ed5380 100644 --- a/stdlib/public/core/RangeReplaceableCollection.swift +++ b/stdlib/public/core/RangeReplaceableCollection.swift @@ -285,12 +285,17 @@ public protocol RangeReplaceableCollection: Collection /// Customization point for `removeLast()`. Implement this function if you /// want to replace the default implementation. /// + /// The collection must not be empty. + /// /// - Returns: A non-nil value if the operation was performed. mutating func _customRemoveLast() -> Element? /// Customization point for `removeLast(_:)`. Implement this function if you /// want to replace the default implementation. /// + /// - Parameter n: The number of elements to remove from the collection. + /// `n` must be greater than or equal to zero and must not exceed the + /// number of elements in the collection. /// - Returns: `true` if the operation was performed. mutating func _customRemoveLast(_ n: Int) -> Bool @@ -591,9 +596,10 @@ extension RangeReplaceableCollection { public mutating func removeFirst(_ k: Int) { if k == 0 { return } _precondition(k >= 0, "Number of elements to remove should be non-negative") - _precondition(count >= k, - "Can't remove more items from a collection than it has") - let end = index(startIndex, offsetBy: k) + guard let end = index(startIndex, offsetBy: k, limitedBy: endIndex) else { + _preconditionFailure( + "Can't remove more items from a collection than it has") + } removeSubrange(startIndex..= 0, "Number of elements to remove should be non-negative") - _precondition(count >= k, - "Can't remove more items from a collection than it contains") - self = self[index(startIndex, offsetBy: k).. Bool { - self = self[startIndex..= 0, "Number of elements to remove should be non-negative") - _precondition(count >= k, - "Can't remove more items from a collection than it contains") if _customRemoveLast(k) { return } let end = endIndex - removeSubrange(index(end, offsetBy: -k)..= 0, "Number of elements to remove should be non-negative") - _precondition(count >= k, - "Can't remove more items from a collection than it contains") if _customRemoveLast(k) { return } let end = endIndex - removeSubrange(index(end, offsetBy: -k).. Int -@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) +@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) internal func _float16ToString( _ value: Float16, debug: Bool diff --git a/stdlib/public/core/SIMDVectorTypes.swift.gyb b/stdlib/public/core/SIMDVectorTypes.swift.gyb index 925253a92854b..cdcd42e0d3fd7 100644 --- a/stdlib/public/core/SIMDVectorTypes.swift.gyb +++ b/stdlib/public/core/SIMDVectorTypes.swift.gyb @@ -253,7 +253,7 @@ extension ${Self}: SIMDScalar { %for (Self, bits) in [('Float16',16), ('Float',32), ('Double',64)]: %if bits == 16: -@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) +@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) %end extension ${Self} : SIMDScalar { diff --git a/stdlib/public/core/String.swift b/stdlib/public/core/String.swift index 95961c5abdbdb..01a1f2e86ed65 100644 --- a/stdlib/public/core/String.swift +++ b/stdlib/public/core/String.swift @@ -501,7 +501,7 @@ extension String { /// memory with room for `capacity` UTF-8 code units, initializes /// that memory, and returns the number of initialized elements. @inline(__always) - @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) + @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) public init( unsafeUninitializedCapacity capacity: Int, initializingUTF8With initializer: ( diff --git a/test/ClangImporter/cfuncs_parse.swift b/test/ClangImporter/cfuncs_parse.swift index 5863fdb13bbce..d522b9d656c1f 100644 --- a/test/ClangImporter/cfuncs_parse.swift +++ b/test/ClangImporter/cfuncs_parse.swift @@ -72,7 +72,7 @@ func test_powl() { } #endif -@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) +@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) func test_f16() { var x = Float16.zero f16ptrfunc(&x) diff --git a/test/Constraints/function_builder_diags.swift b/test/Constraints/function_builder_diags.swift index 1a04e05892926..359fa6bdad05d 100644 --- a/test/Constraints/function_builder_diags.swift +++ b/test/Constraints/function_builder_diags.swift @@ -418,11 +418,14 @@ func testNonExhaustiveSwitch(e: E) { // rdar://problem/59856491 struct TestConstraintGenerationErrors { @TupleBuilder var buildTupleFnBody: String { + let a = nil // expected-error {{'nil' requires a contextual type}} String(nothing) // expected-error {{cannot find 'nothing' in scope}} } func buildTupleClosure() { - tuplify(true) { _ in + // FIXME: suppress the ambiguity error + tuplify(true) { _ in // expected-error {{type of expression is ambiguous without more context}} + let a = nothing // expected-error {{cannot find 'nothing' in scope}} String(nothing) // expected-error {{cannot find 'nothing' in scope}} } } diff --git a/test/Constraints/patterns.swift b/test/Constraints/patterns.swift index a3a2de3f5ee24..3fc400963112f 100644 --- a/test/Constraints/patterns.swift +++ b/test/Constraints/patterns.swift @@ -495,3 +495,14 @@ func rdar63510989() { // expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}} } } + +// rdar://problem/64157451 - compiler crash when using undefined type in pattern +func rdar64157451() { + enum E { + case foo(Int) + } + + func test(e: E) { + if case .foo(let v as DoeNotExist) = e {} // expected-error {{cannot find type 'DoeNotExist' in scope}} + } +} diff --git a/test/Demangle/Inputs/manglings.txt b/test/Demangle/Inputs/manglings.txt index c987ab733d537..ddfe5f5d34b3d 100644 --- a/test/Demangle/Inputs/manglings.txt +++ b/test/Demangle/Inputs/manglings.txt @@ -357,3 +357,4 @@ $s17property_wrappers10WithTuplesV9fractionsSd_S2dtvpfP --> property wrapper bac $sSo17OS_dispatch_queueC4sync7executeyyyXE_tFTOTA ---> {T:$sSo17OS_dispatch_queueC4sync7executeyyyXE_tFTO} partial apply forwarder for @nonobjc __C.OS_dispatch_queue.sync(execute: () -> ()) -> () $sxq_Idgnr_D ---> @differentiable @callee_guaranteed (@in_guaranteed A) -> (@out B) $sxq_Ilgnr_D ---> @differentiable(linear) @callee_guaranteed (@in_guaranteed A) -> (@out B) +$syQo ---> $syQo diff --git a/test/Driver/SourceRanges/range-lifecycle.swift b/test/Driver/SourceRanges/range-lifecycle.swift index 0bb90411ca4ed..426c6aa6a0f35 100644 --- a/test/Driver/SourceRanges/range-lifecycle.swift +++ b/test/Driver/SourceRanges/range-lifecycle.swift @@ -1,3 +1,4 @@ +// REQUIRES: rdar64812676 // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/range-lifecycle/* %t && cp %t/fileB{0-baseline,}.swift diff --git a/test/Driver/loaded_module_trace_swiftinterface.swift b/test/Driver/loaded_module_trace_swiftinterface.swift index a92a34e974d0c..b8bb28265b560 100644 --- a/test/Driver/loaded_module_trace_swiftinterface.swift +++ b/test/Driver/loaded_module_trace_swiftinterface.swift @@ -1,3 +1,4 @@ +// REQUIRES: rdar64941662 // UNSUPPORTED: -windows-msvc // 1) If there is no swiftmodule, use the swiftinterface diff --git a/test/Driver/verbose.swift b/test/Driver/verbose.swift index c180ff99b2781..3a52cb4abb7e8 100644 --- a/test/Driver/verbose.swift +++ b/test/Driver/verbose.swift @@ -1,4 +1,4 @@ // RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-linux-gnu -v %s 2>&1 | %FileCheck %s -check-prefix=VERBOSE_CLANG // RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-msvc -v %s 2>&1 | %FileCheck %s -check-prefix=VERBOSE_CLANG -// VERBOSE_CLANG: clang{{.*}} -v -o +// VERBOSE_CLANG: clang{{.*}} -v {{.*}}-o diff --git a/test/IDE/complete_builder_multiviable.swift b/test/IDE/complete_builder_multiviable.swift new file mode 100644 index 0000000000000..f801da1b77cdd --- /dev/null +++ b/test/IDE/complete_builder_multiviable.swift @@ -0,0 +1,38 @@ +// RUN: %swift-ide-test -code-completion -source-filename %s -code-completion-token COMPLETE1 | %FileCheck %s --check-prefix=CHECK +// RUN: %swift-ide-test -code-completion -source-filename %s -code-completion-token COMPLETE1 | %FileCheck %s --check-prefix=CHECK + +@_functionBuilder +struct Builder { + static func buildBlock(_ v1: T1) -> T1 { v1 } + static func buildBlock(_ v1: T1, _ v2: T2) -> (T1, T2) { v1 } +} + +struct MyValue { + var title: String + var id: Int + var value: Float +} + +func build(@Builder fn: (MyValue) -> T) {} + +struct Container { + init(x: Float) {} + init(x: Int) {} +} + +func test(foo: Foo) { + build { val in + Container(x: val.#^COMPLETE1^#) + } + build { val in + 1 + 2 + Container(x: val.#^COMPLETE2^#) + } +} + +// CHECK: Begin completions, 4 items +// CHECK: Keyword[self]/CurrNominal: self[#MyValue#]; name=self +// CHECK: Decl[InstanceVar]/CurrNominal: title[#String#]; name=title +// CHECK: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: id[#Int#]; name=id +// CHECK: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: value[#Float#]; name=value +// CHECK: End completions diff --git a/test/IDE/complete_in_accessors.swift b/test/IDE/complete_in_accessors.swift index b040f0d58c09d..8e46fd1d5d2de 100644 --- a/test/IDE/complete_in_accessors.swift +++ b/test/IDE/complete_in_accessors.swift @@ -113,6 +113,13 @@ // RUN: %FileCheck %s -check-prefix=WITH_GLOBAL_DECLS < %t.txt // RUN: %FileCheck %s -check-prefix=ACCESSORS_IN_MEMBER_FUNC_2 < %t.txt +// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_OLDVALUE_COPIED | %FileCheck %s -check-prefix=IMPLICIT_OLDVALUE_COPIED +// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_OLDVALUE_MEMBER | %FileCheck %s -check-prefix=IMPLICIT_OLDVALUE_MEMBER +// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICIT_OLDVALUE_COPIEDMEMBER | %FileCheck %s -check-prefix=IMPLICIT_OLDVALUE_COPIEDMEMBER +// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPLICIT_OLDVALUE_COPIED | %FileCheck %s -check-prefix=EXPLICIT_OLDVALUE_COPIED +// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPLICIT_OLDVALUE_MEMBER | %FileCheck %s -check-prefix=EXPLICIT_OLDVALUE_MEMBER +// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPLICIT_OLDVALUE_COPIEDMEMBER | %FileCheck %s -check-prefix=EXPLICIT_OLDVALUE_COPIEDMEMBER + //===--- Helper types that are used in this test struct FooStruct { @@ -247,18 +254,18 @@ willSet { } var globalAccessorDidSet1: Int { - didSet(oldValue) { + didSet { #^GLOBAL_ACCESSOR_DIDSET_1^# } } var globalAccessorDidSet2: Int { - didSet(oldValue) { + didSet { var fs = FooStruct() fs.#^GLOBAL_ACCESSOR_DIDSET_2^# } } var globalAccessorDidSet3 = 42 { -didSet(oldValue) { +didSet { #^GLOBAL_ACCESSOR_DIDSET_3^# } } @@ -337,18 +344,18 @@ struct MemberAccessors { } var memberAccessorDidSet1: Int { - didSet(oldValue) { + didSet { #^MEMBER_ACCESSOR_DIDSET_1^# } } var memberAccessorDidSet2: Int { - didSet(oldValue) { + didSet { var fs = FooStruct() fs.#^MEMBER_ACCESSOR_DIDSET_2^# } } var memberAccessorDidSet3 = 42 { - didSet(oldValue) { + didSet { #^MEMBER_ACCESSOR_DIDSET_3^# } } @@ -424,18 +431,18 @@ func accessorsInFunction(_ functionParam: Int) { } var memberAccessorDidSet1: Int { - didSet(oldValue) { + didSet { #^LOCAL_ACCESSOR_DIDSET_1^# } } var memberAccessorDidSet2: Int { - didSet(oldValue) { + didSet { var fs = FooStruct() fs.#^LOCAL_ACCESSOR_DIDSET_2^# } } var memberAccessorDidSet3: Int { - didSet(oldValue) { + didSet { #^LOCAL_ACCESSOR_DIDSET_3^# } } @@ -481,3 +488,61 @@ struct AccessorsInMemberFunction { } } } + +var testImplicitOldValue1: Int = 0 { + didSet { + var oldV = oldValue + #^IMPLICIT_OLDVALUE_COPIED^# +// IMPLICIT_OLDVALUE_COPIED: Begin completions +// IMPLICIT_OLDVALUE_COPIED-DAG: Decl[LocalVar]/Local: oldV[#Int#]; +// IMPLICIT_OLDVALUE_COPIED-DAG: Decl[LocalVar]/Local: oldValue[#Int#]; +// IMPLICIT_OLDVALUE_COPIED: End completions + } +} +var testImplicitOldValue2: Int = 0 { + didSet { + oldValue.#^IMPLICIT_OLDVALUE_MEMBER^# +// IMPLICIT_OLDVALUE_MEMBER: Begin completions +// IMPLICIT_OLDVALUE_MEMBER-DAG: Keyword[self]/CurrNominal: self[#Int#]; +// IMPLICIT_OLDVALUE_MEMBER: End completions + } +} +var testImplicitOldValue3: Int = 0 { + didSet { + var oldV = oldValue + oldV.#^IMPLICIT_OLDVALUE_COPIEDMEMBER^# +// IMPLICIT_OLDVALUE_COPIEDMEMBER: Begin completions +// IMPLICIT_OLDVALUE_COPIEDMEMBER-DAG: Keyword[self]/CurrNominal: self[#Int#]; +// IMPLICIT_OLDVALUE_COPIEDMEMBER: End completions + } +} + +var testExplicitOldValue1: Int = 0 { + didSet(oldVal) { + var oldV = oldVal + #^EXPLICIT_OLDVALUE_COPIED^# +// EXPLICIT_OLDVALUE_COPIED: Begin completions +// EXPLICIT_OLDVALUE_COPIED-NOT: oldValue +// EXPLICIT_OLDVALUE_COPIED-DAG: Decl[LocalVar]/Local: oldV[#Int#]; +// EXPLICIT_OLDVALUE_COPIED-DAG: Decl[LocalVar]/Local: oldVal[#Int#]; +// EXPLICIT_OLDVALUE_COPIED-NOT: oldValue +// EXPLICIT_OLDVALUE_COPIED: End completions + } +} +var testExplicitOldValue2: Int = 0 { + didSet(oldVal) { + oldVal.#^EXPLICIT_OLDVALUE_MEMBER^# +// EXPLICIT_OLDVALUE_MEMBER: Begin completions +// EXPLICIT_OLDVALUE_MEMBER-DAG: Keyword[self]/CurrNominal: self[#Int#]; +// EXPLICIT_OLDVALUE_MEMBER: End completions + } +} +var testExplicitOldValue3: Int = 0 { + didSet(oldVal) { + var oldV = oldVal + oldV.#^EXPLICIT_OLDVALUE_COPIEDMEMBER^# +// EXPLICIT_OLDVALUE_COPIEDMEMBER: Begin completions +// EXPLICIT_OLDVALUE_COPIEDMEMBER-DAG: Keyword[self]/CurrNominal: self[#Int#]; +// EXPLICIT_OLDVALUE_COPIEDMEMBER: End completions + } +} diff --git a/test/IDE/complete_multiple_trailingclosure.swift b/test/IDE/complete_multiple_trailingclosure.swift index 7dd053a267841..efef1d98aca64 100644 --- a/test/IDE/complete_multiple_trailingclosure.swift +++ b/test/IDE/complete_multiple_trailingclosure.swift @@ -15,6 +15,8 @@ // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_REQUIRED_NEWLINE_3 | %FileCheck %s -check-prefix=INIT_REQUIRED_NEWLINE_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_FALLBACK_1 | %FileCheck %s -check-prefix=INIT_FALLBACK // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_FALLBACK_2 | %FileCheck %s -check-prefix=INIT_FALLBACK +// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBERDECL_SAMELINE | %FileCheck %s -check-prefix=MEMBERDECL_SAMELINE +// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBERDECL_NEWLINE | %FileCheck %s -check-prefix=MEMBERDECL_NEWLINE func globalFunc1(fn1: () -> Int, fn2: () -> String) {} func testGlobalFunc() { @@ -207,3 +209,28 @@ func testFallbackPostfix() { 1 } #^INIT_FALLBACK_2^# } + +protocol P { + func foo() +} +struct TestNominalMember: P { + var value = MyStruct().method1 { 1 } #^MEMBERDECL_SAMELINE^# + #^MEMBERDECL_NEWLINE^# + +// MEMBERDECL_SAMELINE: Begin completions, 4 items +// MEMBERDECL_SAMELINE-DAG: Pattern/ExprSpecific: {#fn2: (() -> String)? {() -> String in|}#}[#(() -> String)?#]; name=fn2: (() -> String)? +// MEMBERDECL_SAMELINE-DAG: Decl[InstanceMethod]/CurrNominal: .enumFunc()[#Void#]; name=enumFunc() +// MEMBERDECL_SAMELINE-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]/IsSystem: [' ']+ {#SimpleEnum#}[#SimpleEnum#]; name=+ SimpleEnum +// MEMBERDECL_SAMELINE-DAG: Keyword[self]/CurrNominal: .self[#SimpleEnum#]; name=self +// MEMBERDECL_SAMELINE: End completions + +// MEMBERDECL_NEWLINE: Begin completions +// MEMBERDECL_NEWLINE-DAG: Pattern/ExprSpecific: {#fn2: (() -> String)? {() -> String in|}#}[#(() -> String)?#]; name=fn2: (() -> String)? +// MEMBERDECL_NEWLINE-DAG: Keyword[enum]/None: enum; name=enum +// MEMBERDECL_NEWLINE-DAG: Keyword[func]/None: func; name=func +// MEMBERDECL_NEWLINE-DAG: Keyword[private]/None: private; name=private +// MEMBERDECL_NEWLINE-DAG: Keyword/None: lazy; name=lazy +// MEMBERDECL_NEWLINE-DAG: Keyword[var]/None: var; name=var +// MEMBERDECL_NEWLINE-DAG: Decl[InstanceMethod]/Super: func foo() {|}; name=foo() +// MEMBERDECL_NEWLINE: End completions +} diff --git a/test/IRGen/class_update_callback_without_fixed_layout.sil b/test/IRGen/class_update_callback_without_fixed_layout.sil index a905c46986b8b..7c95a5a104894 100644 --- a/test/IRGen/class_update_callback_without_fixed_layout.sil +++ b/test/IRGen/class_update_callback_without_fixed_layout.sil @@ -5,6 +5,7 @@ // RUN: %target-swift-frontend -I %t -emit-ir -enable-library-evolution -O %s -target %target-pre-stable-abi-triple // REQUIRES: objc_interop +// UNSUPPORTED: OS=iosmac // UNSUPPORTED: CPU=arm64e // With the old deployment target, these classes use the 'singleton' metadata diff --git a/test/IRGen/eager-class-initialization.swift b/test/IRGen/eager-class-initialization.swift index c3d0bf4bc705d..53b172256bca3 100644 --- a/test/IRGen/eager-class-initialization.swift +++ b/test/IRGen/eager-class-initialization.swift @@ -3,6 +3,7 @@ // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %s -emit-ir -target %target-pre-stable-abi-triple | %FileCheck %s -DINT=i%target-ptrsize --check-prefix=CHECK --check-prefix=CHECK-OLD // REQUIRES: objc_interop +// UNSUPPORTED: OS=iosmac // UNSUPPORTED: CPU=arm64e // See also eager-class-initialization-stable-abi.swift, for the stable ABI diff --git a/test/Interpreter/SDK/Accelerate.swift b/test/Interpreter/SDK/Accelerate.swift deleted file mode 100644 index 416e9d5a298f3..0000000000000 --- a/test/Interpreter/SDK/Accelerate.swift +++ /dev/null @@ -1,79 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test -// -// vU1024Divide() is only available on OS X. -// REQUIRES: OS=macosx - -import Accelerate - -extension vU1024: ExpressibleByIntegerLiteral, CustomStringConvertible, Equatable { - public init(integerLiteral: Int) { - var integerLiteral = integerLiteral - self.init() - memcpy(&self, &integerLiteral, MemoryLayout.size) - } - - init(_ int: Int) { - self.init(integerLiteral: int) - } - - public var description: String { - if self == 0 { - return "0" - } - var digits: [Character] = [] - var intermediate = self - var digit: vU1024 = 0 - repeat { - (intermediate, digit) = quorem(intermediate, 10) - digits.append(Character(UnicodeScalar(Int(digit) + 48)!)) - } while intermediate != 0 - return String(digits.reversed()) - } -} - -extension Int { - init(_ u1024: vU1024) { - var u1024 = u1024 - // NB: Doesn't overflow check - self.init() - memcpy(&self, &u1024, MemoryLayout.size) - } -} - -func *(x: vU1024, y: vU1024) -> vU1024 { - var x = x - var y = y - var result = vU1024() - vU1024HalfMultiply(&x, &y, &result) - return result -} - -func quorem(_ x: vU1024, _ y: vU1024) -> (vU1024, vU1024) { - var x = x - var y = y - var quo = vU1024() - var rem = vU1024() - vU1024Divide(&x, &y, &quo, &rem) - return (quo, rem) -} - -public func ==(x: vU1024, y: vU1024) -> Bool { - var x = x - var y = y - return memcmp(&x, &y, MemoryLayout.size) == 0 -} - -func factorial(_ x: Int) -> vU1024 { - var result: vU1024 = 1 - - for i in 1...x { - result = result * vU1024(i) - } - - return result -} - -// CHECK: 7257415615307998967396728211129263114716991681296451376543577798900561843401706157852350749242617459511490991237838520776666022565442753025328900773207510902400430280058295603966612599658257104398558294257568966313439612262571094946806711205568880457193340212661452800000000000000000000000000000000000000000 -print(factorial(170)) - diff --git a/test/Interpreter/SDK/CGImportAsMember.swift b/test/Interpreter/SDK/CGImportAsMember.swift index e829d6e7db785..da1472f84a113 100644 --- a/test/Interpreter/SDK/CGImportAsMember.swift +++ b/test/Interpreter/SDK/CGImportAsMember.swift @@ -12,9 +12,9 @@ class Colors { class func printColors() { print("Colors") // CHECK: Colors - print(black) // CHECK: Generic Gray Profile - print(white) // CHECK: Generic Gray Profile - print(clear) // CHECK: Generic Gray Profile + print(black) // CHECK: Generic Gray + print(white) // CHECK: Generic Gray + print(clear) // CHECK: Generic Gray } } diff --git a/test/Interpreter/SDK/UIActionSheetHack.swift b/test/Interpreter/SDK/UIActionSheetHack.swift deleted file mode 100644 index 442ff55d494a7..0000000000000 --- a/test/Interpreter/SDK/UIActionSheetHack.swift +++ /dev/null @@ -1,45 +0,0 @@ -// RUN: %target-run-simple-swift | %FileCheck %s -// REQUIRES: executable_test -// REQUIRES: OS=ios - -import UIKit - -let actionSheet = UIActionSheet(title: nil, delegate: nil, cancelButtonTitle: "ABC", destructiveButtonTitle: "DEF") - -// CHECK: {{$}} -print(actionSheet.description) -// CHECK-NEXT: 0 -print(actionSheet.destructiveButtonIndex) -// CHECK-NEXT: 2 -print(actionSheet.numberOfButtons) - - -let actionSheet2 = UIActionSheet(title: nil, delegate: nil, cancelButtonTitle: "ABC", destructiveButtonTitle: "DEF", otherButtonTitles: "G", "H") - -// CHECK: {{$}} -print(actionSheet2.description) -// CHECK-NEXT: 0 -print(actionSheet2.destructiveButtonIndex) -// CHECK-NEXT: 4 -print(actionSheet2.numberOfButtons) - - -let alertView = UIAlertView(title: "Error", message: "The operation completed successfully.", delegate: nil, cancelButtonTitle: "Abort") - -// CHECK: {{$}} -print(alertView.description) -// CHECK-NEXT: 0 -print(alertView.cancelButtonIndex) -// CHECK-NEXT: 1 -print(alertView.numberOfButtons) - - -let alertView2 = UIAlertView(title: "Error", message: "The operation completed successfully.", delegate: nil, cancelButtonTitle: "Abort", otherButtonTitles: "Cry", "Apologize") - -// CHECK: {{$}} -print(alertView2.description) -// CHECK-NEXT: 0 -print(alertView2.cancelButtonIndex) -// CHECK-NEXT: 3 -print(alertView2.numberOfButtons) - diff --git a/test/Interpreter/SDK/autolinking.swift b/test/Interpreter/SDK/autolinking.swift index 74391d2669a84..58a2504362158 100644 --- a/test/Interpreter/SDK/autolinking.swift +++ b/test/Interpreter/SDK/autolinking.swift @@ -36,7 +36,11 @@ if global() != 42 { let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: -2) if dlsym(RTLD_DEFAULT, "global") == nil { - print(String(cString: dlerror())) + if let err = dlerror() { + print(String(cString: err)) + } else { + print("Unknown dlsym error") + } exit(EXIT_FAILURE) } #endif diff --git a/test/Interpreter/generic_casts.swift b/test/Interpreter/generic_casts.swift index 99941a08524d6..ecace2ee16136 100644 --- a/test/Interpreter/generic_casts.swift +++ b/test/Interpreter/generic_casts.swift @@ -181,7 +181,7 @@ func nongenericAnyAsConditionalPAndPCSubConforming(type: Any.Type) -> Bool { func genericAnyAsConditional(type: Any.Type, to: T.Type, expected: Bool) -> Bool { // If we're testing against a runtime that doesn't have the fix this tests, // just pretend we got it right. - if #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) { + if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { return (type as? T.Type) != nil } else { return expected @@ -207,7 +207,7 @@ func nongenericAnyAsUnconditionalPAndPCSubConforming(type: Any.Type) -> Bool { return true } func genericAnyAsUnconditional(type: Any.Type, to: T.Type, expected: Bool) -> Bool { - if #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) { + if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { blackhole(type as! T.Type) } return true diff --git a/test/ModuleInterface/skip-override-keyword.swift b/test/ModuleInterface/skip-override-keyword.swift index fba0d20d5a2bb..f349dac2d11ec 100644 --- a/test/ModuleInterface/skip-override-keyword.swift +++ b/test/ModuleInterface/skip-override-keyword.swift @@ -2,13 +2,23 @@ // RUN: %target-swift-frontend -typecheck -module-name Foo -emit-module-interface-path %t/Foo.swiftinterface %s // RUN: %target-swift-frontend -compile-module-from-interface %t/Foo.swiftinterface -o %t/Foo.swiftmodule +// RUN: %target-swift-frontend -typecheck -enable-testing -module-name FooWithTesting -emit-module-interface-path %t/FooWithTesting.swiftinterface %s +// RUN: %target-swift-frontend -compile-module-from-interface %t/FooWithTesting.swiftinterface -o %t/FooWithTesting.swiftmodule + public class BaseClass { + init() { } var property: Int { return 1 } func doSomething() { } subscript(index: Int) -> Int { get { return 0 } set(newValue) {} } + @usableFromInline func doSomethingInline() {} + @usableFromInline func doSomethingUsableFromInline() {} } + public class DerivedClass: BaseClass { + public override init() { super.init() } public override var property : Int { return 0 } public override func doSomething() { } public override subscript(index: Int) -> Int { get {return 0} set(newValue) {} } + @inlinable public override func doSomethingInline() { super.doSomethingInline() } + @usableFromInline override func doSomethingUsableFromInline() { super.doSomethingUsableFromInline() } } diff --git a/test/PrintAsObjC/resilient-ancestry.swift b/test/PrintAsObjC/resilient-ancestry.swift index 2042d294208f2..12bbfcdcc9a74 100644 --- a/test/PrintAsObjC/resilient-ancestry.swift +++ b/test/PrintAsObjC/resilient-ancestry.swift @@ -11,6 +11,7 @@ // RUN: %check-in-clang %t/resilient.h -I %t // REQUIRES: objc_interop +// UNSUPPORTED: OS=iosmac // See also resilient-ancestry.swift, for the stable ABI deployment target test. diff --git a/test/Runtime/demangleToMetadata.swift b/test/Runtime/demangleToMetadata.swift index dd70eb3bd0575..0c11f12fa5e8e 100644 --- a/test/Runtime/demangleToMetadata.swift +++ b/test/Runtime/demangleToMetadata.swift @@ -441,7 +441,7 @@ DemangleToMetadataTests.test("Nested types in same-type-constrained extensions") // V !: P3 in InnerTEqualsConformsToP1 } -if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) { +if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { DemangleToMetadataTests.test("Round-trip with _mangledTypeName and _typeByName") { func roundTrip(_ type: T.Type) { let mangledName: String? = _mangledTypeName(type) diff --git a/test/SIL/Serialization/deserialize_appkit.sil b/test/SIL/Serialization/deserialize_appkit.sil deleted file mode 100644 index 59b1fbdfcd822..0000000000000 --- a/test/SIL/Serialization/deserialize_appkit.sil +++ /dev/null @@ -1,8 +0,0 @@ -// Make sure that we can deserialize AppKit. -// RUN: %target-sil-opt %platform-sdk-overlay-dir/AppKit.swiftmodule/%target-swiftmodule-name -module-name AppKit > /dev/null -// RUN: llvm-bcanalyzer %platform-sdk-overlay-dir/AppKit.swiftmodule/%target-swiftmodule-name | %FileCheck %s - -// REQUIRES: objc_interop -// REQUIRES: OS=macosx - -// CHECK-NOT: Unknown diff --git a/test/SILOptimizer/copyforward.sil b/test/SILOptimizer/copyforward.sil index 0223f35c370f1..e5238fc665aff 100644 --- a/test/SILOptimizer/copyforward.sil +++ b/test/SILOptimizer/copyforward.sil @@ -915,3 +915,43 @@ bb1: %v = tuple () return %v : $() } + +// Test an "illegal" reinitialization of a stack location. This +// happens because lowering .int_fma_FPIEEE32 knows that the type is +// trivial, so avoids deinitialization. rdar://64671864. +// +// Note: we have given up on enforcing known SIL-patterns in +// CopyForwarding. Instead, we just remove restructions whenever we see +// unexpected patterns. Eventually, we will replace it with an OSSA +// pass and enforce all assumptions about SIL patterns in the verifier. + +// CHECK-LABEL: sil @testCPF : $@convention(thin) (Float) -> @out Float { +// CHECK: bb0(%0 : $*Float, %1 : $Float): +// CHECK: [[TMP1:%.*]] = alloc_stack $Float +// CHECK: store %1 to [[TMP1]] : $*Float +// CHECK: [[TMP2:%.*]] = alloc_stack $Float +// CHECK-NOT: copy_addr +// CHECK: [[FMA:%.*]] = builtin "int_fma_FPIEEE32" +// CHECK: [[RESULT:%.*]] = struct $Float ([[FMA]] : $Builtin.FPIEEE32) +// CHECK: store [[RESULT]] to %0 : $*Float +// CHECK-NOT: copy_addr +// CHECK-NOT: destroy_addr +// CHECK-LABEL: } // end sil function 'testCPF' +sil @testCPF : $@convention(thin) (Float) -> @out Float { +bb0(%0 : $*Float, %1 : $Float): + %2 = alloc_stack $Float + store %1 to %2 : $*Float + %4 = alloc_stack $Float + copy_addr %2 to [initialization] %4 : $*Float + %6 = struct_extract %1 : $Float, #Float._value + %7 = builtin "int_fma_FPIEEE32"(%6 : $Builtin.FPIEEE32, %6 : $Builtin.FPIEEE32, %6 : $Builtin.FPIEEE32) : $Builtin.FPIEEE32 + %8 = struct $Float (%7 : $Builtin.FPIEEE32) + store %8 to %4 : $*Float + copy_addr %4 to [initialization] %0 : $*Float + destroy_addr %4 : $*Float + dealloc_stack %4 : $*Float + destroy_addr %2 : $*Float + dealloc_stack %2 : $*Float + %15 = tuple () + return %15 : $() +} diff --git a/test/SPI/implementation_only_spi_import_exposability.swift b/test/SPI/implementation_only_spi_import_exposability.swift deleted file mode 100644 index aa227d7704351..0000000000000 --- a/test/SPI/implementation_only_spi_import_exposability.swift +++ /dev/null @@ -1,46 +0,0 @@ -/// @_implementationOnly imported decls (SPI or not) should not be exposed in SPI. - -// RUN: %empty-directory(%t) -// RUN: %target-swift-frontend -emit-module -DLIB %s -module-name Lib -emit-module-path %t/Lib.swiftmodule -// RUN: %target-typecheck-verify-swift -DCLIENT -I %t - -#if LIB - -@_spi(A) public func spiFunc() {} - -@_spi(A) public struct SPIStruct { - public init() {} -} - -@_spi(A) public protocol SPIProtocol {} - -public func ioiFunc() {} - -public struct IOIStruct { - public init() {} -} - -public protocol IOIProtocol {} - -#elseif CLIENT - -@_spi(A) @_implementationOnly import Lib - -@_spi(B) public func leakSPIStruct(_ a: SPIStruct) -> SPIStruct { fatalError() } // expected-error 2 {{cannot use struct 'SPIStruct' here; 'Lib' has been imported as implementation-only}} -@_spi(B) public func leakIOIStruct(_ a: IOIStruct) -> IOIStruct { fatalError() } // expected-error 2 {{cannot use struct 'IOIStruct' here; 'Lib' has been imported as implementation-only}} - -public struct PublicStruct : IOIProtocol, SPIProtocol { // expected-error {{cannot use protocol 'IOIProtocol' here; 'Lib' has been imported as implementation-only}} -// expected-error @-1 {{cannot use protocol 'SPIProtocol' here; 'Lib' has been imported as implementation-only}} - public var spiStruct = SPIStruct() // expected-error {{cannot use struct 'SPIStruct' here; 'Lib' has been imported as implementation-only}} - public var ioiStruct = IOIStruct() // expected-error {{cannot use struct 'IOIStruct' here; 'Lib' has been imported as implementation-only}} - - @inlinable - public func publicInlinable() { - spiFunc() // expected-error {{global function 'spiFunc()' is '@_spi' and cannot be referenced from an '@inlinable' function}} - ioiFunc() // expected-error {{global function 'ioiFunc()' cannot be used in an '@inlinable' function because 'Lib' was imported implementation-only}} - let s = SPIStruct() // expected-error {{struct 'SPIStruct' is '@_spi' and cannot be referenced from an '@inlinable' function}} - let i = IOIStruct() // expected-error {{struct 'IOIStruct' cannot be used in an '@inlinable' function because 'Lib' was imported implementation-only}} - } -} - -#endif diff --git a/test/SourceKit/ConformingMethods/basic.swift b/test/SourceKit/ConformingMethods/basic.swift index 539664f08b035..35701bdefb7dc 100644 --- a/test/SourceKit/ConformingMethods/basic.swift +++ b/test/SourceKit/ConformingMethods/basic.swift @@ -26,5 +26,12 @@ func testing(obj: C) { let _ = obj. } -// RUN: %sourcekitd-test -req=conformingmethods -pos=26:14 %s -req-opts=expectedtypes='$s8MyModule7Target2PD;$s8MyModule7Target1PD' -- -module-name MyModule %s > %t.response +// RUN: %sourcekitd-test -req=conformingmethods -pos=26:14 -repeat-request=2 %s -req-opts=expectedtypes='$s8MyModule7Target2PD;$s8MyModule7Target1PD' -- -module-name MyModule %s > %t.response // RUN: %diff -u %s.response %t.response +// RUN: %sourcekitd-test -req=conformingmethods -pos=26:14 -repeat-request=2 %s -req-opts=expectedtypes='$s8MyModule7Target2PD;$s8MyModule7Target1PD',reuseastcontext=0 -- -module-name MyModule %s | %FileCheck %s --check-prefix=DISABLED + +// DISABLED-NOT: key.reuseastcontext +// DISABLED: key.members: [ +// DISABLED-NOT: key.reuseastcontext +// DISABLED: key.members: [ +// DISABLED-NOT: key.reuseastcontext diff --git a/test/SourceKit/ConformingMethods/basic.swift.response b/test/SourceKit/ConformingMethods/basic.swift.response index c21b7146cac75..1ed7aba0a8b18 100644 --- a/test/SourceKit/ConformingMethods/basic.swift.response +++ b/test/SourceKit/ConformingMethods/basic.swift.response @@ -18,3 +18,24 @@ } ] } +{ + key.typename: "C", + key.typeusr: "$s8MyModule1CCD", + key.members: [ + { + key.name: "methodForTarget1()", + key.sourcetext: "methodForTarget1()", + key.description: "methodForTarget1()", + key.typename: "ConcreteTarget1", + key.typeusr: "$s8MyModule15ConcreteTarget1VD" + }, + { + key.name: "methodForTarget2()", + key.sourcetext: "methodForTarget2()", + key.description: "methodForTarget2()", + key.typename: "ConcreteTarget2", + key.typeusr: "$s8MyModule15ConcreteTarget2VD" + } + ], + key.reusingastcontext: 1 +} diff --git a/test/SourceKit/CursorInfo/cursor_info_synthesized_refs.swift b/test/SourceKit/CursorInfo/cursor_info_synthesized_refs.swift new file mode 100644 index 0000000000000..bc13d438183d3 --- /dev/null +++ b/test/SourceKit/CursorInfo/cursor_info_synthesized_refs.swift @@ -0,0 +1,18 @@ +struct Foo { + let x: Int + let y: String + func perform(_ action: (Int, Int) -> ()) {} +} + +func test() { + let x = Foo.init(x: 2, y: "hello") + x.perform { + print($0 + $1) + } +} + +// RUN: %sourcekitd-test -req=cursor -pos=8:17 %s -- %s | %FileCheck -check-prefix=CHECK1 %s +// CHECK1: init(x: Int, y: String) + +// RUN: %sourcekitd-test -req=cursor -pos=10:15 %s -- %s | %FileCheck -check-prefix=CHECK2 %s +// CHECK2: let $0: Int diff --git a/test/SourceKit/Misc/mixed_completion_sequence.swift b/test/SourceKit/Misc/mixed_completion_sequence.swift new file mode 100644 index 0000000000000..ef7a5991280f5 --- /dev/null +++ b/test/SourceKit/Misc/mixed_completion_sequence.swift @@ -0,0 +1,41 @@ +protocol Target1 {} +protocol Target2 {} +protocol Target3 {} + +struct ConcreteTarget1 : Target1 {} +struct ConcreteTarget2 : Target2 {} +struct ConcreteTarget3 : Target3 {} + +protocol P { + associatedtype Assoc + func protocolMethod(asc: Assoc) -> Self +} +extension P { + func protocolMethod(asc: Assoc) -> Self { return self } +} +enum MyEnum { + case foo, bar +} + +class C : P { + typealias Assoc = String + static func staticMethod() -> Self {} + func instanceMethod(x: MyEnum) -> C {} + func methodForTarget1() -> ConcreteTarget1 {} + func methodForTarget2() -> ConcreteTarget2 {} +} + +func testing(obj: C) { + let _ = obj. +} +func testing(obj: C) { + let _ = obj.instanceMethod(x: ) +} + + +// RUN: %sourcekitd-test \ +// RUN: -req=complete -pos=29:14 %s -- %s -module-name MyModule == \ +// RUN: -req=conformingmethods -pos=29:14 -req-opts=expectedtypes='$s8MyModule7Target2PD;$s8MyModule7Target1PD' %s -- %s -module-name MyModule == \ +// RUN: -req=typecontextinfo -pos=32:33 %s -- %s -module-name MyModule == \ +// RUN: -req=complete -pos=29:14 %s -- %s -module-name MyModule > %t.response +// RUN: %diff -u %s.response %t.response diff --git a/test/SourceKit/Misc/mixed_completion_sequence.swift.response b/test/SourceKit/Misc/mixed_completion_sequence.swift.response new file mode 100644 index 0000000000000..daecf7b99587b --- /dev/null +++ b/test/SourceKit/Misc/mixed_completion_sequence.swift.response @@ -0,0 +1,215 @@ +{ + key.results: [ + { + key.kind: source.lang.swift.decl.function.operator.infix, + key.name: "!==", + key.sourcetext: " !== <#T##AnyObject?#>", + key.description: "!==", + key.typename: "Bool", + key.context: source.codecompletion.context.othermodule, + key.typerelation: source.codecompletion.typerelation.unknown, + key.num_bytes_to_erase: 0, + key.is_system: 1, + key.modulename: "Swift" + }, + { + key.kind: source.lang.swift.decl.function.operator.infix, + key.name: "===", + key.sourcetext: " === <#T##AnyObject?#>", + key.description: "===", + key.typename: "Bool", + key.context: source.codecompletion.context.othermodule, + key.typerelation: source.codecompletion.typerelation.unknown, + key.num_bytes_to_erase: 0, + key.is_system: 1, + key.modulename: "Swift" + }, + { + key.kind: source.lang.swift.decl.function.method.instance, + key.name: "instanceMethod(x:)", + key.sourcetext: ".instanceMethod(x: <#T##MyEnum#>)", + key.description: "instanceMethod(x: MyEnum)", + key.typename: "C", + key.context: source.codecompletion.context.thisclass, + key.typerelation: source.codecompletion.typerelation.unknown, + key.num_bytes_to_erase: 0, + key.associated_usrs: "s:8MyModule1CC14instanceMethod1xAcA0A4EnumO_tF", + key.modulename: "MyModule" + }, + { + key.kind: source.lang.swift.decl.function.method.instance, + key.name: "methodForTarget1()", + key.sourcetext: ".methodForTarget1()", + key.description: "methodForTarget1()", + key.typename: "ConcreteTarget1", + key.context: source.codecompletion.context.thisclass, + key.typerelation: source.codecompletion.typerelation.unknown, + key.num_bytes_to_erase: 0, + key.associated_usrs: "s:8MyModule1CC16methodForTarget1AA08ConcreteE0VyF", + key.modulename: "MyModule" + }, + { + key.kind: source.lang.swift.decl.function.method.instance, + key.name: "methodForTarget2()", + key.sourcetext: ".methodForTarget2()", + key.description: "methodForTarget2()", + key.typename: "ConcreteTarget2", + key.context: source.codecompletion.context.thisclass, + key.typerelation: source.codecompletion.typerelation.unknown, + key.num_bytes_to_erase: 0, + key.associated_usrs: "s:8MyModule1CC16methodForTarget2AA08ConcreteE0VyF", + key.modulename: "MyModule" + }, + { + key.kind: source.lang.swift.decl.function.method.instance, + key.name: "protocolMethod(asc:)", + key.sourcetext: ".protocolMethod(asc: <#T##String#>)", + key.description: "protocolMethod(asc: String)", + key.typename: "C", + key.context: source.codecompletion.context.superclass, + key.typerelation: source.codecompletion.typerelation.unknown, + key.num_bytes_to_erase: 0, + key.associated_usrs: "s:8MyModule1PPAAE14protocolMethod3ascx5AssocQz_tF", + key.modulename: "MyModule" + }, + { + key.kind: source.lang.swift.keyword, + key.name: "self", + key.sourcetext: ".self", + key.description: "self", + key.typename: "C", + key.context: source.codecompletion.context.thisclass, + key.typerelation: source.codecompletion.typerelation.unknown, + key.num_bytes_to_erase: 0 + } + ] +} +{ + key.typename: "C", + key.typeusr: "$s8MyModule1CCD", + key.members: [ + { + key.name: "methodForTarget1()", + key.sourcetext: "methodForTarget1()", + key.description: "methodForTarget1()", + key.typename: "ConcreteTarget1", + key.typeusr: "$s8MyModule15ConcreteTarget1VD" + }, + { + key.name: "methodForTarget2()", + key.sourcetext: "methodForTarget2()", + key.description: "methodForTarget2()", + key.typename: "ConcreteTarget2", + key.typeusr: "$s8MyModule15ConcreteTarget2VD" + } + ], + key.reusingastcontext: 1 +} +{ + key.results: [ + { + key.typename: "MyEnum", + key.typeusr: "$s8MyModule0A4EnumOD", + key.implicitmembers: [ + { + key.name: "foo", + key.sourcetext: "foo", + key.description: "foo" + }, + { + key.name: "bar", + key.sourcetext: "bar", + key.description: "bar" + } + ] + } + ], + key.reusingastcontext: 1 +} +{ + key.results: [ + { + key.kind: source.lang.swift.decl.function.operator.infix, + key.name: "!==", + key.sourcetext: " !== <#T##AnyObject?#>", + key.description: "!==", + key.typename: "Bool", + key.context: source.codecompletion.context.othermodule, + key.typerelation: source.codecompletion.typerelation.unknown, + key.num_bytes_to_erase: 0, + key.is_system: 1, + key.modulename: "Swift" + }, + { + key.kind: source.lang.swift.decl.function.operator.infix, + key.name: "===", + key.sourcetext: " === <#T##AnyObject?#>", + key.description: "===", + key.typename: "Bool", + key.context: source.codecompletion.context.othermodule, + key.typerelation: source.codecompletion.typerelation.unknown, + key.num_bytes_to_erase: 0, + key.is_system: 1, + key.modulename: "Swift" + }, + { + key.kind: source.lang.swift.decl.function.method.instance, + key.name: "instanceMethod(x:)", + key.sourcetext: ".instanceMethod(x: <#T##MyEnum#>)", + key.description: "instanceMethod(x: MyEnum)", + key.typename: "C", + key.context: source.codecompletion.context.thisclass, + key.typerelation: source.codecompletion.typerelation.unknown, + key.num_bytes_to_erase: 0, + key.associated_usrs: "s:8MyModule1CC14instanceMethod1xAcA0A4EnumO_tF", + key.modulename: "MyModule" + }, + { + key.kind: source.lang.swift.decl.function.method.instance, + key.name: "methodForTarget1()", + key.sourcetext: ".methodForTarget1()", + key.description: "methodForTarget1()", + key.typename: "ConcreteTarget1", + key.context: source.codecompletion.context.thisclass, + key.typerelation: source.codecompletion.typerelation.unknown, + key.num_bytes_to_erase: 0, + key.associated_usrs: "s:8MyModule1CC16methodForTarget1AA08ConcreteE0VyF", + key.modulename: "MyModule" + }, + { + key.kind: source.lang.swift.decl.function.method.instance, + key.name: "methodForTarget2()", + key.sourcetext: ".methodForTarget2()", + key.description: "methodForTarget2()", + key.typename: "ConcreteTarget2", + key.context: source.codecompletion.context.thisclass, + key.typerelation: source.codecompletion.typerelation.unknown, + key.num_bytes_to_erase: 0, + key.associated_usrs: "s:8MyModule1CC16methodForTarget2AA08ConcreteE0VyF", + key.modulename: "MyModule" + }, + { + key.kind: source.lang.swift.decl.function.method.instance, + key.name: "protocolMethod(asc:)", + key.sourcetext: ".protocolMethod(asc: <#T##String#>)", + key.description: "protocolMethod(asc: String)", + key.typename: "C", + key.context: source.codecompletion.context.superclass, + key.typerelation: source.codecompletion.typerelation.unknown, + key.num_bytes_to_erase: 0, + key.associated_usrs: "s:8MyModule1PPAAE14protocolMethod3ascx5AssocQz_tF", + key.modulename: "MyModule" + }, + { + key.kind: source.lang.swift.keyword, + key.name: "self", + key.sourcetext: ".self", + key.description: "self", + key.typename: "C", + key.context: source.codecompletion.context.thisclass, + key.typerelation: source.codecompletion.typerelation.unknown, + key.num_bytes_to_erase: 0 + } + ], + key.reusingastcontext: 1 +} diff --git a/test/SourceKit/TypeContextInfo/typecontext_basic.swift b/test/SourceKit/TypeContextInfo/typecontext_basic.swift index 79b262e788d04..def196cd861c4 100644 --- a/test/SourceKit/TypeContextInfo/typecontext_basic.swift +++ b/test/SourceKit/TypeContextInfo/typecontext_basic.swift @@ -25,5 +25,12 @@ func test(obj: C) { let _ = obj.foo(x: } -// RUN: %sourcekitd-test -req=typecontextinfo -pos=25:22 %s -- %s > %t.response +// RUN: %sourcekitd-test -req=typecontextinfo -repeat-request=2 -pos=25:22 %s -- %s > %t.response // RUN: %diff -u %s.response %t.response +// RUN: %sourcekitd-test -req=typecontextinfo -repeat-request=2 -pos=25:22 %s -req-opts=reuseastcontext=0 -- %s | %FileCheck %s --check-prefix=DISABLED + +// DISABLED-NOT: key.reuseastcontext +// DISABLED: key.results: [ +// DISABLED-NOT: key.reuseastcontext +// DISABLED: key.results: [ +// DISABLED-NOT: key.reuseastcontext diff --git a/test/SourceKit/TypeContextInfo/typecontext_basic.swift.response b/test/SourceKit/TypeContextInfo/typecontext_basic.swift.response index 83d5f4587e478..1f6373eb5ce08 100644 --- a/test/SourceKit/TypeContextInfo/typecontext_basic.swift.response +++ b/test/SourceKit/TypeContextInfo/typecontext_basic.swift.response @@ -58,3 +58,64 @@ } ] } +{ + key.results: [ + { + key.typename: "Direction", + key.typeusr: "$s17typecontext_basic9DirectionOD", + key.implicitmembers: [ + { + key.name: "east", + key.sourcetext: "east", + key.description: "east" + }, + { + key.name: "west", + key.sourcetext: "west", + key.description: "west" + }, + { + key.name: "vector(x:y:)", + key.sourcetext: "vector(x: <#T##Int#>, y: <#T##Int#>)", + key.description: "vector(x: Int, y: Int)" + }, + { + key.name: "distance(_:)", + key.sourcetext: "distance(<#T##Int#>)", + key.description: "distance(Int)" + } + ] + }, + { + key.typename: "Target", + key.typeusr: "$s17typecontext_basic6TargetVD", + key.implicitmembers: [ + { + key.name: "me", + key.sourcetext: "me", + key.description: "me", + key.doc.brief: "Mine." + }, + { + key.name: "you", + key.sourcetext: "you", + key.description: "you", + key.doc.brief: "Yours." + }, + { + key.name: "them", + key.sourcetext: "them", + key.description: "them", + key.doc.brief: "Theirs." + }, + { + key.name: "all", + key.sourcetext: "all", + key.description: "all", + key.doc.brief: "One for all." + } + ] + } + ], + key.reusingastcontext: 1 +} diff --git a/test/attr/attr_objc_resilience.swift b/test/attr/attr_objc_resilience.swift index 0afd4cefa6acd..0a27520191514 100644 --- a/test/attr/attr_objc_resilience.swift +++ b/test/attr/attr_objc_resilience.swift @@ -4,6 +4,7 @@ // RUN: %target-swift-frontend -typecheck -verify %s -I %t // REQUIRES: objc_interop +// UNSUPPORTED: OS=iosmac import Foundation import resilient_objc_class diff --git a/test/decl/protocol/conforms/nscoding.swift b/test/decl/protocol/conforms/nscoding.swift index 69f839bc0721c..c489407fb0ae8 100644 --- a/test/decl/protocol/conforms/nscoding.swift +++ b/test/decl/protocol/conforms/nscoding.swift @@ -8,6 +8,7 @@ // RUN: %FileCheck --check-prefix=NEGATIVE %s < %t/old.ast // REQUIRES: objc_interop +// UNSUPPORTED: OS=iosmac // UNSUPPORTED: CPU=arm64e // See also nscoding_stable_abi.swift, for the stable ABI deployment diff --git a/test/decl/var/function_builders_availability.swift b/test/decl/var/function_builders_availability.swift new file mode 100644 index 0000000000000..aa22b171f2144 --- /dev/null +++ b/test/decl/var/function_builders_availability.swift @@ -0,0 +1,86 @@ +// RUN: %swift -typecheck -verify -target %target-cpu-apple-macosx10.15 %s +// REQUIRES: OS=macosx + +enum Either { + case first(T) + case second(U) +} + +struct Do { + var value: T +} + +@_functionBuilder +struct TupleBuilder { + static func buildBlock(_ t1: T1) -> (T1) { + return (t1) + } + + static func buildBlock(_ t1: T1, _ t2: T2) -> (T1, T2) { + return (t1, t2) + } + + static func buildBlock(_ t1: T1, _ t2: T2, _ t3: T3) + -> (T1, T2, T3) { + return (t1, t2, t3) + } + + static func buildBlock(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4) + -> (T1, T2, T3, T4) { + return (t1, t2, t3, t4) + } + + static func buildBlock( + _ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5 + ) -> (T1, T2, T3, T4, T5) { + return (t1, t2, t3, t4, t5) + } + + static func buildDo(_ t1: T1) -> Do<(T1)> { + .init(value: t1) + } + + static func buildDo(_ t1: T1, _ t2: T2) -> Do<(T1, T2)> { + .init(value: (t1, t2)) + } + + static func buildDo(_ t1: T1, _ t2: T2, _ t3: T3) + -> Do<(T1, T2, T3)> { + .init(value: (t1, t2, t3)) + } + + static func buildIf(_ value: T?) -> T? { return value } + + static func buildEither(first value: T) -> Either { + return .first(value) + } + static func buildEither(second value: U) -> Either { + return .second(value) + } + + static func buildArray(_ array: [T]) -> [T] { return array } +} + +@available(macOS 10.14, *) +enum Option { + @available(macOS 10.15.4, *) + case best +} + +@TupleBuilder +func bestTuple() -> some Any { // expected-note{{add @available attribute to enclosing global function}} + "Hello" + Option.best // expected-error{{'best' is only available in macOS 10.15.4 or newer}} + // expected-note@-1{{add 'if #available' version check}} +} + +func tuplify(_ cond: Bool, @TupleBuilder body: (Bool) -> T) { + print(body(cond)) +} + +tuplify(true) { x in + x + "Hello" + Option.best // expected-error{{'best' is only available in macOS 10.15.4 or newer}} + // expected-note@-1{{add 'if #available' version check}} +} diff --git a/test/lit.cfg b/test/lit.cfg index a8ada3189a9db..33d2a27135e98 100644 --- a/test/lit.cfg +++ b/test/lit.cfg @@ -409,7 +409,7 @@ if kIsWindows: config.swift_driver_test_options)) ) else: config.substitutions.append( ('%swift_driver', "env SDKROOT= %r %s %s %s" % (config.swift, mcp_opt, config.swift_test_options, config.swift_driver_test_options)) ) - config.substitutions.append( ('%swiftc_driver', "env SDKROOT= %r -toolchain-stdlib-rpath %s %s %s" % (config.swiftc, mcp_opt, config.swift_test_options, config.swift_driver_test_options)) ) + config.substitutions.append( ('%swiftc_driver', "env SDKROOT= %r -toolchain-stdlib-rpath -Xlinker -rpath -Xlinker /usr/lib/swift %s %s %s" % (config.swiftc, mcp_opt, config.swift_test_options, config.swift_driver_test_options)) ) config.substitutions.append( ('%sil-opt', "%r %s %s" % (config.sil_opt, mcp_opt, config.sil_test_options)) ) config.substitutions.append( ('%sil-func-extractor', "%r %s" % (config.sil_func_extractor, mcp_opt)) ) config.substitutions.append( ('%sil-llvm-gen', "%r %s" % (config.sil_llvm_gen, mcp_opt)) ) @@ -849,7 +849,9 @@ if run_vendor == 'apple': config.target_build_swift = ( ("%s %s %s -F %r -toolchain-stdlib-rpath " + - "-Xlinker -rpath -Xlinker %r %s %s %s %s") % + "-Xlinker -rpath -Xlinker %r " + + "-Xlinker -rpath -Xlinker /usr/lib/swift " + + "%s %s %s %s") % (xcrun_prefix, config.swiftc, target_options, extra_frameworks_dir, "/tmp/swifttest-device/lib", @@ -886,7 +888,9 @@ if run_vendor == 'apple': (run_cpu, run_os, run_vers, clang_mcp_opt)) config.target_build_swift = ( - "%s %s %s -F %r -toolchain-stdlib-rpath %s %s %s %s" % + ("%s %s %s -F %r -toolchain-stdlib-rpath %s " + + "-Xlinker -rpath -Xlinker /usr/lib/swift " + + " %s %s %s") % (xcrun_prefix, config.swiftc, target_options, extra_frameworks_dir, sdk_overlay_linker_opt, config.swift_test_options, @@ -943,7 +947,9 @@ if run_vendor == 'apple': config.target_build_swift = ( ("%s %s %s %s -F %r -toolchain-stdlib-rpath " - + "-Xlinker -rpath -Xlinker %r %s %s %s %s " + + "-Xlinker -rpath -Xlinker %r " + + "-Xlinker -rpath -Xlinker /usr/lib/swift " + + "%s %s %s %s " + "-F %r -Xlinker -rpath -Xlinker %r") % (xcrun_prefix, config.swiftc, target_options, maccatalyst_frameworks_component, @@ -1007,7 +1013,8 @@ if run_vendor == 'apple': subst_target_swift_ide_test_mock_sdk_after = \ target_options_for_mock_sdk_after config.target_swiftc_driver = ( - "%s %s -toolchain-stdlib-rpath %s" % + ("%s %s -toolchain-stdlib-rpath %s " + + "-Xlinker -rpath -Xlinker /usr/lib/swift ")% (xcrun_prefix, config.swiftc, target_options)) config.target_clang = ( "%s clang++ %s" % diff --git a/test/stdlib/AVFoundation_Swift4.swift b/test/stdlib/AVFoundation_Swift4.swift deleted file mode 100644 index 9c57d2dd7b795..0000000000000 --- a/test/stdlib/AVFoundation_Swift4.swift +++ /dev/null @@ -1,84 +0,0 @@ -// RUN: %empty-directory(%t) -// RUN: %target-build-swift -swift-version 4 %s -o %t/a.out -// RUN: %target-codesign %t/a.out -// RUN: %target-run %t/a.out -// REQUIRES: objc_interop -// REQUIRES: executable_test -// CoreMedia is not present on watchOS. -// UNSUPPORTED: OS=watchos - -import AVFoundation -import StdlibUnittest - -var AVFoundationTests = TestSuite("AVFoundation_Swift4") - -let pixelFormat = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange - -#if os(macOS) || os(iOS) - -if #available(iOS 5, *) { - AVFoundationTests.test("AVCaptureVideoDataOutput.availableVideoPixelFormatTypes") { - func f(v: AVCaptureVideoDataOutput) -> Bool { - return v.availableVideoPixelFormatTypes.contains(pixelFormat) - } - } -} - -#endif - -#if os(iOS) - -if #available(iOS 7, *) { - AVFoundationTests.test("AVMetadataMachineReadableCodeObject.corners") { - func f(m: AVMetadataMachineReadableCodeObject) -> Bool { - if let c = m.corners.first { - return c.x == 0 - } - return false - } - } -} - -if #available(iOS 10, *) { - AVFoundationTests.test("AVCaptureDevice.Format.supportedColorSpaces") { - func f(df: AVCaptureDevice.Format) -> Bool { - return df.supportedColorSpaces.contains(.sRGB) - } - } - - AVFoundationTests.test("AVCapturePhotoOutput.supportedFlashModes") { - func f(p: AVCapturePhotoOutput) -> Bool { - return p.supportedFlashModes.contains(.off) - } - } - - AVFoundationTests.test("AVCapturePhotoOutput.availablePhotoPixelFormatTypes") { - func f(p: AVCapturePhotoOutput) -> Bool { - return p.availablePhotoPixelFormatTypes.contains(pixelFormat) - } - } - - AVFoundationTests.test("AVCapturePhotoOutput.availableRawPhotoPixelFormatTypes") { - func f(p: AVCapturePhotoOutput) -> Bool { - return p.availableRawPhotoPixelFormatTypes.contains(pixelFormat) - } - } - - AVFoundationTests.test("AVCapturePhotoSettings.availablePreviewPhotoPixelFormatTypes") { - func f(p: AVCapturePhotoSettings) -> Bool { - return p.availablePreviewPhotoPixelFormatTypes.contains(pixelFormat) - } - } -} - -if #available(iOS 11, *) { - AVFoundationTests.test("AVCaptureSynchronizedDataCollection.makeIterator()") { - func f(c: AVCaptureSynchronizedDataCollection) { - for _ in c {} - } - } -} - -#endif - -runAllTests() diff --git a/test/stdlib/Accelerate.swift b/test/stdlib/Accelerate.swift deleted file mode 100644 index 7211442e50cec..0000000000000 --- a/test/stdlib/Accelerate.swift +++ /dev/null @@ -1,580 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var AccelerateTests = TestSuite("Accelerate") - -if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 4.0, *) { - - AccelerateTests.test("BNNS/ImageStackDescriptor") { - var succeed = BNNSImageStackDescriptor(width: 0, height: 0, channels: 0, - row_stride: 0, image_stride: 0, - data_type: .int8) - expectEqual(succeed.data_scale, 1) - expectEqual(succeed.data_bias, 0) - succeed = BNNSImageStackDescriptor(width: 0, height: 0, channels: 0, - row_stride: 0, image_stride: 0, - data_type: .int16, - data_scale: 0.5, data_bias: 0.5) - expectEqual(succeed.data_scale, 0.5) - expectEqual(succeed.data_bias, 0.5) - expectCrashLater() - // indexed8 is not allowed as an imageStack data type. - let _ = BNNSImageStackDescriptor(width: 0, height: 0, channels: 0, - row_stride: 0, image_stride: 0, - data_type: .indexed8) - } - - AccelerateTests.test("BNNS/VectorDescriptor") { - var succeed = BNNSVectorDescriptor(size: 0, data_type: .int8) - expectEqual(succeed.data_scale, 1) - expectEqual(succeed.data_bias, 0) - succeed = BNNSVectorDescriptor(size: 0, data_type: .int8, - data_scale: 0.5, data_bias: 0.5) - expectEqual(succeed.data_scale, 0.5) - expectEqual(succeed.data_bias, 0.5) - expectCrashLater() - // indexed8 is not allowed as a vector data type. - let _ = BNNSVectorDescriptor(size: 0, data_type: .indexed8) - } - - AccelerateTests.test("BNNS/LayerData") { - // The zero layer should have data == nil. - expectEqual(BNNSLayerData.zero.data, nil) - var succeed = BNNSLayerData(data: nil, data_type: .int8) - expectEqual(succeed.data_scale, 1) - expectEqual(succeed.data_bias, 0) - succeed = BNNSLayerData(data: nil, data_type: .int8, data_scale: 0.5, - data_bias: 0.5, data_table: nil) - expectEqual(succeed.data_scale, 0.5) - expectEqual(succeed.data_bias, 0.5) - var table: [Float] = [1.0] - succeed = BNNSLayerData.indexed8(data: nil, data_table: &table) - expectCrashLater() - // indexed8 requires a non-nil data table. - let _ = BNNSLayerData(data: nil, data_type: .indexed8) - } - - AccelerateTests.test("BNNS/Activation") { - expectEqual(BNNSActivation.identity.function, .identity) - let id = BNNSActivation(function: .identity) - expectTrue(id.alpha.isNaN) - expectTrue(id.beta.isNaN) - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP Discrete Cosine Transform -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let n = 1024 - - AccelerateTests.test("vDSP/DiscreteCosineTransform") { - - let source = (0 ..< n).map{ i in - return sin(Float(i) * 0.05) + sin(Float(i) * 0.025) - } - - for transformType in vDSP.DCTTransformType.allCases { - - let dct = vDSP.DCT(count: n, - transformType: transformType) - - var destination = [Float](repeating: 0, - count: n) - - dct?.transform(source, - result: &destination) - - let returnedResult = dct!.transform(source) - - // Legacy API - - let legacySetup = vDSP_DCT_CreateSetup(nil, - vDSP_Length(n), - transformType.dctType)! - - var legacyDestination = [Float](repeating: -1, - count: n) - - vDSP_DCT_Execute(legacySetup, - source, - &legacyDestination) - - expectTrue(elementsAlmostEqual(destination, legacyDestination)) - expectTrue(elementsAlmostEqual(destination, returnedResult)) - } - } -} - -//===----------------------------------------------------------------------===// -// -// Sliding window summation -// -//===----------------------------------------------------------------------===// -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - AccelerateTests.test("vDSP/SinglePrecisionSlidingWindowSum") { - let source: [Float] = [1, 10, 12, 9, 3, 7, 2, 6] - var destination = [Float](repeating: .nan, count: 6) - - vDSP.slidingWindowSum(source, - usingWindowLength: 3, - result: &destination) - - let returnedResult = vDSP.slidingWindowSum(source, - usingWindowLength: 3) - - expectTrue(elementsAlmostEqual(destination, returnedResult)) - expectTrue(destination.map{ Int($0) }.elementsEqual([23, 31, 24, 19, 12, 15])) - } - - AccelerateTests.test("vDSP/DoublePrecisionSlidingWindowSum") { - let source: [Double] = [1, 10, 12, 9, 3, 7, 2, 6] - var destination = [Double](repeating: .nan, count: 6) - - vDSP.slidingWindowSum(source, - usingWindowLength: 3, - result: &destination) - - let returnedResult = vDSP.slidingWindowSum(source, - usingWindowLength: 3) - - expectTrue(elementsAlmostEqual(destination, returnedResult)) - expectTrue(destination.map{ Int($0) }.elementsEqual([23, 31, 24, 19, 12, 15])) - } - -} - -//===----------------------------------------------------------------------===// -// -// Linear interpolation -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let n = 1024 - - AccelerateTests.test("vDSP/SinglePrecisionInterpolateBetweenVectors") { - var result = [Float](repeating: 0, count: n) - var legacyResult = [Float](repeating: -1, count: n) - - let a: [Float] = (0 ..< n).map{ i in - return sin(Float(i) * 0.025) - } - - let b: [Float] = (0 ..< n).map{ i in - return sin(Float(i) * 0.05) - } - - let interpolationConstant: Float = 0.5 - - vDSP.linearInterpolate(a, b, - using: interpolationConstant, - result: &result) - - vDSP_vintb(a, 1, - b, 1, - [interpolationConstant], - &legacyResult, 1, - vDSP_Length(n)) - - let returnedResult = vDSP.linearInterpolate(a, b, - using: interpolationConstant) - - expectTrue(elementsAlmostEqual(result, legacyResult)) - expectTrue(elementsAlmostEqual(result, returnedResult)) - } - - AccelerateTests.test("vDSP/SinglePrecisionInterpolateBetweenNeighbours") { - var result = [Float](repeating: 0, count: n) - var legacyResult = [Float](repeating: -1, count: n) - - let shortSignal: [Float] = (0 ... 10).map{ i in - return sin(Float(i) * 0.1 * .pi * 4) - } - - let controlVector: [Float] = { - var controlVector = [Float](repeating: 0, count: 1024) - - vDSP_vgen([0], - [Float(shortSignal.count)], - &controlVector, 1, - vDSP_Length(n)) - - return controlVector - }() - - vDSP.linearInterpolate(elementsOf: shortSignal, - using: controlVector, - result: &result) - - vDSP_vlint(shortSignal, - controlVector, 1, - &legacyResult, 1, - vDSP_Length(n), - vDSP_Length(shortSignal.count)) - - let returnedResult = vDSP.linearInterpolate(elementsOf: shortSignal, - using: controlVector) - - expectTrue(elementsAlmostEqual(result, legacyResult)) - expectTrue(elementsAlmostEqual(result, returnedResult)) - } - - AccelerateTests.test("vDSP/DoublePrecisionInterpolateBetweenVectors") { - var result = [Double](repeating: 0, count: n) - var legacyResult = [Double](repeating: -1, count: n) - - let a: [Double] = (0 ..< n).map{ i in - return sin(Double(i) * 0.025) - } - - let b: [Double] = (0 ..< n).map{ i in - return sin(Double(i) * 0.05) - } - - let interpolationConstant: Double = 0.5 - - vDSP.linearInterpolate(a, b, - using: interpolationConstant, - result: &result) - - vDSP_vintbD(a, 1, - b, 1, - [interpolationConstant], - &legacyResult, 1, - vDSP_Length(n)) - - let returnedResult = vDSP.linearInterpolate(a, b, - using: interpolationConstant) - - expectTrue(elementsAlmostEqual(result, legacyResult)) - expectTrue(elementsAlmostEqual(result, returnedResult)) - } - - AccelerateTests.test("vDSP/DoublePrecisionInterpolateBetweenNeighbours") { - var result = [Double](repeating: 0, count: n) - var legacyResult = [Double](repeating: -1, count: n) - - let shortSignal: [Double] = (0 ... 10).map{ i in - return sin(Double(i) * 0.1 * .pi * 4) - } - - let controlVector: [Double] = { - var controlVector = [Double](repeating: 0, count: 1024) - - vDSP_vgenD([0], - [Double(shortSignal.count)], - &controlVector, 1, - vDSP_Length(n)) - - return controlVector - }() - - vDSP.linearInterpolate(elementsOf: shortSignal, - using: controlVector, - result: &result) - - vDSP_vlintD(shortSignal, - controlVector, 1, - &legacyResult, 1, - vDSP_Length(n), - vDSP_Length(shortSignal.count)) - - let returnedResult = vDSP.linearInterpolate(elementsOf: shortSignal, - using: controlVector) - - expectTrue(elementsAlmostEqual(result, legacyResult)) - expectTrue(elementsAlmostEqual(result, returnedResult)) - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP difference equation -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - AccelerateTests.test("vDSP/DifferenceEquationSinglePrecision") { - let n = 256 - - let source: [Float] = (0 ..< n).map { - return sin(Float($0) * 0.05).sign == .minus ? -1 : 1 - } - var result = [Float](repeating: 0, count: n) - var legacyResult = [Float](repeating: -1, count: n) - - let coefficients: [Float] = [0.0, 0.1, 0.2, 0.4, 0.8] - - vDSP.twoPoleTwoZeroFilter(source, - coefficients: (coefficients[0], - coefficients[1], - coefficients[2], - coefficients[3], - coefficients[4]), - result: &result) - - legacyResult[0] = 0 - legacyResult[1] = 0 - - vDSP_deq22(source, 1, - coefficients, - &legacyResult, 1, - vDSP_Length(n-2)) - - let returnedResult = vDSP.twoPoleTwoZeroFilter(source, - coefficients: (coefficients[0], - coefficients[1], - coefficients[2], - coefficients[3], - coefficients[4])) - - expectTrue(elementsAlmostEqual(result, legacyResult)) - expectTrue(elementsAlmostEqual(result, returnedResult)) - } - - AccelerateTests.test("vDSP/DifferenceEquationDoublePrecision") { - let n = 256 - - let source: [Double] = (0 ..< n).map { - return sin(Double($0) * 0.05).sign == .minus ? -1 : 1 - } - var result = [Double](repeating: 0, count: n) - var legacyResult = [Double](repeating: -1, count: n) - - let coefficients: [Double] = [0.0, 0.1, 0.2, 0.4, 0.8] - - vDSP.twoPoleTwoZeroFilter(source, - coefficients: (coefficients[0], - coefficients[1], - coefficients[2], - coefficients[3], - coefficients[4]), - result: &result) - - legacyResult[0] = 0 - legacyResult[1] = 0 - - vDSP_deq22D(source, 1, - coefficients, - &legacyResult, 1, - vDSP_Length(n-2)) - - let returnedResult = vDSP.twoPoleTwoZeroFilter(source, - coefficients: (coefficients[0], - coefficients[1], - coefficients[2], - coefficients[3], - coefficients[4])) - - expectTrue(elementsAlmostEqual(result, legacyResult)) - expectTrue(elementsAlmostEqual(result, returnedResult)) - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP downsampling -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - AccelerateTests.test("vDSP/DownsampleSinglePrecision") { - let decimationFactor = 2 - let filterLength: vDSP_Length = 2 - let filter = [Float](repeating: 1 / Float(filterLength), - count: Int(filterLength)) - - let originalSignal: [Float] = [10, 15, 20, 25, 50, 25, 20, 15, 10, - 10, 15, 20, 25, 50, 25, 20, 15, 10] - - let inputLength = vDSP_Length(originalSignal.count) - - let n = vDSP_Length((inputLength - filterLength) / vDSP_Length(decimationFactor)) + 1 - - var result = [Float](repeating: 0, - count: Int(n)) - - - vDSP.downsample(originalSignal, - decimationFactor: decimationFactor, - filter: filter, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: Int(n)) - - vDSP_desamp(originalSignal, - decimationFactor, - filter, - &legacyResult, - n, - filterLength) - - let returnedResult = vDSP.downsample(originalSignal, - decimationFactor: decimationFactor, - filter: filter) - - expectTrue(elementsAlmostEqual(result, legacyResult)) - expectTrue(elementsAlmostEqual(result, returnedResult)) - } - - AccelerateTests.test("vDSP/DownsampleDoublePrecision") { - let decimationFactor = 2 - let filterLength: vDSP_Length = 2 - let filter = [Double](repeating: 1 / Double(filterLength), - count: Int(filterLength)) - - let originalSignal: [Double] = [10, 15, 20, 25, 50, 25, 20, 15, 10, - 10, 15, 20, 25, 50, 25, 20, 15, 10] - - let inputLength = vDSP_Length(originalSignal.count) - - let n = vDSP_Length((inputLength - filterLength) / vDSP_Length(decimationFactor)) + 1 - - var result = [Double](repeating: 0, - count: Int(n)) - - - vDSP.downsample(originalSignal, - decimationFactor: decimationFactor, - filter: filter, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: Int(n)) - - vDSP_desampD(originalSignal, - decimationFactor, - filter, - &legacyResult, - n, - filterLength) - - let returnedResult = vDSP.downsample(originalSignal, - decimationFactor: decimationFactor, - filter: filter) - - expectTrue(elementsAlmostEqual(result, legacyResult)) - expectTrue(elementsAlmostEqual(result, returnedResult)) - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP polynomial evaluation. -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - AccelerateTests.test("vDSP/PolynomialEvaluationSinglePrecision") { - let coefficients: [Float] = [2, 3, 4, 5, 6, 7, 8, 9, 10] - let variables = (0 ... 100).map { return Float($0) } - var result = [Float](repeating: 0, count: variables.count) - - vDSP.evaluatePolynomial(usingCoefficients: coefficients, - withVariables: variables, - result: &result) - - var legacyResult = [Float](repeating: -1, count: variables.count) - - vDSP_vpoly(coefficients, 1, - variables, 1, - &legacyResult, 1, - vDSP_Length(legacyResult.count), - vDSP_Length(coefficients.count - 1)) - - let returnedResult = vDSP.evaluatePolynomial(usingCoefficients: coefficients, - withVariables: variables) - - expectTrue(elementsAlmostEqual(result, legacyResult)) - expectTrue(elementsAlmostEqual(result, returnedResult)) - } - - AccelerateTests.test("vDSP/PolynomialEvaluationDoublePrecision") { - let coefficients: [Double] = [2, 3, 4, 5, 6, 7, 8, 9, 10] - let variables = (0 ... 100).map { return Double($0) } - var result = [Double](repeating: 0, count: variables.count) - - vDSP.evaluatePolynomial(usingCoefficients: coefficients, - withVariables: variables, - result: &result) - - var legacyResult = [Double](repeating: -1, count: variables.count) - - vDSP_vpolyD(coefficients, 1, - variables, 1, - &legacyResult, 1, - vDSP_Length(legacyResult.count), - vDSP_Length(coefficients.count - 1)) - - let returnedResult = vDSP.evaluatePolynomial(usingCoefficients: coefficients, - withVariables: variables) - - expectTrue(elementsAlmostEqual(result, legacyResult)) - expectTrue(elementsAlmostEqual(result, returnedResult)) - } -} - -//===----------------------------------------------------------------------===// -// -// Array almost equal. -// -//===----------------------------------------------------------------------===// - -func elementsAlmostEqual(_ lhs: [T], _ rhs: [T]) -> Bool { - var returnValue = true - zip(lhs, rhs).forEach { - if !isAlmostEqual($0.0, $0.1) { - returnValue = false - return - } - } - return returnValue -} - -func isAlmostEqual(_ lhs: T, - _ rhs: T, - tolerance: T = T.ulpOfOne.squareRoot()) -> Bool { - assert(tolerance >= .ulpOfOne && tolerance < 1, "tolerance should be in [.ulpOfOne, 1).") - guard lhs.isFinite && rhs.isFinite else { - return rescaledAlmostEqual(lhs, rhs, tolerance: tolerance) - } - let scale = max(abs(lhs), abs(rhs), .leastNormalMagnitude) - return abs(lhs - rhs) < scale*tolerance -} - -func rescaledAlmostEqual(_ lhs: T, - _ rhs: T, - tolerance: T) -> Bool { - if lhs.isNaN || rhs.isNaN { return false } - if lhs.isInfinite { - if rhs.isInfinite { return lhs == rhs } - let scaledLhs = T(sign: lhs.sign, - exponent: T.greatestFiniteMagnitude.exponent, - significand: 1) - let scaledRhs = T(sign: .plus, - exponent: -1, - significand: rhs) - return isAlmostEqual(scaledLhs, scaledRhs, tolerance: tolerance) - } - return rescaledAlmostEqual(rhs, lhs, tolerance: tolerance) -} - -runAllTests() - diff --git a/test/stdlib/Accelerate_Quadrature.swift b/test/stdlib/Accelerate_Quadrature.swift deleted file mode 100644 index 8ac2861c6ebaa..0000000000000 --- a/test/stdlib/Accelerate_Quadrature.swift +++ /dev/null @@ -1,310 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var AccelerateQuadratureTests = TestSuite("Accelerate_Quadrature") - -//===----------------------------------------------------------------------===// -// -// Quadrature Tests -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - func vectorExp(x: UnsafeBufferPointer, - y: UnsafeMutableBufferPointer) { - let radius: Double = 12.5 - for i in 0 ..< x.count { - y[i] = sqrt(radius * radius - pow(x[i] - radius, 2)) - } - } - - AccelerateQuadratureTests.test("Quadrature/QNG") { - var diameter: Double = 25 - - // New API: Scalar - let quadrature = Quadrature(integrator: .nonAdaptive, - absoluteTolerance: 1.0e-8, - relativeTolerance: 1.0e-2) - - let result = quadrature.integrate(over: 0.0 ... diameter) { x in - let radius = diameter * 0.5 - return sqrt(radius * radius - pow(x - radius, 2)) - } - - // New API: Vectorized - let vQuadrature = Quadrature(integrator: .nonAdaptive, - absoluteTolerance: 1.0e-8, - relativeTolerance: 1.0e-2) - - let vRresult = vQuadrature.integrate(over: 0.0 ... diameter, - integrand: vectorExp) - - // Legacy API - var integrateFunction: quadrature_integrate_function = { - return quadrature_integrate_function( - fun: { (arg: UnsafeMutableRawPointer?, - n: Int, - x: UnsafePointer, - y: UnsafeMutablePointer - ) in - - guard let diameter = arg?.load(as: Double.self) else { - return - } - - let r = diameter * 0.5 - - (0 ..< n).forEach { i in - y[i] = sqrt(r * r - pow(x[i] - r, 2)) - } - }, - fun_arg: &diameter) - }() - - var options = quadrature_integrate_options(integrator: QUADRATURE_INTEGRATE_QNG, - abs_tolerance: 1.0e-8, - rel_tolerance: 1.0e-2, - qag_points_per_interval: 0, - max_intervals: 0) - - var status = QUADRATURE_SUCCESS - var legacyEstimatedAbsoluteError: Double = 0 - - let legacyResult = quadrature_integrate(&integrateFunction, - 0.0, - diameter, - &options, - &status, - &legacyEstimatedAbsoluteError, - 0, - nil) - - switch result { - case .success(let integralResult, let estimatedAbsoluteError): - expectEqual(integralResult, legacyResult) - expectEqual(estimatedAbsoluteError, legacyEstimatedAbsoluteError) - switch vRresult { - case .success(let vIntegralResult, let vEstimatedAbsoluteError): - expectEqual(integralResult, vIntegralResult) - expectEqual(estimatedAbsoluteError, vEstimatedAbsoluteError) - case .failure(_): - expectationFailure("Vectorized non-adaptive integration failed.", trace: "", - stackTrace: SourceLocStack()) - } - case .failure( _): - expectationFailure("Non-adaptive integration failed.", trace: "", - stackTrace: SourceLocStack()) - } - } - - AccelerateQuadratureTests.test("Quadrature/QAGS") { - var diameter: Double = 25 - - // New API - let quadrature = Quadrature(integrator: .adaptiveWithSingularities(maxIntervals: 11), - absoluteTolerance: 1.0e-8, - relativeTolerance: 1.0e-2) - - let result = quadrature.integrate(over: 0.0 ... diameter) { x in - let radius = diameter * 0.5 - return sqrt(radius * radius - pow(x - radius, 2)) - } - - // New API: Vectorized - let vQuadrature = Quadrature(integrator: .adaptiveWithSingularities(maxIntervals: 11), - absoluteTolerance: 1.0e-8, - relativeTolerance: 1.0e-2) - - let vRresult = vQuadrature.integrate(over: 0.0 ... diameter, - integrand: vectorExp) - - // Legacy API - var integrateFunction: quadrature_integrate_function = { - return quadrature_integrate_function( - fun: { (arg: UnsafeMutableRawPointer?, - n: Int, - x: UnsafePointer, - y: UnsafeMutablePointer - ) in - - guard let diameter = arg?.load(as: Double.self) else { - return - } - - let r = diameter * 0.5 - - (0 ..< n).forEach { i in - y[i] = sqrt(r * r - pow(x[i] - r, 2)) - } - }, - fun_arg: &diameter) - }() - - var options = quadrature_integrate_options(integrator: QUADRATURE_INTEGRATE_QAGS, - abs_tolerance: 1.0e-8, - rel_tolerance: 1.0e-2, - qag_points_per_interval: 0, - max_intervals: 11) - - var status = QUADRATURE_SUCCESS - var legacyEstimatedAbsoluteError = Double(0) - - let legacyResult = quadrature_integrate(&integrateFunction, - 0, - diameter, - &options, - &status, - &legacyEstimatedAbsoluteError, - 0, - nil) - - switch result { - case .success(let integralResult, let estimatedAbsoluteError): - expectEqual(integralResult, legacyResult) - expectEqual(estimatedAbsoluteError, legacyEstimatedAbsoluteError) - switch vRresult { - case .success(let vIntegralResult, let vEstimatedAbsoluteError): - expectEqual(integralResult, vIntegralResult) - expectEqual(estimatedAbsoluteError, vEstimatedAbsoluteError) - case .failure(_): - expectationFailure("Vectorized adaptive with singularities integration failed.", trace: "", - stackTrace: SourceLocStack()) - } - case .failure( _): - expectationFailure("Adaptive with singularities integration failed.", trace: "", - stackTrace: SourceLocStack()) - } - } - - AccelerateQuadratureTests.test("Quadrature/QAG") { - var diameter: Double = 25 - - // New API - let quadrature = Quadrature(integrator: .adaptive(pointsPerInterval: .sixtyOne, - maxIntervals: 7), - absoluteTolerance: 1.0e-8, - relativeTolerance: 1.0e-2) - - let result = quadrature.integrate(over: 0.0 ... diameter) { x in - let radius: Double = diameter * 0.5 - return sqrt(radius * radius - pow(x - radius, 2)) - } - - // New API: Vectorized - let vQuadrature = Quadrature(integrator: .adaptive(pointsPerInterval: .sixtyOne, - maxIntervals: 7), - absoluteTolerance: 1.0e-8, - relativeTolerance: 1.0e-2) - - let vRresult = vQuadrature.integrate(over: 0.0 ... diameter, - integrand: vectorExp) - - // Legacy API - var integrateFunction: quadrature_integrate_function = { - return quadrature_integrate_function( - fun: { (arg: UnsafeMutableRawPointer?, - n: Int, - x: UnsafePointer, - y: UnsafeMutablePointer - ) in - - guard let diameter = arg?.load(as: Double.self) else { - return - } - - let r = diameter * 0.5 - - (0 ..< n).forEach { i in - y[i] = sqrt(r * r - pow(x[i] - r, 2)) - } - }, - fun_arg: &diameter) - }() - - var options = quadrature_integrate_options(integrator: QUADRATURE_INTEGRATE_QAG, - abs_tolerance: 1.0e-8, - rel_tolerance: 1.0e-2, - qag_points_per_interval: 61, - max_intervals: 7) - - var status = QUADRATURE_SUCCESS - var legacyEstimatedAbsoluteError = Double(0) - - let legacyResult = quadrature_integrate(&integrateFunction, - 0, - diameter, - &options, - &status, - &legacyEstimatedAbsoluteError, - 0, - nil) - - switch result { - case .success(let integralResult, let estimatedAbsoluteError): - expectEqual(integralResult, legacyResult) - expectEqual(estimatedAbsoluteError, legacyEstimatedAbsoluteError) - switch vRresult { - case .success(let vIntegralResult, let vEstimatedAbsoluteError): - expectEqual(integralResult, vIntegralResult) - expectEqual(estimatedAbsoluteError, vEstimatedAbsoluteError) - case .failure(_): - expectationFailure("Vectorized adaptive integration failed.", trace: "", - stackTrace: SourceLocStack()) - } - case .failure( _): - expectationFailure("Adaptive integration failed.", trace: "", - stackTrace: SourceLocStack()) - } - } - - AccelerateQuadratureTests.test("Quadrature/ToleranceProperties") { - var quadrature = Quadrature(integrator: .qng, - absoluteTolerance: 1, - relativeTolerance: 2) - - expectEqual(quadrature.absoluteTolerance, 1) - expectEqual(quadrature.relativeTolerance, 2) - - quadrature.absoluteTolerance = 101 - quadrature.relativeTolerance = 102 - - expectEqual(quadrature.absoluteTolerance, 101) - expectEqual(quadrature.relativeTolerance, 102) - } - - AccelerateQuadratureTests.test("Quadrature/QAGPointsPerInterval") { - expectEqual(Quadrature.QAGPointsPerInterval.fifteen.points, 15) - expectEqual(Quadrature.QAGPointsPerInterval.twentyOne.points, 21) - expectEqual(Quadrature.QAGPointsPerInterval.thirtyOne.points, 31) - expectEqual(Quadrature.QAGPointsPerInterval.fortyOne.points, 41) - expectEqual(Quadrature.QAGPointsPerInterval.fiftyOne.points, 51) - expectEqual(Quadrature.QAGPointsPerInterval.sixtyOne.points, 61) - } - - AccelerateQuadratureTests.test("Quadrature/ErrorDescription") { - let a = Quadrature.Error(quadratureStatus: QUADRATURE_ERROR) - expectEqual(a.errorDescription, "Generic error.") - - let b = Quadrature.Error(quadratureStatus: QUADRATURE_INVALID_ARG_ERROR) - expectEqual(b.errorDescription, "Invalid Argument.") - - let c = Quadrature.Error(quadratureStatus: QUADRATURE_INTERNAL_ERROR) - expectEqual(c.errorDescription, "This is a bug in the Quadrature code, please file a bug report.") - - let d = Quadrature.Error(quadratureStatus: QUADRATURE_INTEGRATE_MAX_EVAL_ERROR) - expectEqual(d.errorDescription, "The requested accuracy limit could not be reached with the allowed number of evals/subdivisions.") - - let e = Quadrature.Error(quadratureStatus: QUADRATURE_INTEGRATE_BAD_BEHAVIOUR_ERROR) - expectEqual(e.errorDescription, "Extremely bad integrand behaviour, or excessive roundoff error occurs at some points of the integration interval.") - } -} - -runAllTests() diff --git a/test/stdlib/Accelerate_vDSPBiquad.swift b/test/stdlib/Accelerate_vDSPBiquad.swift deleted file mode 100644 index 26189cc92d343..0000000000000 --- a/test/stdlib/Accelerate_vDSPBiquad.swift +++ /dev/null @@ -1,262 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var Accelerate_vDSPBiquadTests = TestSuite("Accelerate_vDSPBiquad") - -//===----------------------------------------------------------------------===// -// -// vDSP Biquad Filters -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let n = 256 - - // low pass - let b0 = 0.0001 - let b1 = 0.001 - let b2 = 0.0005 - let a1 = -1.9795 - let a2 = 0.98 - - let sections = vDSP_Length(1) - - Accelerate_vDSPBiquadTests.test("vDSP/BiquadNil") { - let biquad = vDSP.Biquad(coefficients: [0.0], - channelCount: 9999, - sectionCount: 9999, - ofType: Float.self) - - expectTrue(biquad == nil) - } - - Accelerate_vDSPBiquadTests.test("vDSP/SingleChannelSinglePrecision") { - let channels = vDSP_Length(1) - - let signal: [Float] = (0 ..< n).map { i in - return sin(Float(i) * 0.1) + sin(Float(i) * 0.01) - } - - var biquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2], - channelCount: sections, - sectionCount: channels, - ofType: Float.self)! - - var returningBiquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2], - channelCount: sections, - sectionCount: channels, - ofType: Float.self)! - - var output = [Float](repeating: 0, - count: n) - - // Legacy... - var legacyOutput = [Float](repeating: -1, - count: n) - - var delays = [Float](repeating: 0.0, - count: Int(2 * sections) + 2) - - let setup = vDSP_biquad_CreateSetup([b0, b1, b2, a1, a2], - sections)! - - for _ in 0 ... 3 { - - biquad.apply(input: signal, - output: &output) - - let returnedOutput = returningBiquad.apply(input: signal) - - vDSP_biquad(setup, - &delays, - signal, 1, - &legacyOutput, 1, - vDSP_Length(n)) - - expectTrue(output.elementsEqual(legacyOutput)) - expectTrue(output.elementsEqual(returnedOutput)) - } - } - - Accelerate_vDSPBiquadTests.test("vDSP/MultiChannelSinglePrecision") { - let channelCount = vDSP_Length(2) - - let signal: [Float] = (0 ..< n).map { i in - return sin(Float(i) * 0.1) + sin(Float(i) * 0.01) - } - - var biquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2, - b0, b1, b2, a1, a2], - channelCount: channelCount, - sectionCount: sections, - ofType: Float.self)! - - var returningBiquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2, - b0, b1, b2, a1, a2], - channelCount: channelCount, - sectionCount: sections, - ofType: Float.self)! - - var output = [Float](repeating: 0, - count: n) - - // Legacy... - var legacyOutput = [Float](repeating: -1, - count: n) - - let setup = vDSP_biquadm_CreateSetup([b0, b1, b2, a1, a2, - b0, b1, b2, a1, a2], - vDSP_Length(sections), - vDSP_Length(channelCount))! - - for _ in 0 ... 3 { - - biquad.apply(input: signal, - output: &output) - - let returnedOutput = returningBiquad.apply(input: signal) - - signal.withUnsafeBufferPointer { inputBuffer in - let inputPointer = inputBuffer.baseAddress! - legacyOutput.withUnsafeMutableBufferPointer { outputBuffer in - let outputPointer = outputBuffer.baseAddress! - - let length = vDSP_Length(n) / channelCount - - var inputs: [UnsafePointer] = (0 ..< channelCount).map { i in - return inputPointer.advanced(by: Int(i * length)) - } - - var outputs: [UnsafeMutablePointer] = (0 ..< channelCount).map { i in - return outputPointer.advanced(by: Int(i * length)) - } - - vDSP_biquadm(setup, &inputs, 1, &outputs, 1, vDSP_Length(n) / channelCount) - } - } - - expectTrue(output.elementsEqual(legacyOutput)) - expectTrue(output.elementsEqual(returnedOutput)) - } - } - - Accelerate_vDSPBiquadTests.test("vDSP/SingleChannelDoublePrecision") { - let channels = vDSP_Length(1) - - let signal: [Double] = (0 ..< n).map { i in - return sin(Double(i) * 0.1) + sin(Double(i) * 0.01) - } - - var biquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2], - channelCount: sections, - sectionCount: channels, - ofType: Double.self)! - - var returningBiquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2], - channelCount: sections, - sectionCount: channels, - ofType: Double.self)! - - var output = [Double](repeating: 0, - count: n) - - // Legacy... - var legacyOutput = [Double](repeating: -1, - count: n) - - var delays = [Double](repeating: 0.0, - count: Int(2 * sections) + 2) - - let setup = vDSP_biquad_CreateSetupD([b0, b1, b2, a1, a2], - sections)! - - for _ in 0 ... 3 { - - biquad.apply(input: signal, - output: &output) - - let returnedOutput = returningBiquad.apply(input: signal) - - vDSP_biquadD(setup, - &delays, - signal, 1, - &legacyOutput, 1, - vDSP_Length(n)) - - expectTrue(output.elementsEqual(legacyOutput)) - expectTrue(output.elementsEqual(returnedOutput)) - } - } - - Accelerate_vDSPBiquadTests.test("vDSP/MultiChannelDoublePrecision") { - let channelCount = vDSP_Length(2) - - let signal: [Double] = (0 ..< n).map { i in - return sin(Double(i) * 0.1) + sin(Double(i) * 0.01) - } - - var biquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2, - b0, b1, b2, a1, a2], - channelCount: channelCount, - sectionCount: sections, - ofType: Double.self)! - - var returningBiquad = vDSP.Biquad(coefficients: [b0, b1, b2, a1, a2, - b0, b1, b2, a1, a2], - channelCount: channelCount, - sectionCount: sections, - ofType: Double.self)! - - var output = [Double](repeating: 0, - count: n) - - // Legacy... - var legacyOutput = [Double](repeating: -1, - count: n) - - let setup = vDSP_biquadm_CreateSetupD([b0, b1, b2, a1, a2, - b0, b1, b2, a1, a2], - vDSP_Length(sections), - vDSP_Length(channelCount))! - - for _ in 0 ... 3 { - - biquad.apply(input: signal, - output: &output) - - let returnedOutput = returningBiquad.apply(input: signal) - - signal.withUnsafeBufferPointer { inputBuffer in - let inputPointer = inputBuffer.baseAddress! - legacyOutput.withUnsafeMutableBufferPointer { outputBuffer in - let outputPointer = outputBuffer.baseAddress! - - let length = vDSP_Length(n) / channelCount - - var inputs: [UnsafePointer] = (0 ..< channelCount).map { i in - return inputPointer.advanced(by: Int(i * length)) - } - - var outputs: [UnsafeMutablePointer] = (0 ..< channelCount).map { i in - return outputPointer.advanced(by: Int(i * length)) - } - - vDSP_biquadmD(setup, &inputs, 1, &outputs, 1, vDSP_Length(n) / channelCount) - } - } - - expectTrue(output.elementsEqual(legacyOutput)) - expectTrue(output.elementsEqual(returnedOutput)) - } - } -} - -runAllTests() diff --git a/test/stdlib/Accelerate_vDSPClippingLimitThreshold.swift b/test/stdlib/Accelerate_vDSPClippingLimitThreshold.swift deleted file mode 100644 index 19a0d4ef63e8c..0000000000000 --- a/test/stdlib/Accelerate_vDSPClippingLimitThreshold.swift +++ /dev/null @@ -1,352 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var Accelerate_vDSPClippingLimitThresholdTests = TestSuite("Accelerate_vDSPClippingLimitThreshold") - -//===----------------------------------------------------------------------===// -// -// vDSP clipping, limit, and threshold tests; single-precision. -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let count = 256 - let n = vDSP_Length(256) - let bounds = Float(-0.5) ... Float(0.5) - let outputConstant: Float = 99 - - let source: [Float] = (0 ..< 256).map { i in - return sin(Float(i) * 0.05) + sin(Float(i) * 0.025) - } - - Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionClipping") { - var result = [Float](repeating: 0, - count: count) - - vDSP.clip(source, - to: bounds, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_vclip(source, 1, - [bounds.lowerBound], - [bounds.upperBound], - &legacyResult, 1, - n) - - let returnedResult = vDSP.clip(source, - to: bounds) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionInvertedClipping") { - var result = [Float](repeating: 0, - count: count) - - vDSP.invertedClip(source, - to: bounds, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_viclip(source, 1, - [bounds.lowerBound], - [bounds.upperBound], - &legacyResult, 1, - n) - - let returnedResult = vDSP.invertedClip(source, - to: bounds) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionThreshold") { - var result = [Float](repeating: 0, - count: count) - - vDSP.threshold(source, - to: bounds.lowerBound, - with: .clampToThreshold, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_vthr(source, 1, - [bounds.lowerBound], - &legacyResult, 1, - n) - - let returnedResult = vDSP.threshold(source, - to: bounds.lowerBound, - with: .clampToThreshold) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionThresholdWithConstant") { - var result = [Float](repeating: 0, - count: count) - - vDSP.threshold(source, - to: bounds.lowerBound, - with: .signedConstant(outputConstant), - result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_vthrsc(source, 1, - [bounds.lowerBound], - [outputConstant], - &legacyResult, 1, - n) - - let returnedResult = vDSP.threshold(source, - to: bounds.lowerBound, - with: .signedConstant(outputConstant)) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionThresholdWithZeroFill") { - var result = [Float](repeating: 0, - count: count) - - vDSP.threshold(source, - to: bounds.lowerBound, - with: .zeroFill, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_vthres(source, 1, - [bounds.lowerBound], - &legacyResult, 1, - n) - - let returnedResult = vDSP.threshold(source, - to: bounds.lowerBound, - with: .zeroFill) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionLimit") { - var result = [Float](repeating: 0, - count: count) - - vDSP.limit(source, - limit: bounds.upperBound, - withOutputConstant: outputConstant, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_vlim(source, 1, - [bounds.upperBound], - [outputConstant], - &legacyResult, 1, - n) - - let returnedResult = vDSP.limit(source, - limit: bounds.upperBound, - withOutputConstant: outputConstant) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP clipping, limit, and threshold tests; double-precision. -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let count = 256 - let n = vDSP_Length(256) - let bounds = Double(-0.5) ... Double(0.5) - let outputConstant: Double = 99 - - let source: [Double] = (0 ..< 256).map { i in - return sin(Double(i) * 0.05) + sin(Double(i) * 0.025) - } - - Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionClipping") { - var result = [Double](repeating: 0, - count: count) - - vDSP.clip(source, - to: bounds, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_vclipD(source, 1, - [bounds.lowerBound], - [bounds.upperBound], - &legacyResult, 1, - n) - - let returnedResult = vDSP.clip(source, - to: bounds) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionInvertedClipping") { - var result = [Double](repeating: 0, - count: count) - - vDSP.invertedClip(source, - to: bounds, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_viclipD(source, 1, - [bounds.lowerBound], - [bounds.upperBound], - &legacyResult, 1, - n) - - let returnedResult = vDSP.invertedClip(source, - to: bounds) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionThreshold") { - var result = [Double](repeating: 0, - count: count) - - vDSP.threshold(source, - to: bounds.lowerBound, - with: .clampToThreshold, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_vthrD(source, 1, - [bounds.lowerBound], - &legacyResult, 1, - n) - - let returnedResult = vDSP.threshold(source, - to: bounds.lowerBound, - with: .clampToThreshold) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionThresholdWithConstant") { - var result = [Double](repeating: 0, - count: count) - - vDSP.threshold(source, - to: bounds.lowerBound, - with: .signedConstant(outputConstant), - result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_vthrscD(source, 1, - [bounds.lowerBound], - [outputConstant], - &legacyResult, 1, - n) - - let returnedResult = vDSP.threshold(source, - to: bounds.lowerBound, - with: .signedConstant(outputConstant)) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionThresholdWithZeroFill") { - var result = [Double](repeating: 0, - count: count) - - vDSP.threshold(source, - to: bounds.lowerBound, - with: .zeroFill, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_vthresD(source, 1, - [bounds.lowerBound], - &legacyResult, 1, - n) - - let returnedResult = vDSP.threshold(source, - to: bounds.lowerBound, - with: .zeroFill) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionLimit") { - var result = [Double](repeating: 0, - count: count) - - vDSP.limit(source, - limit: bounds.upperBound, - withOutputConstant: outputConstant, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_vlimD(source, 1, - [bounds.upperBound], - [outputConstant], - &legacyResult, 1, - n) - - let returnedResult = vDSP.limit(source, - limit: bounds.upperBound, - withOutputConstant: outputConstant) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } -} - -runAllTests() diff --git a/test/stdlib/Accelerate_vDSPComplexOperations.swift b/test/stdlib/Accelerate_vDSPComplexOperations.swift deleted file mode 100644 index 709be26ffd5c7..0000000000000 --- a/test/stdlib/Accelerate_vDSPComplexOperations.swift +++ /dev/null @@ -1,532 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var Accelerate_vDSPComplexOperationsTests = TestSuite("Accelerate_vDSPComplexOperations") - -//===----------------------------------------------------------------------===// -// -// Complex operations tests; single-precision -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let n = 1024 - - var imaginarySource: [Float] = (0 ..< n).map{ i in - return 1 + sin(Float(i) * 0.05) - } - - var realSource: [Float] = (0 ..< n).map{ i in - return 1 + cos(Float(i) * 0.05) - } - - var splitComplexSource = DSPSplitComplex(realp: &realSource, - imagp: &imaginarySource) - - let vectorSource: [Float] = (0 ..< n).map{ i in - return 1 + sin(Float(i) * 0.025) - } - - var realResult = [Float](repeating: 0, count: n) - var imaginaryResult = [Float](repeating: 0, count: n) - var splitComplexResult = DSPSplitComplex(realp: &realResult, - imagp: &imaginaryResult) - - var realLegacyResult = [Float](repeating: -1, count: n) - var imaginaryLegacyResult = [Float](repeating: -1, count: n) - var splitComplexLegacyResult = DSPSplitComplex(realp: &realLegacyResult, - imagp: &imaginaryLegacyResult) - - Accelerate_vDSPComplexOperationsTests.test("vDSP/ComplexAbsolute") { - vDSP.absolute(splitComplexSource, - result: &realResult) - - vDSP_zvabs(&splitComplexSource, 1, - &realLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/SquareMagnitudes") { - vDSP.squareMagnitudes(splitComplexSource, - result: &realResult) - - vDSP_zvmags(&splitComplexSource, 1, - &realLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/Conjugate") { - vDSP.conjugate(splitComplexSource, - count: n, - result: &splitComplexResult) - - vDSP_zvconj(&splitComplexSource, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/ComplexComplexAdd") { - var real = (0 ..< n).map{ i in - return sin(Float(i) * 0.025) - } - var imag = (0 ..< n).map{ i in - return cos(Float(i) * 0.025) - } - var splitComplexSource2 = DSPSplitComplex(realp: &real, - imagp: &imag) - - vDSP.add(splitComplexSource, - to: splitComplexSource2, - count: n, - result: &splitComplexResult) - - vDSP_zvadd(&splitComplexSource, 1, - &splitComplexSource2, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/ComplexComplexDivide") { - var real = (0 ..< n).map{ i in - return sin(Float(i) * 0.025) + 2 - } - var imag = (0 ..< n).map{ i in - return cos(Float(i) * 0.025) + 2 - } - var splitComplexSource2 = DSPSplitComplex(realp: &real, - imagp: &imag) - - vDSP.divide(splitComplexSource, - by: splitComplexSource2, - count: n, - result: &splitComplexResult) - - vDSP_zvdiv(&splitComplexSource2, 1, - &splitComplexSource, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/ComplexComplexDivide") { - var real = (0 ..< n).map{ i in - return sin(Float(i) * 0.025) + 2 - } - var imag = (0 ..< n).map{ i in - return cos(Float(i) * 0.025) + 2 - } - var splitComplexSource2 = DSPSplitComplex(realp: &real, - imagp: &imag) - - vDSP.divide(splitComplexSource, - by: splitComplexSource2, - count: n, - result: &splitComplexResult) - - vDSP_zvdiv(&splitComplexSource2, 1, - &splitComplexSource, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/ComplexComplexSubtract") { - var real = (0 ..< n).map{ i in - return sin(Float(i) * 0.025) + 2 - } - var imag = (0 ..< n).map{ i in - return cos(Float(i) * 0.025) + 2 - } - var splitComplexSource2 = DSPSplitComplex(realp: &real, - imagp: &imag) - - vDSP.subtract(splitComplexSource, - from: splitComplexSource2, - count: n, - result: &splitComplexResult) - - vDSP_zvsub(&splitComplexSource, 1, - &splitComplexSource2, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/ComplexComplexMultiply") { - var real = (0 ..< n).map{ i in - return sin(Float(i) * 0.025) - } - var imag = (0 ..< n).map{ i in - return cos(Float(i) * 0.025) - } - var splitComplexSource2 = DSPSplitComplex(realp: &real, - imagp: &imag) - - vDSP.multiply(splitComplexSource, - by: splitComplexSource2, - count: n, - useConjugate: false, - result: &splitComplexResult) - - vDSP_zvmul(&splitComplexSource, 1, - &splitComplexSource2, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n), - 1) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - - vDSP.multiply(splitComplexSource, - by: splitComplexSource2, - count: n, - useConjugate: true, - result: &splitComplexResult) - - vDSP_zvmul(&splitComplexSource, 1, - &splitComplexSource2, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n), - -1) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/Multiply") { - vDSP.multiply(splitComplexSource, - by: vectorSource, - result: &splitComplexResult) - - vDSP_zrvmul(&splitComplexSource, 1, - vectorSource, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/Divide") { - vDSP.divide(splitComplexSource, - by: vectorSource, - result: &splitComplexResult) - - vDSP_zrvdiv(&splitComplexSource, 1, - vectorSource, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/Phase") { - vDSP.phase(splitComplexSource, - result: &realResult) - - vDSP_zvphas(&splitComplexSource, 1, - &realLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/Copy") { - expectFalse(imaginaryResult.elementsEqual(imaginarySource)) - expectFalse(realResult.elementsEqual(realSource)) - - vDSP.copy(splitComplexSource, - to: &splitComplexResult, - count: n) - - expectTrue(imaginaryResult.elementsEqual(imaginarySource)) - expectTrue(realResult.elementsEqual(realSource)) - } -} - - -//===----------------------------------------------------------------------===// -// -// Complex operations tests; double-precision -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let n = 1024 - - var imaginarySource: [Double] = (0 ..< n).map{ i in - return 1 + sin(Double(i) * 0.05) - } - - var realSource: [Double] = (0 ..< n).map{ i in - return 1 + cos(Double(i) * 0.05) - } - - var splitComplexSource = DSPDoubleSplitComplex(realp: &realSource, - imagp: &imaginarySource) - - let vectorSource: [Double] = (0 ..< n).map{ i in - return 1 + sin(Double(i) * 0.025) - } - - var realResult = [Double](repeating: 0, count: n) - var imaginaryResult = [Double](repeating: 0, count: n) - var splitComplexResult = DSPDoubleSplitComplex(realp: &realResult, - imagp: &imaginaryResult) - - var realLegacyResult = [Double](repeating: -1, count: n) - var imaginaryLegacyResult = [Double](repeating: -1, count: n) - var splitComplexLegacyResult = DSPDoubleSplitComplex(realp: &realLegacyResult, - imagp: &imaginaryLegacyResult) - - Accelerate_vDSPComplexOperationsTests.test("vDSP/ComplexAbsolute") { - vDSP.absolute(splitComplexSource, - result: &realResult) - - vDSP_zvabsD(&splitComplexSource, 1, - &realLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/SquareMagnitudes") { - vDSP.squareMagnitudes(splitComplexSource, - result: &realResult) - - vDSP_zvmagsD(&splitComplexSource, 1, - &realLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/Conjugate") { - vDSP.conjugate(splitComplexSource, - count: n, - result: &splitComplexResult) - - vDSP_zvconjD(&splitComplexSource, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/ComplexComplexAdd") { - var real = (0 ..< n).map{ i in - return sin(Double(i) * 0.025) - } - var imag = (0 ..< n).map{ i in - return cos(Double(i) * 0.025) - } - var splitComplexSource2 = DSPDoubleSplitComplex(realp: &real, - imagp: &imag) - - vDSP.add(splitComplexSource, - to: splitComplexSource2, - count: n, - result: &splitComplexResult) - - vDSP_zvaddD(&splitComplexSource, 1, - &splitComplexSource2, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/ComplexComplexDivide") { - var real = (0 ..< n).map{ i in - return sin(Double(i) * 0.025) + 2 - } - var imag = (0 ..< n).map{ i in - return cos(Double(i) * 0.025) + 2 - } - var splitComplexSource2 = DSPDoubleSplitComplex(realp: &real, - imagp: &imag) - - vDSP.divide(splitComplexSource, - by: splitComplexSource2, - count: n, - result: &splitComplexResult) - - vDSP_zvdivD(&splitComplexSource2, 1, - &splitComplexSource, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/ComplexComplexDivide") { - var real = (0 ..< n).map{ i in - return sin(Double(i) * 0.025) + 2 - } - var imag = (0 ..< n).map{ i in - return cos(Double(i) * 0.025) + 2 - } - var splitComplexSource2 = DSPDoubleSplitComplex(realp: &real, - imagp: &imag) - - vDSP.divide(splitComplexSource, - by: splitComplexSource2, - count: n, - result: &splitComplexResult) - - vDSP_zvdivD(&splitComplexSource2, 1, - &splitComplexSource, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/ComplexComplexSubtract") { - var real = (0 ..< n).map{ i in - return sin(Double(i) * 0.025) + 2 - } - var imag = (0 ..< n).map{ i in - return cos(Double(i) * 0.025) + 2 - } - var splitComplexSource2 = DSPDoubleSplitComplex(realp: &real, - imagp: &imag) - - vDSP.subtract(splitComplexSource, - from: splitComplexSource2, - count: n, - result: &splitComplexResult) - - vDSP_zvsubD(&splitComplexSource, 1, - &splitComplexSource2, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/ComplexComplexMultiply") { - var real = (0 ..< n).map{ i in - return sin(Double(i) * 0.025) - } - var imag = (0 ..< n).map{ i in - return cos(Double(i) * 0.025) - } - var splitComplexSource2 = DSPDoubleSplitComplex(realp: &real, - imagp: &imag) - - vDSP.multiply(splitComplexSource, - by: splitComplexSource2, - count: n, - useConjugate: false, - result: &splitComplexResult) - - vDSP_zvmulD(&splitComplexSource, 1, - &splitComplexSource2, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n), - 1) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - - vDSP.multiply(splitComplexSource, - by: splitComplexSource2, - count: n, - useConjugate: true, - result: &splitComplexResult) - - vDSP_zvmulD(&splitComplexSource, 1, - &splitComplexSource2, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n), - -1) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/Multiply") { - vDSP.multiply(splitComplexSource, - by: vectorSource, - result: &splitComplexResult) - - vDSP_zrvmulD(&splitComplexSource, 1, - vectorSource, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/Divide") { - vDSP.divide(splitComplexSource, - by: vectorSource, - result: &splitComplexResult) - - vDSP_zrvdivD(&splitComplexSource, 1, - vectorSource, 1, - &splitComplexLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - expectTrue(imaginaryResult.elementsEqual(imaginaryLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/Phase") { - vDSP.phase(splitComplexSource, - result: &realResult) - - vDSP_zvphasD(&splitComplexSource, 1, - &realLegacyResult, 1, - vDSP_Length(n)) - - expectTrue(realResult.elementsEqual(realLegacyResult)) - } - - Accelerate_vDSPComplexOperationsTests.test("vDSP/Copy") { - expectFalse(imaginaryResult.elementsEqual(imaginarySource)) - expectFalse(realResult.elementsEqual(realSource)) - - vDSP.copy(splitComplexSource, - to: &splitComplexResult, - count: n) - - expectTrue(imaginaryResult.elementsEqual(imaginarySource)) - expectTrue(realResult.elementsEqual(realSource)) - } -} - -runAllTests() diff --git a/test/stdlib/Accelerate_vDSPConversion.swift b/test/stdlib/Accelerate_vDSPConversion.swift deleted file mode 100644 index f337322184381..0000000000000 --- a/test/stdlib/Accelerate_vDSPConversion.swift +++ /dev/null @@ -1,1018 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var AccelerateTests_vDSPConversion = TestSuite("Accelerate_vDSPConversion") - -//===----------------------------------------------------------------------===// -// -// vDSP polar / rectangular conversion -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - AccelerateTests_vDSPConversion.test("vDSP/SinglePrecisionRectToPolar") { - let source: [Float] = [2, 4, - -10, -20, - 100, -300] - - let n = vDSP_Length(source.count) - - var result = [Float](repeating: 0, - count: source.count) - - vDSP.convert(rectangularCoordinates: source, - toPolarCoordinates: &result) - - var legacyResult = [Float](repeating: -1, - count: source.count) - - vDSP_polar(source, 2, - &legacyResult, 2, - n / 2) - - let returnedResult = vDSP.rectangularToPolar(source) - - expectTrue(returnedResult.elementsEqual(legacyResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/SinglePrecisionPolarToRect") { - let source: [Float] = [2, 4, - -10, -20, - 100, -300] - - let n = vDSP_Length(source.count) - - var result = [Float](repeating: 0, - count: source.count) - - vDSP.convert(polarCoordinates: source, - toRectangularCoordinates: &result) - - var legacyResult = [Float](repeating: -1, - count: source.count) - - vDSP_rect(source, 2, - &legacyResult, 2, - n / 2) - - let returnedResult = vDSP.polarToRectangular(source) - - expectTrue(returnedResult.elementsEqual(legacyResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoublePrecisionRectToPolar") { - let source: [Double] = [2, 4, - -10, -20, - 100, -300] - - let n = vDSP_Length(source.count) - - var result = [Double](repeating: 0, - count: source.count) - - vDSP.convert(rectangularCoordinates: source, - toPolarCoordinates: &result) - - var legacyResult = [Double](repeating: -1, - count: source.count) - - vDSP_polarD(source, 2, - &legacyResult, 2, - n / 2) - - let returnedResult = vDSP.rectangularToPolar(source) - - expectTrue(returnedResult.elementsEqual(legacyResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoublePrecisionRectToPolar") { - let source: [Double] = [2, 4, - -10, -20, - 100, -300] - - let n = vDSP_Length(source.count) - - var result = [Double](repeating: 0, - count: source.count) - - vDSP.convert(polarCoordinates: source, - toRectangularCoordinates: &result) - - var legacyResult = [Double](repeating: -1, - count: source.count) - - vDSP_rectD(source, 2, - &legacyResult, 2, - n / 2) - - let returnedResult = vDSP.polarToRectangular(source) - - expectTrue(returnedResult.elementsEqual(legacyResult)) - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP type-conversion tests -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let n = vDSP_Length(10) - - let floatingPointValues: [Float] = [-10.9, -20.1, 32.99, 14.001, -16.5, - 90.5, 0, -0, -0.00001, 0.000001] - - let floatingPointValuesD: [Double] = [-10.9, -20.1, 32.99, 14.001, -16.5, - 90.5, 0, -0, -0.00001, 0.000001] - - let unsignedIntValues = [5, 250, 0, 99, 127, 65, 78, 1, 33, 10] - let signedIntValues = [5, -126, 0, -99, 125, -65, 78, -1, 33, -10] - - AccelerateTests_vDSPConversion.test("vDSP/FloatToDouble") { - let source = floatingPointValues - var result = [Double](repeating: 0, count: source.count) - var legacyResult = [Double](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result) - - vDSP_vspdp(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatToDouble(source) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoubleToFloat") { - let source = floatingPointValuesD - var result = [Float](repeating: 0, count: source.count) - var legacyResult = [Float](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result) - - vDSP_vdpsp(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.doubleToFloat(source) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/UInt8_to_Float") { - let source = unsignedIntValues.map{ return UInt8($0) } - var result = [Float](repeating: 0, count: source.count) - var legacyResult = [Float](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result) - - vDSP_vfltu8(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.integerToFloatingPoint(source, - floatingPointType: Float.self) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/UInt8_to_Double") { - let source = unsignedIntValues.map{ return UInt8($0) } - var result = [Double](repeating: 0, count: source.count) - var legacyResult = [Double](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result) - - vDSP_vfltu8D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.integerToFloatingPoint(source, - floatingPointType: Double.self) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/UInt16_to_Float") { - let source = unsignedIntValues.map{ return UInt16($0) } - var result = [Float](repeating: 0, count: source.count) - var legacyResult = [Float](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result) - - vDSP_vfltu16(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.integerToFloatingPoint(source, - floatingPointType: Float.self) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/UInt16_to_Double") { - let source = unsignedIntValues.map{ return UInt16($0) } - var result = [Double](repeating: 0, count: source.count) - var legacyResult = [Double](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result) - - vDSP_vfltu16D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.integerToFloatingPoint(source, - floatingPointType: Double.self) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/UInt32_to_Float") { - let source = unsignedIntValues.map{ return UInt32($0) } - var result = [Float](repeating: 0, count: source.count) - var legacyResult = [Float](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result) - - vDSP_vfltu32(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.integerToFloatingPoint(source, - floatingPointType: Float.self) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/UInt32_to_Double") { - let source = unsignedIntValues.map{ return UInt32($0) } - var result = [Double](repeating: 0, count: source.count) - var legacyResult = [Double](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result) - - vDSP_vfltu32D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.integerToFloatingPoint(source, - floatingPointType: Double.self) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/Int8_to_Float") { - let source = signedIntValues.map{ return Int8($0) } - var result = [Float](repeating: 0, count: source.count) - var legacyResult = [Float](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result) - - vDSP_vflt8(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.integerToFloatingPoint(source, - floatingPointType: Float.self) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/Int8_to_Double") { - let source = signedIntValues.map{ return Int8($0) } - var result = [Double](repeating: 0, count: source.count) - var legacyResult = [Double](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result) - - vDSP_vflt8D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.integerToFloatingPoint(source, - floatingPointType: Double.self) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/Int16_to_Float") { - let source = signedIntValues.map{ return Int16($0) } - var result = [Float](repeating: 0, count: source.count) - var legacyResult = [Float](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result) - - vDSP_vflt16(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.integerToFloatingPoint(source, - floatingPointType: Float.self) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/Int16_to_Double") { - let source = signedIntValues.map{ return Int16($0) } - var result = [Double](repeating: 0, count: source.count) - var legacyResult = [Double](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result) - - vDSP_vflt16D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.integerToFloatingPoint(source, - floatingPointType: Double.self) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/Int32_to_Float") { - let source = signedIntValues.map{ return Int32($0) } - var result = [Float](repeating: 0, count: source.count) - var legacyResult = [Float](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result) - - vDSP_vflt32(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.integerToFloatingPoint(source, - floatingPointType: Float.self) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/Int32_to_Double") { - let source = signedIntValues.map{ return Int32($0) } - var result = [Double](repeating: 0, count: source.count) - var legacyResult = [Double](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result) - - vDSP_vflt32D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.integerToFloatingPoint(source, - floatingPointType: Double.self) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/FloatToInt32towardZero") { - let source = floatingPointValues - var result = [Int32](repeating: 0, count: source.count) - var legacyResult = [Int32](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardZero) - - vDSP_vfix32(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: Int32.self, - rounding: .towardZero) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/FloatToInt32towardNearest") { - let source = floatingPointValues - var result = [Int32](repeating: 0, count: source.count) - var legacyResult = [Int32](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardNearestInteger) - - vDSP_vfixr32(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: Int32.self, - rounding: .towardNearestInteger) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoubleToInt32towardZero") { - let source = floatingPointValuesD - var result = [Int32](repeating: 0, count: source.count) - var legacyResult = [Int32](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardZero) - - vDSP_vfix32D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: Int32.self, - rounding: .towardZero) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoubleToInt32towardNearest") { - let source = floatingPointValuesD - var result = [Int32](repeating: 0, count: source.count) - var legacyResult = [Int32](repeating: -1, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardNearestInteger) - - vDSP_vfixr32D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: Int32.self, - rounding: .towardNearestInteger) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/FloatToUInt16towardZero") { - let source = floatingPointValues - var result = [UInt16](repeating: 0, count: source.count) - var legacyResult = [UInt16](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardZero) - - vDSP_vfixu16(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: UInt16.self, - rounding: .towardZero) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/FloatToUInt16towardNearest") { - let source = floatingPointValues - var result = [UInt16](repeating: 0, count: source.count) - var legacyResult = [UInt16](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardNearestInteger) - - vDSP_vfixru16(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: UInt16.self, - rounding: .towardNearestInteger) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoubleToUInt16towardZero") { - let source = floatingPointValuesD - var result = [UInt16](repeating: 0, count: source.count) - var legacyResult = [UInt16](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardZero) - - vDSP_vfixu16D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: UInt16.self, - rounding: .towardZero) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoubleToUInt16towardNearest") { - let source = floatingPointValuesD - var result = [UInt16](repeating: 0, count: source.count) - var legacyResult = [UInt16](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardNearestInteger) - - vDSP_vfixru16D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: UInt16.self, - rounding: .towardNearestInteger) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/FloatToUInt32towardZero") { - let source = floatingPointValues - var result = [UInt32](repeating: 0, count: source.count) - var legacyResult = [UInt32](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardZero) - - vDSP_vfixu32(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: UInt32.self, - rounding: .towardZero) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/FloatToUInt32towardNearest") { - let source = floatingPointValues - var result = [UInt32](repeating: 0, count: source.count) - var legacyResult = [UInt32](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardNearestInteger) - - vDSP_vfixru32(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: UInt32.self, - rounding: .towardNearestInteger) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoubleToUInt32towardZero") { - let source = floatingPointValuesD - var result = [UInt32](repeating: 0, count: source.count) - var legacyResult = [UInt32](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardZero) - - vDSP_vfixu32D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: UInt32.self, - rounding: .towardZero) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoubleToUInt32towardNearest") { - let source = floatingPointValuesD - var result = [UInt32](repeating: 0, count: source.count) - var legacyResult = [UInt32](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardNearestInteger) - - vDSP_vfixru32D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: UInt32.self, - rounding: .towardNearestInteger) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/FloatToInt16towardZero") { - let source = floatingPointValues - var result = [Int16](repeating: 0, count: source.count) - var legacyResult = [Int16](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardZero) - - vDSP_vfix16(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: Int16.self, - rounding: .towardZero) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/FloatToInt16towardNearest") { - let source = floatingPointValues - var result = [Int16](repeating: 0, count: source.count) - var legacyResult = [Int16](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardNearestInteger) - - vDSP_vfixr16(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: Int16.self, - rounding: .towardNearestInteger) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoubleToInt16towardZero") { - let source = floatingPointValuesD - var result = [Int16](repeating: 0, count: source.count) - var legacyResult = [Int16](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardZero) - - vDSP_vfix16D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: Int16.self, - rounding: .towardZero) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoubleToInt16towardNearest") { - let source = floatingPointValuesD - var result = [Int16](repeating: 0, count: source.count) - var legacyResult = [Int16](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardNearestInteger) - - vDSP_vfixr16D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: Int16.self, - rounding: .towardNearestInteger) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/FloatToInt8towardZero") { - let source = floatingPointValues - var result = [Int8](repeating: 0, count: source.count) - var legacyResult = [Int8](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardZero) - - vDSP_vfix8(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: Int8.self, - rounding: .towardZero) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/FloatToInt8towardNearest") { - let source = floatingPointValues - var result = [Int8](repeating: 0, count: source.count) - var legacyResult = [Int8](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardNearestInteger) - - vDSP_vfixr8(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: Int8.self, - rounding: .towardNearestInteger) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoubleToInt8towardZero") { - let source = floatingPointValuesD - var result = [Int8](repeating: 0, count: source.count) - var legacyResult = [Int8](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardZero) - - vDSP_vfix8D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: Int8.self, - rounding: .towardZero) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoubleToInt8towardNearest") { - let source = floatingPointValuesD - var result = [Int8](repeating: 0, count: source.count) - var legacyResult = [Int8](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardNearestInteger) - - vDSP_vfixr8D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: Int8.self, - rounding: .towardNearestInteger) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/FloatToUInt8towardZero") { - let source = floatingPointValues - var result = [UInt8](repeating: 0, count: source.count) - var legacyResult = [UInt8](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardZero) - - vDSP_vfixu8(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: UInt8.self, - rounding: .towardZero) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/FloatToUInt8towardNearest") { - let source = floatingPointValues - var result = [UInt8](repeating: 0, count: source.count) - var legacyResult = [UInt8](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardNearestInteger) - - vDSP_vfixru8(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: UInt8.self, - rounding: .towardNearestInteger) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoubleToUInt8towardZero") { - let source = floatingPointValuesD - var result = [UInt8](repeating: 0, count: source.count) - var legacyResult = [UInt8](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardZero) - - vDSP_vfixu8D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: UInt8.self, - rounding: .towardZero) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/DoubletoUInt8towardNearest") { - let source = floatingPointValuesD - var result = [UInt8](repeating: 0, count: source.count) - var legacyResult = [UInt8](repeating: 99, count: source.count) - - vDSP.convertElements(of: source, to: &result, rounding: .towardNearestInteger) - - vDSP_vfixru8D(source, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.floatingPointToInteger(source, - integerType: UInt8.self, - rounding: .towardNearestInteger) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP decibel conversion -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - AccelerateTests_vDSPConversion.test("vDSP/PowerToDecibelsSinglePrecision") { - let source: [Float] = [1, 10, 100, 2, 4, 8, 16, 101, - 27, 13, 11, 44, 0.5, 99, 0.125] - let zeroReference = Float(7) - let n = source.count - - var result = [Float](repeating: 0, - count: n) - - vDSP.convert(power: source, - toDecibels: &result, - zeroReference: zeroReference) - - var legacyResult = [Float](repeating: -1, - count: n) - - vDSP_vdbcon(source, 1, - [zeroReference], - &legacyResult, 1, - vDSP_Length(n), - 0) - - let returnedResult = vDSP.powerToDecibels(source, - zeroReference: zeroReference) - } - - AccelerateTests_vDSPConversion.test("vDSP/AmplitudeToDecibelsSinglePrecision") { - let source: [Float] = [1, 10, 100, 2, 4, 8, 16, 101, - 27, 13, 11, 44, 0.5, 99, 0.125] - let zeroReference = Float(7) - let n = source.count - - var result = [Float](repeating: 0, - count: n) - - vDSP.convert(amplitude: source, - toDecibels: &result, - zeroReference: zeroReference) - - var legacyResult = [Float](repeating: -1, - count: n) - - vDSP_vdbcon(source, 1, - [zeroReference], - &legacyResult, 1, - vDSP_Length(n), - 1) - - let returnedResult = vDSP.amplitudeToDecibels(source, - zeroReference: zeroReference) - } - - AccelerateTests_vDSPConversion.test("vDSP/PowerToDecibelsDoublePrecision") { - let source: [Double] = [1, 10, 100, 2, 4, 8, 16, 101, - 27, 13, 11, 44, 0.5, 99, 0.125] - let zeroReference = Double(7) - let n = source.count - - var result = [Double](repeating: 0, - count: n) - - vDSP.convert(power: source, - toDecibels: &result, - zeroReference: zeroReference) - - var legacyResult = [Double](repeating: -1, - count: n) - - vDSP_vdbconD(source, 1, - [zeroReference], - &legacyResult, 1, - vDSP_Length(n), - 0) - - let returnedResult = vDSP.powerToDecibels(source, - zeroReference: zeroReference) - } - - AccelerateTests_vDSPConversion.test("vDSP/AmplitudeToDecibelsDoublePrecision") { - let source: [Double] = [1, 10, 100, 2, 4, 8, 16, 101, - 27, 13, 11, 44, 0.5, 99, 0.125] - let zeroReference = Double(7) - let n = source.count - - var result = [Double](repeating: 0, - count: n) - - vDSP.convert(amplitude: source, - toDecibels: &result, - zeroReference: zeroReference) - - var legacyResult = [Double](repeating: -1, - count: n) - - vDSP_vdbconD(source, 1, - [zeroReference], - &legacyResult, 1, - vDSP_Length(n), - 1) - - let returnedResult = vDSP.amplitudeToDecibels(source, - zeroReference: zeroReference) - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP complex format conversion -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - AccelerateTests_vDSPConversion.test("vDSP/ComplexFormatConversionSinglePrecision") { - var real: [Float] = [4, 5, 6] - var imag: [Float] = [1, 2, 3] - let src = DSPSplitComplex(realp: &real, - imagp: &imag) - - var dest = [DSPComplex](repeating: DSPComplex(), - count: 3) - - vDSP.convert(splitComplexVector: src, - toInterleavedComplexVector: &dest) - - var realResult: [Float] = [0, 0, 0] - var imagResult: [Float] = [0, 0, 0] - var result = DSPSplitComplex(realp: &realResult, - imagp: &imagResult) - - vDSP.convert(interleavedComplexVector: dest, - toSplitComplexVector: &result) - - expectTrue(real.elementsEqual(realResult)) - expectTrue(imag.elementsEqual(imagResult)) - } - - AccelerateTests_vDSPConversion.test("vDSP/ComplexFormatConversionDoublePrecision") { - var real: [Double] = [4, 5, 6] - var imag: [Double] = [1, 2, 3] - let src = DSPDoubleSplitComplex(realp: &real, - imagp: &imag) - - var dest = [DSPDoubleComplex](repeating: DSPDoubleComplex(), - count: 3) - - vDSP.convert(splitComplexVector: src, - toInterleavedComplexVector: &dest) - - var realResult: [Double] = [0, 0, 0] - var imagResult: [Double] = [0, 0, 0] - var result = DSPDoubleSplitComplex(realp: &realResult, - imagp: &imagResult) - - vDSP.convert(interleavedComplexVector: dest, - toSplitComplexVector: &result) - - expectTrue(real.elementsEqual(realResult)) - expectTrue(imag.elementsEqual(imagResult)) - } -} - -runAllTests() diff --git a/test/stdlib/Accelerate_vDSPConvolution.swift b/test/stdlib/Accelerate_vDSPConvolution.swift deleted file mode 100644 index 76a707ccd2ab0..0000000000000 --- a/test/stdlib/Accelerate_vDSPConvolution.swift +++ /dev/null @@ -1,352 +0,0 @@ - -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var Accelerate_vDSPConvolutionTests = TestSuite("Accelerate_vDSPConvolution") - -//===----------------------------------------------------------------------===// -// -// vDSP Single-precision 1D convolution and correlation -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let count = 256 - let n = vDSP_Length(256) - - let kernel: [Float] = ( 0 ..< 10 ).map { - return Float($0) / 45 - } - - let signal: [Float] = (0 ..< 256 + 10).map { - return sin(Float($0) * 0.05).sign == .minus ? -1 : 1 - } - - Accelerate_vDSPConvolutionTests.test("vDSP/SinglePrecisionConvolve") { - var result = [Float](repeating: 0, - count: count) - vDSP.convolve(signal, - withKernel: kernel, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_conv(signal, 1, - UnsafePointer(kernel).advanced(by: kernel.count - 1), -1, - &legacyResult, 1, - n, - vDSP_Length(kernel.count)) - - let returnedResult = vDSP.convolve(signal, - withKernel: kernel) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPConvolutionTests.test("vDSP/SinglePrecisionCorrelate") { - var result = [Float](repeating: 0, - count: count) - vDSP.correlate(signal, - withKernel: kernel, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_conv(signal, 1, - kernel, 1, - &legacyResult, 1, - n, - vDSP_Length(kernel.count)) - - let returnedResult = vDSP.correlate(signal, - withKernel: kernel) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP Double-precision 1D convolution and correlation -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let count = 256 - let n = vDSP_Length(256) - - let kernel: [Double] = ( 0 ..< 10 ).map { - return Double($0) / 45 - } - - let signal: [Double] = (0 ..< 256 + 10).map { - return sin(Double($0) * 0.05).sign == .minus ? -1 : 1 - } - - Accelerate_vDSPConvolutionTests.test("vDSP/DoublePrecisionConvolve") { - var result = [Double](repeating: 0, - count: count) - vDSP.convolve(signal, - withKernel: kernel, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_convD(signal, 1, - UnsafePointer(kernel).advanced(by: kernel.count - 1), -1, - &legacyResult, 1, - n, - vDSP_Length(kernel.count)) - - let returnedResult = vDSP.convolve(signal, - withKernel: kernel) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPConvolutionTests.test("vDSP/DoublePrecisionCorrelate") { - var result = [Double](repeating: 0, - count: count) - vDSP.correlate(signal, - withKernel: kernel, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_convD(signal, 1, - kernel, 1, - &legacyResult, 1, - n, - vDSP_Length(kernel.count)) - - let returnedResult = vDSP.correlate(signal, - withKernel: kernel) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP Single-precision 2D convolution -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let width = 512 - let height = 128 - let pixelCount = 512 * 128 - - let pixels: [Float] = (0 ..< pixelCount).map { i in - let x = floor(Float(i) / 1024) * 25 - let y = remainder(Float(i), 1024) * 25 - return (sin(y).sign == .minus && sin(x).sign == .minus) ? 0 : 1 - } - - Accelerate_vDSPConvolutionTests.test("vDSP/SinglePrecision3x3") { - let kernel3x3 = [Float](repeating: 1.0 / 9, count: 9) - - var result = [Float](repeating: .nan, - count: pixelCount) - - vDSP.convolve(pixels, - rowCount: height, columnCount: width, - with3x3Kernel: kernel3x3, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: result.count) - - vDSP_f3x3(pixels, - vDSP_Length(height), vDSP_Length(width), - kernel3x3, - &legacyResult) - - let returnedResult = vDSP.convolve(pixels, - rowCount: height, columnCount: width, - with3x3Kernel: kernel3x3) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPConvolutionTests.test("vDSP/SinglePrecision5x5") { - let kernel5x5 = [Float](repeating: 1.0 / 25, count: 25) - - var result = [Float](repeating: .nan, - count: pixelCount) - - vDSP.convolve(pixels, - rowCount: height, columnCount: width, - with5x5Kernel: kernel5x5, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: result.count) - - vDSP_f5x5(pixels, - vDSP_Length(height), vDSP_Length(width), - kernel5x5, - &legacyResult) - - let returnedResult = vDSP.convolve(pixels, - rowCount: height, columnCount: width, - with5x5Kernel: kernel5x5) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPConvolutionTests.test("vDSP/SinglePrecision7x3") { - let kernel7x3 = [Float](repeating: 1.0 / (7 * 3), count: 7 * 3) - - var result = [Float](repeating: .nan, - count: pixelCount) - - vDSP.convolve(pixels, - rowCount: height, columnCount: width, - withKernel: kernel7x3, - kernelRowCount: 7, kernelColumnCount: 3, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: result.count) - - vDSP_imgfir(pixels, - vDSP_Length(height), vDSP_Length(width), - kernel7x3, - &legacyResult, - 7, 3) - - let returnedResult = vDSP.convolve(pixels, - rowCount: height, columnCount: width, - withKernel: kernel7x3, - kernelRowCount: 7, kernelColumnCount: 3) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP Double-precision 2D convolution -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let width = 512 - let height = 128 - let pixelCount = 512 * 128 - - let pixels: [Double] = (0 ..< pixelCount).map { i in - let x = floor(Double(i) / 1024) * 25 - let y = remainder(Double(i), 1024) * 25 - return (sin(y).sign == .minus && sin(x).sign == .minus) ? 0 : 1 - } - - Accelerate_vDSPConvolutionTests.test("vDSP/DoublePrecision3x3") { - let kernel3x3 = [Double](repeating: 1.0 / 9, count: 9) - - var result = [Double](repeating: .nan, - count: pixelCount) - - vDSP.convolve(pixels, - rowCount: height, columnCount: width, - with3x3Kernel: kernel3x3, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: result.count) - - vDSP_f3x3D(pixels, - vDSP_Length(height), vDSP_Length(width), - kernel3x3, - &legacyResult) - - let returnedResult = vDSP.convolve(pixels, - rowCount: height, columnCount: width, - with3x3Kernel: kernel3x3) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPConvolutionTests.test("vDSP/DoublePrecision5x5") { - let kernel5x5 = [Double](repeating: 1.0 / 25, count: 25) - - var result = [Double](repeating: .nan, - count: pixelCount) - - vDSP.convolve(pixels, - rowCount: height, columnCount: width, - with5x5Kernel: kernel5x5, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: result.count) - - vDSP_f5x5D(pixels, - vDSP_Length(height), vDSP_Length(width), - kernel5x5, - &legacyResult) - - let returnedResult = vDSP.convolve(pixels, - rowCount: height, columnCount: width, - with5x5Kernel: kernel5x5) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPConvolutionTests.test("vDSP/DoublePrecision7x3") { - let kernel7x3 = [Double](repeating: 1.0 / (7 * 3), count: 7 * 3) - - var result = [Double](repeating: .nan, - count: pixelCount) - - vDSP.convolve(pixels, - rowCount: height, columnCount: width, - withKernel: kernel7x3, - kernelRowCount: 7, kernelColumnCount: 3, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: result.count) - - vDSP_imgfirD(pixels, - vDSP_Length(height), vDSP_Length(width), - kernel7x3, - &legacyResult, - 7, 3) - - let returnedResult = vDSP.convolve(pixels, - rowCount: height, columnCount: width, - withKernel: kernel7x3, - kernelRowCount: 7, kernelColumnCount: 3) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } -} - -runAllTests() diff --git a/test/stdlib/Accelerate_vDSPElementwiseArithmetic.swift b/test/stdlib/Accelerate_vDSPElementwiseArithmetic.swift deleted file mode 100644 index 64f5397796d03..0000000000000 --- a/test/stdlib/Accelerate_vDSPElementwiseArithmetic.swift +++ /dev/null @@ -1,898 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var Accelerate_vDSPElementwiseArithmeticTests = TestSuite("Accelerate_vDSPElementwiseArithmetic") - -//===----------------------------------------------------------------------===// -// -// vDSP Single Precision Arithmetic -// -//===----------------------------------------------------------------------===// - -func lround(_ x: Float) -> Int { - return lround(Double(x)) -} - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - var result = [Float.nan] - - var vectorA = [Float.nan] - var vectorB = [Float.nan] - var vectorC = [Float.nan] - - var scalarA = Float.nan - var scalarB = Float.nan - - // c[i] = a[i] + b - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsadd") { - scalarA = 100 - vectorB = [500] - - vDSP.add(scalarA, - vectorB, - result: &result) - - let returnedResult = vDSP.add(scalarA, - vectorB) - - expectEqual(lround(result.first!), 600) - expectEqual(lround(returnedResult.first!), 600) - } - - // c[i] = a[i] + b[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vadd") { - vectorA = [750] - vectorB = [250] - - vDSP.add(vectorA, - vectorB, - result: &result) - - let returnedResult = vDSP.add(vectorA, - vectorB) - - expectEqual(lround(result.first!), 1000) - expectEqual(lround(returnedResult.first!), 1000) - } - - // c[i] = a[i] - b[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsub") { - vectorA = [5] - vectorB = [30] - - vDSP.subtract(vectorA, - vectorB, - result: &result) - - let returnedResult = vDSP.subtract(vectorA, - vectorB) - - expectEqual(lround(result.first!), -25) - expectEqual(lround(returnedResult.first!), -25) - } - - // c[i] = a[i] * b - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsmul") { - scalarA = 100 - vectorB = [3] - - vDSP.multiply(scalarA, - vectorB, - result: &result) - - let returnedResult = vDSP.multiply(scalarA, - vectorB) - - expectEqual(lround(result.first!), 300) - expectEqual(lround(returnedResult.first!), 300) - } - - // a[i] * b[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vmul") { - vectorA = [6] - vectorB = [10] - - vDSP.multiply(vectorA, - vectorB, - result: &result) - - let returnedResult = vDSP.multiply(vectorA, - vectorB) - - expectEqual(lround(result.first!), 60) - expectEqual(lround(returnedResult.first!), 60) - } - - // c[i] = a[i] / b - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsdiv") { - scalarA = 4 - vectorB = [100] - - vDSP.divide(vectorB, - scalarA, - result: &result) - - let returnedResult = vDSP.divide(vectorB, - scalarA) - - expectEqual(lround(result.first!), 25) - expectEqual(lround(returnedResult.first!), 25) - } - - // c[i] = a / b[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/svdiv") { - scalarA = 200 - vectorB = [4] - - vDSP.divide(scalarA, - vectorB, - result: &result) - - let returnedResult = vDSP.divide(scalarA, - vectorB) - - expectEqual(lround(result.first!), 50) - expectEqual(lround(returnedResult.first!), 50) - } - - // c[i] = a[i] / b[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vdiv") { - vectorA = [600] - vectorB = [3] - - vDSP.divide(vectorA, - vectorB, - result: &result) - - let returnedResult = vDSP.divide(vectorA, - vectorB) - - expectEqual(lround(result.first!), 200) - expectEqual(lround(returnedResult.first!), 200) - } - - // o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vaddsub") { - vectorA = [16] - vectorB = [4] - var subtractResult = [ Float.nan ] - - vDSP.addSubtract(vectorA, - vectorB, - addResult: &result, - subtractResult: &subtractResult) - - expectEqual(lround(result.first!), 20) - expectEqual(lround(subtractResult.first!), 12) - - } - - // d[i] = (a[i] + b[i]) * c - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vasm") { - vectorA = [4] - vectorB = [16] - scalarA = 4 - - vDSP.multiply(addition: (vectorA, vectorB), - scalarA, - result: &result) - - let returnedResult = vDSP.multiply(addition: (vectorA, vectorB), - scalarA) - - expectEqual(lround(result.first!), 80) - expectEqual(lround(returnedResult.first!), 80) - } - - // d[i] = (a[i] + b[i]) * c[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vam") { - vectorA = [4] - vectorB = [16] - vectorC = [5] - - vDSP.multiply(addition: (vectorA, vectorB), - vectorC, - result: &result) - - let returnedResult = vDSP.multiply(addition: (vectorA, vectorB), - vectorC) - - expectEqual(lround(result.first!), 100) - expectEqual(lround(returnedResult.first!), 100) - } - - // d[i] = (a[i] - b[i]) * c - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsbsm") { - vectorA = [20] - vectorB = [5] - scalarA = 2 - - vDSP.multiply(subtraction: (vectorA, vectorB), - scalarA, - result: &result) - - let returnedResult = vDSP.multiply(subtraction: (vectorA, vectorB), - scalarA) - - expectEqual(lround(result.first!), 30) - expectEqual(lround(returnedResult.first!), 30) - } - - // d[i] = (a[i] - b[i]) * c[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsbm") { - vectorA = [20] - vectorB = [5] - vectorC = [2] - - vDSP.multiply(subtraction: (vectorA, vectorB), - vectorC, - result: &result) - - let returnedResult = vDSP.multiply(subtraction: (vectorA, vectorB), - vectorC) - - expectEqual(lround(result.first!), 30) - expectEqual(lround(returnedResult.first!), 30) - } - - // a[i]*b[i] + c - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vmsa") { - vectorA = [18] - vectorB = [10] - scalarA = 20 - - vDSP.add(multiplication: (vectorA, vectorB), - scalarA, - result: &result) - - let returnedResult = vDSP.add(multiplication: (vectorA, vectorB), - scalarA) - - expectEqual(lround(result.first!), 200) - expectEqual(lround(returnedResult.first!), 200) - } - - // (a[i] * b) + c[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsma") { - vectorA = [18] - scalarB = 10 - vectorC = [120] - - vDSP.add(multiplication: (vectorA, scalarB), - vectorC, - result: &result) - - let returnedResult = vDSP.add(multiplication: (vectorA, scalarB), - vectorC) - - expectEqual(lround(result.first!), 300) - expectEqual(lround(returnedResult.first!), 300) - } - - // d[i] = (a[i] * b[i]) + c[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vma") { - vectorA = [5] - vectorB = [20] - vectorC = [6] - - vDSP.add(multiplication: (vectorA, vectorB), - vectorC, - result: &result) - - let returnedResult = vDSP.add(multiplication: (vectorA, vectorB), - vectorC) - - expectEqual(lround(result.first!), 106) - expectEqual(lround(returnedResult.first!), 106) - } - - // d[i] = (a[i] * b[i]) - c[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vmsb") { - vectorA = [25] - vectorB = [2] - vectorC = [50] - - vDSP.subtract(multiplication: (vectorB, vectorC), - vectorA, - result: &result) - - let returnedResult = vDSP.subtract(multiplication: (vectorB, vectorC), - vectorA) - - expectEqual(lround(result.first!), 75) - expectEqual(lround(returnedResult.first!), 75) - } - - // e[i] = (a[i] * b) + (c[i] * d) - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsmsma") { - vectorA = [5] - scalarA = 100 - vectorB = [50] - scalarB = 4 - - vDSP.add(multiplication: (vectorA, scalarA), - multiplication: (vectorB, scalarB), - result: &result) - - let returnedResult = vDSP.add(multiplication: (vectorA, scalarA), - multiplication: (vectorB, scalarB)) - - expectEqual(lround(result.first!), 700) - expectEqual(lround(returnedResult.first!), 700) - } - - // E[n] = A[n]*B[n] + C[n]*D[n] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vmma") { - vectorA = [2] - vectorB = [10] - vectorC = [3] - let vectorD: [Float] = [20] - - vDSP.add(multiplication: (vectorA, vectorB), - multiplication: (vectorC, vectorD), - result: &result) - - let returnedResult = vDSP.add(multiplication: (vectorA, vectorB), - multiplication: (vectorC, vectorD)) - - expectEqual(lround(result.first!), 80) - expectEqual(lround(returnedResult.first!), 80) - } - - // e[i] = (a[i] + b[i]) * (c[i] + d[i]) - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vaam") { - vectorA = [2] - vectorB = [8] - vectorC = [3] - let vectorD: [Float] = [17] - - vDSP.multiply(addition: (vectorA, vectorB), - addition: (vectorC, vectorD), - result: &result) - - let returnedResult = vDSP.multiply(addition: (vectorA, vectorB), - addition: (vectorC, vectorD)) - - expectEqual(lround(result.first!), 200) - expectEqual(lround(returnedResult.first!), 200) - } - - // e[i] = (a[i] * b[i]) - (c[i] * d[i]) - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vmmsb") { - vectorA = [2] - vectorB = [3] - vectorC = [5] - let vectorD: [Float] = [15] - - vDSP.subtract(multiplication: (vectorA, vectorB), - multiplication: (vectorC, vectorD), - result: &result) - - let returnedResult = vDSP.subtract(multiplication: (vectorA, vectorB), - multiplication: (vectorC, vectorD)) - - expectEqual(lround(result.first!), -69) - expectEqual(lround(returnedResult.first!), -69) - } - - // e[i] = (a[i] - b[i]) * (c[i] - d[i]) - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsbsbm") { - vectorA = [12] - vectorB = [2] - vectorC = [20] - let vectorD: [Float] = [3] - - vDSP.multiply(subtraction: (vectorA, vectorB), - subtraction: (vectorC, vectorD), - result: &result) - - let returnedResult = vDSP.multiply(subtraction: (vectorA, vectorB), - subtraction: (vectorC, vectorD)) - - expectEqual(lround(result.first!), 170) - expectEqual(lround(returnedResult.first!), 170) - } - - // e[i] = (a[i] + b[i]) * (c[i] - d[i]) - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vasbm") { - vectorA = [16] - vectorB = [4] - vectorC = [102] - let vectorD: [Float] = [2] - - vDSP.multiply(addition: (vectorA, vectorB), - subtraction: (vectorC, vectorD), - result: &result) - - let returnedResult = vDSP.multiply(addition: (vectorA, vectorB), - subtraction: (vectorC, vectorD)) - - expectEqual(lround(result.first!), 2000) - expectEqual(lround(returnedResult.first!), 2000) - } - - // d[n] = a[n]*b + c - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsmsa") { - vectorA = [12] - scalarA = 2 - scalarB = 6 - - vDSP.add(multiplication: (vectorA, scalarA), - scalarB, - result: &result) - - let returnedResult = vDSP.add(multiplication: (vectorA, scalarA), - scalarB) - - expectEqual(lround(result.first!), 30) - expectEqual(lround(returnedResult.first!), 30) - } - - // D[n] = A[n]*B - C[n]; - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsmsb") { - vectorA = [10] - scalarB = 5 - vectorC = [25] - - vDSP.subtract(multiplication: (vectorA, scalarB), - vectorC, - result: &result) - - let returnedResult = vDSP.subtract(multiplication: (vectorA, scalarB), - vectorC) - - expectEqual(lround(result.first!), 25) - expectEqual(lround(returnedResult.first!), 25) - } -} - - -//===----------------------------------------------------------------------===// -// -// vDSP Double Precision Arithmetic -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - var result = [Double.nan] - - var vectorA = [Double.nan] - var vectorB = [Double.nan] - var vectorC = [Double.nan] - - var scalarA = Double.nan - var scalarB = Double.nan - - // c[i] = a[i] + b - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsaddD") { - scalarA = 100 - vectorB = [500] - - vDSP.add(scalarA, - vectorB, - result: &result) - - let returnedResult = vDSP.add(scalarA, - vectorB) - - expectEqual(lround(result.first!), 600) - expectEqual(lround(returnedResult.first!), 600) - } - - // c[i] = a[i] + b[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vaddD") { - vectorA = [750] - vectorB = [250] - - vDSP.add(vectorA, - vectorB, - result: &result) - - let returnedResult = vDSP.add(vectorA, - vectorB) - - expectEqual(lround(result.first!), 1000) - expectEqual(lround(returnedResult.first!), 1000) - } - - // c[i] = a[i] - b[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsubD") { - vectorA = [5] - vectorB = [30] - - vDSP.subtract(vectorA, - vectorB, - result: &result) - - let returnedResult = vDSP.subtract(vectorA, - vectorB) - - expectEqual(lround(result.first!), -25) - expectEqual(lround(returnedResult.first!), -25) - } - - // c[i] = a[i] * b - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsmulD") { - scalarA = 100 - vectorB = [3] - - vDSP.multiply(scalarA, - vectorB, - result: &result) - - let returnedResult = vDSP.multiply(scalarA, - vectorB) - - expectEqual(lround(result.first!), 300) - expectEqual(lround(returnedResult.first!), 300) - } - - // a[i] * b[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vmulD") { - vectorA = [6] - vectorB = [10] - - vDSP.multiply(vectorA, - vectorB, - result: &result) - - let returnedResult = vDSP.multiply(vectorA, - vectorB) - - expectEqual(lround(result.first!), 60) - expectEqual(lround(returnedResult.first!), 60) - } - - // c[i] = a[i] / b - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsdivD") { - scalarA = 4 - vectorB = [100] - - vDSP.divide(vectorB, - scalarA, - result: &result) - - let returnedResult = vDSP.divide(vectorB, - scalarA) - - expectEqual(lround(result.first!), 25) - expectEqual(lround(returnedResult.first!), 25) - } - - // c[i] = a / b[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/svdivD") { - scalarA = 200 - vectorB = [4] - - vDSP.divide(scalarA, - vectorB, - result: &result) - - let returnedResult = vDSP.divide(scalarA, - vectorB) - - expectEqual(lround(result.first!), 50) - expectEqual(lround(returnedResult.first!), 50) - } - - // c[i] = a[i] / b[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vdivD") { - vectorA = [600] - vectorB = [3] - - vDSP.divide(vectorA, - vectorB, - result: &result) - - let returnedResult = vDSP.divide(vectorA, - vectorB) - - expectEqual(lround(result.first!), 200) - expectEqual(lround(returnedResult.first!), 200) - } - - // o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vaddsubD") { - vectorA = [16] - vectorB = [4] - var subtractResult = [ Double.nan ] - - vDSP.addSubtract(vectorA, - vectorB, - addResult: &result, - subtractResult: &subtractResult) - - expectEqual(lround(result.first!), 20) - expectEqual(lround(subtractResult.first!), 12) - } - - // d[i] = (a[i] + b[i]) * c - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vasmD") { - vectorA = [4] - vectorB = [16] - scalarA = 4 - - vDSP.multiply(addition: (vectorA, vectorB), - scalarA, - result: &result) - - let returnedResult = vDSP.multiply(addition: (vectorA, vectorB), - scalarA) - - expectEqual(lround(result.first!), 80) - expectEqual(lround(returnedResult.first!), 80) - } - - // d[i] = (a[i] + b[i]) * c[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vamD") { - vectorA = [4] - vectorB = [16] - vectorC = [5] - - vDSP.multiply(addition: (vectorA, vectorB), - vectorC, - result: &result) - - let returnedResult = vDSP.multiply(addition: (vectorA, vectorB), - vectorC) - - expectEqual(lround(result.first!), 100) - expectEqual(lround(returnedResult.first!), 100) - } - - // d[i] = (a[i] - b[i]) * c - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsbsmD") { - vectorA = [20] - vectorB = [5] - scalarA = 2 - - vDSP.multiply(subtraction: (vectorA, vectorB), - scalarA, - result: &result) - - let returnedResult = vDSP.multiply(subtraction: (vectorA, vectorB), - scalarA) - - expectEqual(lround(result.first!), 30) - expectEqual(lround(returnedResult.first!), 30) - } - - // d[i] = (a[i] - b[i]) * c[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsbmD") { - vectorA = [20] - vectorB = [5] - vectorC = [2] - - vDSP.multiply(subtraction: (vectorA, vectorB), - vectorC, - result: &result) - - let returnedResult = vDSP.multiply(subtraction: (vectorA, vectorB), - vectorC) - - expectEqual(lround(result.first!), 30) - expectEqual(lround(returnedResult.first!), 30) - } - - // a[i]*b[i] + c - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vmsaD") { - vectorA = [18] - vectorB = [10] - scalarA = 20 - - vDSP.add(multiplication: (vectorA, vectorB), - scalarA, - result: &result) - - let returnedResult = vDSP.add(multiplication: (vectorA, vectorB), - scalarA) - - expectEqual(lround(result.first!), 200) - expectEqual(lround(returnedResult.first!), 200) - } - - // (a[i] * b) + c[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsmaD") { - vectorA = [18] - scalarB = 10 - vectorC = [120] - - vDSP.add(multiplication: (vectorA, scalarB), - vectorC, - result: &result) - - let returnedResult = vDSP.add(multiplication: (vectorA, scalarB), - vectorC) - - expectEqual(lround(result.first!), 300) - expectEqual(lround(returnedResult.first!), 300) - } - - // d[i] = (a[i] * b[i]) + c[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vmaD") { - vectorA = [5] - vectorB = [20] - vectorC = [6] - - vDSP.add(multiplication: (vectorA, vectorB), - vectorC, - result: &result) - - let returnedResult = vDSP.add(multiplication: (vectorA, vectorB), - vectorC) - - expectEqual(lround(result.first!), 106) - expectEqual(lround(returnedResult.first!), 106) - } - - // d[i] = (a[i] * b[i]) - c[i] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vmsbD") { - vectorA = [25] - vectorB = [2] - vectorC = [50] - - vDSP.subtract(multiplication: (vectorB, vectorC), - vectorA, - result: &result) - - let returnedResult = vDSP.subtract(multiplication: (vectorB, vectorC), - vectorA) - - expectEqual(lround(result.first!), 75) - expectEqual(lround(returnedResult.first!), 75) - } - - // e[i] = (a[i] * b) + (c[i] * d) - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsmsmaD") { - vectorA = [5] - scalarA = 100 - vectorB = [50] - scalarB = 4 - - vDSP.add(multiplication: (vectorA, scalarA), - multiplication: (vectorB, scalarB), - result: &result) - - let returnedResult = vDSP.add(multiplication: (vectorA, scalarA), - multiplication: (vectorB, scalarB)) - - expectEqual(lround(result.first!), 700) - expectEqual(lround(returnedResult.first!), 700) - } - - // E[n] = A[n]*B[n] + C[n]*D[n] - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vmmaD") { - vectorA = [2] - vectorB = [10] - vectorC = [3] - let vectorD: [Double] = [20] - - vDSP.add(multiplication: (vectorA, vectorB), - multiplication: (vectorC, vectorD), - result: &result) - - let returnedResult = vDSP.add(multiplication: (vectorA, vectorB), - multiplication: (vectorC, vectorD)) - - expectEqual(lround(result.first!), 80) - expectEqual(lround(returnedResult.first!), 80) - } - - // e[i] = (a[i] + b[i]) * (c[i] + d[i]) - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vaamD") { - vectorA = [2] - vectorB = [8] - vectorC = [3] - let vectorD: [Double] = [17] - - vDSP.multiply(addition: (vectorA, vectorB), - addition: (vectorC, vectorD), - result: &result) - - let returnedResult = vDSP.multiply(addition: (vectorA, vectorB), - addition: (vectorC, vectorD)) - - expectEqual(lround(result.first!), 200) - expectEqual(lround(returnedResult.first!), 200) - } - - // e[i] = (a[i] * b[i]) - (c[i] * d[i]) - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vmmsbD") { - vectorA = [2] - vectorB = [3] - vectorC = [5] - let vectorD: [Double] = [15] - - vDSP.subtract(multiplication: (vectorA, vectorB), - multiplication: (vectorC, vectorD), - result: &result) - - let returnedResult = vDSP.subtract(multiplication: (vectorA, vectorB), - multiplication: (vectorC, vectorD)) - - expectEqual(lround(result.first!), -69) - expectEqual(lround(returnedResult.first!), -69) - } - - // e[i] = (a[i] - b[i]) * (c[i] - d[i]) - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsbsbmD") { - vectorA = [12] - vectorB = [2] - vectorC = [20] - let vectorD: [Double] = [3] - - vDSP.multiply(subtraction: (vectorA, vectorB), - subtraction: (vectorC, vectorD), - result: &result) - - let returnedResult = vDSP.multiply(subtraction: (vectorA, vectorB), - subtraction: (vectorC, vectorD)) - - expectEqual(lround(result.first!), 170) - expectEqual(lround(returnedResult.first!), 170) - } - - // e[i] = (a[i] + b[i]) * (c[i] - d[i]) - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vasbmD") { - vectorA = [16] - vectorB = [4] - vectorC = [102] - let vectorD: [Double] = [2] - - vDSP.multiply(addition: (vectorA, vectorB), - subtraction: (vectorC, vectorD), - result: &result) - - let returnedResult = vDSP.multiply(addition: (vectorA, vectorB), - subtraction: (vectorC, vectorD)) - - expectEqual(lround(result.first!), 2000) - expectEqual(lround(returnedResult.first!), 2000) - } - - // d[n] = a[n]*b + c - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsmsaD") { - vectorA = [12] - scalarA = 2 - scalarB = 6 - - vDSP.add(multiplication: (vectorA, scalarA), - scalarB, - result: &result) - - let returnedResult = vDSP.add(multiplication: (vectorA, scalarA), - scalarB) - - expectEqual(lround(result.first!), 30) - expectEqual(lround(returnedResult.first!), 30) - } - - // D[n] = A[n]*B - C[n]; - Accelerate_vDSPElementwiseArithmeticTests.test("vDSP/vsmsbD") { - vectorA = [10] - scalarB = 5 - vectorC = [25] - - vDSP.subtract(multiplication: (vectorA, scalarB), - vectorC, - result: &result) - - let returnedResult = vDSP.subtract(multiplication: (vectorA, scalarB), - vectorC) - - expectEqual(lround(result.first!), 25) - expectEqual(lround(returnedResult.first!), 25) - } -} - - -runAllTests() diff --git a/test/stdlib/Accelerate_vDSPFillClearGenerate.swift b/test/stdlib/Accelerate_vDSPFillClearGenerate.swift deleted file mode 100644 index 66ee215df45c3..0000000000000 --- a/test/stdlib/Accelerate_vDSPFillClearGenerate.swift +++ /dev/null @@ -1,647 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var Accelerate_vDSPFillClearGenerateTests = TestSuite("Accelerate_vDSPFillClearGenerate") - -//===----------------------------------------------------------------------===// -// -// vDSP vector fill, clear, and generation tests -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let count = 256 - let n = vDSP_Length(256) - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/SinglePrecisionFill") { - var result = [Float](repeating: 1, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.fill(&result, - with: 999) - - vDSP_vfill([999], - &legacyResult, 1, - n) - - expectTrue(result.elementsEqual(legacyResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/SinglePrecisionClear") { - var result = [Float](repeating: 1, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.clear(&result) - - vDSP_vclr(&legacyResult, 1, - n) - - expectTrue(result.elementsEqual(legacyResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/DoublePrecisionFill") { - var result = [Double](repeating: 1, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.fill(&result, - with: 999) - - vDSP_vfillD([999], - &legacyResult, 1, - n) - - expectTrue(result.elementsEqual(legacyResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/DoublePrecisionClear") { - var result = [Double](repeating: 1, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.clear(&result) - - vDSP_vclrD(&legacyResult, 1, - n) - - expectTrue(result.elementsEqual(legacyResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/SinglePrecisionHanningNormalized") { - var result = [Float](repeating: 1, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .hanningNormalized, - result: &result, - isHalfWindow: false) - - vDSP_hann_window(&legacyResult, - n, - Int32(vDSP_HANN_NORM)) - - let returnedResult = vDSP.window(ofType: Float.self, - usingSequence: .hanningNormalized, - count: count, - isHalfWindow: false) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/SinglePrecisionHanningNormalizedHalf") { - var result = [Float](repeating: 1, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .hanningNormalized, - result: &result, - isHalfWindow: true) - - vDSP_hann_window(&legacyResult, - n, - Int32(vDSP_HANN_NORM | vDSP_HALF_WINDOW)) - - let returnedResult = vDSP.window(ofType: Float.self, - usingSequence: .hanningNormalized, - count: count, - isHalfWindow: true) - - expectTrue(result[0 ..< count / 2].elementsEqual(legacyResult[0 ..< count / 2])) - expectTrue(result[0 ..< count / 2].elementsEqual(returnedResult[0 ..< count / 2])) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/SinglePrecisionHanningDenormalized") { - var result = [Float](repeating: 1, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .hanningDenormalized, - result: &result, - isHalfWindow: false) - - vDSP_hann_window(&legacyResult, - n, - Int32(vDSP_HANN_DENORM)) - - let returnedResult = vDSP.window(ofType: Float.self, - usingSequence: .hanningDenormalized, - count: count, - isHalfWindow: false) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/SinglePrecisionHanningDenormalizedHalf") { - var result = [Float](repeating: 1, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .hanningDenormalized, - result: &result, - isHalfWindow: true) - - vDSP_hann_window(&legacyResult, - n, - Int32(vDSP_HANN_DENORM | vDSP_HALF_WINDOW)) - - let returnedResult = vDSP.window(ofType: Float.self, - usingSequence: .hanningDenormalized, - count: count, - isHalfWindow: true) - - expectTrue(result[0 ..< count / 2].elementsEqual(legacyResult[0 ..< count / 2])) - expectTrue(result[0 ..< count / 2].elementsEqual(returnedResult[0 ..< count / 2])) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/SinglePrecisionHamming") { - var result = [Float](repeating: 1, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .hamming, - result: &result, - isHalfWindow: false) - - vDSP_hamm_window(&legacyResult, - n, - 0) - - let returnedResult = vDSP.window(ofType: Float.self, - usingSequence: .hamming, - count: count, - isHalfWindow: false) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/SinglePrecisionHammingHalf") { - var result = [Float](repeating: 1, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .hamming, - result: &result, - isHalfWindow: true) - - vDSP_hamm_window(&legacyResult, - n, - Int32(vDSP_HALF_WINDOW)) - - let returnedResult = vDSP.window(ofType: Float.self, - usingSequence: .hamming, - count: count, - isHalfWindow: true) - - expectTrue(result[0 ..< count / 2].elementsEqual(legacyResult[0 ..< count / 2])) - expectTrue(result[0 ..< count / 2].elementsEqual(returnedResult[0 ..< count / 2])) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/SinglePrecisionBlackman") { - var result = [Float](repeating: 1, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .blackman, - result: &result, - isHalfWindow: false) - - vDSP_blkman_window(&legacyResult, - n, - 0) - - let returnedResult = vDSP.window(ofType: Float.self, - usingSequence: .blackman, - count: count, - isHalfWindow: false) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/SinglePrecisionBlackmanHalf") { - var result = [Float](repeating: 1, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .blackman, - result: &result, - isHalfWindow: true) - - vDSP_blkman_window(&legacyResult, - n, - Int32(vDSP_HALF_WINDOW)) - - let returnedResult = vDSP.window(ofType: Float.self, - usingSequence: .blackman, - count: count, - isHalfWindow: true) - - expectTrue(result[0 ..< count / 2].elementsEqual(legacyResult[0 ..< count / 2])) - expectTrue(result[0 ..< count / 2].elementsEqual(returnedResult[0 ..< count / 2])) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/DoublePrecisionHanningNormalized") { - var result = [Double](repeating: 1, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .hanningNormalized, - result: &result, - isHalfWindow: false) - - vDSP_hann_windowD(&legacyResult, - n, - Int32(vDSP_HANN_NORM)) - - let returnedResult = vDSP.window(ofType: Double.self, - usingSequence: .hanningNormalized, - count: count, - isHalfWindow: false) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/DoublePrecisionHanningNormalizedHalf") { - var result = [Double](repeating: 1, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .hanningNormalized, - result: &result, - isHalfWindow: true) - - vDSP_hann_windowD(&legacyResult, - n, - Int32(vDSP_HANN_NORM | vDSP_HALF_WINDOW)) - - let returnedResult = vDSP.window(ofType: Double.self, - usingSequence: .hanningNormalized, - count: count, - isHalfWindow: true) - - expectTrue(result[0 ..< count / 2].elementsEqual(legacyResult[0 ..< count / 2])) - expectTrue(result[0 ..< count / 2].elementsEqual(returnedResult[0 ..< count / 2])) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/DoublePrecisionHanningDenormalized") { - var result = [Double](repeating: 1, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .hanningDenormalized, - result: &result, - isHalfWindow: false) - - vDSP_hann_windowD(&legacyResult, - n, - Int32(vDSP_HANN_DENORM)) - - let returnedResult = vDSP.window(ofType: Double.self, - usingSequence: .hanningDenormalized, - count: count, - isHalfWindow: false) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/DoublePrecisionHanningDenormalizedHalf") { - var result = [Double](repeating: 1, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .hanningDenormalized, - result: &result, - isHalfWindow: true) - - vDSP_hann_windowD(&legacyResult, - n, - Int32(vDSP_HANN_DENORM | vDSP_HALF_WINDOW)) - - let returnedResult = vDSP.window(ofType: Double.self, - usingSequence: .hanningDenormalized, - count: count, - isHalfWindow: true) - - expectTrue(result[0 ..< count / 2].elementsEqual(legacyResult[0 ..< count / 2])) - expectTrue(result[0 ..< count / 2].elementsEqual(returnedResult[0 ..< count / 2])) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/DoublePrecisionHamming") { - var result = [Double](repeating: 1, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .hamming, - result: &result, - isHalfWindow: false) - - vDSP_hamm_windowD(&legacyResult, - n, - 0) - - let returnedResult = vDSP.window(ofType: Double.self, - usingSequence: .hamming, - count: count, - isHalfWindow: false) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/DoublePrecisionHammingHalf") { - var result = [Double](repeating: 1, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .hamming, - result: &result, - isHalfWindow: true) - - vDSP_hamm_windowD(&legacyResult, - n, - Int32(vDSP_HALF_WINDOW)) - - let returnedResult = vDSP.window(ofType: Double.self, - usingSequence: .hamming, - count: count, - isHalfWindow: true) - - expectTrue(result[0 ..< count / 2].elementsEqual(legacyResult[0 ..< count / 2])) - expectTrue(result[0 ..< count / 2].elementsEqual(returnedResult[0 ..< count / 2])) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/DoublePrecisionBlackman") { - var result = [Double](repeating: 1, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .blackman, - result: &result, - isHalfWindow: false) - - vDSP_blkman_windowD(&legacyResult, - n, - 0) - - let returnedResult = vDSP.window(ofType: Double.self, - usingSequence: .blackman, - count: count, - isHalfWindow: false) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/DoublePrecisionBlackmanHalf") { - var result = [Double](repeating: 1, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.formWindow(usingSequence: .blackman, - result: &result, - isHalfWindow: true) - - vDSP_blkman_windowD(&legacyResult, - n, - Int32(vDSP_HALF_WINDOW)) - - let returnedResult = vDSP.window(ofType: Double.self, - usingSequence: .blackman, - count: count, - isHalfWindow: true) - - expectTrue(result[0 ..< count / 2].elementsEqual(legacyResult[0 ..< count / 2])) - expectTrue(result[0 ..< count / 2].elementsEqual(returnedResult[0 ..< count / 2])) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/SinglePrecisionWithRange") { - var result = [Float](repeating: 1, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.formRamp(in: 0 ... 100, - result: &result) - - vDSP_vgen([0], - [100], - &legacyResult, 1, - n) - - let returnedResult = vDSP.ramp(in: Float(0) ... Float(100), - count: count) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/SinglePrecisionRampWithIncrement") { - var result = [Float](repeating: 1, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.formRamp(withInitialValue: 0, - increment: 0.1, - result: &result) - - vDSP_vramp([0], - [0.1], - &legacyResult, 1, - n) - - let returnedResult = vDSP.ramp(withInitialValue: Float(0), - increment: Float(0.1), - count: count) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/SinglePrecisionRampWithMultiplier") { - var result = [Float](repeating: 1, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - let multiplier = (0 ..< n).map{ i in - return sin(Float(i) * 0.05) - } - - var start = Float(10) - - vDSP.formRamp(withInitialValue: &start, - multiplyingBy: multiplier, - increment: 1, - result: &result) - - var legacyStart = Float(10) - - vDSP_vrampmul(multiplier, 1, - &legacyStart, - [1], - &legacyResult, 1, - n) - - var start2 = Float(10) - let returnedResult = vDSP.ramp(withInitialValue: &start2, - multiplyingBy: multiplier, - increment: 1) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - - expectEqual(start, legacyStart) - expectEqual(start, start2) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/StereoSinglePrecisionRampWithMultiplier") { - var result = [Float](repeating: 1, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - let multiplierOne = (0 ..< n).map{ i in - return sin(Float(i) * 0.05) - } - let multiplierTwo = (0 ..< n).map{ i in - return sin(Float(i) * 0.0125) - } - - var start = Float(10) - var resultTwo = [Float](repeating: 2, count: result.count) - - vDSP.formStereoRamp(withInitialValue: &start, - multiplyingBy: multiplierOne, multiplierTwo, - increment: 1, - results: &result, &resultTwo) - - var legacyStart = Float(10) - var legacyResultTwo = [Float](repeating: -2, count: legacyResult.count) - - vDSP_vrampmul2(multiplierOne, multiplierTwo, 1, - &legacyStart, - [1], - &legacyResult, &legacyResultTwo, 1, - n) - - var start2 = Float(10) - let returnedResult = vDSP.stereoRamp(withInitialValue: &start2, - multiplyingBy: multiplierOne, multiplierTwo, - increment: 1) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(resultTwo.elementsEqual(legacyResultTwo)) - expectEqual(start, legacyStart) - - expectTrue(result.elementsEqual(returnedResult.firstOutput)) - expectTrue(resultTwo.elementsEqual(returnedResult.secondOutput)) - expectEqual(start, start2) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/DoublePrecisionRampWithRange") { - var result = [Double](repeating: 1, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.formRamp(in: 0 ... 100, - result: &result) - - vDSP_vgenD([0], - [100], - &legacyResult, 1, - n) - - let returnedResult = vDSP.ramp(in: Double(0) ... Double(100), - count: count) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/DoublePrecisionRampWithRange") { - var result = [Double](repeating: 1, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.formRamp(withInitialValue: 0, - increment: 0.1, - result: &result) - - vDSP_vrampD([0], - [0.1], - &legacyResult, 1, - n) - - let returnedResult = vDSP.ramp(withInitialValue: 0, - increment: 0.1, - count: count) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/DoublePrecisionRampWithMultiplier") { - var result = [Double](repeating: 1, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - let multiplier = (0 ..< n).map{ i in - return sin(Double(i) * 0.05) - } - - var start = Double(10) - - vDSP.formRamp(withInitialValue: &start, - multiplyingBy: multiplier, - increment: 1, - result: &result) - - var legacyStart = Double(10) - - vDSP_vrampmulD(multiplier, 1, - &legacyStart, - [1], - &legacyResult, 1, - n) - - var start2 = Double(10) - let returnedResult = vDSP.ramp(withInitialValue: &start2, - multiplyingBy: multiplier, - increment: 1) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - - expectEqual(start, legacyStart) - expectEqual(start, start2) - } - - Accelerate_vDSPFillClearGenerateTests.test("vDSP/StereoDoublePrecisionRampWithMultiplier") { - var result = [Double](repeating: 1, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - let multiplierOne = (0 ..< n).map{ i in - return sin(Double(i) * 0.05) - } - let multiplierTwo = (0 ..< n).map{ i in - return sin(Double(i) * 0.0125) - } - - var start = Double(10) - var resultTwo = [Double](repeating: 2, count: result.count) - - vDSP.formStereoRamp(withInitialValue: &start, - multiplyingBy: multiplierOne, multiplierTwo, - increment: 1, - results: &result, &resultTwo) - - var legacyStart = Double(10) - var legacyResultTwo = [Double](repeating: -2, count: legacyResult.count) - - vDSP_vrampmul2D(multiplierOne, multiplierTwo, 1, - &legacyStart, - [1], - &legacyResult, &legacyResultTwo, 1, - n) - - var start2 = Double(10) - let returnedResult = vDSP.stereoRamp(withInitialValue: &start2, - multiplyingBy: multiplierOne, multiplierTwo, - increment: 1) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(resultTwo.elementsEqual(legacyResultTwo)) - expectEqual(start, legacyStart) - - expectTrue(result.elementsEqual(returnedResult.firstOutput)) - expectTrue(resultTwo.elementsEqual(returnedResult.secondOutput)) - expectEqual(start, start2) - } -} - -runAllTests() diff --git a/test/stdlib/Accelerate_vDSPFourierTransform.swift b/test/stdlib/Accelerate_vDSPFourierTransform.swift deleted file mode 100644 index 87d74d22eaf34..0000000000000 --- a/test/stdlib/Accelerate_vDSPFourierTransform.swift +++ /dev/null @@ -1,725 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var Accelerate_vDSPFourierTransformTests = TestSuite("Accelerate_vDSPFourierTransform") - - -//===----------------------------------------------------------------------===// -// -// vDSP discrete Fourier transform tests; single-precision -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let n = 2048 - let tau: Float = .pi * 2 - - let frequencies: [Float] = [1, 5, 25, 30, 75, 100, - 300, 500, 512, 1023] - - let inputReal: [Float] = (0 ..< n).map { index in - frequencies.reduce(0) { accumulator, frequency in - let normalizedIndex = Float(index) / Float(n) - return accumulator + sin(normalizedIndex * frequency * tau) - } - } - - let inputImag: [Float] = (0 ..< n).map { index in - frequencies.reduce(0) { accumulator, frequency in - let normalizedIndex = Float(index) / Float(n) - return accumulator + sin(normalizedIndex * 1/frequency * tau) - } - } - - Accelerate_vDSPFourierTransformTests.test("vDSP/SinglePrecisionForwardComplexComplex") { - let fwdDFT = vDSP.DFT(count: n, - direction: .forward, - transformType: .complexComplex, - ofType: Float.self)! - - var outputReal = [Float](repeating: 0, count: n) - var outputImag = [Float](repeating: 0, count: n) - - fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag, - outputReal: &outputReal, - outputImaginary: &outputImag) - - // legacy... - - let legacySetup = vDSP_DFT_zop_CreateSetup(nil, - vDSP_Length(n), - .FORWARD)! - - var legacyOutputReal = [Float](repeating: -1, count: n) - var legacyOutputImag = [Float](repeating: -1, count: n) - - vDSP_DFT_Execute(legacySetup, - inputReal, - inputImag, - &legacyOutputReal, - &legacyOutputImag) - - expectTrue(outputReal.elementsEqual(legacyOutputReal)) - expectTrue(outputImag.elementsEqual(legacyOutputImag)) - - let returnedResult = fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag) - - expectTrue(outputReal.elementsEqual(returnedResult.real)) - expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) - } - - Accelerate_vDSPFourierTransformTests.test("vDSP/SinglePrecisionInverseComplexComplex") { - let fwdDFT = vDSP.DFT(count: n, - direction: .inverse, - transformType: .complexComplex, - ofType: Float.self)! - - var outputReal = [Float](repeating: 0, count: n) - var outputImag = [Float](repeating: 0, count: n) - - fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag, - outputReal: &outputReal, - outputImaginary: &outputImag) - - // legacy... - - let legacySetup = vDSP_DFT_zop_CreateSetup(nil, - vDSP_Length(n), - .INVERSE)! - - var legacyOutputReal = [Float](repeating: -1, count: n) - var legacyOutputImag = [Float](repeating: -1, count: n) - - vDSP_DFT_Execute(legacySetup, - inputReal, - inputImag, - &legacyOutputReal, - &legacyOutputImag) - - expectTrue(outputReal.elementsEqual(legacyOutputReal)) - expectTrue(outputImag.elementsEqual(legacyOutputImag)) - - let returnedResult = fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag) - - expectTrue(outputReal.elementsEqual(returnedResult.real)) - expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) - } - - Accelerate_vDSPFourierTransformTests.test("vDSP/SinglePrecisionForwardComplexReal") { - let fwdDFT = vDSP.DFT(count: n, - direction: .forward, - transformType: .complexReal, - ofType: Float.self)! - - var outputReal = [Float](repeating: 0, count: n / 2) - var outputImag = [Float](repeating: 0, count: n / 2) - - fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag, - outputReal: &outputReal, - outputImaginary: &outputImag) - - // legacy... - - let legacySetup = vDSP_DFT_zrop_CreateSetup(nil, - vDSP_Length(n), - .FORWARD)! - - var legacyOutputReal = [Float](repeating: -1, count: n / 2) - var legacyOutputImag = [Float](repeating: -1, count: n / 2) - - vDSP_DFT_Execute(legacySetup, - inputReal, - inputImag, - &legacyOutputReal, - &legacyOutputImag) - - expectTrue(outputReal.elementsEqual(legacyOutputReal)) - expectTrue(outputImag.elementsEqual(legacyOutputImag)) - - let returnedResult = fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag) - - expectTrue(outputReal.elementsEqual(returnedResult.real)) - expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) - } - - Accelerate_vDSPFourierTransformTests.test("vDSP/SinglePrecisionInverseComplexReal") { - let fwdDFT = vDSP.DFT(count: n, - direction: .inverse, - transformType: .complexReal, - ofType: Float.self)! - - var outputReal = [Float](repeating: 0, count: n / 2) - var outputImag = [Float](repeating: 0, count: n / 2) - - fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag, - outputReal: &outputReal, - outputImaginary: &outputImag) - - // legacy... - - let legacySetup = vDSP_DFT_zrop_CreateSetup(nil, - vDSP_Length(n), - .INVERSE)! - - var legacyOutputReal = [Float](repeating: -1, count: n / 2) - var legacyOutputImag = [Float](repeating: -1, count: n / 2) - - vDSP_DFT_Execute(legacySetup, - inputReal, - inputImag, - &legacyOutputReal, - &legacyOutputImag) - - expectTrue(outputReal.elementsEqual(legacyOutputReal)) - expectTrue(outputImag.elementsEqual(legacyOutputImag)) - - let returnedResult = fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag) - - expectTrue(outputReal.elementsEqual(returnedResult.real)) - expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) - } -} - - -//===----------------------------------------------------------------------===// -// -// vDSP discrete Fourier transform tests; double-precision -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let n = 2048 - let tau: Double = .pi * 2 - - let frequencies: [Double] = [1, 5, 25, 30, 75, 100, - 300, 500, 512, 1023] - - let inputReal: [Double] = (0 ..< n).map { index in - frequencies.reduce(0) { accumulator, frequency in - let normalizedIndex = Double(index) / Double(n) - return accumulator + sin(normalizedIndex * frequency * tau) - } - } - - let inputImag: [Double] = (0 ..< n).map { index in - frequencies.reduce(0) { accumulator, frequency in - let normalizedIndex = Double(index) / Double(n) - return accumulator + sin(normalizedIndex * 1/frequency * tau) - } - } - - Accelerate_vDSPFourierTransformTests.test("vDSP/DoublePrecisionForwardComplexComplex") { - let fwdDFT = vDSP.DFT(count: n, - direction: .forward, - transformType: .complexComplex, - ofType: Double.self)! - - var outputReal = [Double](repeating: 0, count: n) - var outputImag = [Double](repeating: 0, count: n) - - fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag, - outputReal: &outputReal, - outputImaginary: &outputImag) - - // legacy... - - let legacySetup = vDSP_DFT_zop_CreateSetupD(nil, - vDSP_Length(n), - .FORWARD)! - - var legacyOutputReal = [Double](repeating: -1, count: n) - var legacyOutputImag = [Double](repeating: -1, count: n) - - vDSP_DFT_ExecuteD(legacySetup, - inputReal, - inputImag, - &legacyOutputReal, - &legacyOutputImag) - - expectTrue(outputReal.elementsEqual(legacyOutputReal)) - expectTrue(outputImag.elementsEqual(legacyOutputImag)) - - let returnedResult = fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag) - - expectTrue(outputReal.elementsEqual(returnedResult.real)) - expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) - } - - Accelerate_vDSPFourierTransformTests.test("vDSP/DoublePrecisionInverseComplexComplex") { - let fwdDFT = vDSP.DFT(count: n, - direction: .inverse, - transformType: .complexComplex, - ofType: Double.self)! - - var outputReal = [Double](repeating: 0, count: n) - var outputImag = [Double](repeating: 0, count: n) - - fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag, - outputReal: &outputReal, - outputImaginary: &outputImag) - - // legacy... - - let legacySetup = vDSP_DFT_zop_CreateSetupD(nil, - vDSP_Length(n), - .INVERSE)! - - var legacyOutputReal = [Double](repeating: -1, count: n) - var legacyOutputImag = [Double](repeating: -1, count: n) - - vDSP_DFT_ExecuteD(legacySetup, - inputReal, - inputImag, - &legacyOutputReal, - &legacyOutputImag) - - expectTrue(outputReal.elementsEqual(legacyOutputReal)) - expectTrue(outputImag.elementsEqual(legacyOutputImag)) - - let returnedResult = fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag) - - expectTrue(outputReal.elementsEqual(returnedResult.real)) - expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) - } - - Accelerate_vDSPFourierTransformTests.test("vDSP/DoublePrecisionForwardComplexReal") { - let fwdDFT = vDSP.DFT(count: n, - direction: .forward, - transformType: .complexReal, - ofType: Double.self)! - - var outputReal = [Double](repeating: 0, count: n / 2) - var outputImag = [Double](repeating: 0, count: n / 2) - - fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag, - outputReal: &outputReal, - outputImaginary: &outputImag) - - // legacy... - - let legacySetup = vDSP_DFT_zrop_CreateSetupD(nil, - vDSP_Length(n), - .FORWARD)! - - var legacyOutputReal = [Double](repeating: -1, count: n / 2) - var legacyOutputImag = [Double](repeating: -1, count: n / 2) - - vDSP_DFT_ExecuteD(legacySetup, - inputReal, - inputImag, - &legacyOutputReal, - &legacyOutputImag) - - expectTrue(outputReal.elementsEqual(legacyOutputReal)) - expectTrue(outputImag.elementsEqual(legacyOutputImag)) - - let returnedResult = fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag) - - expectTrue(outputReal.elementsEqual(returnedResult.real)) - expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) - } - - Accelerate_vDSPFourierTransformTests.test("vDSP/DoublePrecisionInverseComplexReal") { - let fwdDFT = vDSP.DFT(count: n, - direction: .inverse, - transformType: .complexReal, - ofType: Double.self)! - - var outputReal = [Double](repeating: 0, count: n / 2) - var outputImag = [Double](repeating: 0, count: n / 2) - - fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag, - outputReal: &outputReal, - outputImaginary: &outputImag) - - // legacy... - - let legacySetup = vDSP_DFT_zrop_CreateSetupD(nil, - vDSP_Length(n), - .INVERSE)! - - var legacyOutputReal = [Double](repeating: -1, count: n / 2) - var legacyOutputImag = [Double](repeating: -1, count: n / 2) - - vDSP_DFT_ExecuteD(legacySetup, - inputReal, - inputImag, - &legacyOutputReal, - &legacyOutputImag) - - expectTrue(outputReal.elementsEqual(legacyOutputReal)) - expectTrue(outputImag.elementsEqual(legacyOutputImag)) - - let returnedResult = fwdDFT.transform(inputReal: inputReal, - inputImaginary: inputImag) - - expectTrue(outputReal.elementsEqual(returnedResult.real)) - expectTrue(outputImag.elementsEqual(returnedResult.imaginary)) - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP Fast Fourier Transform Tests -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - Accelerate_vDSPFourierTransformTests.test("vDSP/2DSinglePrecision") { - let width = 256 - let height = 256 - let pixelCount = width * height - let n = pixelCount / 2 - - let pixels: [Float] = (0 ..< pixelCount).map { i in - return abs(sin(Float(i) * 0.001 * 2)) - } - - var sourceImageReal = [Float](repeating: 0, count: n) - var sourceImageImaginary = [Float](repeating: 0, count: n) - - sourceImageReal.withUnsafeMutableBufferPointer { sourceImageRealPtr in - sourceImageImaginary.withUnsafeMutableBufferPointer { sourceImageImaginaryPtr in - - var sourceImage = DSPSplitComplex(realp: sourceImageRealPtr.baseAddress!, - imagp: sourceImageImaginaryPtr.baseAddress!) - - pixels.withUnsafeBytes{ - vDSP_ctoz([DSPComplex]($0.bindMemory(to: DSPComplex.self)), 2, - &sourceImage, 1, - vDSP_Length(pixels.count / 2)) - } - - // Create FFT2D object - let fft2D = vDSP.FFT2D(width: 256, - height: 256, - ofType: DSPSplitComplex.self)! - - // New style transform - var transformedImageReal = [Float](repeating: 0, - count: n) - var transformedImageImaginary = [Float](repeating: 0, - count: n) - - transformedImageReal.withUnsafeMutableBufferPointer { transformedImageRealPtr in - transformedImageImaginary.withUnsafeMutableBufferPointer { transformedImageImaginaryPtr in - - var transformedImage = DSPSplitComplex( - realp: transformedImageRealPtr.baseAddress!, - imagp: transformedImageImaginaryPtr.baseAddress!) - - fft2D.transform(input: sourceImage, - output: &transformedImage, - direction: .forward) - } - } - - // Legacy 2D FFT - - let log2n = vDSP_Length(log2(Float(width * height))) - let legacySetup = vDSP_create_fftsetup( - log2n, - FFTRadix(kFFTRadix2))! - - var legacyTransformedImageReal = [Float](repeating: -1, - count: n) - var legacyTransformedImageImaginary = [Float](repeating: -1, - count: n) - - legacyTransformedImageReal.withUnsafeMutableBufferPointer { legacyTransformedImageRealPtr in - legacyTransformedImageImaginary.withUnsafeMutableBufferPointer { legacyTransformedImageImaginaryPtr in - - var legacyTransformedImage = DSPSplitComplex( - realp: legacyTransformedImageRealPtr.baseAddress!, - imagp: legacyTransformedImageImaginaryPtr.baseAddress!) - - vDSP_fft2d_zrop(legacySetup, - &sourceImage, 1, 0, - &legacyTransformedImage, 1, 0, - vDSP_Length(log2(Float(width))), - vDSP_Length(log2(Float(height))), - FFTDirection(kFFTDirection_Forward)) - } - } - - expectTrue(transformedImageReal.elementsEqual(legacyTransformedImageReal)) - expectTrue(transformedImageImaginary.elementsEqual(legacyTransformedImageImaginary)) - } - } - } - - Accelerate_vDSPFourierTransformTests.test("vDSP/2DDoublePrecision") { - let width = 256 - let height = 256 - let pixelCount = width * height - let n = pixelCount / 2 - - let pixels: [Double] = (0 ..< pixelCount).map { i in - return abs(sin(Double(i) * 0.001 * 2)) - } - - var sourceImageReal = [Double](repeating: 0, count: n) - var sourceImageImaginary = [Double](repeating: 0, count: n) - - sourceImageReal.withUnsafeMutableBufferPointer { sourceImageRealPtr in - sourceImageImaginary.withUnsafeMutableBufferPointer { sourceImageImaginaryPtr in - - var sourceImage = DSPDoubleSplitComplex(realp: sourceImageRealPtr.baseAddress!, - imagp: sourceImageImaginaryPtr.baseAddress!) - - pixels.withUnsafeBytes{ - vDSP_ctozD([DSPDoubleComplex]($0.bindMemory(to: DSPDoubleComplex.self)), 2, - &sourceImage, 1, - vDSP_Length(pixels.count / 2)) - } - - // Create FFT2D object - let fft2D = vDSP.FFT2D(width: 256, - height: 256, - ofType: DSPDoubleSplitComplex.self)! - - // New style transform - var transformedImageReal = [Double](repeating: 0, - count: n) - var transformedImageImaginary = [Double](repeating: 0, - count: n) - - transformedImageReal.withUnsafeMutableBufferPointer { transformedImageRealPtr in - transformedImageImaginary.withUnsafeMutableBufferPointer { transformedImageImaginaryPtr in - - var transformedImage = DSPDoubleSplitComplex( - realp: transformedImageRealPtr.baseAddress!, - imagp: transformedImageImaginaryPtr.baseAddress!) - - fft2D.transform(input: sourceImage, - output: &transformedImage, - direction: .forward) - } - } - - // Legacy 2D FFT - - let log2n = vDSP_Length(log2(Float(width * height))) - let legacySetup = vDSP_create_fftsetupD( - log2n, - FFTRadix(kFFTRadix2))! - - var legacyTransformedImageReal = [Double](repeating: -1, - count: n) - var legacyTransformedImageImaginary = [Double](repeating: -1, - count: n) - - legacyTransformedImageReal.withUnsafeMutableBufferPointer { legacyTransformedImageRealPtr in - legacyTransformedImageImaginary.withUnsafeMutableBufferPointer { legacyTransformedImageImaginaryPtr in - - var legacyTransformedImage = DSPDoubleSplitComplex( - realp: legacyTransformedImageRealPtr.baseAddress!, - imagp: legacyTransformedImageImaginaryPtr.baseAddress!) - - vDSP_fft2d_zropD(legacySetup, - &sourceImage, 1, 0, - &legacyTransformedImage, 1, 0, - vDSP_Length(log2(Float(width))), - vDSP_Length(log2(Float(height))), - FFTDirection(kFFTDirection_Forward)) - } - } - - expectTrue(transformedImageReal.elementsEqual(legacyTransformedImageReal)) - expectTrue(transformedImageImaginary.elementsEqual(legacyTransformedImageImaginary)) - } - } - } - - Accelerate_vDSPFourierTransformTests.test("vDSP/1DSinglePrecision") { - let n = vDSP_Length(2048) - - let frequencies: [Float] = [1, 5, 25, 30, 75, 100, - 300, 500, 512, 1023] - - let tau: Float = .pi * 2 - let signal: [Float] = (0 ... n).map { index in - frequencies.reduce(0) { accumulator, frequency in - let normalizedIndex = Float(index) / Float(n) - return accumulator + sin(normalizedIndex * frequency * tau) - } - } - - let halfN = Int(n / 2) - - var forwardInputReal = [Float](repeating: 0, count: halfN) - var forwardInputImag = [Float](repeating: 0, count: halfN) - - forwardInputReal.withUnsafeMutableBufferPointer { forwardInputRealPtr in - forwardInputImag.withUnsafeMutableBufferPointer { forwardInputImagPtr in - - var forwardInput = DSPSplitComplex(realp: forwardInputRealPtr.baseAddress!, - imagp: forwardInputImagPtr.baseAddress!) - - signal.withUnsafeBytes{ - vDSP_ctoz([DSPComplex]($0.bindMemory(to: DSPComplex.self)), 2, - &forwardInput, 1, - vDSP_Length(signal.count / 2)) - } - - let log2n = vDSP_Length(log2(Float(n))) - - // New API - - guard let fft = vDSP.FFT(log2n: log2n, - radix: .radix2, - ofType: DSPSplitComplex.self) else { - fatalError("Can't create FFT.") - } - - var outputReal = [Float](repeating: 0, count: halfN) - var outputImag = [Float](repeating: 0, count: halfN) - - outputReal.withUnsafeMutableBufferPointer { outputRealPtr in - outputImag.withUnsafeMutableBufferPointer { outputImagPtr in - var forwardOutput = DSPSplitComplex(realp: outputRealPtr.baseAddress!, - imagp: outputImagPtr.baseAddress!) - - fft.transform(input: forwardInput, - output: &forwardOutput, - direction: .forward) - } - } - - // Legacy Style - - let legacySetup = vDSP_create_fftsetup(log2n, - FFTRadix(kFFTRadix2))! - - var legacyOutputReal = [Float](repeating: -1, count: halfN) - var legacyOutputImag = [Float](repeating: -1, count: halfN) - - legacyOutputReal.withUnsafeMutableBufferPointer { legacyOutputRealPtr in - legacyOutputImag.withUnsafeMutableBufferPointer { legacyOutputImagPtr in - var legacyForwardOutput = DSPSplitComplex(realp: legacyOutputRealPtr.baseAddress!, - imagp: legacyOutputImagPtr.baseAddress!) - - vDSP_fft_zrop(legacySetup, - &forwardInput, 1, - &legacyForwardOutput, 1, - log2n, - FFTDirection(kFFTDirection_Forward)) - } - } - - expectTrue(outputReal.elementsEqual(legacyOutputReal)) - expectTrue(outputImag.elementsEqual(legacyOutputImag)) - } - } - } - - Accelerate_vDSPFourierTransformTests.test("vDSP/1DDoublePrecision") { - let n = vDSP_Length(2048) - - let frequencies: [Double] = [1, 5, 25, 30, 75, 100, - 300, 500, 512, 1023] - - let tau: Double = .pi * 2 - let signal: [Double] = (0 ... n).map { index in - frequencies.reduce(0) { accumulator, frequency in - let normalizedIndex = Double(index) / Double(n) - return accumulator + sin(normalizedIndex * frequency * tau) - } - } - - let halfN = Int(n / 2) - - var forwardInputReal = [Double](repeating: 0, count: halfN) - var forwardInputImag = [Double](repeating: 0, count: halfN) - - forwardInputReal.withUnsafeMutableBufferPointer { forwardInputRealPtr in - forwardInputImag.withUnsafeMutableBufferPointer { forwardInputImagPtr in - - var forwardInput = DSPDoubleSplitComplex(realp: forwardInputRealPtr.baseAddress!, - imagp: forwardInputImagPtr.baseAddress!) - - signal.withUnsafeBytes{ - vDSP_ctozD([DSPDoubleComplex]($0.bindMemory(to: DSPDoubleComplex.self)), 2, - &forwardInput, 1, - vDSP_Length(signal.count / 2)) - } - - let log2n = vDSP_Length(log2(Float(n))) - - // New API - - guard let fft = vDSP.FFT(log2n: log2n, - radix: .radix2, - ofType: DSPDoubleSplitComplex.self) else { - fatalError("Can't create FFT.") - } - - var outputReal = [Double](repeating: 0, count: halfN) - var outputImag = [Double](repeating: 0, count: halfN) - - outputReal.withUnsafeMutableBufferPointer { outputRealPtr in - outputImag.withUnsafeMutableBufferPointer { outputImagPtr in - var forwardOutput = DSPDoubleSplitComplex(realp: outputRealPtr.baseAddress!, - imagp: outputImagPtr.baseAddress!) - - fft.transform(input: forwardInput, - output: &forwardOutput, - direction: .forward) - } - } - - // Legacy Style - - let legacySetup = vDSP_create_fftsetupD(log2n, - FFTRadix(kFFTRadix2))! - - var legacyOutputReal = [Double](repeating: -1, count: halfN) - var legacyOutputImag = [Double](repeating: -1, count: halfN) - - legacyOutputReal.withUnsafeMutableBufferPointer { legacyOutputRealPtr in - legacyOutputImag.withUnsafeMutableBufferPointer { legacyOutputImagPtr in - var legacyForwardOutput = DSPDoubleSplitComplex(realp: legacyOutputRealPtr.baseAddress!, - imagp: legacyOutputImagPtr.baseAddress!) - - vDSP_fft_zropD(legacySetup, - &forwardInput, 1, - &legacyForwardOutput, 1, - log2n, - FFTDirection(kFFTDirection_Forward)) - } - } - - expectTrue(outputReal.elementsEqual(legacyOutputReal)) - expectTrue(outputImag.elementsEqual(legacyOutputImag)) - } - } - } - -} - -runAllTests() diff --git a/test/stdlib/Accelerate_vDSPGeometry.swift b/test/stdlib/Accelerate_vDSPGeometry.swift deleted file mode 100644 index b841753c605b9..0000000000000 --- a/test/stdlib/Accelerate_vDSPGeometry.swift +++ /dev/null @@ -1,197 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var Accelerate_vDSPGeometryTests = TestSuite("Accelerate_vDSPGeometry") - -//===----------------------------------------------------------------------===// -// -// vDSP Dot Product -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - Accelerate_vDSPGeometryTests.test("vDSP/SinglePrecisionDot") { - let a: [Float] = [ 1.2, 6.7, 0.22334, 101.9, 90.1, 100.999 ] - let b: [Float] = [99.9, 0.1, 1000.88, 23.99, 27.9, 87.0444] - - let result = vDSP.dot(a, b) - - var legacyResult = Float.nan - - vDSP_dotpr(a, 1, - b, 1, - &legacyResult, - vDSP_Length(a.count)) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPGeometryTests.test("vDSP/DoublePrecisionDot") { - let a: [Double] = [ 1.2, 6.7, 0.22334, 101.9, 90.1, 100.999 ] - let b: [Double] = [99.9, 0.1, 1000.88, 23.99, 27.9, 87.0444] - - let result = vDSP.dot(a, b) - - var legacyResult = Double.nan - - vDSP_dotprD(a, 1, - b, 1, - &legacyResult, - vDSP_Length(a.count)) - - expectEqual(result, legacyResult) - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP Hypotenuse and distance squared -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let xlegs = [(1, 2), (4, 5), (2, 1), (1000, 1), (-1055, 55)] - let ylegs = [(-1000, 2), (4, -50), (-25, -100), (1, 1000), (5, 1)] - - let pointA = [1, 4, 1, -100, -10, 10, 99] - let pointB = [901, 14, 61, -1, -10, -1000, 27] - - Accelerate_vDSPGeometryTests.test("vDSP/SinglePrecisionDist") { - var distResult = [Float](repeating: 0, count: xlegs.count) - - let x: [Float] = xlegs.map{ return Float($0.0) - Float($0.1) } - let y: [Float] = ylegs.map{ return Float($0.0) - Float($0.1) } - - vDSP.hypot(x, y, - result: &distResult) - - var legacyDistResult = [Float](repeating: -1, count: xlegs.count) - - vDSP_vdist(x, 1, - y, 1, - &legacyDistResult, 1, - vDSP_Length(legacyDistResult.count)) - - let returnedResult = vDSP.hypot(x, y) - - expectTrue(distResult.elementsEqual(legacyDistResult)) - expectTrue(distResult.elementsEqual(returnedResult)) - } - - Accelerate_vDSPGeometryTests.test("vDSP/SinglePrecisionPyth") { - var pythgResult = [Float](repeating: 0, count: xlegs.count) - - let x0: [Float] = xlegs.map{ return Float($0.0) } - let x1: [Float] = xlegs.map{ return Float($0.1) } - let y0: [Float] = ylegs.map{ return Float($0.0) } - let y1: [Float] = ylegs.map{ return Float($0.1) } - - vDSP.hypot(x0: x0, x1: x1, - y0: y0, y1: y1, - result: &pythgResult) - - var legacyPythgResult = [Float](repeating: -1, count: xlegs.count) - - vDSP_vpythg(x0, 1, y0, 1, - x1, 1, y1, 1, - &legacyPythgResult, 1, - vDSP_Length(legacyPythgResult.count)) - - let returnedResult = vDSP.hypot(x0: x0, x1: x1, - y0: y0, y1: y1) - - expectTrue(pythgResult.elementsEqual(legacyPythgResult)) - expectTrue(pythgResult.elementsEqual(returnedResult)) - } - - Accelerate_vDSPGeometryTests.test("vDSP/DoublePrecisionDist") { - var distResult = [Double](repeating: 0, count: xlegs.count) - - let x: [Double] = xlegs.map{ return Double($0.0) - Double($0.1) } - let y: [Double] = ylegs.map{ return Double($0.0) - Double($0.1) } - - vDSP.hypot(x, y, - result: &distResult) - - var legacyDistResult = [Double](repeating: -1, count: xlegs.count) - - vDSP_vdistD(x, 1, - y, 1, - &legacyDistResult, 1, - vDSP_Length(legacyDistResult.count)) - - let returnedResult = vDSP.hypot(x, y) - - expectTrue(distResult.elementsEqual(legacyDistResult)) - expectTrue(distResult.elementsEqual(returnedResult)) - } - - Accelerate_vDSPGeometryTests.test("vDSP/DoublePrecisionPyth") { - var pythgResult = [Double](repeating: 0, count: xlegs.count) - - let x0: [Double] = xlegs.map{ return Double($0.0) } - let x1: [Double] = xlegs.map{ return Double($0.1) } - let y0: [Double] = ylegs.map{ return Double($0.0) } - let y1: [Double] = ylegs.map{ return Double($0.1) } - - vDSP.hypot(x0: x0, x1: x1, - y0: y0, y1: y1, - result: &pythgResult) - - var legacyPythgResult = [Double](repeating: -1, count: xlegs.count) - - vDSP_vpythgD(x0, 1, y0, 1, - x1, 1, y1, 1, - &legacyPythgResult, 1, - vDSP_Length(legacyPythgResult.count)) - - let returnedResult = vDSP.hypot(x0: x0, x1: x1, - y0: y0, y1: y1) - - expectTrue(pythgResult.elementsEqual(legacyPythgResult)) - expectTrue(pythgResult.elementsEqual(returnedResult)) - } - - Accelerate_vDSPGeometryTests.test("vDSP/SinglePrecisionDistanceSquared") { - let a = pointA.map{ return Float($0) } - let b = pointB.map{ return Float($0) } - - let result = vDSP.distanceSquared(a, b) - - var legacyResult = Float.nan - - vDSP_distancesq(a, 1, - b, 1, - &legacyResult, - vDSP_Length(a.count)) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPGeometryTests.test("vDSP/DoublePrecisionDistanceSquared") { - let a = pointA.map{ return Double($0) } - let b = pointB.map{ return Double($0) } - - let result = vDSP.distanceSquared(a, b) - - var legacyResult = Double.nan - - vDSP_distancesqD(a, 1, - b, 1, - &legacyResult, - vDSP_Length(a.count)) - - expectEqual(result, legacyResult) - } -} - -runAllTests() diff --git a/test/stdlib/Accelerate_vDSPIntegration.swift b/test/stdlib/Accelerate_vDSPIntegration.swift deleted file mode 100644 index d7a18b509466e..0000000000000 --- a/test/stdlib/Accelerate_vDSPIntegration.swift +++ /dev/null @@ -1,171 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var Accelerate_vDSPIntegrationTests = TestSuite("Accelerate_vDSPIntegration") - -//===----------------------------------------------------------------------===// -// -// vDSP integration tests -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let count = 1024 - let n = vDSP_Length(1024) - - let sourcef: [Float] = (0 ..< 1024).map { - return sin(Float($0) * 0.03) * cos(Float($0) * 0.07) - } - - let sourced: [Double] = (0 ..< 1024).map { - return sin(Double($0) * 0.03) * cos(Double($0) * 0.07) - } - - Accelerate_vDSPIntegrationTests.test("vDSP/SinglePrecisionRunningSum") { - var result = [Float](repeating: 0, - count: count) - - vDSP.integrate(sourcef, - using: .runningSum, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_vrsum(sourcef, 1, - [1], - &legacyResult, 1, - n) - - let returnedResult = vDSP.integrate(sourcef, - using: .runningSum) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPIntegrationTests.test("vDSP/SinglePrecisionTrapezoidal") { - var result = [Float](repeating: 0, - count: count) - - vDSP.integrate(sourcef, - using: .simpson, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_vsimps(sourcef, 1, - [1], - &legacyResult, 1, - n) - - let returnedResult = vDSP.integrate(sourcef, - using: .simpson) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPIntegrationTests.test("vDSP/SinglePrecisionTrapezoidal") { - var result = [Float](repeating: 0, - count: count) - - vDSP.integrate(sourcef, - using: .trapezoidal, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_vtrapz(sourcef, 1, - [1], - &legacyResult, 1, - n) - - let returnedResult = vDSP.integrate(sourcef, - using: .trapezoidal) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPIntegrationTests.test("vDSP/DoublePrecisionRunningSum") { - var result = [Double](repeating: 0, - count: count) - - vDSP.integrate(sourced, - using: .runningSum, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_vrsumD(sourced, 1, - [1], - &legacyResult, 1, - n) - - let returnedResult = vDSP.integrate(sourced, - using: .runningSum) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPIntegrationTests.test("vDSP/DoublePrecisionSimpson") { - var result = [Double](repeating: 0, - count: count) - - vDSP.integrate(sourced, - using: .simpson, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_vsimpsD(sourced, 1, - [1], - &legacyResult, 1, - n) - - let returnedResult = vDSP.integrate(sourced, - using: .simpson) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPIntegrationTests.test("vDSP/DoublePrecisionTrapezoidal") { - var result = [Double](repeating: 0, - count: count) - - vDSP.integrate(sourced, - using: .trapezoidal, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_vtrapzD(sourced, 1, - [1], - &legacyResult, 1, - n) - - let returnedResult = vDSP.integrate(sourced, - using: .trapezoidal) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } -} - -runAllTests() diff --git a/test/stdlib/Accelerate_vDSPReduction.swift b/test/stdlib/Accelerate_vDSPReduction.swift deleted file mode 100644 index eda2008b18e8e..0000000000000 --- a/test/stdlib/Accelerate_vDSPReduction.swift +++ /dev/null @@ -1,403 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var Accelerate_vDSPReductionTests = TestSuite("Accelerate_vDSPReduction") - -//===----------------------------------------------------------------------===// -// -// vDSP vector reduction; single-precision -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let n = vDSP_Length(256) - - let a = (0 ..< 256).map { - return sin(Float($0) * 0.03) * cos(Float($0) * 0.07) - } - - Accelerate_vDSPReductionTests.test("vDSP/SinglePrecisionMaximum") { - let result: Float = vDSP.maximum(a) - - var legacyResult = Float(0) - - vDSP_maxv(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/SinglePrecisionMaximumIndex") { - let result: (vDSP_Length, Float) = vDSP.indexOfMaximum(a) - - var legacyValueResult = Float(0) - var legacyIndexResult = vDSP_Length(0) - - vDSP_maxvi(a, 1, - &legacyValueResult, - &legacyIndexResult, - n) - - expectEqual(result.1, legacyValueResult) - expectEqual(result.0, legacyIndexResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/SinglePrecisionMaximumMagnitude") { - let result: Float = vDSP.maximumMagnitude(a) - - var legacyResult = Float(0) - - vDSP_maxmgv(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/SinglePrecisionMaximumMagnitudeIndex") { - let result: (vDSP_Length, Float) = vDSP.indexOfMaximumMagnitude(a) - - var legacyValueResult = Float(0) - var legacyIndexResult = vDSP_Length(0) - - vDSP_maxmgvi(a, 1, - &legacyValueResult, - &legacyIndexResult, - n) - - expectEqual(result.1, legacyValueResult) - expectEqual(result.0, legacyIndexResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/SinglePrecisionMaximumMagnitudeIndex") { - let result: Float = vDSP.minimum(a) - - var legacyResult = Float(0) - - vDSP_minv(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/SinglePrecisionMinimumIndex") { - let result: (vDSP_Length, Float) = vDSP.indexOfMinimum(a) - - var legacyValueResult = Float(0) - var legacyIndexResult = vDSP_Length(0) - - vDSP_minvi(a, 1, - &legacyValueResult, - &legacyIndexResult, - n) - - expectEqual(result.1, legacyValueResult) - expectEqual(result.0, legacyIndexResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/SinglePrecisionSum") { - let result: Float = vDSP.sum(a) - - var legacyResult = Float(0) - - vDSP_sve(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/SinglePrecisionSumOfSquares") { - let result: Float = vDSP.sumOfSquares(a) - - var legacyResult = Float(0) - - vDSP_svesq(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/SinglePrecisionSumOfElementsAndSquares") { - let result: (Float, Float) = vDSP.sumAndSumOfSquares(a) - - var legacySumResult = Float(0) - var legacySumOfSquaresResult = Float(0) - - vDSP_sve_svesq(a, 1, - &legacySumResult, - &legacySumOfSquaresResult, - n) - - expectEqual(result.0, legacySumResult) - expectEqual(result.1, legacySumOfSquaresResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/SinglePrecisionSumOfMagnitudes") { - let result: Float = vDSP.sumOfMagnitudes(a) - - var legacyResult = Float(0) - - vDSP_svemg(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/MeanSquareSinglePrecision") { - let result = vDSP.meanSquare(a) - - var legacyResult = Float.nan - - vDSP_measqv(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/MeanSquareSinglePrecision") { - let result = vDSP.meanMagnitude(a) - - var legacyResult = Float.nan - - vDSP_meamgv(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/MeanSquareSinglePrecision") { - let result = vDSP.mean(a) - - var legacyResult = Float.nan - - vDSP_meanv(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/RMSSinglePrecision") { - let result = vDSP.rootMeanSquare(a) - - var legacyResult = Float.nan - - vDSP_rmsqv(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } -} - -//===----------------------------------------------------------------------===// -// -// vDSP vector reduction; double-precision -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let n = vDSP_Length(256) - - let a = (0 ..< 256).map { - return sin(Double($0) * 0.03) * cos(Double($0) * 0.07) - } - - Accelerate_vDSPReductionTests.test("vDSP/DoublePrecisionMaximum") { - let result: Double = vDSP.maximum(a) - - var legacyResult = Double(0) - - vDSP_maxvD(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/DoublePrecisionMaximumIndex") { - let result: (vDSP_Length, Double) = vDSP.indexOfMaximum(a) - - var legacyValueResult = Double(0) - var legacyIndexResult = vDSP_Length(0) - - vDSP_maxviD(a, 1, - &legacyValueResult, - &legacyIndexResult, - n) - - expectEqual(result.1, legacyValueResult) - expectEqual(result.0, legacyIndexResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/DoublePrecisionMaximumMagnitude") { - let result: Double = vDSP.maximumMagnitude(a) - - var legacyResult = Double(0) - - vDSP_maxmgvD(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/DoublePrecisionMaximumMagnitudeIndex") { - let result: (vDSP_Length, Double) = vDSP.indexOfMaximumMagnitude(a) - - var legacyValueResult = Double(0) - var legacyIndexResult = vDSP_Length(0) - - vDSP_maxmgviD(a, 1, - &legacyValueResult, - &legacyIndexResult, - n) - - expectEqual(result.1, legacyValueResult) - expectEqual(result.0, legacyIndexResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/DoublePrecisionMaximumMagnitudeIndex") { - let result: Double = vDSP.minimum(a) - - var legacyResult = Double(0) - - vDSP_minvD(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/DoublePrecisionMinimumIndex") { - let result: (vDSP_Length, Double) = vDSP.indexOfMinimum(a) - - var legacyValueResult = Double(0) - var legacyIndexResult = vDSP_Length(0) - - vDSP_minviD(a, 1, - &legacyValueResult, - &legacyIndexResult, - n) - - expectEqual(result.1, legacyValueResult) - expectEqual(result.0, legacyIndexResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/DoublePrecisionSum") { - let result: Double = vDSP.sum(a) - - var legacyResult = Double(0) - - vDSP_sveD(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/DoublePrecisionSumOfSquares") { - let result: Double = vDSP.sumOfSquares(a) - - var legacyResult = Double(0) - - vDSP_svesqD(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/DoublePrecisionSumOfElementsAndSquares") { - let result: (Double, Double) = vDSP.sumAndSumOfSquares(a) - - var legacySumResult = Double(0) - var legacySumOfSquaresResult = Double(0) - - vDSP_sve_svesqD(a, 1, - &legacySumResult, - &legacySumOfSquaresResult, - n) - - expectEqual(result.0, legacySumResult) - expectEqual(result.1, legacySumOfSquaresResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/DoublePrecisionSumOfMagnitudes") { - let result: Double = vDSP.sumOfMagnitudes(a) - - var legacyResult = Double(0) - - vDSP_svemgD(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/MeanSquareDoublePrecision") { - let result = vDSP.meanSquare(a) - - var legacyResult = Double.nan - - vDSP_measqvD(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/MeanSquareDoublePrecision") { - let result = vDSP.meanMagnitude(a) - - var legacyResult = Double.nan - - vDSP_meamgvD(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/MeanSquareDoublePrecision") { - let result = vDSP.mean(a) - - var legacyResult = Double.nan - - vDSP_meanvD(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } - - Accelerate_vDSPReductionTests.test("vDSP/RMSDoublePrecision") { - let result = vDSP.rootMeanSquare(a) - - var legacyResult = Double.nan - - vDSP_rmsqvD(a, 1, - &legacyResult, - n) - - expectEqual(result, legacyResult) - } -} - -runAllTests() diff --git a/test/stdlib/Accelerate_vDSPSingleVectorOps.swift b/test/stdlib/Accelerate_vDSPSingleVectorOps.swift deleted file mode 100644 index f7cae8d8e69cf..0000000000000 --- a/test/stdlib/Accelerate_vDSPSingleVectorOps.swift +++ /dev/null @@ -1,462 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var Accelerate_vDSPSingleVectorOpsTests = TestSuite("Accelerate_vDSPSingleVectorOps") - -//===----------------------------------------------------------------------===// -// -// vDSP Extrema, absolute & negative, reversing, sorting -// and single vector arithmetic; single-precision -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let count = 50 - let n = vDSP_Length(50) - - let a = (0 ..< 50).map { - return sin(Float($0 * 3)) - } - let b = (0 ..< 50).map { - return sin(Float($0 * 7)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/SinglePrecisionMin") { - var result = [Float](repeating: .nan, - count: count) - - vDSP.minimum(a, - b, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_vmin(a, 1, - b, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.minimum(a, - b) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/SinglePrecisionMax") { - var result = [Float](repeating: .nan, - count: count) - - vDSP.maximum(a, - b, - result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_vmax(a, 1, - b, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.maximum(a, - b) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/SinglePrecisionAbsolute") { - var result = [Float](repeating: 0, - count: count) - - vDSP.absolute(a, result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_vabs(a, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.absolute(a) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/SinglePrecisionNegativeAbsolute") { - var result = [Float](repeating: 0, - count: count) - - vDSP.negativeAbsolute(a, result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_vnabs(a, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.negativeAbsolute(a) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/SinglePrecisionNegative") { - var result = [Float](repeating: 0, - count: count) - - vDSP.negative(a, result: &result) - - var legacyResult = [Float](repeating: -1, - count: count) - - vDSP_vneg(a, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.negative(a) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/SinglePrecisionReverse") { - var mutableA = a - var mutableLegacyA = a - - vDSP.reverse(&mutableA) - - vDSP_vrvrs(&mutableLegacyA, 1, - n) - - expectTrue(mutableA.elementsEqual(mutableLegacyA)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/SinglePrecisionSort") { - var mutableA = a - var mutableLegacyA = a - - vDSP.sort(&mutableA, - sortOrder: .ascending) - - vDSP_vsort(&mutableLegacyA, - n, - 1) - - expectTrue(mutableA.elementsEqual(mutableLegacyA)) - - vDSP.sort(&mutableA, - sortOrder: .descending) - - vDSP_vsort(&mutableLegacyA, - n, - -1) - - expectTrue(mutableA.elementsEqual(mutableLegacyA)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/SinglePrecisionSquare") { - var result = [Float](repeating: 0, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.square(a, - result: &result) - - vDSP_vsq(a, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.square(a) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/SinglePrecisionSignedSquare") { - var result = [Float](repeating: 0, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.signedSquare(a, - result: &result) - - vDSP_vssq(a, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.signedSquare(a) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/SinglePrecisionTruncateToFraction") { - var result = [Float](repeating: 0, count: count) - var legacyResult = [Float](repeating: -1, count: count) - - vDSP.trunc(a, - result: &result) - - vDSP_vfrac(a, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.trunc(a) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/SinglePrecisionZeroCrossing") { - let crossingCount = vDSP.countZeroCrossings(a) - - var legacyCrossingCount = vDSP_Length(0) - var legacyLastCrossingIndex = vDSP_Length(0) - - vDSP_nzcros(a, 1, - n, - &legacyLastCrossingIndex, - &legacyCrossingCount, - n) - - expectEqual(crossingCount, legacyCrossingCount) - } - -} - -//===----------------------------------------------------------------------===// -// -// vDSP Extrema, absolute & negative, reversing, sorting -// and single vector arithmetic; double-precision -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - let count = 50 - let n = vDSP_Length(50) - - let a = (0 ..< 50).map { - return sin(Double($0 * 3)) - } - let b = (0 ..< 50).map { - return sin(Double($0 * 7)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/DoublePrecisionMin") { - var result = [Double](repeating: .nan, - count: count) - - vDSP.minimum(a, - b, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_vminD(a, 1, - b, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.minimum(a, - b) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/DoublePrecisionMax") { - var result = [Double](repeating: .nan, - count: count) - - vDSP.maximum(a, - b, - result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_vmaxD(a, 1, - b, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.maximum(a, - b) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/DoublePrecisionAbsolute") { - var result = [Double](repeating: 0, - count: count) - - vDSP.absolute(a, result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_vabsD(a, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.absolute(a) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/DoublePrecisionNegativeAbsolute") { - var result = [Double](repeating: 0, - count: count) - - vDSP.negativeAbsolute(a, result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_vnabsD(a, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.negativeAbsolute(a) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/DoublePrecisionNegative") { - var result = [Double](repeating: 0, - count: count) - - vDSP.negative(a, result: &result) - - var legacyResult = [Double](repeating: -1, - count: count) - - vDSP_vnegD(a, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.negative(a) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/DoublePrecisionReverse") { - var mutableA = a - var mutableLegacyA = a - - vDSP.reverse(&mutableA) - - vDSP_vrvrsD(&mutableLegacyA, 1, - n) - - expectTrue(mutableA.elementsEqual(mutableLegacyA)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/DoublePrecisionSort") { - var mutableA = a - var mutableLegacyA = a - - vDSP.sort(&mutableA, - sortOrder: .ascending) - - vDSP_vsortD(&mutableLegacyA, - n, - 1) - - expectTrue(mutableA.elementsEqual(mutableLegacyA)) - - vDSP.sort(&mutableA, - sortOrder: .descending) - - vDSP_vsortD(&mutableLegacyA, - n, - -1) - - expectTrue(mutableA.elementsEqual(mutableLegacyA)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/DoublePrecisionSquare") { - var result = [Double](repeating: 0, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.square(a, - result: &result) - - vDSP_vsqD(a, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.square(a) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/DoublePrecisionSignedSquare") { - var result = [Double](repeating: 0, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.signedSquare(a, - result: &result) - - vDSP_vssqD(a, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.signedSquare(a) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/DoublePrecisionTruncateToFraction") { - var result = [Double](repeating: 0, count: count) - var legacyResult = [Double](repeating: -1, count: count) - - vDSP.trunc(a, - result: &result) - - vDSP_vfracD(a, 1, - &legacyResult, 1, - n) - - let returnedResult = vDSP.trunc(a) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vDSPSingleVectorOpsTests.test("vDSP/DoublePrecisionZeroCrossing") { - let crossingCount = vDSP.countZeroCrossings(a) - - var legacyCrossingCount = vDSP_Length(0) - var legacyLastCrossingIndex = vDSP_Length(0) - - vDSP_nzcrosD(a, 1, - n, - &legacyLastCrossingIndex, - &legacyCrossingCount, - n) - - expectEqual(crossingCount, legacyCrossingCount) - } -} - -runAllTests() diff --git a/test/stdlib/Accelerate_vForce.swift b/test/stdlib/Accelerate_vForce.swift deleted file mode 100644 index 2d0f9bf8da973..0000000000000 --- a/test/stdlib/Accelerate_vForce.swift +++ /dev/null @@ -1,1269 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50301438 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var Accelerate_vForceTests = TestSuite("Accelerate_vForce") - -//===----------------------------------------------------------------------===// -// -// vForce single-precision tests -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - var result = [Float]() - var legacyResult = [Float]() - let x: [Float] = [2, 4, -6.876, 10.9, -100.3, 100] - let y: [Float] = [-10, -20, 40, 60, -80, -300] - let z: [Float] = [-0.6, 0.2, -0.1, 0.9, -0.1, 0.1] - let count = 6 - var n: Int32 = 6 - - Accelerate_vForceTests.test("vForce/SinglePrecisionCeiling") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.ceil(x, - result: &result) - - vvceilf(&legacyResult, - x, - &n) - - let returnedResult = vForce.ceil(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionFloor") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.floor(x, - result: &result) - - vvfloorf(&legacyResult, - x, - &n) - - let returnedResult = vForce.floor(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionCopySign") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.copysign(magnitudes: x, - signs: y, - result: &result) - - vvcopysignf(&legacyResult, - x, - y, - &n) - - let returnedResult = vForce.copysign(magnitudes: x, - signs: y) - - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionModulus") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.truncatingRemainder(dividends: x, - divisors: y, - result: &result) - - vvfmodf(&legacyResult, - x, - y, - &n) - - let returnedResult = vForce.truncatingRemainder(dividends: x, - divisors: y) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionModulusParameters") { - var scalarResult = [Float.nan] - let scalarNumerator = [Float(20)] - let scalarDenominator = [Float(6)] - - vForce.truncatingRemainder(dividends: scalarNumerator, - divisors: scalarDenominator, - result: &scalarResult) - - expectEqual(Int(scalarResult.first!), 2) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionRemainder") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.remainder(dividends: x, - divisors: y, - result: &result) - - vvremainderf(&legacyResult, - x, - y, - &n) - - let returnedResult = vForce.remainder(dividends: x, - divisors: y) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionRemainderParameters") { - var scalarResult = [Float.nan] - let scalarNumerator = [Float(20)] - let scalarDenominator = [Float(6)] - - vForce.remainder(dividends: scalarNumerator, - divisors: scalarDenominator, - result: &scalarResult) - - expectEqual(Int(scalarResult.first!), 2) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionIntegerTruncation") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.trunc(x, - result: &result) - - vvintf(&legacyResult, - x, - &n) - - let returnedResult = vForce.trunc(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionNearestInteger") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.nearestInteger(x, - result: &result) - - vvnintf(&legacyResult, - x, - &n) - - let returnedResult = vForce.nearestInteger(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionrsqrt") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.rsqrt(x, - result: &result) - - vvrsqrtf(&legacyResult, - x, - &n) - - let returnedResult = vForce.rsqrt(x) - - expectTrue(result.filter{!$0.isNaN}.elementsEqual(legacyResult.filter{!$0.isNaN})) - expectTrue(result.filter{!$0.isNaN}.elementsEqual(returnedResult.filter{!$0.isNaN})) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionsqrt") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.sqrt(x, - result: &result) - - vvsqrtf(&legacyResult, - x, - &n) - - let returnedResult = vForce.sqrt(x) - - expectTrue(result.filter{!$0.isNaN}.elementsEqual(legacyResult.filter{!$0.isNaN})) - expectTrue(result.filter{!$0.isNaN}.elementsEqual(returnedResult.filter{!$0.isNaN})) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionReciprocal") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.reciprocal(x, - result: &result) - - vvrecf(&legacyResult, - x, - &n) - - let returnedResult = vForce.reciprocal(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionExp") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.exp(x, - result: &result) - - vvexpf(&legacyResult, - x, - &n) - - let returnedResult = vForce.exp(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionExpm1") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.expm1(x, - result: &result) - - vvexpm1f(&legacyResult, - x, - &n) - - let returnedResult = vForce.expm1(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionExp2") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.exp2(x, - result: &result) - - vvexp2f(&legacyResult, - x, - &n) - - let returnedResult = vForce.exp2(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionLog2") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.log2(x, - result: &result) - - vvlog2f(&legacyResult, - x, - &n) - - let returnedResult = vForce.log2(x) - - expectTrue(result.filter{!$0.isNaN}.elementsEqual(legacyResult.filter{!$0.isNaN})) - expectTrue(result.filter{!$0.isNaN}.elementsEqual(returnedResult.filter{!$0.isNaN})) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionLog10") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.log10(x, - result: &result) - - vvlog10f(&legacyResult, - x, - &n) - - let returnedResult = vForce.log10(x) - - expectTrue(result.filter{!$0.isNaN}.elementsEqual(legacyResult.filter{!$0.isNaN})) - expectTrue(result.filter{!$0.isNaN}.elementsEqual(returnedResult.filter{!$0.isNaN})) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionUnbiasedExponent") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.logb(x, - result: &result) - - vvlogbf(&legacyResult, - x, - &n) - - let returnedResult = vForce.logb(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionPower") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.pow(bases: x, - exponents: y, - result: &result) - - vvpowf(&legacyResult, - y, - x, - &n) - - let returnedResult = vForce.pow(bases: x, - exponents: y) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionPower") { - var scalarResult = [Float.nan] - let scalarBase = [Float(10)] - let scalarExponent = [Float(2)] - - vForce.pow(bases: scalarBase, - exponents: scalarExponent, - result: &scalarResult) - - expectEqual(Int(scalarResult.first!), 100) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionSine") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.sin(x, - result: &result) - - vvsinf(&legacyResult, - x, - &n) - - let returnedResult = vForce.sin(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionSinPi") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.sinPi(x, - result: &result) - - vvsinpif(&legacyResult, - x, - &n) - - let returnedResult = vForce.sinPi(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionCosine") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.cos(x, - result: &result) - - vvcosf(&legacyResult, - x, - &n) - - let returnedResult = vForce.cos(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionCosPi") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.cosPi(x, - result: &result) - - vvcospif(&legacyResult, - x, - &n) - - let returnedResult = vForce.cosPi(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionSinCos") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - var cosResult = [Float](repeating: .nan, count: result.count) - var legacyCosResult = [Float](repeating: .nan, count: result.count) - - vForce.sincos(x, - sinResult: &result, - cosResult: &cosResult) - - vvsincosf(&legacyResult, - &legacyCosResult, - x, - &n) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(cosResult.elementsEqual(legacyCosResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionTangent") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.tan(x, - result: &result) - - vvtanf(&legacyResult, - x, - &n) - - let returnedResult = vForce.tan(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionTanPi") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.tanPi(x, - result: &result) - - vvtanpif(&legacyResult, - x, - &n) - - let returnedResult = vForce.tanPi(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionArcsin") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.asin(z, - result: &result) - - vvasinf(&legacyResult, - z, - &n) - - let returnedResult = vForce.asin(z) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionArccos") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.acos(z, - result: &result) - - vvacosf(&legacyResult, - z, - &n) - - let returnedResult = vForce.acos(z) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionArctan") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.atan(z, - result: &result) - - vvatanf(&legacyResult, - z, - &n) - - let returnedResult = vForce.atan(z) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionSinh") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.sinh(x, - result: &result) - - vvsinhf(&legacyResult, - x, - &n) - - let returnedResult = vForce.sinh(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionCosh") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.cosh(x, - result: &result) - - vvcoshf(&legacyResult, - x, - &n) - - let returnedResult = vForce.cosh(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionTanh") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.tanh(z, - result: &result) - - vvtanhf(&legacyResult, - z, - &n) - - let returnedResult = vForce.tanh(z) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionAsinh") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.asinh(z, - result: &result) - - vvasinhf(&legacyResult, - z, - &n) - - let returnedResult = vForce.asinh(z) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionAcosh") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.acosh(x, - result: &result) - - vvacoshf(&legacyResult, - x, - &n) - - let returnedResult = vForce.acosh(x) - expectTrue(result.filter{!$0.isNaN}.elementsEqual(legacyResult.filter{!$0.isNaN})) - expectTrue(result.filter{!$0.isNaN}.elementsEqual(returnedResult.filter{!$0.isNaN})) - } - - Accelerate_vForceTests.test("vForce/SinglePrecisionAtan") { - result = [Float](repeating: 0, count: count) - legacyResult = [Float](repeating: -1, count: count) - - vForce.atanh(z, - result: &result) - - vvatanhf(&legacyResult, - z, - &n) - - let returnedResult = vForce.atanh(z) - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } -} - -//===----------------------------------------------------------------------===// -// -// vForce double precision tests -// -//===----------------------------------------------------------------------===// - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - - var result = [Double]() - var legacyResult = [Double]() - let x: [Double] = [2, 4, -6.876, 10.9, -100.3, 100] - let y: [Double] = [-10, -20, 40, 60, -80, -300] - let z: [Double] = [-0.6, 0.2, -0.1, 0.9, -0.1, 0.1] - let count = 6 - var n: Int32 = 6 - - Accelerate_vForceTests.test("vForce/DoublePrecisionCeiling") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.ceil(x, - result: &result) - - vvceil(&legacyResult, - x, - &n) - - let returnedResult = vForce.ceil(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionFloor") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.floor(x, - result: &result) - - vvfloor(&legacyResult, - x, - &n) - - let returnedResult = vForce.floor(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionCopySign") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.copysign(magnitudes: x, - signs: y, - result: &result) - - vvcopysign(&legacyResult, - x, - y, - &n) - - let returnedResult = vForce.copysign(magnitudes: x, - signs: y) - - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionModulus") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.truncatingRemainder(dividends: x, - divisors: y, - result: &result) - - vvfmod(&legacyResult, - x, - y, - &n) - - let returnedResult = vForce.truncatingRemainder(dividends: x, - divisors: y) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionModulusParameters") { - var scalarResult = [Double.nan] - let scalarNumerator = [Double(20)] - let scalarDenominator = [Double(6)] - - vForce.truncatingRemainder(dividends: scalarNumerator, - divisors: scalarDenominator, - result: &scalarResult) - - expectEqual(Int(scalarResult.first!), 2) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionRemainder") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.remainder(dividends: x, - divisors: y, - result: &result) - - vvremainder(&legacyResult, - x, - y, - &n) - - let returnedResult = vForce.remainder(dividends: x, - divisors: y) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionRemainderParameters") { - var scalarResult = [Double.nan] - let scalarNumerator = [Double(20)] - let scalarDenominator = [Double(6)] - - vForce.remainder(dividends: scalarNumerator, - divisors: scalarDenominator, - result: &scalarResult) - - expectEqual(Int(scalarResult.first!), 2) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionIntegerTruncation") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.trunc(x, - result: &result) - - vvint(&legacyResult, - x, - &n) - - let returnedResult = vForce.trunc(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionNearestInteger") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.nearestInteger(x, - result: &result) - - vvnint(&legacyResult, - x, - &n) - - let returnedResult = vForce.nearestInteger(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionrsqrt") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.rsqrt(x, - result: &result) - - vvrsqrt(&legacyResult, - x, - &n) - - let returnedResult = vForce.rsqrt(x) - - expectTrue(result.filter{!$0.isNaN}.elementsEqual(legacyResult.filter{!$0.isNaN})) - expectTrue(result.filter{!$0.isNaN}.elementsEqual(returnedResult.filter{!$0.isNaN})) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionsqrt") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.sqrt(x, - result: &result) - - vvsqrt(&legacyResult, - x, - &n) - - let returnedResult = vForce.sqrt(x) - - expectTrue(result.filter{!$0.isNaN}.elementsEqual(legacyResult.filter{!$0.isNaN})) - expectTrue(result.filter{!$0.isNaN}.elementsEqual(returnedResult.filter{!$0.isNaN})) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionReciprocal") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.reciprocal(x, - result: &result) - - vvrec(&legacyResult, - x, - &n) - - let returnedResult = vForce.reciprocal(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionExp") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.exp(x, - result: &result) - - vvexp(&legacyResult, - x, - &n) - - let returnedResult = vForce.exp(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionExpm1") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.expm1(x, - result: &result) - - vvexpm1(&legacyResult, - x, - &n) - - let returnedResult = vForce.expm1(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionExp2") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.exp2(x, - result: &result) - - vvexp2(&legacyResult, - x, - &n) - - let returnedResult = vForce.exp2(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionLog2") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.log2(x, - result: &result) - - vvlog2(&legacyResult, - x, - &n) - - let returnedResult = vForce.log2(x) - - expectTrue(result.filter{!$0.isNaN}.elementsEqual(legacyResult.filter{!$0.isNaN})) - expectTrue(result.filter{!$0.isNaN}.elementsEqual(returnedResult.filter{!$0.isNaN})) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionLog10") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.log10(x, - result: &result) - - vvlog10(&legacyResult, - x, - &n) - - let returnedResult = vForce.log10(x) - - expectTrue(result.filter{!$0.isNaN}.elementsEqual(legacyResult.filter{!$0.isNaN})) - expectTrue(result.filter{!$0.isNaN}.elementsEqual(returnedResult.filter{!$0.isNaN})) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionUnbiasedExponent") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.logb(x, - result: &result) - - vvlogb(&legacyResult, - x, - &n) - - let returnedResult = vForce.logb(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionPower") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.pow(bases: x, - exponents: y, - result: &result) - - vvpow(&legacyResult, - y, - x, - &n) - - let returnedResult = vForce.pow(bases: x, - exponents: y) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionPower") { - var scalarResult = [Double.nan] - let scalarBase = [Double(10)] - let scalarExponent = [Double(2)] - - vForce.pow(bases: scalarBase, - exponents: scalarExponent, - result: &scalarResult) - - expectEqual(Int(scalarResult.first!), 100) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionSine") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.sin(x, - result: &result) - - vvsin(&legacyResult, - x, - &n) - - let returnedResult = vForce.sin(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionSinPi") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.sinPi(x, - result: &result) - - vvsinpi(&legacyResult, - x, - &n) - - let returnedResult = vForce.sinPi(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionCosine") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.cos(x, - result: &result) - - vvcos(&legacyResult, - x, - &n) - - let returnedResult = vForce.cos(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionCosPi") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.cosPi(x, - result: &result) - - vvcospi(&legacyResult, - x, - &n) - - let returnedResult = vForce.cosPi(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionSinCos") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - var cosResult = [Double](repeating: .nan, count: result.count) - var legacyCosResult = [Double](repeating: .nan, count: result.count) - - vForce.sincos(x, - sinResult: &result, - cosResult: &cosResult) - - vvsincos(&legacyResult, - &legacyCosResult, - x, - &n) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(cosResult.elementsEqual(legacyCosResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionTangent") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.tan(x, - result: &result) - - vvtan(&legacyResult, - x, - &n) - - let returnedResult = vForce.tan(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionTanPi") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.tanPi(x, - result: &result) - - vvtanpi(&legacyResult, - x, - &n) - - let returnedResult = vForce.tanPi(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionArcsin") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.asin(z, - result: &result) - - vvasin(&legacyResult, - z, - &n) - - let returnedResult = vForce.asin(z) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionArccos") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.acos(z, - result: &result) - - vvacos(&legacyResult, - z, - &n) - - let returnedResult = vForce.acos(z) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionArctan") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.atan(z, - result: &result) - - vvatan(&legacyResult, - z, - &n) - - let returnedResult = vForce.atan(z) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionSinh") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.sinh(x, - result: &result) - - vvsinh(&legacyResult, - x, - &n) - - let returnedResult = vForce.sinh(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionCosh") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.cosh(x, - result: &result) - - vvcosh(&legacyResult, - x, - &n) - - let returnedResult = vForce.cosh(x) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionTanh") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.tanh(z, - result: &result) - - vvtanh(&legacyResult, - z, - &n) - - let returnedResult = vForce.tanh(z) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionAsinh") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.asinh(z, - result: &result) - - vvasinh(&legacyResult, - z, - &n) - - let returnedResult = vForce.asinh(z) - - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionAcosh") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.acosh(x, - result: &result) - - vvacosh(&legacyResult, - x, - &n) - - let returnedResult = vForce.acosh(x) - expectTrue(result.filter{!$0.isNaN}.elementsEqual(legacyResult.filter{!$0.isNaN})) - expectTrue(result.filter{!$0.isNaN}.elementsEqual(returnedResult.filter{!$0.isNaN})) - } - - Accelerate_vForceTests.test("vForce/DoublePrecisionAtan") { - result = [Double](repeating: 0, count: count) - legacyResult = [Double](repeating: -1, count: count) - - vForce.atanh(z, - result: &result) - - vvatanh(&legacyResult, - z, - &n) - - let returnedResult = vForce.atanh(z) - expectTrue(result.elementsEqual(legacyResult)) - expectTrue(result.elementsEqual(returnedResult)) - } -} - -runAllTests() diff --git a/test/stdlib/Accelerate_vImage.swift b/test/stdlib/Accelerate_vImage.swift deleted file mode 100644 index 2d301ae8bc2cc..0000000000000 --- a/test/stdlib/Accelerate_vImage.swift +++ /dev/null @@ -1,666 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: rdar50244151 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import Accelerate - -var Accelerate_vImageTests = TestSuite("Accelerate_vImage") - -if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { - let width = UInt(64) - let height = UInt(32) - let widthi = 64 - let heighti = 32 - - //===----------------------------------------------------------------------===// - // - // MARK: Converter - // - //===----------------------------------------------------------------------===// - - Accelerate_vImageTests.test("vImage/CVConverters") { - let colorSpace = CGColorSpaceCreateDeviceRGB() - - let cgFormat = vImage_CGImageFormat(bitsPerComponent: 8, - bitsPerPixel: 32, - colorSpace: colorSpace, - bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.first.rawValue), - renderingIntent: .defaultIntent)! - - let cvFormat = vImageCVImageFormat.make(format: .format32ABGR, - matrix: kvImage_ARGBToYpCbCrMatrix_ITU_R_601_4.pointee, - chromaSiting: .center, - colorSpace: colorSpace, - alphaIsOpaqueHint: false)! - - let coreVideoToCoreGraphics = try! vImageConverter.make(sourceFormat: cvFormat, - destinationFormat: cgFormat, - flags: .printDiagnosticsToConsole) - - let coreGraphicsToCoreVideo = try! vImageConverter.make(sourceFormat: cgFormat, - destinationFormat: cvFormat, - flags: .printDiagnosticsToConsole) - - let pixels: [UInt8] = (0 ..< width * height * 4).map { _ in - return UInt8.random(in: 0 ..< 255) - } - - let image = makeRGBA8888Image(from: pixels, - width: width, - height: height)! - - let sourceCGBuffer = try! vImage_Buffer(cgImage: image) - var intermediateCVBuffer = try! vImage_Buffer(width: widthi, height: heighti, bitsPerPixel: 32) - var destinationCGBuffer = try! vImage_Buffer(width: widthi, height: heighti, bitsPerPixel: 32) - - try! coreGraphicsToCoreVideo.convert(source: sourceCGBuffer, - destination: &intermediateCVBuffer) - - try! coreVideoToCoreGraphics.convert(source: intermediateCVBuffer, - destination: &destinationCGBuffer) - - let destinationPixels: [UInt8] = arrayFromBuffer(buffer: destinationCGBuffer, - channelCount: 4, - count: pixels.count) - - expectEqual(destinationPixels, pixels) - - expectEqual(coreVideoToCoreGraphics.destinationBuffers(colorSpace: colorSpace), - coreGraphicsToCoreVideo.sourceBuffers(colorSpace: colorSpace)) - - expectEqual(coreVideoToCoreGraphics.sourceBuffers(colorSpace: colorSpace), - coreGraphicsToCoreVideo.destinationBuffers(colorSpace: colorSpace)) - } - - /* Disabled due to - Accelerate_vImageTests.test("vImage/BufferOrder") { - let sourceFormat = vImage_CGImageFormat(bitsPerComponent: 8, - bitsPerPixel: 32, - colorSpace: CGColorSpaceCreateDeviceCMYK(), - bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue), - renderingIntent: .defaultIntent)! - - let destinationFormat = vImage_CGImageFormat(bitsPerComponent: 8, - bitsPerPixel: 24, - colorSpace: CGColorSpace(name: CGColorSpace.genericLab)!, - bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue), - renderingIntent: .defaultIntent)! - - let converter = try! vImageConverter.make(sourceFormat: sourceFormat, - destinationFormat: destinationFormat) - - let sBuffers = converter.sourceBuffers(colorSpace: sourceFormat.colorSpace.takeRetainedValue()) - let dBuffers = converter.destinationBuffers(colorSpace: destinationFormat.colorSpace.takeRetainedValue()) - - expectEqual(sBuffers, [.coreGraphics]) - expectEqual(dBuffers, [.coreGraphics]) - } - */ - - Accelerate_vImageTests.test("vImage/AnyToAnyError") { - var error = kvImageNoError - - let format = vImage_CGImageFormat(bitsPerComponent: 8, - bitsPerPixel: 32, - colorSpace: CGColorSpaceCreateDeviceCMYK(), - bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue), - renderingIntent: .defaultIntent)! - - expectCrashLater() - _ = try! vImageConverter.make(sourceFormat: format, - destinationFormat: format, - flags: .imageExtend) - } - - Accelerate_vImageTests.test("vImage/AnyToAny") { - let pixels: [UInt8] = (0 ..< width * height * 4).map { _ in - return UInt8.random(in: 0 ..< 255) - } - - let image = makeRGBA8888Image(from: pixels, - width: width, - height: height)! - - let sourceFormat = vImage_CGImageFormat(cgImage: image)! - - let destinationFormat = vImage_CGImageFormat(bitsPerComponent: 8, - bitsPerPixel: 32, - colorSpace: CGColorSpaceCreateDeviceCMYK(), - bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue), - renderingIntent: .defaultIntent)! - - let sourceBuffer = try! vImage_Buffer(cgImage: image) - var destinationBuffer = try! vImage_Buffer(width: widthi, height: heighti, - bitsPerPixel: 32) - - // New API - - let converter = try! vImageConverter.make(sourceFormat: sourceFormat, - destinationFormat: destinationFormat) - - try! converter.convert(source: sourceBuffer, - destination: &destinationBuffer) - - let mustOperateOutOfPlace = try! converter.mustOperateOutOfPlace(source: sourceBuffer, - destination: destinationBuffer) - - // Legacy API - - var legacyDestinationBuffer = try! vImage_Buffer(width: widthi, height: heighti, - bitsPerPixel: 32) - - var legacyConverter: vImageConverter? - - withUnsafePointer(to: destinationFormat) { dest in - withUnsafePointer(to: sourceFormat) { src in - legacyConverter = vImageConverter_CreateWithCGImageFormat( - src, - dest, - nil, - vImage_Flags(kvImageNoFlags), - nil)?.takeRetainedValue() - } - } - - _ = withUnsafePointer(to: sourceBuffer) { src in - vImageConvert_AnyToAny(legacyConverter!, - src, - &legacyDestinationBuffer, - nil, - vImage_Flags(kvImageNoFlags)) - } - - var e = kvImageNoError - withUnsafePointer(to: sourceBuffer) { src in - withUnsafePointer(to: destinationBuffer) { dest in - e = vImageConverter_MustOperateOutOfPlace(legacyConverter!, - src, - dest, - vImage_Flags(kvImageNoFlags)) - } - } - let legacyMustOperateOutOfPlace = e == kvImageOutOfPlaceOperationRequired - - // Compare results - - let destinationPixels: [UInt8] = arrayFromBuffer(buffer: destinationBuffer, - channelCount: 4, - count: pixels.count) - let legacyDestinationPixels: [UInt8] = arrayFromBuffer(buffer: legacyDestinationBuffer, - channelCount: 4, - count: pixels.count) - - expectTrue(legacyDestinationPixels.elementsEqual(destinationPixels)) - - expectEqual(converter.sourceBufferCount, 1) - expectEqual(converter.destinationBufferCount, 1) - expectEqual(legacyMustOperateOutOfPlace, mustOperateOutOfPlace) - - sourceBuffer.free() - destinationBuffer.free() - legacyDestinationBuffer.free() - } - - //===----------------------------------------------------------------------===// - // - // MARK: Buffer - // - //===----------------------------------------------------------------------===// - - Accelerate_vImageTests.test("vImage/IllegalSize") { - expectCrashLater() - let buffer = try! vImage_Buffer(width: -1, height: -1, - bitsPerPixel: 32) - } - - Accelerate_vImageTests.test("vImage/IllegalSize") { - expectCrashLater() - let buffer = try! vImage_Buffer(width: 99999999, height: 99999999, - bitsPerPixel: 99999999) - } - - Accelerate_vImageTests.test("vImage/InitWithInvalidImageFormat") { - let pixels: [UInt8] = (0 ..< width * height).map { _ in - return UInt8.random(in: 0 ..< 255) - } - - let image = makePlanar8Image(from: pixels, - width: width, - height: height)! - - let format = vImage_CGImageFormat(bitsPerComponent: 8, - bitsPerPixel: 32, - colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!, - bitmapInfo: CGBitmapInfo(rawValue: 0))! - - var error = kvImageNoError - - expectCrashLater() - let buffer = try! vImage_Buffer(cgImage: image, - format: format) - } - - Accelerate_vImageTests.test("vImage/CreateCGImage") { - let pixels: [UInt8] = (0 ..< width * height * 4).map { _ in - return UInt8.random(in: 0 ..< 255) - } - - let image = makeRGBA8888Image(from: pixels, - width: width, - height: height)! - - let buffer = try! vImage_Buffer(cgImage: image) - - let format = vImage_CGImageFormat(cgImage: image)! - - let bufferImage = try! buffer.createCGImage(format: format) - - let imagePixels = imageToPixels(image: image) - let bufferImagePixels = imageToPixels(image: bufferImage) - - expectTrue(imagePixels.elementsEqual(bufferImagePixels)) - - buffer.free() - } - - Accelerate_vImageTests.test("vImage/CopyBadWidth") { - var source = try! vImage_Buffer(width: 10, height: 100, bitsPerPixel: 32) - var destination = try! vImage_Buffer(width: 20, height: 20, bitsPerPixel: 32) - - expectCrashLater() - try! source.copy(destinationBuffer: &destination, - pixelSize: 4) - } - - Accelerate_vImageTests.test("vImage/CopyBadHeight") { - var source = try! vImage_Buffer(width: 100, height: 10, bitsPerPixel: 32) - var destination = try! vImage_Buffer(width: 20, height: 20, bitsPerPixel: 32) - - expectCrashLater() - try! source.copy(destinationBuffer: &destination, - pixelSize: 4) - } - - Accelerate_vImageTests.test("vImage/Copy") { - let pixels: [UInt8] = (0 ..< width * height * 4).map { _ in - return UInt8.random(in: 0 ..< 255) - } - - let image = makeRGBA8888Image(from: pixels, - width: width, - height: height)! - - let source = try! vImage_Buffer(cgImage: image) - - var destination = try! vImage_Buffer(width: widthi, height: heighti, - bitsPerPixel: 32) - - try! source.copy(destinationBuffer: &destination, - pixelSize: 4) - - let sourcePixels: [UInt8] = arrayFromBuffer(buffer: source, - channelCount: 4, - count: pixels.count) - let destinationPixels: [UInt8] = arrayFromBuffer(buffer: destination, - channelCount: 4, - count: pixels.count) - - expectTrue(sourcePixels.elementsEqual(destinationPixels)) - - source.free() - destination.free() - } - - Accelerate_vImageTests.test("vImage/InitializeWithFormat") { - let pixels: [UInt8] = (0 ..< width * height * 4).map { _ in - return UInt8.random(in: 0 ..< 255) - } - - let image = makeRGBA8888Image(from: pixels, - width: width, - height: height)! - - let format = vImage_CGImageFormat(cgImage: image)! - - let buffer = try! vImage_Buffer(cgImage: image, - format: format) - - let bufferPixels: [UInt8] = arrayFromBuffer(buffer: buffer, - channelCount: 4, - count: pixels.count) - - expectTrue(bufferPixels.elementsEqual(pixels)) - expectEqual(buffer.rowBytes, Int(width) * 4) - expectEqual(buffer.width, width) - expectEqual(buffer.height, height) - - buffer.free() - } - - Accelerate_vImageTests.test("vImage/Alignment") { - // New API - - var alignment = try! vImage_Buffer.preferredAlignmentAndRowBytes(width: widthi, - height: heighti, - bitsPerPixel: 32) - - // Legacy API - - var legacyBuffer = vImage_Buffer() - let legacyAlignment = vImageBuffer_Init(&legacyBuffer, - height, width, - 32, - vImage_Flags(kvImageNoAllocate)) - - expectEqual(alignment.alignment, legacyAlignment) - expectEqual(alignment.rowBytes, legacyBuffer.rowBytes) - - legacyBuffer.free() - } - - Accelerate_vImageTests.test("vImage/CreateBufferFromCGImage") { - let pixels: [UInt8] = (0 ..< width * height * 4).map { _ in - return UInt8.random(in: 0 ..< 255) - } - - let image = makeRGBA8888Image(from: pixels, - width: width, - height: height)! - - // New API - - let buffer = try! vImage_Buffer(cgImage: image) - - // Legacy API - - let legacyBuffer: vImage_Buffer = { - var format = vImage_CGImageFormat(cgImage: image)! - - var buffer = vImage_Buffer() - - vImageBuffer_InitWithCGImage(&buffer, - &format, - nil, - image, - vImage_Flags(kvImageNoFlags)) - - return buffer - }() - - let bufferPixels: [UInt8] = arrayFromBuffer(buffer: buffer, - channelCount: 4, - count: pixels.count) - - let legacyBufferPixels: [UInt8] = arrayFromBuffer(buffer: legacyBuffer, - channelCount: 4, - count: pixels.count) - - expectTrue(bufferPixels.elementsEqual(legacyBufferPixels)) - - expectEqual(buffer.width, legacyBuffer.width) - expectEqual(buffer.height, legacyBuffer.height) - expectEqual(buffer.rowBytes, legacyBuffer.rowBytes) - - expectEqual(buffer.size, CGSize(width: Int(width), - height: Int(height))) - - buffer.free() - free(legacyBuffer.data) - } - - //===----------------------------------------------------------------------===// - // - // MARK: CVImageFormat - // - //===----------------------------------------------------------------------===// - - Accelerate_vImageTests.test("vImage/MakeFromPixelBuffer") { - let pixelBuffer = makePixelBuffer(pixelFormat: kCVPixelFormatType_420YpCbCr8Planar)! - - let format = vImageCVImageFormat.make(buffer: pixelBuffer)! - - expectEqual(format.channels, [vImage.BufferType.luminance, - vImage.BufferType.Cb, - vImage.BufferType.Cr]) - } - - Accelerate_vImageTests.test("vImage/MakeFormat4444YpCbCrA8") { - let format = vImageCVImageFormat.make(format: .format4444YpCbCrA8, - matrix: kvImage_ARGBToYpCbCrMatrix_ITU_R_709_2.pointee, - chromaSiting: .center, - colorSpace: CGColorSpaceCreateDeviceRGB(), - alphaIsOpaqueHint: false)! - - // test alphaIsOpaqueHint - - expectEqual(format.alphaIsOpaqueHint, false) - - format.alphaIsOpaqueHint = true - - expectEqual(format.alphaIsOpaqueHint, true) - - // test colorSpace - - expectEqual(String(format.colorSpace!.name!), "kCGColorSpaceDeviceRGB") - - format.colorSpace = CGColorSpace(name: CGColorSpace.extendedLinearSRGB)! - - expectEqual(String(format.colorSpace!.name!), "kCGColorSpaceExtendedLinearSRGB") - - // test channel names - - let channels = format.channels - - expectEqual(channels, - [vImage.BufferType.Cb, - vImage.BufferType.luminance, - vImage.BufferType.Cr, - vImage.BufferType.alpha]) - - let description = format.channelDescription(bufferType: channels.first!) - - expectEqual(description?.min, 0) - expectEqual(description?.max, 255) - expectEqual(description?.full, 240) - expectEqual(description?.zero, 128) - } - - Accelerate_vImageTests.test("vImage/MakeFormat420YpCbCr8Planar") { - let format = vImageCVImageFormat.make(format: .format420YpCbCr8Planar, - matrix: kvImage_ARGBToYpCbCrMatrix_ITU_R_709_2.pointee, - chromaSiting: .center, - colorSpace: CGColorSpaceCreateDeviceRGB(), - alphaIsOpaqueHint: false)! - - // test chromaSiting - - expectEqual(format.chromaSiting, vImageCVImageFormat.ChromaSiting.center) - - format.chromaSiting = .dv420 - - expectEqual(format.chromaSiting, vImageCVImageFormat.ChromaSiting.dv420) - - // test formatCode - - expectEqual(format.formatCode, kCVPixelFormatType_420YpCbCr8Planar) - - // test channelCount - - expectEqual(format.channelCount, 3) - } - - //===----------------------------------------------------------------------===// - // - // MARK: CGImageFormat - // - //===----------------------------------------------------------------------===// - - Accelerate_vImageTests.test("vImage/CGImageFormatIllegalValues") { - - let formatOne = vImage_CGImageFormat(bitsPerComponent: -1, - bitsPerPixel: 32, - colorSpace: CGColorSpaceCreateDeviceRGB(), - bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)) - - let formatTwo = vImage_CGImageFormat(bitsPerComponent: 8, - bitsPerPixel: -1, - colorSpace: CGColorSpaceCreateDeviceRGB(), - bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)) - - expectTrue(formatOne == nil) - expectTrue(formatTwo == nil) - } - - Accelerate_vImageTests.test("vImage/CGImageFormatFromCGImage") { - let pixels: [UInt8] = (0 ..< width * height).map { _ in - return UInt8.random(in: 0 ..< 255) - } - - let image = makePlanar8Image(from: pixels, - width: width, - height: height)! - - var format = vImage_CGImageFormat(cgImage: image)! - - var legacyFormat = vImage_CGImageFormat(bitsPerComponent: 8, - bitsPerPixel: 8, - colorSpace: Unmanaged.passRetained(CGColorSpaceCreateDeviceGray()), - bitmapInfo: CGBitmapInfo(rawValue: 0), - version: 0, - decode: nil, - renderingIntent: .defaultIntent) - - expectTrue(vImageCGImageFormat_IsEqual(&format, &legacyFormat)) - } - - Accelerate_vImageTests.test("vImage/CGImageFormatLightweightInit") { - let colorspace = CGColorSpaceCreateDeviceRGB() - let renderingIntent = CGColorRenderingIntent.defaultIntent - let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue) - - var format = vImage_CGImageFormat(bitsPerComponent: 8, - bitsPerPixel: 32, - colorSpace: colorspace, - bitmapInfo: bitmapInfo)! - - var legacyFormat = vImage_CGImageFormat(bitsPerComponent: 8, - bitsPerPixel: 32, - colorSpace: Unmanaged.passRetained(colorspace), - bitmapInfo: bitmapInfo, - version: 0, - decode: nil, - renderingIntent: renderingIntent) - - expectTrue(vImageCGImageFormat_IsEqual(&format, &legacyFormat)) - expectTrue(format.componentCount == 4) - } - - //===----------------------------------------------------------------------===// - // - // MARK: Helper Functions - // - //===----------------------------------------------------------------------===// - - func makePixelBuffer(pixelFormat: OSType) -> CVPixelBuffer? { - var pixelBuffer: CVPixelBuffer? = nil - CVPixelBufferCreate(kCFAllocatorDefault, - 1, - 1, - pixelFormat, - [:] as CFDictionary?, - &pixelBuffer) - - return pixelBuffer - } - - func arrayFromBuffer(buffer: vImage_Buffer, - channelCount: Int, - count: Int) -> Array { - - if (buffer.rowBytes == Int(buffer.width) * MemoryLayout.stride * channelCount) { - let ptr = buffer.data.bindMemory(to: T.self, - capacity: count) - - let buf = UnsafeBufferPointer(start: ptr, count: count) - return Array(buf) - } else { - var returnArray = [T]() - - let perRowCount = Int(buffer.width) * MemoryLayout.stride * channelCount - var ptr = buffer.data.bindMemory(to: T.self, - capacity: perRowCount) - - for _ in 0 ..< buffer.height { - let buf = UnsafeBufferPointer(start: ptr, count: perRowCount) - - returnArray.append(contentsOf: Array(buf)) - - ptr = ptr.advanced(by: buffer.rowBytes) - } - - return returnArray - } - } - - func imageToPixels(image: CGImage) -> [UInt8] { - let pixelCount = image.width * image.height - - let pixelData = image.dataProvider?.data - let pixels: UnsafePointer = CFDataGetBytePtr(pixelData) - let buf = UnsafeBufferPointer(start: pixels, count: pixelCount) - return Array(buf) - } - - func makePlanar8Image(from pixels: [UInt8], - width: UInt, - height: UInt) -> CGImage? { - - if - let outputData = CFDataCreate(nil, pixels, pixels.count), - let cgDataProvider = CGDataProvider(data: outputData) { - - return CGImage(width: Int(width), - height: Int(height), - bitsPerComponent: 8, - bitsPerPixel: 8, - bytesPerRow: Int(width), - space: CGColorSpaceCreateDeviceGray(), - bitmapInfo: CGBitmapInfo(rawValue: 0), - provider: cgDataProvider, - decode: nil, - shouldInterpolate: false, - intent: CGColorRenderingIntent.defaultIntent) - - } - return nil - } - - func makeRGBA8888Image(from pixels: [UInt8], - width: UInt, - height: UInt) -> CGImage? { - - if - let outputData = CFDataCreate(nil, pixels, pixels.count), - let cgDataProvider = CGDataProvider(data: outputData) { - - return CGImage(width: Int(width), - height: Int(height), - bitsPerComponent: 8, - bitsPerPixel: 8 * 4, - bytesPerRow: Int(width) * 4, - space: CGColorSpace(name: CGColorSpace.sRGB)!, - bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue), - provider: cgDataProvider, - decode: nil, - shouldInterpolate: false, - intent: CGColorRenderingIntent.defaultIntent) - - } - return nil - } -} -runAllTests() diff --git a/test/stdlib/AppKit_Swift4.swift b/test/stdlib/AppKit_Swift4.swift deleted file mode 100644 index d30fa4f603db9..0000000000000 --- a/test/stdlib/AppKit_Swift4.swift +++ /dev/null @@ -1,140 +0,0 @@ -// RUN: %empty-directory(%t) -// RUN: %target-build-swift -swift-version 4 %s -o %t/a.out -// RUN: %target-run %t/a.out -// REQUIRES: executable_test -// REQUIRES: OS=macosx -// REQUIRES: objc_interop - -import AppKit -import StdlibUnittest -import StdlibUnittestFoundationExtras - -let AppKitTests = TestSuite("AppKit_Swift4") - -AppKitTests.test("NSEventMaskFromType") { - let eventType: NSEvent.EventType = .keyDown - let eventMask = NSEvent.EventTypeMask(type: eventType) - expectEqual(eventMask, .keyDown) -} - -AppKitTests.test("NSWindowDepth.availableDepths") { - let depths = NSWindow.Depth.availableDepths - expectGT(depths.count, 0) - for depth in depths { - expectNotEqual(depth.rawValue, 0) - } -} - -AppKitTests.test("NSRectFills") { - let bitmapImage = NSBitmapImageRep( - bitmapDataPlanes: nil, pixelsWide: 3, pixelsHigh: 3, - bitsPerSample: 8, samplesPerPixel: 4, - hasAlpha: true, isPlanar: false, - colorSpaceName: .deviceRGB, - bytesPerRow: 0, bitsPerPixel: 0)! - let graphicsContext = NSGraphicsContext(bitmapImageRep: bitmapImage)! - NSGraphicsContext.saveGraphicsState() - NSGraphicsContext.current = graphicsContext - - let canvas = NSRect(x: 0, y: 0, width: 3, height: 3) - let bottomLeft = NSRect(x: 0, y: 0, width: 1, height: 1) - let bottomCenter = NSRect(x: 1, y: 0, width: 1, height: 1) - let bottomRight = NSRect(x: 2, y: 0, width: 1, height: 1) - let middleCenter = NSRect(x: 1, y: 1, width: 1, height: 1) - let middleRight = NSRect(x: 2, y: 1, width: 1, height: 1) - let topLeft = NSRect(x: 0, y: 2, width: 1, height: 1) - let topCenter = NSRect(x: 1, y: 2, width: 1, height: 1) - let topRight = NSRect(x: 2, y: 2, width: 1, height: 1) - let red = NSColor(deviceRed: 1.0, green: 0.0, blue: 0.0, alpha: 1.0) - let green = NSColor(deviceRed: 0.0, green: 1.0, blue: 0.0, alpha: 1.0) - let blue = NSColor(deviceRed: 0.0, green: 0.0, blue: 1.0, alpha: 1.0) - let black = NSColor(deviceRed: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) - let white = NSColor(deviceRed: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) - - // Blank out the canvas with white - white.set() - canvas.fill() - - // Fill the bottomLeft and middleRight with red using the Sequence convenience - red.set() - [bottomLeft, middleRight].fill() - - // Fill the bottom right corner by clipping to it, and then filling the canvas - NSGraphicsContext.saveGraphicsState() - topRight.clip() - black.set() - canvas.fill() - NSGraphicsContext.restoreGraphicsState() - - // Fill bottomRight and topLeft by clipping to them and filling a superset - NSGraphicsContext.saveGraphicsState() - [bottomRight, topLeft].clip() - green.set() - canvas.fill() - blue.set() - // effectively fill bottomRight only - NSRect(x: 0, y: 0, width: 3, height: 1).fill() - NSGraphicsContext.restoreGraphicsState() - - // Fill the center regions using the Sequence<(Rect, Color)> convenience - [(topCenter, blue), - (middleCenter, green), - (bottomCenter, red)].fill() - - NSGraphicsContext.restoreGraphicsState() - - expectEqual(bitmapImage.colorAt(x: 0, y: 0), green) - expectEqual(bitmapImage.colorAt(x: 1, y: 0), blue) - expectEqual(bitmapImage.colorAt(x: 2, y: 0), black) - expectEqual(bitmapImage.colorAt(x: 0, y: 1), white) - expectEqual(bitmapImage.colorAt(x: 1, y: 1), green) - expectEqual(bitmapImage.colorAt(x: 2, y: 1), red) - expectEqual(bitmapImage.colorAt(x: 0, y: 2), red) - expectEqual(bitmapImage.colorAt(x: 1, y: 2), red) - expectEqual(bitmapImage.colorAt(x: 2, y: 2), blue) -} - -AppKitTests.test("NSColor.Literals") { - if #available(macOS 10.12, *) { - // Color literal in the extended sRGB color space. - let c1 = #colorLiteral(red: 1.358, green: -0.074, blue: -0.012, alpha: 1.0) - - var printedC1 = "" - print(c1, to: &printedC1) - expectTrue(printedC1.contains("extended")) - } -} - -AppKitTests.test("NSLayoutPriority") { - let highPriority: NSLayoutConstraint.Priority = .defaultHigh - - let adjustedPriority1 = highPriority + 1 - let adjustedPriority1RawValue: Float = NSLayoutConstraint.Priority.defaultHigh.rawValue + 1 - expectEqual(adjustedPriority1.rawValue, adjustedPriority1RawValue) - - let adjustedPriority2 = highPriority - 5.0 - let adjustedPriority2RawValue: Float = NSLayoutConstraint.Priority.defaultHigh.rawValue - 5.0 - expectEqual(adjustedPriority2.rawValue, adjustedPriority2RawValue) - - let adjustedPriority3 = 5.0 + highPriority - let adjustedPriority3RawValue: Float = 5.0 + NSLayoutConstraint.Priority.defaultHigh.rawValue - expectEqual(adjustedPriority3.rawValue, adjustedPriority3RawValue) - - // Inferred typing from result type - let adjustedPriority4: NSLayoutConstraint.Priority = .defaultHigh + 2.0 - let adjustedPriority4RawValue: Float = NSLayoutConstraint.Priority.defaultHigh.rawValue + 2.0 - expectEqual(adjustedPriority4.rawValue, adjustedPriority4RawValue) - - // Comparable - expectTrue(adjustedPriority1 > adjustedPriority2) - expectTrue(adjustedPriority2 < adjustedPriority1) - - // Compound assignment - var variablePriority: NSLayoutConstraint.Priority = .defaultHigh - variablePriority += 1 - variablePriority -= 5.0 - let variablePriorityRawValue: Float = NSLayoutConstraint.Priority.defaultHigh.rawValue + 1 - 5.0 - expectEqual(variablePriority.rawValue, variablePriorityRawValue) -} - -runAllTests() diff --git a/test/stdlib/AssetsLibrary.swift b/test/stdlib/AssetsLibrary.swift deleted file mode 100644 index c2277fb5cf5db..0000000000000 --- a/test/stdlib/AssetsLibrary.swift +++ /dev/null @@ -1,16 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test -// REQUIRES: OS=ios - -import AssetsLibrary - -// Test the enumerateGroupsWithTypes overload that accepts UInt32. -// This should compile and not crash at runtime. - -let library = ALAssetsLibrary() -library.enumerateGroupsWithTypes(ALAssetsGroupAll, - usingBlock: {(group: ALAssetsGroup?, stop: UnsafeMutablePointer?) -> Void in - print("Swift usingBlock")}, - failureBlock: {(error: Error?) -> Void in - print("Swift failureBlock")}) - diff --git a/test/stdlib/Casts.swift b/test/stdlib/Casts.swift index abab9b680b4ac..95bfd67ceb3e1 100644 --- a/test/stdlib/Casts.swift +++ b/test/stdlib/Casts.swift @@ -84,7 +84,7 @@ CastsTests.test("Optional.none can be casted to Optional.none in generic c #if _runtime(_ObjC) protocol P2 {} CastsTests.test("Cast from ObjC existential to Protocol (SR-3871)") { - if #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) { + if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { struct S: P2 {} class ObjCWrapper { diff --git a/test/stdlib/CloudKit.swift b/test/stdlib/CloudKit.swift deleted file mode 100644 index 38ca45c77c3ef..0000000000000 --- a/test/stdlib/CloudKit.swift +++ /dev/null @@ -1,84 +0,0 @@ -// RUN: %empty-directory(%t) -// RUN: %target-build-swift -swift-version 4 -F %sdk/System/Library/PrivateFrameworks %s -o %t/a.out-4 && %target-codesign %t/a.out-4 && %target-run %t/a.out-4 -// RUN: %target-build-swift -swift-version 4.2 -F %sdk/System/Library/PrivateFrameworks %s -o %t/a.out-4.2 && %target-codesign %t/a.out-4.2 && %target-run %t/a.out-4.2 -// REQUIRES: executable_test -// REQUIRES: objc_interop - -import CloudKit -import StdlibUnittest -import StdlibUnittestFoundationExtras - -let CloudKitTests = TestSuite("CloudKit") - - -CloudKitTests.test("Type renames") { - if #available(macOS 10.10, iOS 8.0, tvOS 9.0, watchOS 3.0, *) { -#if swift(>=4.2) - let _: CKRecord.ID? = nil - let _: CKRecord.Reference? = nil - let _: CKRecordZone.ID? = nil - let _: CKNotification.ID? = nil - let _: CKQueryOperation.Cursor? = nil - let _: CKModifyRecordsOperation.RecordSavePolicy? = nil - let _: CKNotification.NotificationType? = nil - let _: CKQueryNotification.Reason? = nil - let _: CKRecordZone.Capabilities? = nil -#else - let _: CKRecordID? = nil - let _: CKReference? = nil - let _: CKRecordZoneID? = nil - let _: CKNotificationID? = nil - let _: CKQueryCursor? = nil - let _: CKRecordSavePolicy? = nil - let _: CKNotificationType? = nil - let _: CKQueryNotificationReason? = nil - let _: CKRecordZoneCapabilities? = nil -#endif - } - - if #available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { -#if swift(>=4.2) - let _: CKShare.Participant? = nil - let _: CKUserIdentity.LookupInfo? = nil - let _: CKShare.Metadata? = nil - let _: CKDatabase.Scope? = nil -#else - let _: CKShareParticipant? = nil - let _: CKUserIdentityLookupInfo? = nil - let _: CKShareMetadata? = nil - let _: CKDatabaseScope? = nil -#endif - } - - if #available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) { -#if swift(>=4.2) - let _: CKOperation.Configuration? = nil - let _: CKOperationGroup.TransferSize? = nil -#else - let _: CKOperationConfiguration? = nil - let _: CKOperationGroupTransferSize? = nil -#endif - } - -#if !os(watchOS) - if #available(macOS 10.10, iOS 8.0, tvOS 9.0, *) { -#if swift(>=4.2) - let _: CKSubscription.SubscriptionType? = nil - let _: CKSubscription.NotificationInfo? = nil -#else - let _: CKSubscriptionType? = nil - let _: CKNotificationInfo? = nil -#endif // swift(>=4.2) - } - - if #available(macOS 10.12, iOS 10.0, tvOS 10.0, *) { -#if swift(>=4.2) - let _: CKQuerySubscription.Options? = nil -#else - let _: CKQuerySubscriptionOptions? = nil -#endif // swift(>=4.2) - } -#endif // !os(watchOS) -} - -runAllTests() diff --git a/test/stdlib/Compression.swift b/test/stdlib/Compression.swift deleted file mode 100644 index f49d2d18d387b..0000000000000 --- a/test/stdlib/Compression.swift +++ /dev/null @@ -1,148 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test -// REQUIRES: objc_interop - -import StdlibUnittest -import Compression -import Foundation - -// Read from Data -class DataSource { - - private var _buf : Data - private var _bufSize : Int // total byte count - private var _pos : Int // next byte to read - - public init(_ d: Data) { - _buf = d - _bufSize = d.count - _pos = 0 - } - - public func readData(ofLength len: Int) -> Data? { - let n = min(len,_bufSize - _pos) - if (n == 0) { return nil } // EOF - let d = _buf.subdata(in: _pos ..< _pos + n) - _pos += n - return d - } - -} - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) -func ofiltercompress_ifilterdecompress( - _ contents: Data, using algo: Algorithm -) throws -> Bool { - - var payload = Data() - var decompressed = Data() - - // Output filter compress - let f = DataSource(contents) - let ofilter = try OutputFilter(.compress, using: algo) { (x: Data?) -> () in - if let x = x { payload.append(x) } - } - while (true) { - let i = f.readData(ofLength: 900) - try ofilter.write(i) // will finalize when i is empty - if i == nil { break } - } - - // Input filter decompress - let g = DataSource(payload) - let ifilter = try InputFilter(.decompress, using: algo) { (x: Int) -> Data? in - return g.readData(ofLength: x) - } - while let i = try ifilter.readData(ofLength: 400) { - decompressed.append(i) - } - - print("ofilter | ifilter \(algo): \(contents.count) -> \(payload.count) -> \(decompressed.count)") - return contents == decompressed -} - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) -func ifiltercompress_ofilterdecompress( - _ contents: Data, using algo: Algorithm -) throws -> Bool { - - var payload = Data() - var decompressed = Data() - - // Input filter compress - let f = DataSource(contents) - let ifilter = try InputFilter(.compress, using: algo) {(x: Int) -> Data? in - return f.readData(ofLength:x) - } - while let i = try ifilter.readData(ofLength: 400) { - payload.append(i) - } - - // Output filter decompress - let g = DataSource(payload) - let ofilter = try OutputFilter(.decompress, using: algo) {(x: Data?) -> () in - if let x = x { - decompressed.append(x) - } - } - while (true) { - let i = g.readData(ofLength: 900) - try ofilter.write(i) // will finalize when i is empty - if i == nil { break } - } - - print("ifilter | ofilter \(algo): \(contents.count) -> \(payload.count) -> \(decompressed.count)") - - return contents == decompressed -} - -func randomString(withBlockLength n: Int) -> String { - var strings = [String]() - for _ in 0 ..< n { - var s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " - // Change some random chars - for _ in 1...10 { - let pos = Int.random(in: 0 ..< s.count) - let idx = s.index(s.startIndex, offsetBy: pos) - s = String(s[..> (SwiftTesting) -+ (NSArray *)testGettingSomeDictionaries; -@end - -NS_ASSUME_NONNULL_END diff --git a/test/stdlib/Inputs/CoreDataHelper/CoreDataHelper.m b/test/stdlib/Inputs/CoreDataHelper/CoreDataHelper.m deleted file mode 100644 index 75313c8b34775..0000000000000 --- a/test/stdlib/Inputs/CoreDataHelper/CoreDataHelper.m +++ /dev/null @@ -1,7 +0,0 @@ -#import "CoreDataHelper.h" - -@implementation NSFetchRequest (SwiftTesting) -+ (NSArray> *)testGettingSomeDictionaries { - return @[ @{}, @{} ]; -} -@end diff --git a/test/stdlib/Inputs/FloatingPointConversion.swift.gyb b/test/stdlib/Inputs/FloatingPointConversion.swift.gyb index 715510c53ceb9..f6f98723b3eb7 100644 --- a/test/stdlib/Inputs/FloatingPointConversion.swift.gyb +++ b/test/stdlib/Inputs/FloatingPointConversion.swift.gyb @@ -31,7 +31,7 @@ var FloatingPointConversionFailures = TestSuite("FloatingPointToFloatingPointCon % if OtherSignificandBits <= SelfSignificandBits: % if OtherFloat == 'Float16': -if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) { +if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { % end FloatingPointConversionTruncations.test("${OtherFloat}To${Self}Conversion") @@ -56,7 +56,7 @@ FloatingPointConversionTruncations.test("${OtherFloat}To${Self}Conversion") % else: % if Self == 'Float16': -if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) { +if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { % end FloatingPointConversionTruncations.test("${OtherFloat}To${Self}Conversion") .forEach(in: [ @@ -77,7 +77,7 @@ FloatingPointConversionTruncations.test("${OtherFloat}To${Self}Conversion") % end % if 'Float16' in [Self, OtherFloat]: -if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) { +if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { % end FloatingPointConversionTruncations.test("${OtherFloat}To${Self}Conversion/special") { expectEqual( 1.0 as ${Self}, ${Self}(exactly: 1.0 as ${OtherFloat})) @@ -138,7 +138,7 @@ _UnimplementedError() extension ${OtherInt} { % if Self == 'Float16': - @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) + @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) % end static var _test${Self}Conversion: [(${OtherInt}, ${OtherInt}, ${OtherInt}?)] { if bitWidth > ${Self}.significandBitCount + 1 { @@ -165,7 +165,7 @@ extension ${OtherInt} { } % if Self == 'Float16': -if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) { +if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { % end FixedPointConversionTruncations.test("${OtherInt}to${Self}") .forEach(in: ${OtherInt}._test${Self}Conversion) { diff --git a/test/stdlib/Intents.swift b/test/stdlib/Intents.swift deleted file mode 100644 index cbb78ea184ba6..0000000000000 --- a/test/stdlib/Intents.swift +++ /dev/null @@ -1,233 +0,0 @@ -// RUN: %empty-directory(%t) -// RUN: %target-build-swift %s -o %t/a.out4 -swift-version 4 && %target-codesign %t/a.out4 && %target-run %t/a.out4 -// RUN: %target-build-swift %s -o %t/a.out42 -swift-version 4.2 && %target-codesign %t/a.out42 && %target-run %t/a.out42 -// REQUIRES: executable_test -// REQUIRES: objc_interop - -// UNSUPPORTED: OS=tvos - -import Intents -import StdlibUnittest - -let IntentsTestSuite = TestSuite("Intents") - -#if swift(>=4.2) -let swiftVersion = "4.2" -#else -let swiftVersion = "4" -#endif - -#if !os(macOS) -if #available(iOS 10.0, watchOS 3.2, *) { - - IntentsTestSuite.test("ErrorDomain/\(swiftVersion)") { - expectEqual("IntentsErrorDomain", INIntentErrorDomain) - } - - IntentsTestSuite.test("extension/\(swiftVersion)") { - expectEqual("IntentsErrorDomain", INIntentError.errorDomain) - } -} -#endif - -#if os(iOS) -if #available(iOS 11.0, *) { - - IntentsTestSuite.test("INParameter KeyPath/\(swiftVersion)") { - let param = INParameter(keyPath: \INRequestRideIntent.pickupLocation) - expectEqual("pickupLocation", param?.parameterKeyPath) - if let typ = param?.parameterClass { - expectEqual(INRequestRideIntent.self, typ) - } - else { - expectUnreachable() - } - } - - IntentsTestSuite.test("INSetProfileInCarIntent/defaultProfile availability/\(swiftVersion)") { - func f(profile: INSetProfileInCarIntent) { - var isDefaultProfile = profile.isDefaultProfile - expectType(Bool?.self, &isDefaultProfile) - } - } -} -#endif - -#if os(iOS) || os(watchOS) -if #available(iOS 12.0, watchOS 5.0, *) { - - // helper functions to build test data - func buildIntent(_ identifier: String) -> INIntent { - let person = INPerson(personHandle: INPersonHandle(value: "123-456-7890", type: .phoneNumber), nameComponents: nil, displayName: "test person \(identifier)", image: nil, contactIdentifier: nil, customIdentifier: "testPerson \(identifier)") - return INSendMessageIntent(recipients: [person], content: "test content \(identifier)", speakableGroupName: INSpeakableString(spokenPhrase: "test group \(identifier)"), conversationIdentifier: nil, serviceName: "test service \(identifier)", sender: person) - } - func buildUserActivity(_ identifier: String) -> NSUserActivity { - return NSUserActivity(activityType: "test activity \(identifier)") - } - - IntentsTestSuite.test("INShortcutOverlay/is enum/\(swiftVersion)") { - // INIntent - let originalIntent = buildIntent("A") - let shortcutWithIntent: INShortcut = .intent(originalIntent) - switch shortcutWithIntent { - case .intent(let intent): - expectEqual(intent, originalIntent) - case .userActivity: - expectUnreachable() - } - // test convenince properties - expectEqual(shortcutWithIntent.intent, originalIntent) - expectEqual(shortcutWithIntent.userActivity, nil) - // test convenince init - expectEqual(INShortcut(intent: originalIntent), shortcutWithIntent) - - // NSUserActivity - let originalUserActivity = buildUserActivity("A") - let shortcutWithNSUA: INShortcut = .userActivity(originalUserActivity) - switch shortcutWithNSUA { - case .intent: - expectUnreachable() - case .userActivity(let userActivity): - expectEqual(userActivity, originalUserActivity) - } - // test convenince properties - expectEqual(shortcutWithNSUA.intent, nil) - expectEqual(shortcutWithNSUA.userActivity, originalUserActivity) - // test convenince init - expectEqual(INShortcut(userActivity: originalUserActivity), shortcutWithNSUA) - } - - IntentsTestSuite.test("INShortcutOverlay/conformances/\(swiftVersion)") { - let intentA = buildIntent("A") - let shortcutIntentA: INShortcut = .intent(intentA) - let shortcutIntentA2: INShortcut = .intent(intentA) - let shortcutIntentB: INShortcut = .intent(buildIntent("B")) - let userActivityA = buildUserActivity("A") - let shortcutUserActivityA: INShortcut = .userActivity(userActivityA) - let shortcutUserActivityA2: INShortcut = .userActivity(userActivityA) - let shortcutUserActivityB: INShortcut = .userActivity(buildUserActivity("B")) - - // Equatable - expectEqual(shortcutIntentA, shortcutIntentA2) - expectNotEqual(shortcutIntentA, shortcutIntentB) - expectEqual(shortcutUserActivityA, shortcutUserActivityA2) - expectNotEqual(shortcutUserActivityA, shortcutUserActivityB) - expectNotEqual(shortcutIntentA, shortcutUserActivityA) - - // Hashable - // expectEqual(shortcutIntentA.hashValue, shortcutIntentA.hashValue) -// expectEqual(shortcutUserActivityA.hashValue, shortcutUserActivityA.hashValue) - - // Strings - let _: String = shortcutIntentA.description - let _: String = shortcutIntentA.debugDescription - } - - // Make sure the shortcut property of INVoiceShortcut is imported as the overlay enum type - IntentsTestSuite.test("INShortcutOverlay/INVoiceShortcut propertyIsEnum/\(swiftVersion)") { - // NOTE: we can't actually run this one becuase we can't easily create an INVoiceShortcut, but at least type-check it - func f(voiceShortcut: INVoiceShortcut) { - switch voiceShortcut.shortcut { - case .intent(let intent): - print("got intent \(intent)") - case .userActivity(let userActivity): - print("got userActivity \(userActivity)") - } - } - } -} -#endif - -#if os(iOS) || os(watchOS) -if #available(iOS 10.0, watchOS 3.2, *) { - - IntentsTestSuite.test("INRideOption usesMeteredFare/\(swiftVersion)") { - func f(rideOption: inout INRideOption) { -#if swift(>=4) - rideOption.usesMeteredFare = true - expectType(Bool?.self, &rideOption.usesMeteredFare) - expectTrue(rideOption.usesMeteredFare ?? false) -#else - rideOption.usesMeteredFare = NSNumber(value: true) - expectType(NSNumber?.self, &rideOption.usesMeteredFare) - expectTrue(rideOption.usesMeteredFare?.boolValue ?? false) -#endif - } - } - -} -#endif - -#if os(iOS) -if #available(iOS 11.0, *) { - IntentsTestSuite.test("INSetProfileInCarIntent Initializers/\(swiftVersion)") { -#if swift(>=4) - _ = INSetProfileInCarIntent() - _ = INSetProfileInCarIntent(isDefaultProfile: nil) - _ = INSetProfileInCarIntent(profileName: nil) - _ = INSetProfileInCarIntent(profileName: nil, isDefaultProfile: nil) - _ = INSetProfileInCarIntent(profileNumber: nil) - _ = INSetProfileInCarIntent(profileNumber: nil, isDefaultProfile: nil) - _ = INSetProfileInCarIntent(profileNumber: nil, profileName: nil) - _ = INSetProfileInCarIntent( - profileNumber: nil, profileName: nil, isDefaultProfile: nil) -#else - _ = INSetProfileInCarIntent() - _ = INSetProfileInCarIntent(defaultProfile: nil) - _ = INSetProfileInCarIntent(profileName: nil) - _ = INSetProfileInCarIntent(profileName: nil, defaultProfile: nil) - _ = INSetProfileInCarIntent(profileNumber: nil) - _ = INSetProfileInCarIntent(profileNumber: nil, defaultProfile: nil) - _ = INSetProfileInCarIntent(profileNumber: nil, profileName: nil) - _ = INSetProfileInCarIntent( - profileNumber: nil, profileName: nil, defaultProfile: nil) -#endif - } -} -#endif - -#if os(iOS) || os(watchOS) -if #available(iOS 12.0, watchOS 5.0, *) { - - IntentsTestSuite.test("INPlayMediaIntent Initializer/\(swiftVersion)") { - let intent = INPlayMediaIntent(mediaItems: nil, mediaContainer: nil, playShuffled: false, playbackRepeatMode: .unknown, resumePlayback: true) - expectFalse(intent.playShuffled ?? true) - expectTrue(intent.resumePlayback ?? false) - } - -} -#endif - -#if os(iOS) - - IntentsTestSuite.test("Car Commands Intents Initializer/\(swiftVersion)") { - if #available(iOS 12.0, *) { - _ = INSetProfileInCarIntent(profileNumber: nil, profileName: nil, isDefaultProfile: nil, carName: nil) - _ = INSetClimateSettingsInCarIntent(enableFan: nil, enableAirConditioner: nil, enableClimateControl: nil, enableAutoMode: nil, airCirculationMode: .unknown, fanSpeedIndex: nil, fanSpeedPercentage: nil, relativeFanSpeedSetting: .unknown, temperature: nil, relativeTemperatureSetting: .unknown, climateZone: .unknown, carName: nil) - _ = INSetDefrosterSettingsInCarIntent(enable: nil, defroster: .unknown, carName: nil) - _ = INSetSeatSettingsInCarIntent(enableHeating: nil, enableCooling: nil, enableMassage: nil, seat: .unknown, level: nil, relativeLevel: .unknown, carName: nil) - } - - if #available(iOS 11.0, *) { - _ = INSetProfileInCarIntent(profileNumber: nil, profileName: nil, isDefaultProfile: nil) - _ = INSetClimateSettingsInCarIntent(enableFan: nil, enableAirConditioner: nil, enableClimateControl: nil, enableAutoMode: nil, airCirculationMode: .unknown, fanSpeedIndex: nil, fanSpeedPercentage: nil, relativeFanSpeedSetting: .unknown, temperature: nil, relativeTemperatureSetting: .unknown, climateZone: .unknown) - _ = INSetDefrosterSettingsInCarIntent(enable: nil, defroster: .unknown) - _ = INSetSeatSettingsInCarIntent(enableHeating: nil, enableCooling: nil, enableMassage: nil, seat: .unknown, level: nil, relativeLevel: .unknown) - } - } - -#endif - -#if os(iOS) || os(watchOS) -if #available(iOS 12.0, watchOS 5.0, *) { - - IntentsTestSuite.test("INIntent Images/\(swiftVersion)") { - let intent = INSendPaymentIntent(payee: nil, currencyAmount: nil, note: nil) - intent.setImage(nil, forParameterNamed: \INSendPaymentIntent.payee) - intent.setImage(nil, forParameterNamed: \.payee) - } - -} -#endif - -runAllTests() diff --git a/test/stdlib/MapKit.swift b/test/stdlib/MapKit.swift deleted file mode 100644 index 76625f26d8aa0..0000000000000 --- a/test/stdlib/MapKit.swift +++ /dev/null @@ -1,39 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test -// REQUIRES: objc_interop - -import CoreLocation -import MapKit -import StdlibUnittest -import StdlibUnittestFoundationExtras - -var mapKit = TestSuite("MapKit") - -func coordinatesEqual(_ x: CLLocationCoordinate2D, _ y: CLLocationCoordinate2D) - -> Bool { - return x.latitude == y.latitude && x.longitude == y.longitude -} -func spansEqual(_ x: MKCoordinateSpan, _ y: MKCoordinateSpan) - -> Bool { - return x.latitudeDelta == y.latitudeDelta - && x.longitudeDelta == y.longitudeDelta -} - -if #available(tvOS 9.2, *) { - mapKit.test("CLLocationCoordinate2D bridging") { - expectBridgeToNSValue(CLLocationCoordinate2D(latitude: 17, longitude: 38), - nsValueInitializer: { NSValue(mkCoordinate: $0) }, - nsValueGetter: { $0.mkCoordinateValue }, - equal: coordinatesEqual) - } - - mapKit.test("MKCoordinateSpan bridging") { - expectBridgeToNSValue(MKCoordinateSpan(latitudeDelta: 6, - longitudeDelta: 79), - nsValueInitializer: { NSValue(mkCoordinateSpan: $0) }, - nsValueGetter: { $0.mkCoordinateSpanValue }, - equal: spansEqual) - } -} - -runAllTests() diff --git a/test/stdlib/MediaPlayer.swift b/test/stdlib/MediaPlayer.swift deleted file mode 100644 index 597cd0386acba..0000000000000 --- a/test/stdlib/MediaPlayer.swift +++ /dev/null @@ -1,91 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test -// REQUIRES: objc_interop -// REQUIRES: OS=ios - -import MediaPlayer -import StdlibUnittest -import StdlibUnittestFoundationExtras - -let MediaPlayerTests = TestSuite("MediaPlayer") - -MediaPlayerTests.test("decodablePlayParameters") { - if #available(iOS 11.0, *) { - let identifier = "1234567890" - let kind = "song" - let isLibrary = true - let playParamsData = """ -{ - "id": "\(identifier)", - "kind": "\(kind)", - "isLibrary": \(isLibrary) -} -""".data(using: .utf8)! - - do { - let decoder = JSONDecoder() - let playParameters = try decoder.decode(MPMusicPlayerPlayParameters.self, from: playParamsData) - let playParametersDictionary = playParameters.dictionary - expectEqual(identifier, playParametersDictionary["id"] as! String) - expectEqual(kind, playParametersDictionary["kind"] as! String) - expectEqual(isLibrary, playParametersDictionary["isLibrary"] as! Bool) - } - catch { - expectUnreachableCatch(error) - } - } -} - -MediaPlayerTests.test("decodingInvalidPlayParameters") { - if #available(iOS 11.0, *) { - let invalidPlayParamsData = """ -{ - "kind": "song" -} -""".data(using: .utf8)! - - do { - let decoder = JSONDecoder() - let _ = try decoder.decode(MPMusicPlayerPlayParameters.self, from: invalidPlayParamsData) - expectUnreachable() - } - catch DecodingError.dataCorrupted(_) {} - catch { - expectUnreachableCatch(error) - } - } -} - - -MediaPlayerTests.test("encodablePlayParameters") { - if #available(iOS 11.0, *) { - let identifier = "1234567890" - let kind = "song" - let isLibrary = true - let correspondingPlayParamsString = """ -{"id":"\(identifier)","kind":"\(kind)","isLibrary":\(isLibrary)} -""" - - let playParametersDictionary: [String: Any] = [ - "id": identifier, - "kind": kind, - "isLibrary": isLibrary - ] - guard let playParameters = MPMusicPlayerPlayParameters(dictionary: playParametersDictionary) else { - expectUnreachable() - return - } - - do { - let encoder = JSONEncoder() - let encodedPlayParamsData = try encoder.encode(playParameters) - let encodedPlayParamsString = String(data: encodedPlayParamsData, encoding: .utf8)! - expectEqual(correspondingPlayParamsString, encodedPlayParamsString) - } - catch { - expectUnreachableCatch(error) - } - } -} - -runAllTests() diff --git a/test/stdlib/Metal.swift b/test/stdlib/Metal.swift deleted file mode 100644 index f4386869bd5df..0000000000000 --- a/test/stdlib/Metal.swift +++ /dev/null @@ -1,331 +0,0 @@ -// RUN: %empty-directory(%t) -// RUN: %target-build-swift %s -o %t/a.out4 -swift-version 4 && %target-codesign %t/a.out4 && %target-run %t/a.out4 -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -// REQUIRES: executable_test - -import StdlibUnittest - -import Metal - -var MetalTests = TestSuite("Metal") - -if #available(OSX 10.13, iOS 11.0, tvOS 11.0, *) { - - // Call each overlay to ensure nothing explodes - - MetalTests.test("MTLArgumentEncoder") { - func apiAvailabilityTest() { - /* Setup */ - - let device = MTLCreateSystemDefaultDevice()! - let buf = device.makeBuffer( - length: 64, options: MTLResourceOptions.storageModeShared)! - let texDesc = MTLTextureDescriptor() - texDesc.usage = MTLTextureUsage.renderTarget - let tex = device.makeTexture(descriptor: texDesc)! - let smplr = device.makeSamplerState(descriptor: MTLSamplerDescriptor()) - - var arguments = [MTLArgumentDescriptor]() - arguments.append(MTLArgumentDescriptor()) - arguments.append(MTLArgumentDescriptor()) - arguments.append(MTLArgumentDescriptor()) - arguments[0].dataType = MTLDataType.pointer - arguments[0].index = 0 - arguments[1].dataType = MTLDataType.texture - arguments[1].index = 1 - arguments[2].dataType = MTLDataType.sampler - arguments[2].index = 2 - if #available(OSX 10.14, iOS 12.0, tvOS 12.0, *){ - arguments.append(MTLArgumentDescriptor()) - arguments[3].dataType = MTLDataType.indirectCommandBuffer - arguments[3].index = 3 - } - - /* Call APIs */ - - let argEncoder = device.makeArgumentEncoder(arguments: arguments)! - argEncoder.setArgumentBuffer(buf, offset: 0) - argEncoder.setBuffers([buf], offsets: [0], range: 0..<1) - argEncoder.setTextures([tex], range: 1..<2) - argEncoder.setSamplerStates([smplr], range: 2..<3) - - if #available(OSX 10.14, iOS 12.0, tvOS 12.0, *){ - let icbDesc = MTLIndirectCommandBufferDescriptor() - icbDesc.commandTypes = [.draw, .drawIndexed] - icbDesc.inheritBuffers = false - icbDesc.maxVertexBufferBindCount = 1 - icbDesc.maxFragmentBufferBindCount = 1 - let icb = device.makeIndirectCommandBuffer (descriptor: icbDesc, maxCommandCount: 1, options: MTLResourceOptions.storageModeShared )! - argEncoder.setIndirectCommandBuffers([icb], range: 3..<4) - } - } - } - - MetalTests.test("MTLBlitCommandEncoder") { - func apiAvailabilityTest() { - - /* Setup */ - - let device = MTLCreateSystemDefaultDevice()! - let queue = device.makeCommandQueue()! - let cmdBuf = queue.makeCommandBuffer()! - let bltCmdEncdr = cmdBuf.makeBlitCommandEncoder()! - - /* Call APIs */ - - let buf = device.makeBuffer(length: 4, options: MTLResourceOptions())! - bltCmdEncdr.fill(buffer: buf, range: 0.. Bool { @@ -70,16 +66,6 @@ ${ testCase("CGAffineTransform", "CGAffineTransform(rotationAngle: .pi)", N #endif -#if os(iOS) || os(tvOS) || os(watchOS) - -${ testCase("CGRect", "CGRect(x: 17, y: 38, width: 6, height: 79)", "cgRect", "(==)") } -${ testCase("CGPoint", "CGPoint(x: 17, y: 38)", "cgPoint", "(==)") } -${ testCase("CGSize", "CGSize(width: 6, height: 79)", "cgSize", "(==)") } -${ testCase("CGVector", "CGVector(dx: 6, dy: 79)", "cgVector", "(==)") } -${ testCase("CGAffineTransform", "CGAffineTransform(rotationAngle: .pi)", "cgAffineTransform", "(==)") } - -#endif - nsValueBridging.test("NSValue can only be cast back to its original type") { let range = NSRange(location: 17, length: 38) let rangeObject: Any = NSValue(range: range) diff --git a/test/stdlib/NaturalLanguage.swift b/test/stdlib/NaturalLanguage.swift deleted file mode 100644 index f55d740a77f64..0000000000000 --- a/test/stdlib/NaturalLanguage.swift +++ /dev/null @@ -1,91 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test -// REQUIRES: objc_interop - -import StdlibUnittest - -import NaturalLanguage - - -var tests = TestSuite("NaturalLanguage") - -if #available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) { - tests.test("recognizer") { - let recognizer = NLLanguageRecognizer() - let str = "This is a test mein Freund" - recognizer.processString(str) - recognizer.languageHints = [.english: 0.9, .german: 0.1] - let lang = recognizer.dominantLanguage - expectEqual(NLLanguage.english, lang) - let hypotheses = recognizer.languageHypotheses(withMaximum: 2) - expectEqual(hypotheses.count, 2) - let enProb = hypotheses[.english] ?? 0.0 - let deProb = hypotheses[.german] ?? 0.0 - let frProb = hypotheses[.french] ?? 0.0 - expectNotEqual(0.0, enProb) - expectNotEqual(0.0, deProb) - expectEqual(0.0, frProb) - } - - tests.test("tokenizer") { - let tokenizer = NLTokenizer(unit:.word) - let str = "This is a test. 😀" - let strRange = Range(NSMakeRange(0, 18), in: str)! - tokenizer.string = str - tokenizer.setLanguage(.english) - let tokenRange1 = tokenizer.tokenRange(at: str.startIndex) - let tokenArray = tokenizer.tokens(for: strRange) - let tokenRange2 = tokenArray[0] - expectEqual(tokenRange1, tokenRange2) - expectEqual("This", str[tokenRange1]) - expectEqual(5, tokenArray.count) - var numTokens = 0 - tokenizer.enumerateTokens(in: strRange) { (tokenRange, attrs) -> Bool in - if (numTokens == 0) { - expectEqual(tokenRange, tokenRange1) - } - numTokens = numTokens + 1 - return true - } - expectEqual(5, numTokens) - expectEqual("😀", str[tokenArray[4]]) - } - - - tests.test("tagger") { - let tagger = NLTagger(tagSchemes: [.tokenType]) - let str = "This is a test. 😀" - let strRange = Range(NSMakeRange(0, 18), in: str)! - tagger.string = str - tagger.setLanguage(.english, range: strRange) - let ortho = NSOrthography.defaultOrthography(forLanguage: "en") - tagger.setOrthography(ortho, range: strRange) - let (tag1, tokenRange1) = tagger.tag(at: str.startIndex, unit: .word, scheme: .tokenType) - let tags = tagger.tags(in: strRange, unit: .word, scheme: .tokenType, options: .omitWhitespace) - let (tag2, tokenRange2) = tags[0] - let tokenRange3 = tagger.tokenRange(at: str.startIndex, unit: .word) - expectEqual(NLTag.word, tag1) - expectEqual(NLTag.word, tag2) - expectEqual(tokenRange1, tokenRange2) - expectEqual(tokenRange2, tokenRange3) - expectEqual("This", str[tokenRange1]) - expectEqual(6, tags.count) - var numTokens = 0 - tagger.enumerateTags(in: strRange, unit: .word, scheme: .tokenType, options: .omitWhitespace) { (tag, tokenRange) -> Bool in - let (tagAt, tokenRangeAt) = tagger.tag(at: tokenRange.lowerBound, unit: .word, scheme: .tokenType) - expectEqual(tag, tagAt) - expectEqual(tokenRange, tokenRangeAt) - if (numTokens == 0) { - expectEqual(NLTag.word, tag) - expectEqual(tokenRange, tokenRange1) - } - numTokens += 1 - return true - } - expectEqual(6, numTokens) - let (_, tokenRange4) = tags[5] - expectEqual("😀", str[tokenRange4]) - } -} - -runAllTests() diff --git a/test/stdlib/Network.swift b/test/stdlib/Network.swift deleted file mode 100644 index aa9e3d1f79625..0000000000000 --- a/test/stdlib/Network.swift +++ /dev/null @@ -1,908 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - - -import Network -import Foundation -import StdlibUnittest - - -defer { runAllTests() } - -var NetworkAPI = TestSuite("NetworkAPI") - -#if !os(watchOS) - -if #available(macOS 10.14, iOS 12.0, tvOS 12.0, *) { - NetworkAPI.test("constants") { - expectNotNil(NWConnection.ContentContext.defaultMessage) - expectNotNil(NWConnection.ContentContext.finalMessage) - expectNotNil(NWConnection.ContentContext.defaultStream) - expectNotNil(NWParameters.tcp) - expectNotNil(NWParameters.tls) - expectNotNil(NWParameters.udp) - expectNotNil(NWParameters.dtls) - expectNotNil(IPv4Address.any) - expectNotNil(IPv4Address.broadcast) - expectNotNil(IPv4Address.loopback) - expectNotNil(IPv4Address.allHostsGroup) - expectNotNil(IPv4Address.allRoutersGroup) - expectNotNil(IPv4Address.allReportsGroup) - expectNotNil(IPv4Address.mdnsGroup) - expectNotNil(IPv6Address.any) - expectNotNil(IPv6Address.loopback) - expectNotNil(IPv6Address.nodeLocalNodes) - expectNotNil(IPv6Address.linkLocalNodes) - expectNotNil(IPv6Address.linkLocalRouters) - expectNotNil(NWEndpoint.Port.any) - expectNotNil(NWEndpoint.Port.ssh) - expectNotNil(NWEndpoint.Port.smtp) - expectNotNil(NWEndpoint.Port.http) - expectNotNil(NWEndpoint.Port.pop) - expectNotNil(NWEndpoint.Port.imap) - expectNotNil(NWEndpoint.Port.https) - expectNotNil(NWEndpoint.Port.imaps) - expectNotNil(NWEndpoint.Port.socks) - } - - NetworkAPI.test("NWEndpoint") { - let hostEndpoint = NWEndpoint.hostPort(host: "www.apple.com", port: .http) - expectNotNil(hostEndpoint) - expectNil(hostEndpoint.interface) - - let bonjourEndpoint = NWEndpoint.service(name: "myprinter", type: "_ipp._tcp", domain: "local", interface: nil) - expectNotNil(bonjourEndpoint) - expectNil(bonjourEndpoint.interface) - - let unixEndpoint = NWEndpoint.unix(path: "/foo/bar") - expectNotNil(unixEndpoint) - expectNil(unixEndpoint.interface) - } - - NetworkAPI.test("NWEndpoint.Host") { - var host = NWEndpoint.Host("www.apple.com") - expectNotNil(host) - expectNil(host.interface) - - host = NWEndpoint.Host("127.0.0.1") - expectNotNil(host) - expectNil(host.interface) - - host = NWEndpoint.Host("::1") - expectNotNil(host) - expectNil(host.interface) - - host = NWEndpoint.Host("::1%lo0") - expectNotNil(host) - expectNotNil(host.interface) - if let interface = host.interface { - expectEqual(interface.name, "lo0") - expectEqual(interface.type, .loopback) - } - - var ipv4Address = IPv4Address("127.0.0.1") - expectNotNil(ipv4Address) - expectNotNil(ipv4Address!.rawValue) - expectEqual(ipv4Address!.rawValue.count, 4) - expectNil(ipv4Address!.interface) - expectTrue(ipv4Address!.isLoopback) - - let otherIPv4Address = IPv4Address("127.0.0.1") - expectEqual(ipv4Address, otherIPv4Address) - - ipv4Address = IPv4Address("169.254.1.0") - expectNotNil(ipv4Address) - expectTrue(ipv4Address!.isLinkLocal) - - ipv4Address = IPv4Address("224.0.0.1") - expectNotNil(ipv4Address) - expectTrue(ipv4Address!.isMulticast) - - var ipv6Address = IPv6Address("::0") - expectNotNil(ipv6Address) - expectTrue(ipv6Address!.isAny) - expectNotNil(ipv6Address!.rawValue) - expectEqual(ipv6Address!.rawValue.count, 16) - expectNil(ipv6Address!.interface) - - ipv6Address = IPv6Address("::1") - expectNotNil(ipv6Address) - expectTrue(ipv6Address!.isLoopback) - expectNil(ipv6Address!.interface) - - ipv6Address = IPv6Address("::1%lo0") - expectNotNil(ipv6Address) - expectTrue(ipv6Address!.isLoopback) - expectNotNil(ipv6Address!.interface) - if let interface = ipv6Address!.interface { - expectEqual(interface.name, "lo0") - expectEqual(interface.type, .loopback) - } - - ipv6Address = IPv6Address("::1.2.3.4") - expectNotNil(ipv6Address) - expectTrue(ipv6Address!.isIPv4Compatabile) - - ipv6Address = IPv6Address("::ffff:1.2.3.4") - expectNotNil(ipv6Address) - expectTrue(ipv6Address!.isIPv4Mapped) - - ipv4Address = ipv6Address!.asIPv4 - expectNotNil(ipv4Address) - - ipv6Address = IPv6Address("2002::1") - expectNotNil(ipv6Address) - expectTrue(ipv6Address!.is6to4) - - ipv6Address = IPv6Address("fe80::1") - expectNotNil(ipv6Address) - expectTrue(ipv6Address!.isLinkLocal) - - ipv6Address = IPv6Address("ff02::1") - expectNotNil(ipv6Address) - expectTrue(ipv6Address!.isMulticast) - - expectEqual(ipv6Address!.multicastScope, .linkLocal) - - // Try a bad multicast scope - ipv6Address = IPv6Address("ff03::1") - expectNotNil(ipv6Address) - expectTrue(ipv6Address!.isMulticast) - expectTrue(ipv6Address!.multicastScope != .linkLocal) - } - - NetworkAPI.test("NWEndpoint.Port") { - let port: NWEndpoint.Port = 1234 - expectNotNil(port) - expectEqual(port.rawValue, 1234) - - expectEqual(NWEndpoint.Port.https, 443) - expectEqual(NWEndpoint.Port("https")!.rawValue, 443) - } - - NetworkAPI.test("NWParameters") { - var parameters = NWParameters.tcp - expectNotNil(parameters) - expectTrue(parameters.defaultProtocolStack.internetProtocol is NWProtocolIP.Options) - expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options) - expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 0) - - parameters = parameters.copy() - expectTrue(parameters.defaultProtocolStack.internetProtocol is NWProtocolIP.Options) - expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options) - expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 0) - - parameters = NWParameters.udp - expectNotNil(parameters) - expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolUDP.Options) - expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 0) - - parameters = NWParameters.tls - expectNotNil(parameters) - expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options) - expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 1) - expectTrue(parameters.defaultProtocolStack.applicationProtocols[0] is NWProtocolTLS.Options) - - parameters.defaultProtocolStack.transportProtocol = NWProtocolUDP.Options() - expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolUDP.Options) - - parameters = NWParameters.tls - expectNotNil(parameters) - expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options) - - parameters = NWParameters.dtls - expectNotNil(parameters) - expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolUDP.Options) - expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 1) - expectTrue(parameters.defaultProtocolStack.applicationProtocols[0] is NWProtocolTLS.Options) - - parameters = NWParameters(tls:nil, tcp:NWProtocolTCP.Options()) - expectNotNil(parameters) - expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options) - expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 0) - - parameters = NWParameters(dtls:nil, udp:NWProtocolUDP.Options()) - expectNotNil(parameters) - expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolUDP.Options) - expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 0) - - parameters = NWParameters(tls:NWProtocolTLS.Options(), tcp:NWProtocolTCP.Options()) - expectNotNil(parameters) - expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options) - expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 1) - expectTrue(parameters.defaultProtocolStack.applicationProtocols[0] is NWProtocolTLS.Options) - - parameters = NWParameters(dtls:NWProtocolTLS.Options(), udp:NWProtocolUDP.Options()) - expectNotNil(parameters) - expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolUDP.Options) - expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 1) - expectTrue(parameters.defaultProtocolStack.applicationProtocols[0] is NWProtocolTLS.Options) - - parameters = NWParameters() - expectNotNil(parameters) - expectNotNil(parameters.defaultProtocolStack) - expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 0) - expectNil(parameters.defaultProtocolStack.transportProtocol) - - parameters.defaultProtocolStack.transportProtocol = NWProtocolTCP.Options() - - expectNil(parameters.requiredInterface) - - expectEqual(parameters.requiredInterfaceType, NWInterface.InterfaceType.other) - parameters.requiredInterfaceType = .wifi - expectEqual(parameters.requiredInterfaceType, NWInterface.InterfaceType.wifi) - - expectTrue(parameters.prohibitedInterfaces == nil || - parameters.prohibitedInterfaces!.count == 0) - - expectTrue(parameters.prohibitedInterfaceTypes == nil || - parameters.prohibitedInterfaceTypes!.count == 0) - parameters.prohibitedInterfaceTypes = [ .cellular ] - expectTrue(parameters.prohibitedInterfaceTypes!.count == 1) - expectEqual(parameters.prohibitedInterfaceTypes![0], .cellular) - - expectEqual(parameters.prohibitExpensivePaths, false) - parameters.prohibitExpensivePaths = true; - expectEqual(parameters.prohibitExpensivePaths, true) - - expectEqual(parameters.preferNoProxies, false) - parameters.preferNoProxies = true; - expectEqual(parameters.preferNoProxies, true) - - expectNil(parameters.requiredLocalEndpoint) - parameters.requiredLocalEndpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: 1234) - expectNotNil(parameters.requiredLocalEndpoint) - - expectEqual(parameters.allowLocalEndpointReuse, false) - parameters.allowLocalEndpointReuse = true; - expectEqual(parameters.allowLocalEndpointReuse, true) - - expectEqual(parameters.acceptLocalOnly, false) - parameters.acceptLocalOnly = true; - expectEqual(parameters.acceptLocalOnly, true) - - expectEqual(parameters.serviceClass, NWParameters.ServiceClass.bestEffort) - parameters.serviceClass = .background; - expectEqual(parameters.serviceClass, NWParameters.ServiceClass.background) - - expectEqual(parameters.multipathServiceType, NWParameters.MultipathServiceType.disabled) - parameters.multipathServiceType = .handover; - expectEqual(parameters.multipathServiceType, NWParameters.MultipathServiceType.handover) - - expectEqual(parameters.expiredDNSBehavior, NWParameters.ExpiredDNSBehavior.systemDefault) - parameters.expiredDNSBehavior = .allow; - expectEqual(parameters.expiredDNSBehavior, NWParameters.ExpiredDNSBehavior.allow) - - expectEqual(parameters.allowFastOpen, false) - parameters.allowFastOpen = true; - expectEqual(parameters.allowFastOpen, true) - - expectEqual(parameters.includePeerToPeer, false) - parameters.includePeerToPeer = true; - expectEqual(parameters.includePeerToPeer, true) - } - - NetworkAPI.test("NWProtocolTCP") { - expectNotNil(NWProtocolTCP.definition) - expectEqual(NWProtocolTCP.definition.name, "tcp") - - let options = NWProtocolTCP.Options() - expectNotNil(options) - - expectEqual(options.noDelay, false) - options.noDelay = true; - expectEqual(options.noDelay, true) - - expectEqual(options.noPush, false) - options.noPush = true; - expectEqual(options.noDelay, true) - - expectEqual(options.noOptions, false) - options.noOptions = true; - expectEqual(options.noOptions, true) - - expectEqual(options.enableKeepalive, false) - options.enableKeepalive = true; - expectEqual(options.enableKeepalive, true) - - expectEqual(options.keepaliveCount, 0) - options.keepaliveCount = 5; - expectEqual(options.keepaliveCount, 5) - - expectEqual(options.keepaliveIdle, 0) - options.keepaliveIdle = 5; - expectEqual(options.keepaliveIdle, 5) - - expectEqual(options.keepaliveInterval, 0) - options.keepaliveInterval = 5; - expectEqual(options.keepaliveInterval, 5) - - expectEqual(options.maximumSegmentSize, 0) - options.maximumSegmentSize = 500; - expectEqual(options.maximumSegmentSize, 500) - - expectEqual(options.connectionTimeout, 0) - options.connectionTimeout = 60; - expectEqual(options.connectionTimeout, 60) - - expectEqual(options.persistTimeout, 0) - options.persistTimeout = 60; - expectEqual(options.persistTimeout, 60) - - expectEqual(options.connectionDropTime, 0) - options.connectionDropTime = 60; - expectEqual(options.connectionDropTime, 60) - - expectEqual(options.retransmitFinDrop, false) - options.retransmitFinDrop = true; - expectEqual(options.retransmitFinDrop, true) - - expectEqual(options.disableAckStretching, false) - options.disableAckStretching = true; - expectEqual(options.disableAckStretching, true) - - expectEqual(options.enableFastOpen, false) - options.enableFastOpen = true; - expectEqual(options.enableFastOpen, true) - - expectEqual(options.disableECN, false) - options.disableECN = true; - expectEqual(options.disableECN, true) - } - - NetworkAPI.test("NWProtocolUDP") { - expectNotNil(NWProtocolUDP.definition) - expectEqual(NWProtocolUDP.definition.name, "udp") - - let options = NWProtocolUDP.Options() - expectNotNil(options) - - expectEqual(options.preferNoChecksum, false) - options.preferNoChecksum = true; - expectEqual(options.preferNoChecksum, true) - } - - NetworkAPI.test("NWProtocolIP") { - expectNotNil(NWProtocolIP.definition) - expectEqual(NWProtocolIP.definition.name, "ip") - - let parameters = NWParameters() - let options = parameters.defaultProtocolStack.internetProtocol - expectNotNil(options) - - expectTrue(options is NWProtocolIP.Options) - - let ipOptions = options as! NWProtocolIP.Options - - expectEqual(ipOptions.version, .any) - ipOptions.version = .v6; - expectEqual(ipOptions.version, .v6) - - expectEqual(ipOptions.hopLimit, 0) - ipOptions.hopLimit = 5; - expectEqual(ipOptions.hopLimit, 5) - - expectEqual(ipOptions.useMinimumMTU, false) - ipOptions.useMinimumMTU = true; - expectEqual(ipOptions.useMinimumMTU, true) - - expectEqual(ipOptions.disableFragmentation, false) - ipOptions.disableFragmentation = true; - expectEqual(ipOptions.disableFragmentation, true) - - let metadata = NWProtocolIP.Metadata() - expectNotNil(metadata) - - expectEqual(metadata.ecn, .nonECT) - metadata.ecn = .ect0; - expectEqual(metadata.ecn, .ect0) - - expectEqual(metadata.serviceClass, .bestEffort) - metadata.serviceClass = .background; - expectEqual(metadata.serviceClass, .background) - - expectEqual(metadata.receiveTime, 0) - } - - NetworkAPI.test("NWProtocolTLS") { - expectNotNil(NWProtocolTLS.definition) - expectEqual(NWProtocolTLS.definition.name, "tls") - - let options = NWProtocolTLS.Options() - expectNotNil(options) - expectNotNil(options.securityProtocolOptions) - } - - NetworkAPI.test("NWPath") - .skip(.iOSSimulatorAny("Path not fully supported on simulator")) - .skip(.tvOSSimulatorAny("Path not fully supported on simulator")) - .code { - let testQueue = DispatchQueue(label: "testQueue") - let group = DispatchGroup() - - let monitor = NWPathMonitor() - expectNotNil(monitor) - - monitor.pathUpdateHandler = { (newPath) in - expectNotNil(newPath) - group.leave() - } - - group.enter(); - monitor.start(queue: testQueue) - - let path = monitor.currentPath - expectNotNil(path) - - let result = group.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - - expectEqual(monitor.queue, testQueue) - - expectNil(path.localEndpoint) - expectNil(path.remoteEndpoint) - - for interface in path.availableInterfaces { - expectNotNil(interface.name) - expectTrue(interface.index != 0) - } - - monitor.cancel() - - let wifiMonitor = NWPathMonitor(requiredInterfaceType: .wifi) - expectNotNil(wifiMonitor) - - wifiMonitor.start(queue: testQueue) - - let wifiPath = wifiMonitor.currentPath - expectNotNil(wifiPath) - - if wifiPath.status == .satisfied { - expectTrue(wifiPath.usesInterfaceType(.wifi)) - expectTrue(wifiPath.supportsIPv4 || wifiPath.supportsIPv6 || wifiPath.supportsDNS) - expectTrue(wifiPath.availableInterfaces.count > 0) - var someInterfaceWiFi = false - for interface in wifiPath.availableInterfaces { - if (interface.type == .wifi) { - someInterfaceWiFi = true - break - } - } - expectTrue(someInterfaceWiFi) - } - - wifiMonitor.cancel() - - let loopbackMonitor = NWPathMonitor(requiredInterfaceType: .loopback) - expectNotNil(loopbackMonitor) - - loopbackMonitor.start(queue: testQueue) - - let loopbackPath = loopbackMonitor.currentPath - expectNotNil(loopbackPath) - - expectTrue(!loopbackPath.isExpensive) - - loopbackMonitor.cancel() - } - - NetworkAPI.test("NWListener failure") - .skip(.iOSSimulatorAny("Path not fully supported on simulator")) - .skip(.tvOSSimulatorAny("Path not fully supported on simulator")) - .code { - let parameters: NWParameters = .tcp - parameters.requiredLocalEndpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: 1234) - - var listener: NWListener? = nil - do { - listener = try NWListener(using: parameters, on: 2345) - } catch { - print("Received listener error: \(error).") - } - expectNil(listener) - } - - NetworkAPI.test("NWListener") - .skip(.iOSSimulatorAny("Path not fully supported on simulator")) - .skip(.tvOSSimulatorAny("Path not fully supported on simulator")) - .code { - let testQueue = DispatchQueue(label: "testQueue") - let group = DispatchGroup() - let advertiseGroup = DispatchGroup() - - let listener = try! NWListener(using: .tcp, on: 1234) - expectNotNil(listener) - - listener.service = NWListener.Service(type: "_ipp._tcp") - - listener.stateUpdateHandler = { (newState) in - switch(newState) { - case .ready: - group.leave() - case .failed(let error): - expectNotNil(error) - listener.cancel() - case .cancelled: - group.leave() - default: - break - } - } - - listener.newConnectionHandler = { (newConn) in - expectNotNil(newConn) - newConn.forceCancel() - } - - listener.serviceRegistrationUpdateHandler = { (serviceChange) in - switch(serviceChange) { - case .add(let endpoint): - expectNotNil(endpoint) - case .remove(let endpoint): - expectNotNil(endpoint) - } - advertiseGroup.leave() - } - - group.enter() - advertiseGroup.enter() - listener.start(queue: testQueue) - - // Wait for ready - var result = group.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - - // Wait for advertise - result = advertiseGroup.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - - expectEqual(listener.queue, testQueue) - expectTrue(listener.parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options) - expectEqual(listener.port, 1234) - - group.enter() - listener.cancel() - - // Wait for cancelled - result = group.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - } - - NetworkAPI.test("NWConnection creation") { - var connection = NWConnection(host: "localhost", port: 2345, using:.tcp) - expectNotNil(connection) - - connection = NWConnection(to: .hostPort(host: "localhost", port: 2345), using:.tcp) - expectNotNil(connection) - - connection = NWConnection(to: .service(name: "myprinter", type: "_ipp._tcp", domain: "local", interface: nil), using:.tcp) - expectNotNil(connection) - - connection = NWConnection(to: .unix(path: "/foo/bar"), using:.tcp) - expectNotNil(connection) - } - - NetworkAPI.test("NWConnection Waiting Reset") - .skip(.iOSSimulatorAny("Path not fully supported on simulator")) - .skip(.tvOSSimulatorAny("Path not fully supported on simulator")) - .code { - let testQueue = DispatchQueue(label: "testQueue") - let group = DispatchGroup() - - let connection = NWConnection(host: "localhost", port: 3456, using:.tls) - expectNotNil(connection) - - connection.stateUpdateHandler = { (newState) in - switch(newState) { - case .waiting(let error): - expectNotNil(error) - switch(error) { - case .posix(let code): - expectEqual(code, .ECONNREFUSED) - default: - break - } - group.leave() - case .failed(let error): - expectNotNil(error) - connection.cancel() - case .cancelled: - group.leave() - default: - break - } - } - - group.enter() - connection.start(queue: testQueue) - - // Wait for waiting - var result = group.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - - connection.restart() - - group.enter() - connection.cancel() - - // Wait for cancelled - result = group.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - } - - NetworkAPI.test("NWConnection Waiting DNS") - .skip(.iOSSimulatorAny("Path not fully supported on simulator")) - .skip(.tvOSSimulatorAny("Path not fully supported on simulator")) - .code { - let testQueue = DispatchQueue(label: "testQueue") - let group = DispatchGroup() - - let connection = NWConnection(host: "foobar.fake.apple.com", port: .https, using:.tls) - expectNotNil(connection) - - connection.stateUpdateHandler = { (newState) in - switch(newState) { - case .waiting(let error): - expectNotNil(error) - switch(error) { - case .dns(let code): - expectEqual(code, DNSServiceErrorType(kDNSServiceErr_NoSuchRecord)) - default: - break - } - group.leave() - case .failed(let error): - expectNotNil(error) - connection.cancel() - case .cancelled: - group.leave() - default: - break - } - } - - group.enter() - connection.start(queue: testQueue) - - // Wait for waiting - var result = group.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - - group.enter() - connection.cancel() - - // Wait for cancelled - result = group.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - } - - NetworkAPI.test("NWConnection TCP") - .skip(.iOSSimulatorAny("Path not fully supported on simulator")) - .skip(.tvOSSimulatorAny("Path not fully supported on simulator")) - .code { - let testQueue = DispatchQueue(label: "testQueue") - let group = DispatchGroup() - let viableGroup = DispatchGroup() - let pathGroup = DispatchGroup() - let sendGroup = DispatchGroup() - let receiveGroup = DispatchGroup() - - let listener = try! NWListener(using: .tcp, on: 2345) - expectNotNil(listener) - - var inboundConnection: NWConnection? = nil - listener.newConnectionHandler = { (newConn) in - expectNotNil(newConn) - inboundConnection = newConn - newConn.receive(minimumIncompleteLength: 5, maximumLength: 5) { (receivedContent, context, isComplete, receivedError) in - expectTrue(!isComplete) - expectNil(receivedError) - expectNotNil(receivedContent) - expectNotNil(context) - receiveGroup.leave() - } - newConn.start(queue: testQueue) - } - listener.start(queue: testQueue) - - // Make sure connecting by address works - let ipv4Address = IPv4Address("127.0.0.1") - let connection = NWConnection(to: NWEndpoint.hostPort(host: .ipv4(ipv4Address!), port: 2345), using:.tcp) - expectNotNil(connection) - - connection.stateUpdateHandler = { (newState) in - switch(newState) { - case .ready: - group.leave() - case .failed(let error): - expectNotNil(error) - connection.cancel() - case .cancelled: - group.leave() - default: - break - } - } - - connection.pathUpdateHandler = { (newPath) in - expectNotNil(newPath) - pathGroup.leave() - } - - connection.viabilityUpdateHandler = { (isViable) in - expectTrue(isViable) - viableGroup.leave() - } - - connection.betterPathUpdateHandler = { (betterPathAvailable) in - expectTrue(!betterPathAvailable) - } - - group.enter() - viableGroup.enter() - pathGroup.enter() - receiveGroup.enter() - connection.start(queue: testQueue) - - // Wait for ready - var result = group.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - - let path = connection.currentPath - expectNotNil(path) - if let path = path { - expectTrue(path.usesInterfaceType(.loopback)) - expectNotNil(path.localEndpoint) - expectNotNil(path.remoteEndpoint) - } - - let metadata = connection.metadata(definition: NWProtocolTCP.definition) - expectNotNil(metadata) - expectTrue(metadata is NWProtocolTCP.Metadata) - - let tcpMetadata = metadata as! NWProtocolTCP.Metadata - expectEqual(tcpMetadata.availableReceiveBuffer, 0) - expectEqual(tcpMetadata.availableSendBuffer, 0) - - // Wait for viable - result = viableGroup.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - - // Wait for path - result = pathGroup.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - - expectEqual(connection.queue, testQueue) - expectTrue(connection.parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options) - expectNotNil(connection.endpoint) - - sendGroup.enter() - - let sendContent: Data = "hello".data(using: .utf8)! - connection.send(content: sendContent, isComplete: false, completion: .contentProcessed({ (sendError) in - expectNil(sendError) - sendGroup.leave() - })) - - // Wait for send - result = sendGroup.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - - // Wait for receive - result = receiveGroup.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - - // Send complete - connection.send(content: sendContent, contentContext: .finalMessage, isComplete: true, completion: .idempotent) - - group.enter() - connection.cancel() - - // Wait for cancelled - result = group.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - - if let inboundConnection = inboundConnection { - inboundConnection.forceCancel() - } - listener.cancel() - } - - NetworkAPI.test("NWConnection UDP") - .skip(.iOSSimulatorAny("Path not fully supported on simulator")) - .skip(.tvOSSimulatorAny("Path not fully supported on simulator")) - .code { - let testQueue = DispatchQueue(label: "testQueue") - let group = DispatchGroup() - let cancelGroup = DispatchGroup() - let receiveGroup = DispatchGroup() - - var inboundConnection: NWConnection? = nil - let listener = try! NWListener(using: .udp, on: 4567) - expectNotNil(listener) - - listener.newConnectionHandler = { (newConn) in - expectNotNil(newConn) - inboundConnection = newConn - newConn.receiveMessage() { (receivedContent, context, isComplete, receivedError) in - expectTrue(isComplete) - expectNil(receivedError) - expectNotNil(receivedContent) - expectNotNil(context) - receiveGroup.leave() - } - newConn.start(queue: testQueue) - } - listener.start(queue: testQueue) - - let connection = NWConnection(host: "localhost", port: 4567, using:.udp) - expectNotNil(connection) - - connection.stateUpdateHandler = { (newState) in - switch(newState) { - case .ready: - group.leave() - case .failed(let error): - expectNotNil(error) - connection.cancel() - case .cancelled: - cancelGroup.leave() - default: - break - } - } - - group.enter() - receiveGroup.enter() - connection.start(queue: testQueue) - - // Wait for ready - var result = group.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - - expectEqual(connection.queue, testQueue) - expectTrue(connection.parameters.defaultProtocolStack.transportProtocol is NWProtocolUDP.Options) - expectNotNil(connection.endpoint) - - let ipMetadata = NWProtocolIP.Metadata() - ipMetadata.ecn = .ect0 - let sendContext = NWConnection.ContentContext(identifier: "sendHello", expiration: 5000, priority: 1.0, isFinal: false, antecedent: nil, metadata: [ipMetadata]) - - expectNotNil(sendContext) - expectNotNil(sendContext.protocolMetadata) - expectNil(sendContext.antecedent) - expectEqual(sendContext.expirationMilliseconds, 5000) - expectEqual(sendContext.relativePriority, 1.0) - expectEqual(sendContext.isFinal, false) - expectEqual(sendContext.identifier, "sendHello") - - let sendContent: Data = "hello".data(using: .utf8)! - - connection.batch { - connection.send(content: sendContent, contentContext: sendContext, completion: .idempotent) - } - - // Wait for receive - result = receiveGroup.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - - cancelGroup.enter() - - connection.cancelCurrentEndpoint() - connection.cancel() - - // Wait for cancelled - result = cancelGroup.wait(timeout: DispatchTime.now() + .seconds(10)) - expectTrue(result == .success) - - if let inboundConnection = inboundConnection { - inboundConnection.forceCancel() - } - listener.cancel() - } -} - -#endif diff --git a/test/stdlib/OptionSetTest.swift b/test/stdlib/OptionSetTest.swift index 05fea8eaebe14..221cec6b03ed6 100644 --- a/test/stdlib/OptionSetTest.swift +++ b/test/stdlib/OptionSetTest.swift @@ -94,7 +94,7 @@ tests.test("set algebra") { p = P.boxOrBag let removed = p.remove(P.satchelOrBag) - if #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) { + if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { // https://github.com/apple/swift/pull/28378 expectEqual(P.bag, removed) } diff --git a/test/stdlib/PrintFloat.swift.gyb b/test/stdlib/PrintFloat.swift.gyb index f95113e9a6108..09d8e9dc49bb2 100644 --- a/test/stdlib/PrintFloat.swift.gyb +++ b/test/stdlib/PrintFloat.swift.gyb @@ -345,7 +345,7 @@ let PrintTests = TestSuite("FloatingPointPrinting") % for FloatType in ['Float16', 'Float', 'Double', 'Float80']: % if FloatType == 'Float16': -@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) +@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) % end % if FloatType == 'Float80': #if !os(Windows) && (arch(i386) || arch(x86_64)) @@ -383,7 +383,7 @@ fileprivate func expectDescription(_ expected: String, _ object: ${FloatType}, // that is closest (as an infinitely-precise real number) to the original // binary float (interpreted as an infinitely-precise real number). % if FloatType == 'Float16': -@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) +@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) % end fileprivate func expectAccurateDescription(_ object: ${FloatType}, _ message: @autoclosure () -> String = "", @@ -584,7 +584,7 @@ PrintTests.test("Printable_CDouble") { expectDescription("-1.0", CDouble(-1.0)) } -if #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) { +if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { PrintTests.test("Printable_Float16") { func asFloat16(_ f: Float16) -> Float16 { return f } diff --git a/test/stdlib/QuartzCore.swift b/test/stdlib/QuartzCore.swift deleted file mode 100644 index c32702758c6bd..0000000000000 --- a/test/stdlib/QuartzCore.swift +++ /dev/null @@ -1,63 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test -// REQUIRES: objc_interop - -// QuartzCore is not present on watchOS. -// UNSUPPORTED: OS=watchos - -import QuartzCore -import StdlibUnittest -import StdlibUnittestFoundationExtras - -var CanaryAssocObjectHandle: UInt8 = 0 - -// Attach a LifetimeTracked associated object to an object so we can see that -// the object died. -func hangCanary(_ o: AnyObject) { - objc_setAssociatedObject(o, &CanaryAssocObjectHandle, LifetimeTracked(0), - .OBJC_ASSOCIATION_RETAIN_NONATOMIC) -} - -let deviceRGB = CGColorSpaceCreateDeviceRGB() - -class FooLayer: CALayer { - var black: CGColor - var white = CGColor(colorSpace: deviceRGB, components: [1,1,1,1])! - - override init() { - black = CGColor(colorSpace: deviceRGB, components: [0,0,0,1])! - super.init() - hangCanary(self) - } - - required init?(coder: NSCoder) { - black = coder.decodeObject(forKey: "black") as! CGColor - super.init(coder: coder) - } - - override var description: String { - return "FooLayer" - } -} - -let quartzCore = TestSuite("QuartzCore") - -quartzCore.test("CALayer retain/release through subclass initializers") { - let layer = FooLayer() - expectEqual("FooLayer", "\(layer)") -} - -func equalCATransform3D(_ x: CATransform3D, _ y: CATransform3D) -> Bool { - var xx = x, yy = y - return memcmp(&xx, &yy, MemoryLayout.size) == 0 -} - -quartzCore.test("CATransform3D bridges to NSValue") { - expectBridgeToNSValue(CATransform3DMakeRotation(.pi, 1, 0, 0), - nsValueInitializer: { NSValue(caTransform3D: $0) }, - nsValueGetter: { $0.caTransform3DValue }, - equal: equalCATransform3D) -} - -runAllTests() - diff --git a/test/stdlib/SceneKit.swift b/test/stdlib/SceneKit.swift deleted file mode 100644 index 2472340141b6e..0000000000000 --- a/test/stdlib/SceneKit.swift +++ /dev/null @@ -1,243 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import StdlibUnittestFoundationExtras - - -import SceneKit - -// SceneKit is only available on iOS 8.0 and above and on OS X 10.8 and above. -// That said SCNMatrix4Scale &co are only available on OS X 10.10 and above. - -var SceneKitTests = TestSuite("SceneKit") - -if #available(iOS 8.0, OSX 10.10, *) { - let scn_vec3_ref = SCNVector3Make(1, 2, 3) - let scn_vec4_ref = SCNVector4Make(1, 2, 3, 4) - let scn_mat4_ref = SCNMatrix4Scale(SCNMatrix4Translate(SCNMatrix4MakeRotation(SCNFloat(M_PI), 1, 0, 0), 1, 2, 3), 10, 20, 30) - - // MARK: Exposing SCNFloat - - SceneKitTests.test("SCNFloat") { - let f = Float(1.0) - let scn_float_from_f = SCNFloat(f) - expectEqual(scn_float_from_f, 1.0) - - let d = Double(2.0) - let scn_float_from_d = SCNFloat(d) - expectEqual(scn_float_from_d, 2.0) - - let cg = CGFloat(3.0) - let scn_float_from_cg = SCNFloat(cg as NSNumber) - expectEqual(scn_float_from_cg, 3.0) - - let node = SCNNode() - node.position.x = scn_float_from_f - node.position.y = scn_float_from_d - node.position.z = scn_float_from_cg - expectTrue(SCNVector3EqualToVector3(node.position, scn_vec3_ref)) - - let f1: SCNFloat = scn_vec3_ref.x - let f2: SCNFloat = scn_vec4_ref.y - expectEqual(f1, 1.0); - expectEqual(f2, 2.0); - } - - // MARK: Working with SCNVector3 - - SceneKitTests.test("SCNVector3.init()/Literal") { - let scn_vec3_from_lit = SCNVector3(1, 2, 3) - expectTrue(SCNVector3EqualToVector3(scn_vec3_from_lit, scn_vec3_ref)) - } - - SceneKitTests.test("SCNVector3.init()/Float") { - let f1: Float = 1.0 - let f2: Float = 2.0 - let f3: Float = 3.0 - let scn_vec3_from_f = SCNVector3(f1, f2, f3) - expectTrue(SCNVector3EqualToVector3(scn_vec3_from_f, scn_vec3_ref)) - } - - SceneKitTests.test("SCNVector3.init()/CGFloat") { - let d1: CGFloat = 1.0 - let d2: CGFloat = 2.0 - let d3: CGFloat = 3.0 - let scn_vec3_from_cg = SCNVector3(d1, d2, d3) - expectTrue(SCNVector3EqualToVector3(scn_vec3_from_cg, scn_vec3_ref)) - } - - SceneKitTests.test("SCNVector3.init()/Double") { - let d1: Double = 1.0 - let d2: Double = 2.0 - let d3: Double = 3.0 - let scn_vec3_from_d = SCNVector3(d1, d2, d3) - expectTrue(SCNVector3EqualToVector3(scn_vec3_from_d, scn_vec3_ref)) - } - - SceneKitTests.test("SCNVector3.init()/Int") { - let i1: Int = 1 - let i2: Int = 2 - let i3: Int = 3 - let scn_vec3_from_i = SCNVector3(i1, i2, i3) - expectTrue(SCNVector3EqualToVector3(scn_vec3_from_i, scn_vec3_ref)) - } - - SceneKitTests.test("SCNVector3.init()/float3") { - let v3 = float3(1, 2, 3) - let scn_vec3_from_float3 = SCNVector3(v3) - expectTrue(SCNVector3EqualToVector3(scn_vec3_from_float3, scn_vec3_ref)) - } - - SceneKitTests.test("SCNVector3.init()/double3") { - let v3 = double3(1, 2, 3) - let scn_vec3_from_double3 = SCNVector3(v3) - expectTrue(SCNVector3EqualToVector3(scn_vec3_from_double3, scn_vec3_ref)) - } - - SceneKitTests.test("SCNVector3.init()/mix") { - let f1: Float = 1.0 - let d2: CGFloat = 2.0 - let scn_vec3_from_mixed = SCNVector3(f1, Float(d2), 3) - expectTrue(SCNVector3EqualToVector3(scn_vec3_from_mixed, scn_vec3_ref)) - } - - SceneKitTests.test("float3.init()/SCNVector3") { - let v3 = float3(scn_vec3_ref) - expectEqual(v3.x, 1.0) - expectEqual(v3.y, 2.0) - expectEqual(v3.z, 3.0) - } - - SceneKitTests.test("double3.init()/SCNVector3") { - let v3 = double3(scn_vec3_ref) - expectEqual(v3.x, 1.0) - expectEqual(v3.y, 2.0) - expectEqual(v3.z, 3.0) - } - - // MARK: Working with SCNVector4 - - SceneKitTests.test("SCNVector4.init()/Literal") { - let scn_vec4_from_lit = SCNVector4(1, 2, 3, 4) - expectTrue(SCNVector4EqualToVector4(scn_vec4_from_lit, scn_vec4_ref)) - } - - SceneKitTests.test("SCNVector4.init()/Float") { - let f1: Float = 1.0 - let f2: Float = 2.0 - let f3: Float = 3.0 - let f4: Float = 4.0 - let scn_vec4_from_f = SCNVector4(f1, f2, f3, f4) - expectTrue(SCNVector4EqualToVector4(scn_vec4_from_f, scn_vec4_ref)) - } - - SceneKitTests.test("SCNVector4.init()/CGFloat") { - let d1: CGFloat = 1.0 - let d2: CGFloat = 2.0 - let d3: CGFloat = 3.0 - let d4: CGFloat = 4.0 - let scn_vec4_from_cg = SCNVector4(d1, d2, d3, d4) - expectTrue(SCNVector4EqualToVector4(scn_vec4_from_cg, scn_vec4_ref)) - } - - SceneKitTests.test("SCNVector4.init()/Double") { - let d1: Double = 1.0 - let d2: Double = 2.0 - let d3: Double = 3.0 - let d4: Double = 4.0 - let scn_vec4_from_d = SCNVector4(d1, d2, d3, d4) - expectTrue(SCNVector4EqualToVector4(scn_vec4_from_d, scn_vec4_ref)) - } - - SceneKitTests.test("SCNVector4.init()/Int") { - let i1: Int = 1 - let i2: Int = 2 - let i3: Int = 3 - let i4: Int = 4 - let scn_vec4_from_i = SCNVector4(i1, i2, i3, i4) - expectTrue(SCNVector4EqualToVector4(scn_vec4_from_i, scn_vec4_ref)) - } - - SceneKitTests.test("SCNVector4.init()/float4") { - let v4 = float4(1, 2, 3, 4) - let scn_vec4_from_float4 = SCNVector4(v4) - expectTrue(SCNVector4EqualToVector4(scn_vec4_from_float4, scn_vec4_ref)) - } - - SceneKitTests.test("SCNVector4.init()/double4") { - let v4 = double4(1, 2, 3, 4) - let scn_vec4_from_double4 = SCNVector4(v4) - expectTrue(SCNVector4EqualToVector4(scn_vec4_from_double4, scn_vec4_ref)) - } - - SceneKitTests.test("SCNVector4.init()/mix") { - let f1: Float = 1.0 - let d2: CGFloat = 2.0 - let f4: Float = 4.0 - let scn_vec4_from_mixed = SCNVector4(f1, Float(d2), 3, f4) - expectTrue(SCNVector4EqualToVector4(scn_vec4_from_mixed, scn_vec4_ref)) - } - - SceneKitTests.test("float4.init()/SCNVector4") { - let v4 = float4(scn_vec4_ref) - expectEqual(v4.x, 1.0) - expectEqual(v4.y, 2.0) - expectEqual(v4.z, 3.0) - expectEqual(v4.w, 4.0) - } - - SceneKitTests.test("double4.init()/SCNVector4") { - let v4 = double4(scn_vec4_ref) - expectEqual(v4.x, 1.0) - expectEqual(v4.y, 2.0) - expectEqual(v4.z, 3.0) - expectEqual(v4.w, 4.0) - } - - // MARK: Working with SCNMatrix4 - - SceneKitTests.test("SCNMatrix4.init()/float4x4 + float4x4.init()/SCNMatrix4") { - let mat4_from_scn_mat4 = float4x4(scn_mat4_ref) - let scn_vec4_from_mat4 = SCNMatrix4(mat4_from_scn_mat4) - expectTrue(SCNMatrix4EqualToMatrix4(scn_vec4_from_mat4, scn_mat4_ref)) - } - - SceneKitTests.test("SCNMatrix4.init()/double4x4 + double4x4.init()/SCNMatrix4") { - let mat4_from_scn_mat4 = double4x4(scn_mat4_ref) - let scn_vec4_from_mat4 = SCNMatrix4(mat4_from_scn_mat4) - expectTrue(SCNMatrix4EqualToMatrix4(scn_vec4_from_mat4, scn_mat4_ref)) - } - - func equalVector3s(_ x: SCNVector3, _ y: SCNVector3) -> Bool { - return x.x == y.x && x.y == y.y && x.z == y.z - } - func equalVector4s(_ x: SCNVector4, _ y: SCNVector4) -> Bool { - return x.x == y.x && x.y == y.y && x.z == y.z && x.w == y.w - } - func equalMatrix4s(_ x: SCNMatrix4, _ y: SCNMatrix4) -> Bool { - var xx = x, yy = y - return memcmp(&xx, &yy, MemoryLayout.size) == 0 - } - - SceneKitTests.test("NSValue bridging") { - expectBridgeToNSValue(scn_vec3_ref, - nsValueInitializer: { NSValue(scnVector3: $0) }, - nsValueGetter: { $0.scnVector3Value }, - equal: equalVector3s) - expectBridgeToNSValue(scn_vec4_ref, - nsValueInitializer: { NSValue(scnVector4: $0) }, - nsValueGetter: { $0.scnVector4Value }, - equal: equalVector4s) - expectBridgeToNSValue(scn_mat4_ref, - nsValueInitializer: { NSValue(scnMatrix4: $0) }, - nsValueGetter: { $0.scnMatrix4Value }, - equal: equalMatrix4s) - } -} - -runAllTests() - diff --git a/test/stdlib/StringCreate.swift b/test/stdlib/StringCreate.swift index be0798b74fa7a..9bdce7e0c317d 100644 --- a/test/stdlib/StringCreate.swift +++ b/test/stdlib/StringCreate.swift @@ -46,7 +46,7 @@ StringCreateTests.test("String(decoding:as:)") { "", String(decoding: UnsafeBufferPointer(_empty: ()), as: UTF32.self)) } -if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) { +if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { StringCreateTests.test("String(unsafeUninitializedCapacity:initializingUTF8With:)") { for simpleString in SimpleString.allCases { let expected = simpleString.rawValue diff --git a/test/stdlib/TestData.swift b/test/stdlib/TestData.swift index 224d58c09fa63..93ebe3ca3d953 100644 --- a/test/stdlib/TestData.swift +++ b/test/stdlib/TestData.swift @@ -3839,7 +3839,8 @@ class TestData : TestDataSuper { } func test_increaseCount() { - guard #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) else { return } + // https://github.com/apple/swift/pull/28919 + guard #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) else { return } let initials: [Range] = [ 0..<0, 0..<2, @@ -3862,7 +3863,8 @@ class TestData : TestDataSuper { } func test_decreaseCount() { - guard #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) else { return } + // https://github.com/apple/swift/pull/28919 + guard #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) else { return } let initials: [Range] = [ 0..<0, 0..<2, diff --git a/test/stdlib/TestDecimal.swift b/test/stdlib/TestDecimal.swift index 2e0b13a5c2b80..ee0c7e492432f 100644 --- a/test/stdlib/TestDecimal.swift +++ b/test/stdlib/TestDecimal.swift @@ -501,7 +501,7 @@ class TestDecimal : TestDecimalSuper { } func test_Round() { - let testCases = [ + var testCases = [ // expected, start, scale, round ( 0, 0.5, 0, Decimal.RoundingMode.down ), ( 1, 0.5, 0, Decimal.RoundingMode.up ), @@ -515,14 +515,18 @@ class TestDecimal : TestDecimalSuper { ( -1, -0.5, 0, Decimal.RoundingMode.down ), ( -2, -2.5, 0, Decimal.RoundingMode.up ), - ( -3, -2.5, 0, Decimal.RoundingMode.bankers ), - ( -4, -3.5, 0, Decimal.RoundingMode.bankers ), ( -5, -5.2, 0, Decimal.RoundingMode.plain ), ( -4.5, -4.5, 1, Decimal.RoundingMode.down ), ( -5.5, -5.5, 1, Decimal.RoundingMode.up ), ( -6.5, -6.5, 1, Decimal.RoundingMode.plain ), ( -7.5, -7.5, 1, Decimal.RoundingMode.bankers ), + ] + if #available(macOS 10.16, iOS 14, watchOS 7, tvOS 14, *) { + testCases += [ + ( -2, -2.5, 0, Decimal.RoundingMode.bankers ), + ( -4, -3.5, 0, Decimal.RoundingMode.bankers ), ] + } for testCase in testCases { let (expected, start, scale, mode) = testCase var num = Decimal(start) diff --git a/test/stdlib/UIKit.swift b/test/stdlib/UIKit.swift deleted file mode 100644 index 41d5d8f8742ea..0000000000000 --- a/test/stdlib/UIKit.swift +++ /dev/null @@ -1,346 +0,0 @@ -// RUN: %empty-directory(%t) -// RUN: %target-build-swift -swift-version 4 %s -o %t/a.out4 && %target-codesign %t/a.out4 && %target-run %t/a.out4 -// RUN: %target-build-swift -swift-version 4.2 %s -o %t/a.out4_2 && %target-codesign %t/a.out4_2 && %target-run %t/a.out4_2 -// REQUIRES: executable_test -// UNSUPPORTED: OS=macosx -// REQUIRES: objc_interop - -import UIKit -import StdlibUnittest -import StdlibUnittestFoundationExtras - -#if swift(>=4.2) - let UIKitTests = TestSuite("UIKit_Swift4_2") -#else - let UIKitTests = TestSuite("UIKit_Swift4") -#endif - -#if !os(watchOS) && !os(tvOS) -private func printDevice(_ o: UIDeviceOrientation) -> String { - return "\(o.isPortrait) \(o.isLandscape) \(o.isFlat) \(o.isValidInterfaceOrientation)" -} - -private func printInterface(_ o: UIInterfaceOrientation) -> String { - return "\(o.isPortrait) \(o.isLandscape)" -} - -UIKitTests.test("UIDeviceOrientation") { - expectEqual("false false false false", printDevice(.unknown)) - expectEqual("true false false true", printDevice(.portrait)) - expectEqual("true false false true", printDevice(.portraitUpsideDown)) - expectEqual("false true false true", printDevice(.landscapeLeft)) - expectEqual("false true false true", printDevice(.landscapeRight)) - expectEqual("false false true false", printDevice(.faceUp)) - expectEqual("false false true false", printDevice(.faceDown)) -#if !swift(>=4.2) - // Orientation functions should still be available - _ = UIDeviceOrientationIsLandscape - _ = UIDeviceOrientationIsPortrait - _ = UIDeviceOrientationIsValidInterfaceOrientation -#endif -} - -UIKitTests.test("UIInterfaceOrientation") { - expectEqual("false false", printInterface(.unknown)) - expectEqual("true false", printInterface(.portrait)) - expectEqual("true false", printInterface(.portraitUpsideDown)) - expectEqual("false true", printInterface(.landscapeLeft)) - expectEqual("false true", printInterface(.landscapeRight)) -#if !swift(>=4.2) - // Orientation functions should still be available - _ = UIInterfaceOrientationIsLandscape - _ = UIInterfaceOrientationIsPortrait -#endif -} -#endif // !os(watchOS) && !os(tvOS) - -UIKitTests.test("UIEdgeInsets") { - let insets = [ - UIEdgeInsets(top: 1.0, left: 2.0, bottom: 3.0, right: 4.0), - UIEdgeInsets(top: 1.0, left: 2.0, bottom: 3.1, right: 4.0), - UIEdgeInsets.zero - ] - checkEquatable(insets, oracle: { $0 == $1 }) - expectFalse(UIEdgeInsetsEqualToEdgeInsets(insets[0], insets[1])) - - let encodedInsets = try! JSONEncoder().encode(insets[0]) - let decodedInsets = try! JSONDecoder().decode(UIEdgeInsets.self, from: encodedInsets) - expectTrue(decodedInsets == insets[0]) -} - -UIKitTests.test("NSDirectionalEdgeInsets") { - guard #available(iOS 11.0, tvOS 11.0, watchOS 5.0, *) else { return } - let insets = [ - NSDirectionalEdgeInsets(top: 1.0, leading: 2.0, bottom: 3.0, trailing: 4.0), - NSDirectionalEdgeInsets(top: 1.0, leading: 2.0, bottom: 3.1, trailing: 4.0), - NSDirectionalEdgeInsets.zero - ] - checkEquatable(insets, oracle: { $0 == $1 }) - // NSDirectionalEdgeInsetsEqualToDirectionalEdgeInsets was never exposed in Swift - - let encodedInsets = try! JSONEncoder().encode(insets[0]) - let decodedInsets = try! JSONDecoder().decode(NSDirectionalEdgeInsets.self, from: encodedInsets) - expectTrue(decodedInsets == insets[0]) -} - -UIKitTests.test("UIOffset") { - let offsets = [ - UIOffset(horizontal: 1.0, vertical: 2.0), - UIOffset(horizontal: 1.0, vertical: 3.0), - UIOffset.zero - ] - checkEquatable(offsets, oracle: { $0 == $1 }) - expectFalse(UIOffsetEqualToOffset(offsets[0], offsets[1])) - - let encodedOffset = try! JSONEncoder().encode(offsets[0]) - let decodedOffset = try! JSONDecoder().decode(UIOffset.self, from: encodedOffset) - expectTrue(decodedOffset == offsets[0]) -} - -#if os(iOS) || os(tvOS) -UIKitTests.test("UIFloatRange") { - guard #available(iOS 9.0, tvOS 9.0, *) else { return } - #if swift(>=4.2) - let zero = UIFloatRange.zero - #else - let zero = UIFloatRangeZero - #endif - - let ranges = [ - UIFloatRange(minimum: 1.0, maximum: 2.0), - UIFloatRange(minimum: 1.0, maximum: 3.0), - zero - ] - checkEquatable(ranges, oracle: { $0 == $1 }) - expectFalse(UIFloatRangeIsEqualToRange(ranges[0], ranges[1])) - - let encodedRange = try! JSONEncoder().encode(ranges[0]) - let decodedRange = try! JSONDecoder().decode(UIFloatRange.self, from: encodedRange) - expectTrue(decodedRange == ranges[0]) -} -#endif - -UIKitTests.test("UIFont.Weight") { - guard #available(iOS 8.2, *) else { return } - #if swift(>=4) // Swift 4 - let regularFontWeight: UIFont.Weight = .regular - - expectTrue(regularFontWeight == .regular) - expectTrue(regularFontWeight > .light) - expectTrue(regularFontWeight < .heavy) - expectTrue(regularFontWeight + 0.1 == 0.1 + regularFontWeight) - #else // Swift 3 - let regularFontWeight: UIFontWeight = UIFontWeightRegular - - expectTrue(regularFontWeight == UIFontWeightRegular) - expectTrue(regularFontWeight > UIFontWeightLight) - expectTrue(regularFontWeight < UIFontWeightHeavy) - expectTrue(regularFontWeight + 0.1 == 0.1 + UIFontWeightRegular) - #endif -} - -#if !os(watchOS) -UIKitTests.test("UILayoutPriority") { - let lowLayoutPriority: UILayoutPriority = .defaultLow - let highLayoutPriority: UILayoutPriority = .defaultHigh - - expectTrue(lowLayoutPriority < highLayoutPriority) - - expectTrue(lowLayoutPriority + 2.0 == UILayoutPriority(lowLayoutPriority.rawValue + 2.0)) - expectTrue(2.0 + lowLayoutPriority == UILayoutPriority(lowLayoutPriority.rawValue + 2.0)) - expectTrue(lowLayoutPriority - 2.0 == UILayoutPriority(lowLayoutPriority.rawValue - 2.0)) - expectTrue(highLayoutPriority - lowLayoutPriority == highLayoutPriority.rawValue - lowLayoutPriority.rawValue) - - expectTrue(lowLayoutPriority + (highLayoutPriority - lowLayoutPriority) == highLayoutPriority) - - var mutablePriority = lowLayoutPriority - mutablePriority -= 1.0 - mutablePriority += 2.0 - expectTrue(mutablePriority == lowLayoutPriority + 1.0) - - let priorotyRange = lowLayoutPriority...highLayoutPriority - expectTrue(priorotyRange.contains(.defaultLow)) - expectFalse(priorotyRange.contains(.required)) -} -#endif - -#if !os(watchOS) -UIKitTests.test("UIWindow.Level") { - #if swift(>=4.2) // Swift 4.2 - let normalWindowLevel: UIWindow.Level = .normal - - expectTrue(normalWindowLevel == .normal) - expectTrue(normalWindowLevel < .alert) - expectTrue(normalWindowLevel + 1 == 1 + normalWindowLevel) - #else // Swift 3 and 4 - let normalWindowLevel: UIWindowLevel = UIWindowLevelNormal - - expectTrue(normalWindowLevel == UIWindowLevelNormal) - expectTrue(normalWindowLevel < UIWindowLevelAlert) - expectTrue(normalWindowLevel + 1 == 1 + UIWindowLevelNormal) - #endif -} -#endif - -#if !os(watchOS) -class TestChildView : UIView, CustomPlaygroundQuickLookable { - convenience init() { - self.init(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) - } - var customPlaygroundQuickLook: PlaygroundQuickLook { - return .text("child") - } -} - -UIKitTests.test("CustomPlaygroundQuickLookable") { - switch PlaygroundQuickLook(reflecting: TestChildView()) { - case .text("child"): break - default: expectUnreachable( - "TestChildView custom quicklookable should have been invoked") - } -} -#endif - -UIKitTests.test("NSValue bridging") { - expectBridgeToNSValue(UIEdgeInsets(top: 17, left: 38, bottom: 6, right: 79), - nsValueInitializer: { NSValue(uiEdgeInsets: $0) }, - nsValueGetter: { $0.uiEdgeInsetsValue }, - equal: (==)) - if #available(iOS 11.0, tvOS 11.0, watchOS 5.0, *) { - expectBridgeToNSValue(NSDirectionalEdgeInsets(top: 86, leading: 75, bottom: 30, trailing: 9), - nsValueInitializer: { NSValue(directionalEdgeInsets: $0) }, - nsValueGetter: { $0.directionalEdgeInsetsValue }, - equal: (==)) - } - expectBridgeToNSValue(UIOffset(horizontal: 17, vertical: 38), - nsValueInitializer: { NSValue(uiOffset: $0) }, - nsValueGetter: { $0.uiOffsetValue }, - equal: (==)) -} - -#if os(iOS) || os(tvOS) -UIKitTests.test("UIContentSizeCategory comparison") { - if #available(iOS 11.0, tvOS 11.0, *) { - expectTrue(UIContentSizeCategory.large < UIContentSizeCategory.extraLarge) - expectTrue(UIContentSizeCategory.large <= UIContentSizeCategory.extraLarge) - expectFalse(UIContentSizeCategory.large >= UIContentSizeCategory.extraLarge) - expectFalse(UIContentSizeCategory.large > UIContentSizeCategory.extraLarge) - expectFalse(UIContentSizeCategory.large == UIContentSizeCategory.extraLarge) - - expectTrue(UIContentSizeCategory.extraLarge > UIContentSizeCategory.large) - expectTrue(UIContentSizeCategory.extraLarge >= UIContentSizeCategory.large) - expectFalse(UIContentSizeCategory.extraLarge < UIContentSizeCategory.large) - expectFalse(UIContentSizeCategory.extraLarge <= UIContentSizeCategory.large) - expectFalse(UIContentSizeCategory.extraLarge == UIContentSizeCategory.large) - - expectTrue(UIContentSizeCategory.large == UIContentSizeCategory.large) - expectTrue(UIContentSizeCategory.large >= UIContentSizeCategory.large) - expectTrue(UIContentSizeCategory.large <= UIContentSizeCategory.large) - expectFalse(UIContentSizeCategory.large > UIContentSizeCategory.large) - expectFalse(UIContentSizeCategory.large < UIContentSizeCategory.large) - - expectTrue(UIContentSizeCategory.accessibilityExtraExtraExtraLarge.isAccessibilityCategory) - expectFalse(UIContentSizeCategory.extraSmall.isAccessibilityCategory) - } -} -#endif - -#if os(iOS) || os(watchOS) || os(tvOS) -UIKitTests.test("UIFontMetrics scaling") { - if #available(iOS 11.0, watchOS 4.0, tvOS 11.0, *) { - let metrics = UIFont.TextStyle.headline.metrics - expectTrue(metrics != nil) -#if !swift(>=4.2) - _ = UIFontTextStyle.headline.metrics -#endif - } -} -#endif - -#if os(iOS) || os(tvOS) -UIKitTests.test("UIFocusEnvironment") { - if #available(iOS 11.0, tvOS 11.0, *) { - let item1 = UIView() - let item2 = UIView() - _ = item1.contains(item2) - _ = item1.isFocused - } -} -#endif - -#if os(iOS) - -UIKitTests.test("NSItemProviderReadingWriting support") { - if #available(iOS 11.0, *) { - func f(session: T) { - _ = session.canLoadObjects(ofClass: String.self) - _ = session.canLoadObjects(ofClass: URL.self) - } - func g(session: T) { - _ = session.loadObjects(ofClass: String.self) { _ in ()} - _ = session.loadObjects(ofClass: URL.self) { _ in () } - } - - let pc0 = UIPasteConfiguration(forAccepting: String.self) - let pc1 = UIPasteConfiguration(forAccepting: URL.self) - pc0.addTypeIdentifiers(forAccepting: URL.self) - pc1.addTypeIdentifiers(forAccepting: String.self) - - var pb = UIPasteboard.general - pb.setObjects(["Hello"]) - pb.setObjects([URL(string: "https://www.apple.com")!]) - pb.setObjects(["Hello"], localOnly: true, expirationDate: nil) - pb.setObjects([URL(string: "https://www.apple.com")!], localOnly: true, expirationDate: nil) - } -} - -#endif - -#if os(iOS) -UIKitTests.test("UIPrintError compatibility") { - #if swift(>=4.2) - _ = UIPrintError.Code.notAvailable - _ = UIPrintError.Code.noContent - _ = UIPrintError.Code.unknownImageFormat - _ = UIPrintError.Code.jobFailed - #else - _ = UIPrintingNotAvailableError - _ = UIPrintNoContentError - _ = UIPrintUnknownImageFormatError - _ = UIPrintJobFailedError - #endif -} -#endif - -#if !os(watchOS) -UIKitTests.test("UIApplicationMain") { - #if swift(>=4.2) - _ = { UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, nil) } - #endif - _ = { UIApplicationMain(CommandLine.argc, UnsafeMutableRawPointer(CommandLine.unsafeArgv).bindMemory(to: UnsafeMutablePointer.self, capacity: Int(CommandLine.argc)), nil, nil) } -} -#endif - -UIKitTests.test("UIAccessibilityTraits") { - #if swift(>=4.2) - let traits: UIAccessibilityTraits = [.link, .button] - expectTrue(traits.contains(.link)) - expectFalse(traits.contains(.header)) - #else - let _: UIAccessibilityTraits = UIAccessibilityTraitLink | UIAccessibilityTraitButton - #endif -} - -#if !os(watchOS) -UIKitTests.test("UITextDirection") { - #if swift(>=4.2) - let _: UITextDirection = .storage(.forward) - let _: UITextDirection = .layout(.right) - #else - let _: UITextDirection = UITextStorageDirection.backward.rawValue - #endif -} -#endif - - -runAllTests() diff --git a/test/stdlib/UIViewControllerAdditions.swift b/test/stdlib/UIViewControllerAdditions.swift deleted file mode 100644 index 5979d242a0fd0..0000000000000 --- a/test/stdlib/UIViewControllerAdditions.swift +++ /dev/null @@ -1,62 +0,0 @@ -// RxUN: %target-build-swift -g %s -o %t/ViewControllerAdditions.out -// RxUN: %target-run %t/ViewControllerAdditions.out %S/Inputs/UIViewControllerAdditions/* | %FileCheck %s -// RUN: %target-run-simple-swift %S/Inputs/UIViewControllerAdditions/* | %FileCheck %s -// REQUIRES: executable_test - -// REQUIRES: OS=ios - -import UIKit - -// _TtC1a15View1Controller.nib -class View1Controller : UIViewController { } - -// _TtC1a15View2.nib -class View2Controller : UIViewController { } - -// a.View3Controller.nib -class View3Controller : UIViewController { } - -// a.View4.nib -class View4Controller : UIViewController { } - -// View5Controller.nib -class View5Controller : UIViewController { } - -// View6.nib -class View6Controller : UIViewController { } - -// no nib -class MissingViewController : UIViewController { } - -let nsarg1 = CommandLine.arguments[1] as NSString -let bundlePath = nsarg1.deletingLastPathComponent -let bundle = Bundle(path: bundlePath) - -let v1 = View1Controller(nibName:nil, bundle:bundle) -print("tag 1 0=\(v1.view.tag) you're it") -// CHECK: tag 1 0=0 you're it - -let v2 = View2Controller(nibName:nil, bundle:bundle) -print("tag 2 0=\(v2.view.tag) you're it") -// CHECK: tag 2 0=0 you're it - -let v3 = View3Controller(nibName:nil, bundle:bundle) -print("tag 3 3=\(v3.view.tag) you're it") -// CHECK: tag 3 3=3 you're it - -let v4 = View4Controller(nibName:nil, bundle:bundle) -print("tag 4 4=\(v4.view.tag) you're it") -// CHECK: tag 4 4=4 you're it - -let v5 = View5Controller(nibName:nil, bundle:bundle) -print("tag 5 5=\(v5.view.tag) you're it") -// CHECK: tag 5 5=5 you're it - -let v6 = View6Controller(nibName:nil, bundle:bundle) -print("tag 6 6=\(v6.view.tag) you're it") -// CHECK: tag 6 6=6 you're it - -let v7 = MissingViewController(nibName:nil, bundle:bundle) -print("tag 7 0=\(v7.view.tag) you're it") -// CHECK: tag 7 0=0 you're it - diff --git a/test/stdlib/Vision.swift b/test/stdlib/Vision.swift deleted file mode 100644 index 4b89bb0ccff93..0000000000000 --- a/test/stdlib/Vision.swift +++ /dev/null @@ -1,29 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest - -import Vision - - -var testsuite = TestSuite("Vision") - -if #available(OSX 10.13, iOS 11.0, tvOS 11.0, *) { - testsuite.test("normalizedPoints overlay") { - // NOTE: This function is here only to validate syntactical correctness of the overlay. - func overlaySyntaxTest(region: VNFaceLandmarkRegion2D) -> [CGPoint] { - return region.normalizedPoints - } - } - - testsuite.test("pointsInImage() overlay") { - // NOTE: This function is here only to validate syntactical correctness of the overlay. - func overlaySyntaxTest(region: VNFaceLandmarkRegion2D) -> [CGPoint] { - return region.pointsInImage(imageSize: CGSize(width: 1024, height: 768)) - } - } -} - -runAllTests() diff --git a/test/stdlib/os.swift b/test/stdlib/os.swift deleted file mode 100644 index 42dd8d9455801..0000000000000 --- a/test/stdlib/os.swift +++ /dev/null @@ -1,55 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: objc_interop - -import os -import Foundation -import StdlibUnittest - -defer { runAllTests() } - -var osAPI = TestSuite("osAPI") - -if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { - osAPI.test("log") { - os_log("test: %d", 42) - os_log("test2: %@", "test") - } - - osAPI.test("logData") { - let data = "hello logging world".data(using: .utf8)! - - data.withUnsafeBytes { (bytes: UnsafePointer) in - os_log("%.3P", OpaquePointer(bytes)) - os_log("%.10P", OpaquePointer(bytes)) - os_log("%.*P", data.count, OpaquePointer(bytes)) - } - } - - osAPI.test("newLog") { - let newLog = OSLog(subsystem: "com.apple.Swift", category: "Test") - os_log("test", log: newLog) - } -} - -if #available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) { - osAPI.test("signpost") { - let interestingLog = OSLog(subsystem: "com.apple.example.swift", - category: .pointsOfInterest) - os_log(.info, log: interestingLog, "a=%d b=%d c=%d", 1, 2, 3) - os_signpost(.event, log: interestingLog, name: "Basic Sans Message") - os_signpost(.begin, log: interestingLog, name: "Basic Test", "%d", 42) - os_signpost(.event, log: interestingLog, name: "Basic Test", "%d", 43) - os_signpost(.end, log: interestingLog, name: "Basic Test", "%d", 44) - - let log = OSLog(subsystem: "com.apple.swift", category: "SignpostIDs") - let v: UInt64 = 15 - let spidOne = OSSignpostID(v) - let spidTwo = OSSignpostID(16 as UInt64) - os_signpost(.event, log: log, name: "With Signpost ID", signpostID: spidOne) - os_signpost(.event, log: log, name: "With Signpost ID", signpostID: spidTwo) - os_signpost(.event, log: log, name: "Negative Test", signpostID: .null) - os_signpost(.event, log: log, name: "Negative Test", signpostID: .invalid) - } -} diff --git a/test/stdlib/os_log_format.m b/test/stdlib/os_log_format.m deleted file mode 100644 index ee1594e78a925..0000000000000 --- a/test/stdlib/os_log_format.m +++ /dev/null @@ -1,200 +0,0 @@ -// RUN: %empty-directory(%t) -// RUN: %clang %target-cc-options -g -O0 -isysroot %sdk -I %swift_src_root/stdlib/public/Darwin/os -framework Foundation %swift_src_root/stdlib/public/Darwin/os/format.m %swift_src_root/stdlib/public/Darwin/os/os_trace_blob.c %s -o %t/os_log_format -// RUN: %target-run %t/os_log_format | %FileCheck %s - -// REQUIRES: objc_interop -// REQUIRES: executable_test - -#import -#import - -#import "format.h" - -// CHECK-NOT: FAIL -// CHECK: PASS - -static bool -compare_buffers(char *fail_prefix, char *bufa, char *bufb, size_t size) -{ - if (!memcmp(bufa, bufb, size)) { - return true; - } - - os_log_fmt_hdr_t hdra = (os_log_fmt_hdr_t)bufa; - os_log_fmt_hdr_t hdrb = (os_log_fmt_hdr_t)bufb; - - if (hdra->hdr_flags != hdrb->hdr_flags) { - printf("FAIL: %s: header flags mismatch (0x%x != 0x%x)\n", fail_prefix, - hdra->hdr_flags, hdrb->hdr_flags); - return false; - } - - if (hdra->hdr_cmd_cnt != hdrb->hdr_cmd_cnt) { - printf("FAIL: %s: command count mismatch (0x%x != 0x%x)\n", fail_prefix, - hdra->hdr_cmd_cnt, hdrb->hdr_cmd_cnt); - return false; - } - - os_log_fmt_cmd_t cmda = (os_log_fmt_cmd_t)((uint8_t *)hdra + - sizeof(os_log_fmt_hdr_s)); - os_log_fmt_cmd_t cmdb = (os_log_fmt_cmd_t)((uint8_t *)hdrb + - sizeof(os_log_fmt_hdr_s)); - - for (size_t idx = 0; idx < hdra->hdr_cmd_cnt; idx++) { - if (cmda->cmd_flags != cmdb->cmd_flags) { - printf("FAIL: %s: command %zu flags mismatch (0x%x != 0x%x)\n", - fail_prefix, idx, cmda->cmd_flags, cmdb->cmd_flags); - return false; - } - if (cmda->cmd_type != cmdb->cmd_type) { - printf("FAIL: %s: command %zu type mismatch (0x%x != 0x%x)\n", - fail_prefix, idx, cmda->cmd_type, cmdb->cmd_type); - return false; - } - if (cmda->cmd_size != cmdb->cmd_size) { - printf("FAIL: %s: command %zu size mismatch (0x%x != 0x%x)\n", - fail_prefix, idx, cmda->cmd_size, cmdb->cmd_size); - return false; - } - if (memcmp(cmda->cmd_data, cmdb->cmd_data, cmda->cmd_size)) { - printf("FAIL: %s: command %zu data mismatch\n", fail_prefix, idx); - printf("COMPILER: "); - for (size_t i=0; icmd_size; i++) { - printf("%02x ", cmda->cmd_data[i]); - } - printf("\nOVERLAY: "); - for (size_t i=0; icmd_size; i++) { - printf("%02x ", cmdb->cmd_data[i]); - } - printf("\n"); - return false; - } - cmda = (os_log_fmt_cmd_t)((uint8_t *)cmda + sizeof(os_log_fmt_cmd_s) - + cmda->cmd_size); - cmdb = (os_log_fmt_cmd_t)((uint8_t *)cmdb + sizeof(os_log_fmt_cmd_s) - + cmdb->cmd_size); - } - return true; -} - -static bool -_t_log_encode(char buf[OS_LOG_FMT_BUF_SIZE], int saved_errno, - os_trace_blob_t blob, const char *format, ...) -{ - va_list va; - bool rv; - - va_start(va, format); - rv = _os_log_encode(buf, format, va, saved_errno, blob); - va_end(va); - return rv; -} - -#define compiler_format(buf, fmt, ...) ({ \ - __builtin_os_log_format(buf, fmt, ##__VA_ARGS__); \ - (uint32_t)__builtin_os_log_format_buffer_size(fmt, ##__VA_ARGS__); \ - }) - -#define overlay_format(buf, fmt, ...) ({ \ - os_trace_blob_s ob = { \ - .ob_s = os_trace_buf, \ - .ob_size = OS_LOG_FMT_BUF_SIZE, \ - .ob_maxsize = OS_LOG_FMT_BUF_SIZE, \ - .ob_binary = true \ - }; \ - _t_log_encode(os_trace_buf, 0, &ob, fmt, ##__VA_ARGS__); \ - (uint32_t)ob.ob_len; \ - }) - -int -main(int argc, char **argv) -{ - static char compiler_buf[8192]; - static char os_trace_buf[OS_LOG_FMT_BUF_SIZE]; - uint32_t compiler_size, our_size; - int i; - -#define ACCEPT(_fmt, ...) ({ \ - compiler_size = compiler_format(compiler_buf, _fmt, ##__VA_ARGS__); \ - our_size = overlay_format(os_trace_buf, _fmt, ##__VA_ARGS__); \ - if (!compare_buffers("during: \"" _fmt "\"", compiler_buf, os_trace_buf, \ - our_size)) { \ - exit(1); \ - } \ - }) - - ACCEPT("doesn't even have an argument"); - - ACCEPT("simple char %hhd", (char)10); - ACCEPT("simple short %hd", (short)10); - ACCEPT("simple integer %d", 10); - ACCEPT("simple long long %lld", (long long)10); - ACCEPT("simple pointer %p", "sad"); - - ACCEPT("simple float %f", (float)1.5); - ACCEPT("simple double %f", 1.5); -#ifdef __LP64__ - // Disabled because the upstream clang output for long double changed - // and causes CI fallout - // ACCEPT("simple long double %Lf", (long double)1.5); -#endif - - ACCEPT("integer with a static width %666d", 10); - ACCEPT("integer with a static precision %.42d", 10); - ACCEPT("integer with a static width & precision %666.42d", 10); - ACCEPT("integer with dynamic width %*d", 666, 10); - ACCEPT("integer with dynamic precision %.*d", 42, 10); - ACCEPT("integer with dynamic width & precision %*.*d", 666, 42, 10); - - // All the %s tests below are disabled for the overlay because - // the overlay assumes %s really means %@. - - // ACCEPT("simple string %s", "sad"); - // ACCEPT("string with a static width %666s", "sad"); - // ACCEPT("string with a static precision %.42s", "sad"); - // ACCEPT("string with a static width & precision %666.42s", "sad"); - // ACCEPT("string with dynamic width %*s", 666, "sad"); - // ACCEPT("string with dynamic precision %.*s", 42, "sad"); - // ACCEPT("string with dynamic width & precision %*.*s", 666, 42, "sad"); - - ACCEPT("data with a static precision %.42P", "sad"); - ACCEPT("data with a static width & precision %666.42P", "sad"); - ACCEPT("data with dynamic precision %.*P", 42, "sad"); - ACCEPT("data with dynamic width & precision %*.*P", 666, 42, "sad"); - - ACCEPT("simple object %@", @"sad"); - ACCEPT("object with a static width %666@", @"sad"); - ACCEPT("object with dynamic width %*@", 666, @"sad"); - - // privacy and annotations - ACCEPT("simple integer %{public}d", 10); - ACCEPT("simple integer %{private}d", 10); - ACCEPT("simple integer %{public, blah}d", 10); - ACCEPT("simple integer %{public, builtin:blah::bluh}d", 10); - - ACCEPT("integer with a static width %{private}666d", 10); - ACCEPT("integer with a static precision %{private}.42d", 10); - ACCEPT("integer with a static width & precision %{private}666.42d", 10); - ACCEPT("integer with dynamic width %{private}*d", 666, 10); - ACCEPT("integer with dynamic precision %{private}.*d", 42, 10); - ACCEPT("integer with dynamic width & precision %{private}*.*d", 666, 42, 10); - - // ACCEPT("simple string %{private}s", "sad"); - // ACCEPT("string with a static width %{private}666s", "sad"); - // ACCEPT("string with a static precision %{private}.42s", "sad"); - // ACCEPT("string with a static width & precision %{private}666.42s", "sad"); - // ACCEPT("string with dynamic width %{private}*s", 666, "sad"); - // ACCEPT("string with dynamic precision %{private}.*s", 42, "sad"); - // ACCEPT("string with dynamic width & precision %{private}*.*s", 666, 42, "sad"); - - ACCEPT("data with a static precision %{private}.42P", "sad"); - ACCEPT("data with a static width & precision %{private}666.42P", "sad"); - ACCEPT("data with dynamic precision %{private}.*P", 42, "sad"); - ACCEPT("data with dynamic width & precision %{private}*.*P", 666, 42, "sad"); - - ACCEPT("simple object %{private}@", @"sad"); - ACCEPT("object with a static width %{private}666@", @"sad"); - ACCEPT("object with dynamic width %{private}*@", 666, @"sad"); - - printf("PASS\n"); -} diff --git a/test/stdlib/simd.swift.gyb b/test/stdlib/simd.swift.gyb deleted file mode 100644 index e948ecbf19729..0000000000000 --- a/test/stdlib/simd.swift.gyb +++ /dev/null @@ -1,323 +0,0 @@ -// RUN: %target-run-simple-swiftgyb -// REQUIRES: executable_test - -// FIXME: No simd module on linux rdar://problem/20795411 -// XFAIL: linux, windows -// XFAIL: OS=wasi - -import simd -import StdlibUnittest - - -% scalar_types = ['Float', 'Double', 'Int32', 'UInt32'] -% float_types = ['Float', 'Double'] -% ctype = { 'Float':'float', 'Double':'double', 'Int32':'int', 'UInt32':'uint'} -% component = ['.x','.y','.z','.w'] - -% for type in scalar_types: -% for cols in [2,3,4]: -// Workaround -% vectype = ctype[type] + str(cols) -func same(_ x: ${vectype}, _ y: ${vectype}) -> Bool { - for i in 0..<${cols} { -// Workaround -% if type in float_types: - if x[i] != y[i] && !(x[i].isNaN && y[i].isNaN) { return false } -% else: - if x[i] != y[i] { return false } -% end - } - return true -} -% if type in float_types: -// Workaround -% for rows in [2,3,4]: -// Workaround -% mattype = ctype[type] + str(cols) + 'x' + str(rows) -func same(_ x: ${mattype}, _ y: ${mattype}) -> Bool { - for i in 0..<${cols} { - if !same(x[i], y[i]) { return false } - } - return true -} -% end # for rows in [2,3,4] -% end # if type in float_types -% end # for cols in [2,3,4] -% end # for type in scalar_types - - - -/* -func same(_ x:M, _ y:M) -> Bool { - for i in 0 ..< x.columns { - if (!same(x[i], y[i])) { return false } - } - return true -} -*/ - -var simdTestSuite = TestSuite("simd") - -simdTestSuite.test("sizes") { -// C interop requires that vector be the right size. - expectEqual(8, MemoryLayout.size) - expectEqual(16, MemoryLayout.size) - expectEqual(16, MemoryLayout.size) - expectEqual(8, MemoryLayout.size) - expectEqual(16, MemoryLayout.size) - expectEqual(16, MemoryLayout.size) - expectEqual(16, MemoryLayout.size) - expectEqual(32, MemoryLayout.size) - expectEqual(32, MemoryLayout.size) - - expectEqual(16, MemoryLayout.size) - expectEqual(32, MemoryLayout.size) - expectEqual(32, MemoryLayout.size) - expectEqual(24, MemoryLayout.size) - expectEqual(48, MemoryLayout.size) - expectEqual(48, MemoryLayout.size) - expectEqual(32, MemoryLayout.size) - expectEqual(64, MemoryLayout.size) - expectEqual(64, MemoryLayout.size) - - expectEqual(32, MemoryLayout.size) - expectEqual(64, MemoryLayout.size) - expectEqual(64, MemoryLayout.size) - expectEqual(48, MemoryLayout.size) - expectEqual(96, MemoryLayout.size) - expectEqual(96, MemoryLayout.size) - expectEqual(64, MemoryLayout.size) - expectEqual(128, MemoryLayout.size) - expectEqual(128, MemoryLayout.size) -} - -simdTestSuite.test("alignment") { - struct GenericLayout { - let t: T = 0 as! T - let v: int4 = [1,2,3,4] - } - - let g = GenericLayout() - expectEqual(0, g.t) - expectEqual([1,2,3,4], g.v) -} - - -simdTestSuite.test("vector init") { -% for type in scalar_types: -% for size in [2,3,4]: -// Workaround -% vectype = ctype[type] + str(size) -% vec = 'v_' + vectype - - // Check empty initializer. - var ${vec} = ${vectype}() - expectEqualTest(${[0]*size}, ${vec}, sameValue: same) - - // Check literal initializer. - ${vec} = ${vectype}(2) - expectEqualTest(${[2]*size}, ${vec}, sameValue: same) - - // Check scalar initializer. - expectEqualTest(${vectype}(${type}(2)), ${vec}, sameValue: same) - - // Check elementwise initializer. - ${vec} = ${vectype}(${', '.join(map(lambda i: str(i), range(size)))}) - expectEqualTest(${range(size)}, ${vec}, sameValue: same) - - // Check labeled elementwise initializer. - ${vec} = ${vectype}(${', '.join(map(lambda i: - component[i][1:] + ':' + str(i), - range(size)))}) - expectEqualTest(${range(size)}, ${vec}, sameValue: same) - - // Previous checks implicitly use the array initializer, so we're good - // with that one already. - -% end # for size in [2,3,4] -% end # for type in scalar_types -} - -simdTestSuite.test("vector elements") { -% for type in scalar_types: -% for size in [2,3,4]: -// Workaround -% vectype = ctype[type] + str(size) -% vec = 'v_' + vectype - var ${vec} = ${vectype}() - - // Check getting and setting .xyzw -% for i in range(size): - ${vec + component[i]} = ${2*i} - expectEqual(${vec + component[i]}, ${2*i}) -% end - - // Check getting and setting [i] - for i in 0..<${size} { ${vec}[i] = ${vec}[i]/2 } - expectEqualTest(${vec}, ${range(size)}, sameValue: same) - -% end # for size in [2,3,4] -% end # for type in scalar_types -} - -% for type in scalar_types: -// ---- -% if type not in float_types: -// ---- -% for size in [2,3,4]: -// ---- -% vectype = ctype[type] + str(size) - -simdTestSuite.test("${vectype} wrapping arithmetic") { - - expectEqual(${vectype}(.max) &+ ${vectype}(1), - ${vectype}(.min)) - - expectEqual(${vectype}(.min) &- ${vectype}(1), - ${vectype}(.max)) - - expectEqual(${vectype}(.max) &* ${vectype}(.max), - ${vectype}(1)) - expectEqual(${vectype}(.max) &* .max, - ${vectype}(1)) - expectEqual(.max &* ${vectype}(.max), - ${vectype}(1)) -} - -% end -% end -% end - -simdTestSuite.test("vector distance") { -% for type in float_types: - let ${ctype[type]}2_x = ${ctype[type]}2(0,5) - let ${ctype[type]}2_y = ${ctype[type]}2(3,1) - expectEqual(5, distance(${ctype[type]}2_x, ${ctype[type]}2_y)) - expectEqual(0, distance(${ctype[type]}2_x, ${ctype[type]}2_x)) - expectEqual(25, distance_squared(${ctype[type]}2_x, ${ctype[type]}2_y)) - expectEqual(0, distance_squared(${ctype[type]}2_x, ${ctype[type]}2_x)) - - let ${ctype[type]}3_x = ${ctype[type]}3(-1,-2,-4) - let ${ctype[type]}3_y = ${ctype[type]}3( 1, 1, 2) - expectEqual(7, distance(${ctype[type]}3_x, ${ctype[type]}3_y)) - expectEqual(0, distance(${ctype[type]}3_x, ${ctype[type]}3_x)) - expectEqual(49, distance_squared(${ctype[type]}3_x, ${ctype[type]}3_y)) - expectEqual(0, distance_squared(${ctype[type]}3_x, ${ctype[type]}3_x)) - - let ${ctype[type]}4_x = ${ctype[type]}4(-1, 0, 1, 1) - let ${ctype[type]}4_y = ${ctype[type]}4( 0, 1, 0, 2) - expectEqual(2, distance(${ctype[type]}4_x, ${ctype[type]}4_y)) - expectEqual(0, distance(${ctype[type]}4_x, ${ctype[type]}4_x)) - expectEqual(4, distance_squared(${ctype[type]}4_x, ${ctype[type]}4_y)) - expectEqual(0, distance_squared(${ctype[type]}4_x, ${ctype[type]}4_x)) -% end # for type in float_types -} - -simdTestSuite.test("matrix init") { -% for type in float_types: -% for cols in [2,3,4]: -// Workaround -% for rows in [2,3,4]: -// Workaround -% mattype = ctype[type] + str(cols) + 'x' + str(rows) -% coltype = ctype[type] + str(rows) -% mat = 'm_' + mattype -% diagsize = rows if rows < cols else cols - - // Check empty initializer. - var ${mat} = ${mattype}() - expectEqualTest(${mat}, ${mattype}(${[[0]*rows]*cols}), sameValue: same) - - // Check scalar initializer. - ${mat} = ${mattype}(2) - for i in 0..<${rows} { - for j in 0..<${cols} { - if i == j { expectEqual(${mat}[i, i], 2) } - else { expectEqual(${mat}[j, i], 0) } - } - } - - // Check diagonal initializer. - ${mat} = ${mattype}(diagonal: ${range(diagsize)}) - for i in 0..<${rows} { - for j in 0..<${cols} { - if i == j { expectEqual(${mat}[i, i], ${type}(i)) } - else { expectEqual(${mat}[j, i], 0) } - } - } - - // All the previous checks implicitly used the column initializer. - - // Check row initializer. - ${mat} = ${mattype}(rows:[ -% for i in range(rows): - ${range(i*cols, (i+1)*cols)}, -% end # for i - ]) - for i in 0..<${rows} { - for j in 0..<${cols} { - expectEqual(${mat}[j, i], ${type}(${cols}*i + j)) - } - } - -% end # for rows -% end # for cols -% end # for type -} - -simdTestSuite.test("matrix elements") { -% for type in float_types: -% for cols in [2,3,4]: -// Workaround -% for rows in [2,3,4]: -// Workaround -% mattype = ctype[type] + str(cols) + 'x' + str(rows) -% coltype = ctype[type] + str(rows) -% mat = 'm_' + mattype -% basis = type.lower() + 'basis' + str(cols) + 'x' + str(rows) -% diagsize = rows if rows < cols else cols - - // Check getting and setting columns. - let ${basis} : [${coltype}] = [ -% for i in range(cols): - [${', '.join(map(lambda j: - '1' if i == j else '0', - range(rows)))}], -% end - ] - var ${mat} = ${mattype}() - for i in 0..<${cols} { - ${mat}[i] = ${type}(i+1)*${basis}[i] - } - expectEqualTest( - ${mat}, ${mattype}(diagonal:${range(1, diagsize + 1)}), sameValue: same) - for i in 0..<${cols} { - expectEqualTest(${mat}[i], ${type}(i + 1)*${basis}[i], sameValue: same) - } - - // Check getting and setting elements (and transpose). - ${mat} = ${mattype}() - for i in 0..<${rows} { - for j in 0..<${cols} { - ${mat}[j, i] = ${type}(${cols}*i + j) - } - } - var ${'trans'+mat} = ${mat}.transpose - for j in 0..<${cols} { - for i in 0..<${rows} { - expectEqual(${'trans'+mat}[i, j], ${type}(${cols}*i + j)) - } - } - -% end # for rows -% end # for cols -% end # for type -} - -simdTestSuite.test("debug description") { - expectEqual("SIMD2(1.0, 2.5)", - SIMD2(1.0, 2.5).debugDescription) -} - -runAllTests() - diff --git a/test/stdlib/subString.swift b/test/stdlib/subString.swift index e670910bb55b9..8e7ee6cc9183c 100644 --- a/test/stdlib/subString.swift +++ b/test/stdlib/subString.swift @@ -255,7 +255,7 @@ SubstringTests.test("UTF8View") { // The specialization for Substring.withContiguousStorageIfAvailable was // added in https://github.com/apple/swift/pull/29146. - guard #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) else { + guard #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) else { return } checkHasContiguousStorage(t) diff --git a/test/swift-indent/basic.swift b/test/swift-indent/basic.swift index c4e160d818de2..e1a837f4b0324 100644 --- a/test/swift-indent/basic.swift +++ b/test/swift-indent/basic.swift @@ -1036,3 +1036,30 @@ private var secondThing = item .filter {}, firstThing = 20, thirdThing = 56 + + +// Function decls missing their parameter list and body shouldn't pick up the next token as a continuation. + +struct BarType { + func bar +} + +struct <#name#> { + <#fields#> +} + +struct <#name#> { + <#fields#> + func foo() {} +} + + +// Array literal elements should have their continuation lines indented relative to their first line. + +doStuffWithList([ + baseThing() + .map { $0 } + .append(\.sdfsdf), + secondItem + .filter {$0 < 10} +]) diff --git a/tools/SourceKit/include/SourceKit/Core/LangSupport.h b/tools/SourceKit/include/SourceKit/Core/LangSupport.h index a30759b298842..52421f9746df1 100644 --- a/tools/SourceKit/include/SourceKit/Core/LangSupport.h +++ b/tools/SourceKit/include/SourceKit/Core/LangSupport.h @@ -618,6 +618,7 @@ class TypeContextInfoConsumer { virtual void handleResult(const TypeContextInfoItem &Result) = 0; virtual void failed(StringRef ErrDescription) = 0; + virtual void setReusingASTContext(bool flag) = 0; }; struct ConformingMethodListResult { @@ -642,6 +643,7 @@ class ConformingMethodListConsumer { virtual ~ConformingMethodListConsumer() {} virtual void handleResult(const ConformingMethodListResult &Result) = 0; + virtual void setReusingASTContext(bool flag) = 0; virtual void failed(StringRef ErrDescription) = 0; }; @@ -810,12 +812,14 @@ class LangSupport { virtual void getExpressionContextInfo(llvm::MemoryBuffer *inputBuf, unsigned Offset, + OptionsDictionary *options, ArrayRef Args, TypeContextInfoConsumer &Consumer, Optional vfsOptions) = 0; virtual void getConformingMethodList(llvm::MemoryBuffer *inputBuf, unsigned Offset, + OptionsDictionary *options, ArrayRef Args, ArrayRef ExpectedTypes, ConformingMethodListConsumer &Consumer, diff --git a/tools/SourceKit/lib/SwiftLang/SwiftConformingMethodList.cpp b/tools/SourceKit/lib/SwiftLang/SwiftConformingMethodList.cpp index 62ef9c6d25191..aca4e04d9b00c 100644 --- a/tools/SourceKit/lib/SwiftLang/SwiftConformingMethodList.cpp +++ b/tools/SourceKit/lib/SwiftLang/SwiftConformingMethodList.cpp @@ -26,6 +26,13 @@ using namespace SourceKit; using namespace swift; using namespace ide; +static void translateConformingMethodListOptions(OptionsDictionary &from, + ConformingMethodList::Options &to) { + static UIdent KeyReuseASTContext("key.conformingmethods.reuseastcontext"); + + from.valueForOption(KeyReuseASTContext, to.reuseASTContextIfPossible); +} + static bool swiftConformingMethodListImpl( SwiftLangSupport &Lang, llvm::MemoryBuffer *UnresolvedInputFile, unsigned Offset, ArrayRef Args, @@ -44,12 +51,14 @@ static bool swiftConformingMethodListImpl( auto SF = CI.getCodeCompletionFile(); performCodeCompletionSecondPass(*SF.get(), *callbacksFactory); + Consumer.setReusingASTContext(reusingASTContext); }); } void SwiftLangSupport::getConformingMethodList( llvm::MemoryBuffer *UnresolvedInputFile, unsigned Offset, - ArrayRef Args, ArrayRef ExpectedTypeNames, + OptionsDictionary *optionsDict, ArrayRef Args, + ArrayRef ExpectedTypeNames, SourceKit::ConformingMethodListConsumer &SKConsumer, Optional vfsOptions) { std::string error; @@ -60,6 +69,11 @@ void SwiftLangSupport::getConformingMethodList( if (!fileSystem) return SKConsumer.failed(error); + ConformingMethodList::Options options; + if (optionsDict) { + translateConformingMethodListOptions(*optionsDict, options); + } + class Consumer : public ide::ConformingMethodListConsumer { SourceKit::ConformingMethodListConsumer &SKConsumer; @@ -68,7 +82,7 @@ void SwiftLangSupport::getConformingMethodList( : SKConsumer(SKConsumer) {} /// Convert an IDE result to a SK result and send it to \c SKConsumer . - void handleResult(const ide::ConformingMethodListResult &Result) { + void handleResult(const ide::ConformingMethodListResult &Result) override { SmallString<512> SS; llvm::raw_svector_ostream OS(SS); @@ -172,11 +186,15 @@ void SwiftLangSupport::getConformingMethodList( SKConsumer.handleResult(SKResult); } + + void setReusingASTContext(bool flag) override { + SKConsumer.setReusingASTContext(flag); + } } Consumer(SKConsumer); if (!swiftConformingMethodListImpl(*this, UnresolvedInputFile, Offset, Args, ExpectedTypeNames, Consumer, fileSystem, - /*EnableASTCaching=*/false, error)) { + options.reuseASTContextIfPossible, error)) { SKConsumer.failed(error); } } diff --git a/tools/SourceKit/lib/SwiftLang/SwiftLangSupport.h b/tools/SourceKit/lib/SwiftLang/SwiftLangSupport.h index b29e59a6b665c..b3ab4208a6ef7 100644 --- a/tools/SourceKit/lib/SwiftLang/SwiftLangSupport.h +++ b/tools/SourceKit/lib/SwiftLang/SwiftLangSupport.h @@ -220,6 +220,18 @@ class SessionCacheMap { }; } // end namespace CodeCompletion +namespace TypeContextInfo { +struct Options { + bool reuseASTContextIfPossible = true; +}; +} // namespace TypeContextInfo + +namespace ConformingMethodList { +struct Options { + bool reuseASTContextIfPossible = true; +}; +} // namespace ConformingMethodList + class SwiftInterfaceGenMap { llvm::StringMap IFaceGens; mutable llvm::sys::Mutex Mtx; @@ -596,11 +608,13 @@ class SwiftLangSupport : public LangSupport { std::function> &)> Receiver) override; void getExpressionContextInfo(llvm::MemoryBuffer *inputBuf, unsigned Offset, + OptionsDictionary *options, ArrayRef Args, TypeContextInfoConsumer &Consumer, Optional vfsOptions) override; void getConformingMethodList(llvm::MemoryBuffer *inputBuf, unsigned Offset, + OptionsDictionary *options, ArrayRef Args, ArrayRef ExpectedTypes, ConformingMethodListConsumer &Consumer, diff --git a/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp b/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp index 14a802fe12bb6..5d8e389ca2565 100644 --- a/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp +++ b/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp @@ -415,14 +415,13 @@ static void printAnnotatedDeclaration(const ValueDecl *VD, while (VD->isImplicit() && VD->getOverriddenDecl()) VD = VD->getOverriddenDecl(); - // If this is a property wrapper backing property (_foo) or projected value - // ($foo) and the wrapped property is not implicit, still print it. - if (auto *VarD = dyn_cast(VD)) { - if (auto *Wrapped = VarD->getOriginalWrappedProperty()) { - if (!Wrapped->isImplicit()) - PO.TreatAsExplicitDeclList.push_back(VD); - } - } + // VD may be a compiler synthesized member, constructor, or shorthand argument + // so always print it even if it's implicit. + // + // FIXME: Update PrintOptions::printQuickHelpDeclaration to print implicit + // decls by default. That causes issues due to newlines being printed before + // implicit OpaqueTypeDecls at time of writing. + PO.TreatAsExplicitDeclList.push_back(VD); // Wrap this up in XML, as that's what we'll use for documentation comments. OS<<""; @@ -446,14 +445,14 @@ void SwiftLangSupport::printFullyAnnotatedDeclaration(const ValueDecl *VD, while (VD->isImplicit() && VD->getOverriddenDecl()) VD = VD->getOverriddenDecl(); - // If this is a property wrapper backing property (_foo) or projected value - // ($foo) and the wrapped property is not implicit, still print it. - if (auto *VarD = dyn_cast(VD)) { - if (auto *Wrapped = VarD->getOriginalWrappedProperty()) { - if (!Wrapped->isImplicit()) - PO.TreatAsExplicitDeclList.push_back(VD); - } - } + // VD may be a compiler synthesized member, constructor, or shorthand argument + // so always print it even if it's implicit. + // + // FIXME: Update PrintOptions::printQuickHelpDeclaration to print implicit + // decls by default. That causes issues due to newlines being printed before + // implicit OpaqueTypeDecls at time of writing. + PO.TreatAsExplicitDeclList.push_back(VD); + VD->print(Printer, PO); } diff --git a/tools/SourceKit/lib/SwiftLang/SwiftTypeContextInfo.cpp b/tools/SourceKit/lib/SwiftLang/SwiftTypeContextInfo.cpp index 2ea49522cc25b..c95fb09391770 100644 --- a/tools/SourceKit/lib/SwiftLang/SwiftTypeContextInfo.cpp +++ b/tools/SourceKit/lib/SwiftLang/SwiftTypeContextInfo.cpp @@ -25,6 +25,13 @@ using namespace SourceKit; using namespace swift; using namespace ide; +static void translateTypeContextInfoOptions(OptionsDictionary &from, + TypeContextInfo::Options &to) { + static UIdent KeyReuseASTContext("key.typecontextinfo.reuseastcontext"); + + from.valueForOption(KeyReuseASTContext, to.reuseASTContextIfPossible); +} + static bool swiftTypeContextInfoImpl( SwiftLangSupport &Lang, llvm::MemoryBuffer *UnresolvedInputFile, unsigned Offset, ide::TypeContextInfoConsumer &Consumer, @@ -41,16 +48,22 @@ static bool swiftTypeContextInfoImpl( auto SF = CI.getCodeCompletionFile(); performCodeCompletionSecondPass(*SF.get(), *callbacksFactory); + Consumer.setReusingASTContext(reusingASTContext); }); } void SwiftLangSupport::getExpressionContextInfo( llvm::MemoryBuffer *UnresolvedInputFile, unsigned Offset, - ArrayRef Args, + OptionsDictionary *optionsDict, ArrayRef Args, SourceKit::TypeContextInfoConsumer &SKConsumer, Optional vfsOptions) { std::string error; + TypeContextInfo::Options options; + if (optionsDict) { + translateTypeContextInfoOptions(*optionsDict, options); + } + // FIXME: the use of None as primary file is to match the fact we do not read // the document contents using the editor documents infrastructure. auto fileSystem = getFileSystem(vfsOptions, /*primaryFile=*/None, error); @@ -144,15 +157,19 @@ void SwiftLangSupport::getExpressionContextInfo( Consumer(SourceKit::TypeContextInfoConsumer &SKConsumer) : SKConsumer(SKConsumer){}; - void handleResults(ArrayRef Results) { + void handleResults(ArrayRef Results) override { for (auto &Item : Results) handleSingleResult(Item); } + + void setReusingASTContext(bool flag) override { + SKConsumer.setReusingASTContext(flag); + } } Consumer(SKConsumer); if (!swiftTypeContextInfoImpl(*this, UnresolvedInputFile, Offset, Consumer, - Args, fileSystem, /*EnableASTCaching=*/false, - error)) { + Args, fileSystem, + options.reuseASTContextIfPossible, error)) { SKConsumer.failed(error); } } diff --git a/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp b/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp index 21683a1f976a6..7f9d37228fb62 100644 --- a/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp +++ b/tools/SourceKit/tools/sourcekitd-test/sourcekitd-test.cpp @@ -298,13 +298,14 @@ static int printDiags(); static void getSemanticInfo(sourcekitd_variant_t Info, StringRef Filename); -static void addCodeCompleteOptions(sourcekitd_object_t Req, TestOptions &Opts) { +static void addRequestOptions(sourcekitd_object_t Req, TestOptions &Opts, + sourcekitd_uid_t Key, StringRef(prefix)) { if (!Opts.RequestOptions.empty()) { sourcekitd_object_t CCOpts = sourcekitd_request_dictionary_create(nullptr, nullptr, 0); for (auto &Opt : Opts.RequestOptions) { auto KeyValue = StringRef(Opt).split('='); - std::string KeyStr("key.codecomplete."); + std::string KeyStr(prefix.str()); KeyStr.append(KeyValue.first.str()); sourcekitd_uid_t Key = sourcekitd_uid_get_from_cstr(KeyStr.c_str()); @@ -312,14 +313,27 @@ static void addCodeCompleteOptions(sourcekitd_object_t Req, TestOptions &Opts) { if (KeyValue.first == "filtertext") { sourcekitd_request_dictionary_set_stringbuf( CCOpts, Key, KeyValue.second.data(), KeyValue.second.size()); + } else if (KeyValue.first == "expectedtypes") { + SmallVector expectedTypeNames; + KeyValue.second.split(expectedTypeNames, ';'); + + auto typenames = sourcekitd_request_array_create(nullptr, 0); + for (auto &name : expectedTypeNames) { + std::string n = name.str(); + sourcekitd_request_array_set_string(typenames, + SOURCEKITD_ARRAY_APPEND, + n.c_str()); + } + // NOTE: 'key.expectedtypes' directly to the request. + sourcekitd_request_dictionary_set_value(Req, KeyExpectedTypes, + typenames); } else { int64_t Value = 0; KeyValue.second.getAsInteger(0, Value); sourcekitd_request_dictionary_set_int64(CCOpts, Key, Value); } } - sourcekitd_request_dictionary_set_value(Req, KeyCodeCompleteOptions, - CCOpts); + sourcekitd_request_dictionary_set_value(Req, Key, CCOpts); sourcekitd_request_release(CCOpts); } } @@ -444,28 +458,6 @@ static int handleTestInvocation(ArrayRef Args, return 0; } -static int setExpectedTypes(const sourcekitd_test::TestOptions &Opts, - sourcekitd_object_t Req) { - for (auto &Opt : Opts.RequestOptions) { - auto KeyValue = StringRef(Opt).split('='); - if (KeyValue.first == "expectedtypes") { - SmallVector expectedTypeNames; - KeyValue.second.split(expectedTypeNames, ';'); - - auto typenames = sourcekitd_request_array_create(nullptr, 0); - for (auto &name : expectedTypeNames) { - std::string n = name.str(); - sourcekitd_request_array_set_string(typenames, SOURCEKITD_ARRAY_APPEND, n.c_str()); - } - sourcekitd_request_dictionary_set_value(Req, KeyExpectedTypes, typenames); - } else { - llvm::errs() << "invalid key '" << KeyValue.first << "' in -req-opts\n"; - return 1; - } - } - return 0; -} - static bool sendGlobalConfigRequest() { TestOptions Opts; sourcekitd_object_t Req = sourcekitd_request_dictionary_create(nullptr, @@ -601,7 +593,7 @@ static int handleTestInvocation(TestOptions Opts, TestOptions &InitOpts) { sourcekitd_request_dictionary_set_string(Req, KeyName, SemaName.c_str()); // Default to sort by name. Opts.RequestOptions.insert(Opts.RequestOptions.begin(), "sort.byname=1"); - addCodeCompleteOptions(Req, Opts); + addRequestOptions(Req, Opts, KeyCodeCompleteOptions, "key.codecomplete."); break; case SourceKitRequest::CodeCompleteOpen: @@ -609,7 +601,7 @@ static int handleTestInvocation(TestOptions Opts, TestOptions &InitOpts) { RequestCodeCompleteOpen); sourcekitd_request_dictionary_set_int64(Req, KeyOffset, ByteOffset); sourcekitd_request_dictionary_set_string(Req, KeyName, SemaName.c_str()); - addCodeCompleteOptions(Req, Opts); + addRequestOptions(Req, Opts, KeyCodeCompleteOptions, "key.codecomplete."); break; case SourceKitRequest::CodeCompleteClose: @@ -624,7 +616,7 @@ static int handleTestInvocation(TestOptions Opts, TestOptions &InitOpts) { RequestCodeCompleteUpdate); sourcekitd_request_dictionary_set_int64(Req, KeyOffset, ByteOffset); sourcekitd_request_dictionary_set_string(Req, KeyName, SemaName.c_str()); - addCodeCompleteOptions(Req, Opts); + addRequestOptions(Req, Opts, KeyCodeCompleteOptions, "key.codecomplete."); break; case SourceKitRequest::CodeCompleteCacheOnDisk: @@ -673,13 +665,16 @@ static int handleTestInvocation(TestOptions Opts, TestOptions &InitOpts) { sourcekitd_request_dictionary_set_uid(Req, KeyRequest, RequestTypeContextInfo); sourcekitd_request_dictionary_set_int64(Req, KeyOffset, ByteOffset); + addRequestOptions(Req, Opts, KeyTypeContextInfoOptions, + "key.typecontextinfo."); break; case SourceKitRequest::ConformingMethodList: sourcekitd_request_dictionary_set_uid(Req, KeyRequest, RequestConformingMethodList); sourcekitd_request_dictionary_set_int64(Req, KeyOffset, ByteOffset); - setExpectedTypes(Opts, Req); + addRequestOptions(Req, Opts, KeyConformingMethodListOptions, + "key.conformingmethods."); break; case SourceKitRequest::CursorInfo: @@ -711,7 +706,10 @@ static int handleTestInvocation(TestOptions Opts, TestOptions &InitOpts) { case SourceKitRequest::CollectExpresstionType: { sourcekitd_request_dictionary_set_uid(Req, KeyRequest, RequestCollectExpressionType); - setExpectedTypes(Opts, Req); + // NOTE: KeyCodeCompletion and the prefix are just dummy. This request + // only accepts 'expectedtypes' which is placed to the Req root dictionary. + addRequestOptions(Req, Opts, KeyCodeCompleteOptions, + "key.expression.type."); break; } diff --git a/tools/SourceKit/tools/sourcekitd/lib/API/Requests.cpp b/tools/SourceKit/tools/sourcekitd/lib/API/Requests.cpp index ad8f88ca29617..d4aa6dc19cc7c 100644 --- a/tools/SourceKit/tools/sourcekitd/lib/API/Requests.cpp +++ b/tools/SourceKit/tools/sourcekitd/lib/API/Requests.cpp @@ -176,11 +176,13 @@ static sourcekitd_response_t codeCompleteClose(StringRef name, int64_t Offset); static sourcekitd_response_t typeContextInfo(llvm::MemoryBuffer *InputBuf, int64_t Offset, + Optional optionsDict, ArrayRef Args, Optional vfsOptions); static sourcekitd_response_t conformingMethodList(llvm::MemoryBuffer *InputBuf, int64_t Offset, + Optional optionsDict, ArrayRef Args, ArrayRef ExpectedTypes, Optional vfsOptions); @@ -993,7 +995,9 @@ static void handleSemanticRequest( int64_t Offset; if (Req.getInt64(KeyOffset, Offset, /*isOptional=*/false)) return Rec(createErrorRequestInvalid("missing 'key.offset'")); - return Rec(typeContextInfo(InputBuf.get(), Offset, Args, + Optional options = + Req.getDictionary(KeyTypeContextInfoOptions); + return Rec(typeContextInfo(InputBuf.get(), Offset, options, Args, std::move(vfsOptions))); } @@ -1008,9 +1012,11 @@ static void handleSemanticRequest( SmallVector ExpectedTypeNames; if (Req.getStringArray(KeyExpectedTypes, ExpectedTypeNames, true)) return Rec(createErrorRequestInvalid("invalid 'key.expectedtypes'")); + Optional options = + Req.getDictionary(KeyConformingMethodListOptions); return Rec( - conformingMethodList(InputBuf.get(), Offset, Args, ExpectedTypeNames, - std::move(vfsOptions))); + conformingMethodList(InputBuf.get(), Offset, options, Args, + ExpectedTypeNames, std::move(vfsOptions))); } if (!SourceFile.hasValue()) @@ -2261,17 +2267,20 @@ void SKGroupedCodeCompletionConsumer::setAnnotatedTypename(bool flag) { static sourcekitd_response_t typeContextInfo(llvm::MemoryBuffer *InputBuf, int64_t Offset, + Optional optionsDict, ArrayRef Args, Optional vfsOptions) { ResponseBuilder RespBuilder; class Consumer : public TypeContextInfoConsumer { + ResponseBuilder RespBuilder; ResponseBuilder::Array SKResults; Optional ErrorDescription; public: Consumer(ResponseBuilder Builder) - : SKResults(Builder.getDictionary().setArray(KeyResults)) {} + : RespBuilder(Builder), + SKResults(Builder.getDictionary().setArray(KeyResults)) {} void handleResult(const TypeContextInfoItem &Item) override { auto SKElem = SKResults.appendDictionary(); @@ -2288,6 +2297,11 @@ static sourcekitd_response_t typeContextInfo(llvm::MemoryBuffer *InputBuf, } } + void setReusingASTContext(bool flag) override { + if (flag) + RespBuilder.getDictionary().setBool(KeyReusingASTContext, flag); + } + void failed(StringRef ErrDescription) override { ErrorDescription = ErrDescription.str(); } @@ -2298,8 +2312,12 @@ static sourcekitd_response_t typeContextInfo(llvm::MemoryBuffer *InputBuf, } } Consumer(RespBuilder); + std::unique_ptr options; + if (optionsDict) + options = std::make_unique(*optionsDict); + LangSupport &Lang = getGlobalContext().getSwiftLangSupport(); - Lang.getExpressionContextInfo(InputBuf, Offset, Args, Consumer, + Lang.getExpressionContextInfo(InputBuf, Offset, options.get(), Args, Consumer, std::move(vfsOptions)); if (Consumer.isError()) @@ -2313,6 +2331,7 @@ static sourcekitd_response_t typeContextInfo(llvm::MemoryBuffer *InputBuf, static sourcekitd_response_t conformingMethodList(llvm::MemoryBuffer *InputBuf, int64_t Offset, + Optional optionsDict, ArrayRef Args, ArrayRef ExpectedTypes, Optional vfsOptions) { @@ -2341,6 +2360,11 @@ conformingMethodList(llvm::MemoryBuffer *InputBuf, int64_t Offset, } } + void setReusingASTContext(bool flag) override { + if (flag) + SKResult.setBool(KeyReusingASTContext, flag); + } + void failed(StringRef ErrDescription) override { ErrorDescription = ErrDescription.str(); } @@ -2351,9 +2375,13 @@ conformingMethodList(llvm::MemoryBuffer *InputBuf, int64_t Offset, } } Consumer(RespBuilder); + std::unique_ptr options; + if (optionsDict) + options = std::make_unique(*optionsDict); + LangSupport &Lang = getGlobalContext().getSwiftLangSupport(); - Lang.getConformingMethodList(InputBuf, Offset, Args, ExpectedTypes, Consumer, - std::move(vfsOptions)); + Lang.getConformingMethodList(InputBuf, Offset, options.get(), Args, + ExpectedTypes, Consumer, std::move(vfsOptions)); if (Consumer.isError()) return createErrorRequestFailed(Consumer.getErrorDescription()); diff --git a/utils/gyb_sourcekit_support/UIDs.py b/utils/gyb_sourcekit_support/UIDs.py index 33b80673032c5..f9811a49e331c 100644 --- a/utils/gyb_sourcekit_support/UIDs.py +++ b/utils/gyb_sourcekit_support/UIDs.py @@ -99,6 +99,8 @@ def __init__(self, internal_name, external_name): KEY('EducationalNotePaths', 'key.educational_note_paths'), KEY('FormatOptions', 'key.editor.format.options'), KEY('CodeCompleteOptions', 'key.codecomplete.options'), + KEY('TypeContextInfoOptions', 'key.typecontextinfo.options'), + KEY('ConformingMethodListOptions', 'key.conformingmethods.options'), KEY('FilterRules', 'key.codecomplete.filterrules'), KEY('NextRequestStart', 'key.nextrequeststart'), KEY('Popular', 'key.popular'), diff --git a/validation-test/stdlib/CoreAudio.swift b/validation-test/stdlib/CoreAudio.swift deleted file mode 100644 index 399cff4b5a459..0000000000000 --- a/validation-test/stdlib/CoreAudio.swift +++ /dev/null @@ -1,303 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest -import StdlibCollectionUnittest - - -import CoreAudio - -// Used in tests below. -extension AudioBuffer : Equatable {} - -public func == (lhs: AudioBuffer, rhs: AudioBuffer) -> Bool { - return lhs.mNumberChannels == rhs.mNumberChannels && - lhs.mDataByteSize == rhs.mDataByteSize && - lhs.mData == rhs.mData -} - -var CoreAudioTestSuite = TestSuite("CoreAudio") - -// The size of the non-flexible part of an AudioBufferList. -#if arch(i386) || arch(arm) -let ablHeaderSize = 4 -#elseif arch(x86_64) || arch(arm64) -let ablHeaderSize = 8 -#endif - -CoreAudioTestSuite.test("UnsafeBufferPointer.init(_: AudioBuffer)") { - do { - let audioBuffer = AudioBuffer( - mNumberChannels: 0, mDataByteSize: 0, mData: nil) - let result: UnsafeBufferPointer = UnsafeBufferPointer(audioBuffer) - expectEqual(nil, result.baseAddress) - expectEqual(0, result.count) - } - - do { - let audioBuffer = AudioBuffer( - mNumberChannels: 2, mDataByteSize: 1024, - mData: UnsafeMutableRawPointer(bitPattern: 0x1234_5678)) - let result: UnsafeBufferPointer = UnsafeBufferPointer(audioBuffer) - expectEqual(audioBuffer.mData, UnsafeRawPointer(result.baseAddress!)) - expectEqual(256, result.count) - } -} - -CoreAudioTestSuite.test("UnsafeMutableBufferPointer.init(_: AudioBuffer)") { - do { - let audioBuffer = AudioBuffer( - mNumberChannels: 0, mDataByteSize: 0, mData: nil) - let result: UnsafeMutableBufferPointer = - UnsafeMutableBufferPointer(audioBuffer) - expectEqual(nil, result.baseAddress) - expectEqual(0, result.count) - } - - do { - let audioBuffer = AudioBuffer( - mNumberChannels: 2, mDataByteSize: 1024, - mData: UnsafeMutableRawPointer(bitPattern: 0x1234_5678)) - let result: UnsafeMutableBufferPointer = - UnsafeMutableBufferPointer(audioBuffer) - expectEqual(audioBuffer.mData!, UnsafeMutableRawPointer(result.baseAddress!)) - expectEqual(256, result.count) - } -} - -CoreAudioTestSuite.test( - "AudioBuffer.init(_: UnsafeMutableBufferPointer, numberOfChannels: Int)") { - do { - // NULL pointer. - let buffer = UnsafeMutableBufferPointer(start: nil, count: 0) - let result = AudioBuffer(buffer, numberOfChannels: 2) - expectEqual(2, result.mNumberChannels) - expectEqual(0, result.mDataByteSize) - expectEqual(nil, result.mData) - } - do { - // Non-NULL pointer. - let buffer = UnsafeMutableBufferPointer( - start: UnsafeMutablePointer(bitPattern: 0x1234_5678), count: 0) - let result = AudioBuffer(buffer, numberOfChannels: 2) - expectEqual(2, result.mNumberChannels) - expectEqual(0, result.mDataByteSize) - expectEqual(buffer.baseAddress, result.mData) - } -} - -CoreAudioTestSuite.test( - "AudioBuffer.init(_: UnsafeMutableBufferPointer, numberOfChannels: Int)/trap") { -#if arch(i386) || arch(arm) - let overflowingCount = Int.max -#elseif arch(x86_64) || arch(arm64) - let overflowingCount = Int(UInt32.max) -#endif - let buffer = UnsafeMutableBufferPointer( - start: UnsafeMutablePointer(bitPattern: 0x1234_5678), - count: overflowingCount) - - expectCrashLater() - // An overflow happens when we try to compute the value for mDataByteSize. - _ = AudioBuffer(buffer, numberOfChannels: 2) -} - -CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)") { - expectEqual(ablHeaderSize + MemoryLayout.stride, - AudioBufferList.sizeInBytes(maximumBuffers: 1)) - expectEqual(ablHeaderSize + 16 * MemoryLayout.stride, - AudioBufferList.sizeInBytes(maximumBuffers: 16)) -} - -CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/count<0") { - expectCrashLater() - _ = AudioBufferList.sizeInBytes(maximumBuffers: -1) -} - -CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/count==0") { - expectCrashLater() - _ = AudioBufferList.sizeInBytes(maximumBuffers: -1) -} - -CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/overflow") { - expectCrashLater() - _ = AudioBufferList.sizeInBytes(maximumBuffers: Int.max) -} - -CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)") { - do { - let ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 1) - expectEqual(1, ablPtrWrapper.count) - free(ablPtrWrapper.unsafeMutablePointer) - } - do { - let ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 16) - expectEqual(16, ablPtrWrapper.count) - free(ablPtrWrapper.unsafeMutablePointer) - } -} - -CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/count==0") { - expectCrashLater() - _ = AudioBufferList.allocate(maximumBuffers: 0) -} - -CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/count<0") { - expectCrashLater() - _ = AudioBufferList.allocate(maximumBuffers: -1) -} - -CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/overflow") { - expectCrashLater() - _ = AudioBufferList.allocate(maximumBuffers: Int.max) -} - -CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer/AssociatedTypes") { - typealias Subject = UnsafeMutableAudioBufferListPointer - expectRandomAccessCollectionAssociatedTypes( - collectionType: Subject.self, - iteratorType: IndexingIterator.self, - subSequenceType: Slice.self, - indexType: Int.self, - indicesType: CountableRange.self) -} - -CoreAudioTestSuite.test( - "UnsafeMutableAudioBufferListPointer.init(_: UnsafeMutablePointer)," + - "UnsafeMutableAudioBufferListPointer.unsafePointer," + - "UnsafeMutableAudioBufferListPointer.unsafeMutablePointer") { - do { - let ablPtrWrapper = UnsafeMutableAudioBufferListPointer(nil) - expectNil(ablPtrWrapper) - } - - do { - let ablPtrWrapper = UnsafeMutableAudioBufferListPointer( - UnsafeMutablePointer(bitPattern: 0x1234_5678)!) - expectEqual( - UnsafePointer(bitPattern: 0x1234_5678), - ablPtrWrapper.unsafePointer) - expectEqual( - UnsafePointer(bitPattern: 0x1234_5678), - ablPtrWrapper.unsafeMutablePointer) - } - - do { - let ablPtrWrapper = UnsafeMutableAudioBufferListPointer( - UnsafeMutablePointer(bitPattern: 0x1234_5678)) - expectNotNil(ablPtrWrapper) - expectEqual( - UnsafePointer(bitPattern: 0x1234_5678), - ablPtrWrapper!.unsafePointer) - expectEqual( - UnsafePointer(bitPattern: 0x1234_5678), - ablPtrWrapper!.unsafeMutablePointer) - } -} - -CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.count") { - let sizeInBytes = AudioBufferList.sizeInBytes(maximumBuffers: 16) - let rawPtr = UnsafeMutableRawPointer.allocate( - byteCount: sizeInBytes, alignment: MemoryLayout.alignment) - let ablPtr = rawPtr.bindMemory(to: AudioBufferList.self, - capacity: sizeInBytes / MemoryLayout.stride) - - // It is important that 'ablPtrWrapper' is a 'let'. We are verifying that - // the 'count' property has a nonmutating setter. - let ablPtrWrapper = UnsafeMutableAudioBufferListPointer(ablPtr) - - // Test getter. - rawPtr.storeBytes(of: 0x1234_5678, as: UInt32.self) - expectEqual(0x1234_5678, ablPtrWrapper.count) - - // Test setter. - ablPtrWrapper.count = 0x7765_4321 - expectEqual(0x7765_4321, rawPtr.load(as: UInt32.self)) - - rawPtr.deallocate() -} - -CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.subscript(_: Int)") { - let sizeInBytes = AudioBufferList.sizeInBytes(maximumBuffers: 16) - - let rawPtr = UnsafeMutableRawPointer.allocate( - byteCount: sizeInBytes, alignment: 1) - - let ablPtr = rawPtr.bindMemory( - to: AudioBufferList.self, - capacity: sizeInBytes / MemoryLayout.stride) - - // It is important that 'ablPtrWrapper' is a 'let'. We are verifying that - // the subscript has a nonmutating setter. - let ablPtrWrapper = UnsafeMutableAudioBufferListPointer(ablPtr) - - do { - // Test getter. - let audioBuffer = AudioBuffer( - mNumberChannels: 2, mDataByteSize: 1024, - mData: UnsafeMutableRawPointer(bitPattern: 0x1234_5678)) - - let bufPtr = (rawPtr + ablHeaderSize).assumingMemoryBound( - to: AudioBuffer.self) - bufPtr.pointee = audioBuffer - ablPtrWrapper.count = 1 - - expectEqual(2, ablPtrWrapper[0].mNumberChannels) - expectEqual(1024, ablPtrWrapper[0].mDataByteSize) - expectEqual(audioBuffer.mData, ablPtrWrapper[0].mData) - } - - do { - // Test setter. - let audioBuffer = AudioBuffer( - mNumberChannels: 5, mDataByteSize: 256, - mData: UnsafeMutableRawPointer(bitPattern: 0x8765_4321 as UInt)) - - ablPtrWrapper.count = 2 - ablPtrWrapper[1] = audioBuffer - - let audioBufferPtr = (rawPtr + ablHeaderSize).assumingMemoryBound( - to: AudioBuffer.self) + 1 - expectEqual(5, audioBufferPtr.pointee.mNumberChannels) - expectEqual(256, audioBufferPtr.pointee.mDataByteSize) - expectEqual(audioBuffer.mData, audioBufferPtr.pointee.mData) - } - - ablPtr.deallocate() -} - -CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.subscript(_: Int)/trap") { - let ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 4) - - ablPtrWrapper[0].mNumberChannels = 42 - ablPtrWrapper[1].mNumberChannels = 42 - ablPtrWrapper[2].mNumberChannels = 42 - ablPtrWrapper[3].mNumberChannels = 42 - - expectCrashLater() - ablPtrWrapper[4].mNumberChannels = 42 -} - -CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer/Collection") { - var ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 16) - expectType(UnsafeMutableAudioBufferListPointer.self, &ablPtrWrapper) - - var expected: [AudioBuffer] = [] - for i in 0..<16 { - let audioBuffer = AudioBuffer( - mNumberChannels: UInt32(2 + i), mDataByteSize: UInt32(1024 * i), - mData: UnsafeMutableRawPointer(bitPattern: 0x1234_5678 + i * 10)) - - ablPtrWrapper[i] = audioBuffer - expected.append(audioBuffer) - } - - // FIXME: use checkMutableRandomAccessCollection, when we have that function. - checkRandomAccessCollection(expected, ablPtrWrapper) - free(ablPtrWrapper.unsafeMutablePointer) -} - -runAllTests() diff --git a/validation-test/stdlib/CoreData.swift b/validation-test/stdlib/CoreData.swift deleted file mode 100644 index 9be14aea7037d..0000000000000 --- a/validation-test/stdlib/CoreData.swift +++ /dev/null @@ -1,42 +0,0 @@ -// RUN: %empty-directory(%t) - -// RUN: %target-clang %S/Inputs/CoreDataHelper/CoreDataHelper.m -c -o %t/CoreDataHelper.o -g -fmodules -// RUN: %target-build-swift %s -import-objc-header %S/Inputs/CoreDataHelper/CoreDataHelper.h -Xlinker %t/CoreDataHelper.o -o %t/main -// RUN: %target-codesign %t/main -// RUN: %target-run %t/main - -// REQUIRES: executable_test -// REQUIRES: objc_interop - -import CoreData -import StdlibUnittest - -var CoreDataTests = TestSuite("CoreData") - -CoreDataTests.test("conformsToProtocol") { - expectTrue(NSDictionary.conforms(to: NSFetchRequestResult.self)) - expectTrue(NSManagedObject.conforms(to: NSFetchRequestResult.self)) -} - -CoreDataTests.test("downcasting") { - var dictionaries = NSFetchRequest.testGettingSomeDictionaries() - expectType([NSFetchRequestResult].self, &dictionaries) - - let casted = dictionaries as? [[NSObject: AnyObject]] - expectNotNil(casted) - expectEqual([[:] as NSDictionary, [:] as NSDictionary] as NSArray, casted! as NSArray) - expectEqual([[:] as NSDictionary, [:] as NSDictionary] as NSArray, dictionaries as! [[NSObject: AnyObject]] as NSArray) -} - -CoreDataTests.test("bridging") { - var dictionaries = NSFetchRequest.testGettingSomeDictionaries() - expectType([NSDictionary].self, &dictionaries) - expectEqual([[:], [:]], dictionaries) - - let casted = dictionaries as? [[NSObject: AnyObject]] - expectNotNil(casted) - expectEqual([[:] as NSDictionary, [:] as NSDictionary] as NSArray, casted! as NSArray) - expectEqual([[:] as NSDictionary, [:] as NSDictionary] as NSArray, dictionaries as! [[NSObject: AnyObject]] as NSArray) -} - -runAllTests() diff --git a/validation-test/stdlib/CoreMedia.swift b/validation-test/stdlib/CoreMedia.swift deleted file mode 100644 index a214952faf693..0000000000000 --- a/validation-test/stdlib/CoreMedia.swift +++ /dev/null @@ -1,196 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest - - -import CoreMedia - -var CoreMediaTests = TestSuite("CoreMedia") - -// This is a basic smoke test to check that the overlay works. It should be -// replaced with comprehensive tests. -CoreMediaTests.test("OverlaySmokeTest") { - expectTrue(CMTimeMake(1, 10).isValid) - expectTrue(CMTimeRangeMake(CMTimeMake(1, 10), CMTimeMake(2, 20)).isValid) -} - -CoreMediaTests.test("CMTime(value:timescale:)") { - let time = CMTime(value: 7, timescale: 1) - expectTrue(time.isValid) - expectEqual(7, time.value) - expectEqual(1, time.timescale) -} - -CoreMediaTests.test("CMTime(seconds:preferredTimescale:)") { - let time = CMTime(seconds: 7.0, preferredTimescale: 600) - expectTrue(time.isValid) - expectEqual(7.0, time.seconds) -} - -CoreMediaTests.test("CMTime/Comparable") { - let instances: [(Int, CMTime)] = [ - (-9999, CMTime(seconds: -Double.infinity, preferredTimescale: 600)), - (10, CMTime(seconds: 10.0, preferredTimescale: 600)), - (10, CMTime(seconds: 10.0, preferredTimescale: 600)), - (20, CMTime(seconds: 20.0, preferredTimescale: 600)), - (30, CMTime(seconds: 30.0, preferredTimescale: 600)), - (9999, CMTime(seconds: Double.infinity, preferredTimescale: 600)), - ] - func comparisonOracle(i: Int, j: Int) -> ExpectedComparisonResult { - return instances[i].0 <=> instances[j].0 - } - checkComparable(instances.map { $0.1 }, oracle: comparisonOracle) -} - -CoreMediaTests.test("CMTimeRange(start:duration:)") { - let start = CMTime(seconds: 10.0, preferredTimescale: 600) - let duration = CMTime(seconds: 5.0, preferredTimescale: 600) - let range = CMTimeRange(start: start, duration: duration) - expectEqual(start, range.start) - expectEqual(duration, range.duration) -} - -CoreMediaTests.test("CMTimeRange(start:end:)") { - let start = CMTime(seconds: 10.0, preferredTimescale: 600) - let end = CMTime(seconds: 20.0, preferredTimescale: 600) - let range = CMTimeRange(start: start, end: end) - expectEqual(start, range.start) - expectEqual(end, range.end) -} - -CoreMediaTests.test("CMTimeRange/Equatable") { - let time10 = CMTime(seconds: 10.0, preferredTimescale: 600) - let time20 = CMTime(seconds: 20.0, preferredTimescale: 600) - let timeInf = CMTime(seconds: Double.infinity, preferredTimescale: 600) - - let instances: [(Int, CMTimeRange)] = [ - (10, CMTimeRangeMake(time10, time10)), - (10, CMTimeRangeMake(time10, time10)), - - (20, CMTimeRangeMake(time10, time20)), - (20, CMTimeRangeMake(time10, time20)), - - (9999, CMTimeRangeMake(timeInf, time20)), - (9999, CMTimeRangeMake(timeInf, time20)), - ] - func comparisonOracle(i: Int, j: Int) -> Bool { - return instances[i].0 == instances[j].0 - } - checkEquatable(instances.map { $0.1 }, oracle: comparisonOracle) -} - - -var CMTimeTests = TestSuite("CMTime") - -let t1 = CMTimeMake(1, 10) -let t2 = CMTimeMake(2, 10) - -CMTimeTests.test("isValid") { - expectFalse(kCMTimeInvalid.isValid) - expectTrue(t1.isValid) -} - -CMTimeTests.test("isPositiveInfinity") { - expectTrue(kCMTimePositiveInfinity.isPositiveInfinity) - expectFalse(t1.isPositiveInfinity) -} - -CMTimeTests.test("isNegativeInfinity") { - expectTrue(kCMTimeNegativeInfinity.isNegativeInfinity) - expectFalse(t1.isNegativeInfinity) -} - -CMTimeTests.test("isIndefinite") { - expectTrue(kCMTimeIndefinite.isIndefinite) - expectFalse(t1.isIndefinite) -} - -CMTimeTests.test("isNumeric") { - expectFalse(kCMTimeInvalid.isNumeric) - expectFalse(kCMTimePositiveInfinity.isNumeric) - expectFalse(kCMTimeNegativeInfinity.isNumeric) - expectFalse(kCMTimeIndefinite.isNumeric) - expectTrue(t1.isNumeric) - - expectFalse(t1.hasBeenRounded) - - expectEqual(0.1, t1.seconds) - - t1.convertScale(100, method: CMTimeRoundingMethod.`default`) - - var t1a = t1.convertScale(11, method: CMTimeRoundingMethod.`default`) - expectTrue(t1a.hasBeenRounded) -} - -CMTimeTests.test("operators") { - expectEqual(CMTimeMake(3, 10), t1 + t2) - expectEqual(CMTimeMake(1, 10), t2 - t1) - - expectFalse(t1 < kCMTimeZero) - expectFalse(t1 == kCMTimeZero) - expectTrue(t1 > kCMTimeZero) - - expectFalse(t1 <= kCMTimeZero) - expectTrue(t1 >= kCMTimeZero) - expectTrue(t1 != kCMTimeZero) -} - -let r1 = CMTimeRangeMake(kCMTimeZero, CMTimeMake(1, 1)) -let r2 = CMTimeRangeMake(kCMTimeZero, kCMTimeZero) -let r3 = CMTimeRangeMake(CMTimeMake(1, 1), CMTimeMake(3, 2)) - -var CMTimeRangeTests = TestSuite("CMTimeRange") - -CMTimeRangeTests.test("isValid") { - expectTrue(r1.isValid) - expectTrue(r2.isValid) - expectTrue(r3.isValid) - expectFalse(kCMTimeRangeInvalid.isValid) -} - -CMTimeRangeTests.test("isIndefinite") { - expectFalse(r1.isIndefinite) - expectFalse(r2.isIndefinite) - expectFalse(r3.isIndefinite) -} - -CMTimeRangeTests.test("isEmpty") { - expectFalse(r1.isEmpty) - expectTrue(r2.isEmpty) - expectFalse(r3.isEmpty) -} - -CMTimeRangeTests.test("start/end") { - expectEqual(CMTimeMake(1, 1), r3.start) - expectEqual(CMTimeMake(5, 2), r3.end) -} - -CMTimeRangeTests.test("union") { - expectEqual(r1, r1.union(r2)) - expectEqual(r2, r2.union(r2)) - expectNotEqual(r3, r2.union(r3)) -} - -CMTimeRangeTests.test("intersection") { - expectEqual(r2, r1.intersection(r2)) - expectEqual(r2, r1.intersection(r3)) -} - -CMTimeRangeTests.test("contains") { - expectTrue(r1.containsTimeRange(r2)) - expectFalse(r2.containsTimeRange(r2)) - expectFalse(r2.containsTimeRange(r1)) - expectFalse(r3.containsTime(kCMTimeZero)) -} - -CMTimeRangeTests.test("operators") { - expectFalse(r1 == r2) - expectTrue(r1 != r2) -} - -runAllTests() - diff --git a/validation-test/stdlib/CryptoTokenKitTests.swift b/validation-test/stdlib/CryptoTokenKitTests.swift deleted file mode 100644 index e3497176c0b12..0000000000000 --- a/validation-test/stdlib/CryptoTokenKitTests.swift +++ /dev/null @@ -1,91 +0,0 @@ -// RUN: %target-typecheck-verify-swift - -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos -// UNSUPPORTED: OS=tvos -// UNSUPPORTED: OS=ios - -import CryptoTokenKit -import Security - -if #available(OSX 10.12, *) { - struct TKSmartCardTest { - func t1(manager: TKSmartCardSlotManager, name: String) { - manager.getSlot(withName: name) { (slot: TKSmartCardSlot?) in - let _: TKSmartCardSlot.State = slot!.state - } - } - - let p1 = TKSmartCardPINFormat.Charset.numeric - let p2 = TKSmartCardPINFormat.Encoding.ascii - let p3 = TKSmartCardPINFormat.Encoding.bcd - let p4 = TKSmartCardPINFormat.Justification.left - let p5 = TKSmartCardUserInteractionForPINOperation.Completion.key - let p6 = TKSmartCardUserInteractionForSecurePINChange.Confirmation.current - let p7 = TKSmartCardProtocol.t0 - let p8 = TKSmartCardProtocol.t1 - let p9 = TKSmartCardProtocol.t15 - let p10 = TKSmartCardATR.InterfaceGroup() - - func t2(card: TKSmartCard) throws { - card.isSensitive = card.isValid - card.transmit(Data()) { (response: Data?, error: Error?) in - } - - card.userInteractionForSecurePINVerification(TKSmartCardPINFormat(), - apdu: Data(), pinByteOffset: 0) - card.userInteractionForSecurePINChange(TKSmartCardPINFormat(), - apdu: Data(), currentPINByteOffset: 0, newPINByteOffset: 0) - - card.send(ins: 0xa4, p1: 0x04, p2: 0x00, data:Data(), le: 0) { - (response: Data?, sw: UInt16, error: Error?) in - } - - card.send(ins: 0xa4, p1: 0x04, p2: 0x00, le: 0) { - (response: Data?, sw: UInt16, error: Error?) in - } - - card.send(ins: 0xa4, p1: 0x04, p2: 0x00, data:Data()) { - (response: Data?, sw: UInt16, error: Error?) in - } - - card.send(ins: 0xa4, p1: 0x04, p2: 0x00) { - (response: Data?, sw: UInt16, error: Error?) in - } - - let _: Int = try card.withSession() { - let (_, _): (UInt16, Data) = try card.send(ins: 0xa4, p1: 0x04, - p2: 0x00, data: Data(), le: 0) - let (_, _): (UInt16, Data) = try card.send(ins: 0xa4, p1: 0x04, - p2: 0x00, le: 0) - let (_, _): (UInt16, Data) = try card.send(ins: 0xa4, p1: 0x04, - p2: 0x00, data: Data()) - let (_, _): (UInt16, Data) = try card.send(ins: 0xa4, p1: 0x04, - p2: 0x00) - return 1 - } - } - } - - struct TKTokenTest { - func f1(session: TKTokenSession, sessionDelegate: TKTokenSessionDelegate, - algorithm: TKTokenKeyAlgorithm, - parameters: TKTokenKeyExchangeParameters) throws { - let _: Bool = sessionDelegate.tokenSession!(session, supports: .none, - keyObjectID: "", algorithm: algorithm) - let _: Data = try sessionDelegate.tokenSession!(session, sign: Data(), - keyObjectID: "", algorithm: algorithm) - let _: Data = try sessionDelegate.tokenSession!(session, decrypt: Data(), - keyObjectID: "", algorithm: algorithm) - let _: Data = try sessionDelegate.tokenSession!(session, - performKeyExchange: Data(), keyObjectID: "", algorithm: algorithm, - parameters: parameters) - let _: Bool = algorithm.isAlgorithm(.rsaSignatureDigestPKCS1v15SHA1) - let _: Bool = algorithm.supportsAlgorithm(.rsaSignatureDigestPKCS1v15SHA1) - } - - func f2(token: TKToken, delegate: TKTokenDelegate) throws { - let _: TKTokenSession = try delegate.createSession(token) - } - } -} diff --git a/validation-test/stdlib/GameplayKit.swift b/validation-test/stdlib/GameplayKit.swift deleted file mode 100644 index 767416aec95e6..0000000000000 --- a/validation-test/stdlib/GameplayKit.swift +++ /dev/null @@ -1,133 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest - - -import GameplayKit - -// GameplayKit is only available on iOS 9.0 and above, OS X 10.11 and above, and -// tvOS 9.0 and above. - -var GamePlayKitTests = TestSuite("GameplayKit") - -if #available(OSX 10.12, iOS 10.0, tvOS 10.0, *) { - - GamePlayKitTests.test("GKPath_float2") { - let vec: [float2] = [float2(3.0), float2(4.0)] - let path = GKPath(points: vec, radius: Float(30), cyclical: true) - expectEqual(path.numPoints, 2) - expectEqual(path.radius, Float(30)) - expectEqual(path.isCyclical, true) - } - GamePlayKitTests.test("GKPath_float3") { - let vec: [float3] = [float3(3.0), float3(4.0)] - let path = GKPath(points: vec, radius: Float(30), cyclical: true) - expectEqual(path.numPoints, 2) - expectEqual(path.radius, Float(30)) - expectEqual(path.isCyclical, true) - } - GamePlayKitTests.test("GKPolygonObstacle") { - let vec = [float2(3.0, 3.0), float2(3.0, -3.0), float2(-3.0, 3.0), float2(-3.0, -3.0)] - let obstacle = GKPolygonObstacle(points: vec) - expectEqual(obstacle.vertexCount, 4) - } - GamePlayKitTests.test("GKEntity") { - @objc(MovementComponent) - class MovementComponent: GKComponent { - override func update(deltaTime seconds: TimeInterval) {} - override func didAddToEntity() {} - override func willRemoveFromEntity() {} - } - let comp = MovementComponent() - let entity = GKEntity() - entity.addComponent(comp) - expectEqual(entity.components.count, 1) - let grabbedComp = entity.component(ofType: MovementComponent.self) - expectEqual(grabbedComp, comp) - entity.removeComponent(ofType: MovementComponent.self) - expectEqual(entity.components.count, 0) - } -} - -if #available(OSX 10.11, iOS 9.0, tvOS 9.0, *) { - -class TestComponent : GKComponent {} -class OtherTestComponent : GKComponent {} - -class TestState1 : GKState {} -class TestState2 : GKState {} - -GamePlayKitTests.test("GKEntity.component(ofType)") { - let entity = GKEntity() - entity.addComponent(TestComponent()) - - do { - var componentForTestComponent = - entity.component(ofType: TestComponent.self) - var componentForOtherTestComponent_nil = - entity.component(ofType: OtherTestComponent.self) - - expectNotNil(componentForTestComponent) - expectType(Optional.self, &componentForTestComponent) - - expectNil(componentForOtherTestComponent_nil) - } - - entity.removeComponent(ofType: TestComponent.self) - entity.addComponent(OtherTestComponent()) - - do { - var componentForOtherTestComponent = - entity.component(ofType: OtherTestComponent.self) - var componentForTestComponent_nil = - entity.component(ofType: TestComponent.self) - - expectNotNil(componentForOtherTestComponent) - expectType(Optional.self, &componentForOtherTestComponent) - - expectNil(componentForTestComponent_nil) - } -} - -GamePlayKitTests.test("GKStateMachine.state(forClass:)") { - do { - // Construct a state machine with a custom subclass as the only state. - let stateMachine = GKStateMachine( - states: [TestState1()]) - - var stateForTestState1 = - stateMachine.state(forClass: TestState1.self) - var stateForTestState2_nil = - stateMachine.state(forClass: TestState2.self) - - expectNotNil(stateForTestState1) - expectType(Optional.self, &stateForTestState1) - - expectNil(stateForTestState2_nil) - } - - do { - // Construct a state machine with a custom subclass as the only state. - let stateMachine = GKStateMachine( - states: [TestState2()]) - - var stateForTestState2 = - stateMachine.state(forClass: TestState2.self) - var stateForTestState1_nil = - stateMachine.state(forClass: TestState1.self) - - expectNotNil(stateForTestState2) - expectType(Optional.self, &stateForTestState2) - - expectNil(stateForTestState1_nil) - } -} - -} // if #available(OSX 10.11, iOS 9.0, tvOS 9.0, *) - -runAllTests() - diff --git a/validation-test/stdlib/IOKitOverlay.swift b/validation-test/stdlib/IOKitOverlay.swift deleted file mode 100644 index 9c057a71f0da2..0000000000000 --- a/validation-test/stdlib/IOKitOverlay.swift +++ /dev/null @@ -1,24 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test -// REQUIRES: OS=macosx - -import IOKit -import IOKit.hid -import StdlibUnittest - - -var IOKitTests = TestSuite("IOKit") - -IOKitTests.test("IOReturn value") { - // Error codes are computed by a helper function so it's enough to test one. - // The value is taken from the OS X 10.11 SDK. - expectEqual(Int(kIOReturnStillOpen), -536870190) -} - -IOKitTests.test("IOReturn type") { - let manager = IOHIDManagerCreate(nil, 0) - let result = IOHIDManagerClose(manager, 0) - expectTrue(type(of: result) == type(of: kIOReturnNotOpen)) -} - -runAllTests() diff --git a/validation-test/stdlib/ModelIO.swift b/validation-test/stdlib/ModelIO.swift deleted file mode 100644 index a1bd1f907ec63..0000000000000 --- a/validation-test/stdlib/ModelIO.swift +++ /dev/null @@ -1,334 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test -// UNSUPPORTED: OS=watchos -// REQUIRES: objc_interop - -import StdlibUnittest - -import Foundation -import ModelIO - -var ModelIOTests = TestSuite("ModelIO") - -if #available(OSX 10.13, iOS 11.0, tvOS 11.0, *) { - ModelIOTests.test("MDLAnimatedScalar/accessors") - .skip(.always("rdar://problem/50449570")).code { - let animatedVal = MDLAnimatedScalar() - let testCount = 10 - let testTimeVal = 5.0 - let testFloatVal:Float = 1.0 - let testDoubleVal = Double(testFloatVal) - let fArray = [Float](repeating: testFloatVal, count: testCount) - let dArray = [Double](repeating: testDoubleVal, count: testCount) - var times = [TimeInterval](repeating: testTimeVal, count: testCount) - animatedVal.reset(floatArray: fArray, atTimes: times) - let floats = animatedVal.floatArray - animatedVal.reset(doubleArray: dArray, atTimes: times) - let doubles = animatedVal.doubleArray - times = animatedVal.times - - expectEqual(floats.count, testCount) - expectEqual(doubles.count, testCount) - expectEqual(times.count, testCount) - - for idx in 0.. -// -// Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") -// in consideration of your agreement to the following terms, and your use, -// installation, modification or redistribution of this Apple software -// constitutes acceptance of these terms. If you do not agree with these -// terms, please do not use, install, modify or redistribute this Apple -// software. -// -// In consideration of your agreement to abide by the following terms, and -// subject to these terms, Apple grants you a personal, non - exclusive -// license, under Apple's copyrights in this original Apple software (the -// "Apple Software"), to use, reproduce, modify and redistribute the Apple -// Software, with or without modifications, in source and / or binary forms -// provided that if you redistribute the Apple Software in its entirety and -// without modifications, you must retain this notice and the following text -// and disclaimers in all such redistributions of the Apple Software. Neither -// the name, trademarks, service marks or logos of Apple Inc. may be used to -// endorse or promote products derived from the Apple Software without specific -// prior written permission from Apple. Except as expressly stated in this -// notice, no other rights or licenses, express or implied, are granted by -// Apple herein, including but not limited to any patent rights that may be -// infringed by your derivative works or by other works in which the Apple -// Software may be incorporated. -// -// The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO -// WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED -// WARRANTIES OF NON - INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A -// PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION -// ALONE OR IN COMBINATION WITH YOUR PRODUCTS. -// -// IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION -// AND / OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER -// UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR -// OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Copyright (C) 2008 Apple Inc. All Rights Reserved. -// - - -import OpenCL -import StdlibUnittest - - -import Foundation -import Darwin - -let KernelSource = "\n" + -"__kernel void square( \n" + -" __global float* input, \n" + -" __global float* output, \n" + -" const unsigned int count) \n" + -"{ \n" + -" int i = get_global_id(0); \n" + -" if (i < count) \n" + -" output[i] = input[i] * input[i]; \n" + -"} \n" + -"\n" - - -let DATA_SIZE = 1024 - -var tests = TestSuite("MiscSDKOverlay") - -tests.test("clSetKernelArgsListAPPLE") { - var err: cl_int // error code returned from api calls - - var data = [Float](repeating: 0, count: DATA_SIZE) // original data set given to device - var results = [Float](repeating: 0, count: DATA_SIZE) // results returned from device - var correct: Int // number of correct results returned - - var global: size_t // global domain size for our calculation - var local: size_t = 0 // local domain size for our calculation - - var device_id: cl_device_id? = nil // compute device id - var context: cl_context? // compute context - var commands: cl_command_queue? // compute command queue - var program: cl_program? // compute program - var kernel: cl_kernel? // compute kernel - - // Fill our data set with random float values - // - var count = DATA_SIZE - for i in 0..) -> cl_program in - var s: UnsafePointer? = p - return withUnsafeMutablePointer(to: &s) { - return clCreateProgramWithSource(context, 1, $0, nil, &err) - } - } - if (program == nil) - { - print("Error: Failed to create compute program!") - exit(EXIT_FAILURE) - } - - // Build the program executable - // - err = clBuildProgram(program, 0, nil, nil, nil, nil) - if (err != CL_SUCCESS) - { - var len: Int = 0 - - var buffer = [CChar](repeating: 0, count: 2048) - - print("Error: Failed to build program executable!") - clGetProgramBuildInfo( - program, device_id, cl_program_build_info(CL_PROGRAM_BUILD_LOG), 2048, &buffer, &len) - print("\(String(cString: buffer))") - exit(1) - } - - // Create the compute kernel in the program we wish to run - // - kernel = clCreateKernel(program, "square", &err) - if (kernel == nil || err != cl_int(CL_SUCCESS)) - { - print("Error: Failed to create compute kernel!") - exit(1) - } - - // Create the input and output arrays in device memory for our calculation - // - guard var input = clCreateBuffer(context, cl_mem_flags(CL_MEM_READ_ONLY), MemoryLayout.size * count, nil, nil), - var output = clCreateBuffer(context, cl_mem_flags(CL_MEM_WRITE_ONLY), MemoryLayout.size * count, nil, nil) else { - print("Error: Failed to allocate device memory!") - exit(1) - } - - // Write our data set into the input array in device memory - // - err = clEnqueueWriteBuffer(commands, input, cl_bool(CL_TRUE), 0, MemoryLayout.size * count, data, 0, nil, nil) - if (err != CL_SUCCESS) - { - print("Error: Failed to write to source array!") - exit(1) - } - - // Set the arguments to our compute kernel - // - err = 0 - err = withUnsafePointer(to: &input) { - inputPtr in withUnsafePointer(to: &output) { - outputPtr in withUnsafePointer(to: &count) { - countPtr in - clSetKernelArgsListAPPLE( - kernel!, 3, - 0, MemoryLayout.size, inputPtr, - 1, MemoryLayout.size, outputPtr, - 2, MemoryLayout.size(ofValue: countPtr.pointee), countPtr) - } - } - } - - - if (err != CL_SUCCESS) - { - print("Error: Failed to set kernel arguments! \(err)") - exit(1) - } - - // Get the maximum work group size for executing the kernel on the device - // - err = clGetKernelWorkGroupInfo(kernel, device_id, cl_kernel_work_group_info(CL_KERNEL_WORK_GROUP_SIZE), MemoryLayout.size(ofValue: local), &local, nil) - if (err != CL_SUCCESS) - { - print("Error: Failed to retrieve kernel work group info! \(err)") - exit(1) - } - - // Execute the kernel over the entire range of our 1d input data set - // using the maximum number of work group items for this device - // - global = count - err = clEnqueueNDRangeKernel(commands, kernel, 1, nil, &global, &local, 0, nil, nil) - if (err != 0) - { - print("Error: Failed to execute kernel!") - exit(EXIT_FAILURE) - } - - // Wait for the command commands to get serviced before reading back results - // - clFinish(commands) - - // Read back the results from the device to verify the output - // - err = clEnqueueReadBuffer(commands, output, cl_bool(CL_TRUE), 0, MemoryLayout.size * count, &results, cl_uint(0), nil, nil) - if (err != CL_SUCCESS) - { - print("Error: Failed to read output array! \(err)") - exit(1) - } - - // Validate our results - // - correct = 0 - for i in 0..! - let collectionsFetch: PHFetchResult! - let listsFetch: PHFetchResult! - - func testPHChange(change: PHChange) { - let assetDetails: PHObjectChangeDetails? - = change.changeDetails(for: asset) - let collectionDetails: PHObjectChangeDetails? - = change.changeDetails(for: collection) - let listDetails: PHObjectChangeDetails? - = change.changeDetails(for: list) - - let assetsFetchDetails: PHFetchResultChangeDetails? - = change.changeDetails(for: assetsFetch) - let collectionsFetchDetails: PHFetchResultChangeDetails? - = change.changeDetails(for: collectionsFetch) - let listsFetchDetails: PHFetchResultChangeDetails? - = change.changeDetails(for: listsFetch) - assert(assetDetails != nil) - assert(collectionDetails != nil) - assert(listDetails != nil) - assert(assetsFetchDetails != nil) - assert(collectionsFetchDetails != nil) - assert(listsFetchDetails != nil) - } - } -} - -#elseif os(macOS) - -if #available(macOS 10.14, *) { - // compile time only validation test for the SDK overlay, - // because PHProjectChangeRequest pretty much requires a GUI app - struct GenericPHProjectChangeRequest { - let asset: PHAsset! - let assetsFetch: PHFetchResult! - - func testPHProjectChangeRequest(changeRequest: PHProjectChangeRequest) { - changeRequest.removeAssets(assetsFetch) - changeRequest.removeAssets([asset]) - } - } - -} - -#endif diff --git a/validation-test/stdlib/SafariServices.swift b/validation-test/stdlib/SafariServices.swift deleted file mode 100644 index 22b03765ad137..0000000000000 --- a/validation-test/stdlib/SafariServices.swift +++ /dev/null @@ -1,20 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: OS=macosx -// REQUIRES: objc_interop - -import StdlibUnittest - -import Foundation -import SafariServices - -var SafariServicesTests = TestSuite("SafariServices") -if #available(OSX 10.12, *) { - SafariServicesTests.test("API") { - _ = SFSafariServicesAvailable() - _ = SFSafariServicesAvailable(.version10_0) - _ = SFSafariServicesAvailable(.version10_1) - } -} -runAllTests() diff --git a/validation-test/stdlib/SceneKit.swift b/validation-test/stdlib/SceneKit.swift deleted file mode 100644 index 7ac2955afaa6f..0000000000000 --- a/validation-test/stdlib/SceneKit.swift +++ /dev/null @@ -1,429 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: objc_interop -// UNSUPPORTED: OS=watchos - -import StdlibUnittest - - -import SceneKit - -// SceneKit is only available on iOS 8.0 and above and on OS X 10.8 and above. - -var SceneKitTests = TestSuite("SceneKit") - -func bytesFromNSData(_ data: NSData) -> [UInt8] { - let bytePtr = data.bytes.bindMemory(to: UInt8.self, capacity: data.length) - return Array(UnsafeBufferPointer(start: bytePtr, count: data.length)) -} - -func floatsFromNSData(_ data: NSData) -> [Float] { - let floatPtr = data.bytes.bindMemory(to: Float.self, capacity: data.length) - return Array(UnsafeBufferPointer(start: floatPtr, count: data.length / MemoryLayout.size)) -} - -if #available(iOS 8.0, *) { - SceneKitTests.test("SCNGeometryElement.init(indices:primitiveType:)/Int") { - let element = SCNGeometryElement( - indices: [ 1, 2, Int.max, 4, 5, 6 ], - primitiveType: .triangles) - - expectEqual(.triangles, element.primitiveType) - expectEqual(2, element.primitiveCount) - #if arch(i386) || arch(arm) - expectEqual( - [ - 1,0,0,0, - 2,0,0,0, - 0xff,0xff,0xff,0x7f, - 4,0,0,0, - 5,0,0,0, - 6,0,0,0, - ], - bytesFromNSData(element.data as NSData)) - expectEqual(4, element.bytesPerIndex) - #elseif arch(x86_64) || arch(arm64) - expectEqual( - [ - 1,0,0,0, 0,0,0,0, - 2,0,0,0, 0,0,0,0, - 0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0x7f, - 4,0,0,0, 0,0,0,0, - 5,0,0,0, 0,0,0,0, - 6,0,0,0, 0,0,0,0, - ], - bytesFromNSData(element.data as NSData)) - expectEqual(8, element.bytesPerIndex) - #else - _portThisCode() - #endif - } - - SceneKitTests.test("SCNGeometryElement.init(indices:primitiveType:)/Int16") { - let element = SCNGeometryElement( - indices: [ 1, 2, Int16.max, Int16.max/2, 5, 6 ] as [Int16], - primitiveType: .triangles) - - expectEqual(.triangles, element.primitiveType) - expectEqual(2, element.primitiveCount) - expectEqual( - [ - 1, 0, - 2, 0, - 0xff, 0x7f, - 0xff, 0x3f, - 5, 0, - 6, 0 - ], - bytesFromNSData(element.data as NSData)) - expectEqual(2, element.bytesPerIndex) - } - - SceneKitTests.test("SCNGeometryElement.init(indices:primitiveType:)/Triangles") { - let element = SCNGeometryElement( - indices: [ 1, 2, UInt8.max, UInt8.max/2, 5, 6 ] as [UInt8], - primitiveType: .triangles) - - expectEqual(.triangles, element.primitiveType) - expectEqual(2, element.primitiveCount) - expectEqual( - [ 1, 2, UInt8.max, UInt8.max/2, 5, 6 ], - bytesFromNSData(element.data as NSData)) - expectEqual(1, element.bytesPerIndex) - } - - SceneKitTests.test("SCNGeometryElement.init(indices:primitiveType:)/TriangleStrip") { - let element = SCNGeometryElement( - indices: [ 1, 2, 3, 4, 5, 6 ] as [UInt8], - primitiveType: .triangleStrip) - - expectEqual(.triangleStrip, element.primitiveType) - expectEqual(4, element.primitiveCount) - expectEqual( - [ 1, 2, 3, 4, 5, 6 ], - bytesFromNSData(element.data as NSData)) - expectEqual(1, element.bytesPerIndex) - } - - SceneKitTests.test("SCNGeometryElement.init(indices:primitiveType:)/Line") { - let element = SCNGeometryElement( - indices: [ 1, 2, 3, 4, 5, 6 ] as [UInt8], - primitiveType: .line) - - expectEqual(.line, element.primitiveType) - expectEqual(3, element.primitiveCount) - expectEqual( - [ 1, 2, 3, 4, 5, 6 ], - bytesFromNSData(element.data as NSData)) - expectEqual(1, element.bytesPerIndex) - } - - SceneKitTests.test("SCNGeometryElement.init(indices:primitiveType:)/Point") { - let element = SCNGeometryElement( - indices: [ 1, 2, 3, 4, 5, 6 ] as [UInt8], - primitiveType: .point) - - expectEqual(.point, element.primitiveType) - expectEqual(6, element.primitiveCount) - expectEqual( - [ 1, 2, 3, 4, 5, 6 ], - bytesFromNSData(element.data as NSData)) - expectEqual(1, element.bytesPerIndex) - } - - SceneKitTests.test("SCNGeometrySource.init(vertices:)") { - let source = SCNGeometrySource(vertices: [SCNVector3(1, 2, 3), - SCNVector3(4, 5, 6)]) - - expectEqual(source.semantic, SCNGeometrySource.Semantic.vertex) - expectEqual(source.vectorCount, 2) - expectEqual(source.componentsPerVector, 3) - - expectEqual(source.bytesPerComponent, MemoryLayout.size) - let positions = floatsFromNSData(source.data as NSData) - expectEqual(positions[2], 3) - expectEqual(positions[4], 5) - } - - SceneKitTests.test("SCNGeometrySource.init(normals:)") { - let source = SCNGeometrySource(normals: [SCNVector3(1, 2, 3), - SCNVector3(4, 5, 6)]) - - expectEqual(source.semantic, SCNGeometrySource.Semantic.normal) - expectEqual(source.vectorCount, 2) - expectEqual(source.componentsPerVector, 3) - - expectEqual(source.bytesPerComponent, MemoryLayout.size) - let normals = floatsFromNSData(source.data as NSData) - expectEqual(normals[2], 3) - expectEqual(normals[4], 5) - } - - SceneKitTests.test("SCNGeometrySource.init(textureCoordinates:)") { - let source = SCNGeometrySource(textureCoordinates: [CGPoint(x: 1, y: 2), - CGPoint(x: 4, y: 5)]) - - expectEqual(source.semantic, SCNGeometrySource.Semantic.texcoord) - expectEqual(source.vectorCount, 2) - expectEqual(source.componentsPerVector, 2) - - let uvs = floatsFromNSData(source.data as NSData) - expectEqual(uvs[1], 2) - expectEqual(uvs[3], 5) - } - - SceneKitTests.test("SCNSceneSource.entryWithIdentifier(uid:withClass:)") - .skip(.iOSAny("does not support COLLADA files")) - .skip(.iOSSimulatorAny("does not support COLLADA files")) - .skip(.tvOSAny("does not support COLLADA files")) - .skip(.tvOSSimulatorAny("does not support COLLADA files")) - .skip(.watchOSAny("does not support COLLADA files")) - .skip(.watchOSSimulatorAny("does not support COLLADA files")) - .code { - let sceneDescription = - "" + - "" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " 0.022516" + - " " + - " " + - " 1" + - " " + - " " + - " 1" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " 0.022516" + - " " + - " " + - " 1" + - " " + - " " + - " 1" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " -5 -5 0 5 -5 0 -5 5 0 5 5 0 " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " 0 0 1 0 0 1 0 0 1 0 0 1 " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " 0 0 1 0 0 1 1 1 " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - "

0 1 3 0 3 2

" + - "
" + - "
" + - "
" + - " " + - " " + - " " + - " -2.5 -2.5 2.5 -2.5 2.5 2.5 2.5 -2.5 2.5 2.5 2.5 2.5 2.5 -2.5 2.5 2.5 2.5 2.5 2.5 -2.5 -2.5 2.5 2.5 -2.5 2.5 -2.5 -2.5 2.5 2.5 -2.5 -2.5 -2.5 -2.5 -2.5 2.5 -2.5 -2.5 -2.5 -2.5 -2.5 2.5 -2.5 -2.5 -2.5 2.5 -2.5 2.5 2.5 -2.5 2.5 2.5 -2.5 2.5 -2.5 2.5 2.5 2.5 2.5 2.5 -2.5 -2.5 -2.5 -2.5 -2.5 -2.5 2.5 2.5 -2.5 -2.5 2.5 -2.5 2.5 " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " 0 0 1 0 0 1 0 0 1 0 0 1 1 0 -4.37114e-08 1 0 -4.37114e-08 1 0 -4.37114e-08 1 0 -4.37114e-08 -8.74228e-08 0 -1 -8.74228e-08 0 -1 -8.74228e-08 0 -1 -8.74228e-08 0 -1 -1 0 1.19249e-08 -1 0 1.19249e-08 -1 0 1.19249e-08 -1 0 1.19249e-08 0 1 -4.37114e-08 0 1 -4.37114e-08 0 1 -4.37114e-08 0 1 -4.37114e-08 0 -1 -4.37114e-08 0 -1 -4.37114e-08 0 -1 -4.37114e-08 0 -1 -4.37114e-08 " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " 0 0 0 1 1 0 1 1 0 0 0 1 1 0 1 1 0 0 0 1 1 0 1 1 0 0 0 1 1 0 1 1 0 0 0 1 1 0 1 1 0 0 0 1 1 0 1 1 " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - "

0 3 1 0 2 3 4 7 5 4 6 7 8 11 9 8 10 11 12 15 13 12 14 15 16 19 17 16 18 19 20 23 21 20 22 23

" + - "
" + - "
" + - "
" + - "
" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - "
" - - let sceneData = sceneDescription.data( - using: .utf8, - allowLossyConversion: true)! - let sceneSource = SCNSceneSource(data: sceneData as Data, options: nil)! - - do { - var unarchivedPlaneGeometry = - sceneSource.entryWithIdentifier("plane", withClass: SCNGeometry.self) - var unarchivedPlaneNode_nil = - sceneSource.entryWithIdentifier("plane-node", withClass: SCNNode.self) - - expectNotNil(unarchivedPlaneGeometry) - expectType(Optional.self, &unarchivedPlaneGeometry) - - expectNil(unarchivedPlaneNode_nil) - } - - do { - var unarchivedBoxGeometry = - sceneSource.entryWithIdentifier("box", withClass: SCNGeometry.self) - var unarchivedBoxGeometry_nil = - sceneSource.entryWithIdentifier("box-node", withClass: SCNGeometry.self) - - expectNotNil(unarchivedBoxGeometry) - expectType(Optional.self, &unarchivedBoxGeometry) - - expectNil(unarchivedBoxGeometry_nil) - } - - do { - var unarchivedBoxNode = - sceneSource.entryWithIdentifier("box-node", withClass: SCNNode.self) - var unarchivedBoxNode_nil = - sceneSource.entryWithIdentifier("box", withClass: SCNNode.self) - - expectNotNil(unarchivedBoxNode) - expectType(Optional.self, &unarchivedBoxNode) - - expectNil(unarchivedBoxNode_nil) - } - } - - if #available(OSX 10.10, *) { - SceneKitTests.test("SCNBoundingVolume.boundingBox/getter") { - let box = SCNBox(width: 42, height: 0.5, length: 1337, chamferRadius: 0) - let boundingBox = box.boundingBox - - expectEqual(boundingBox.max.x, 21) - expectEqual(boundingBox.max.x, -boundingBox.min.x) - expectEqual(boundingBox.max.y, 0.25) - expectEqual(boundingBox.max.y, -boundingBox.min.y) - expectEqual(boundingBox.max.z, 668.5) - expectEqual(boundingBox.max.z, -boundingBox.min.z) - } - - SceneKitTests.test("SCNBoundingVolume.boundingBox/setter") { - let max = SCNVector3(42, 0.414, 1337) - let min = SCNVector3(-42, -0.414, -1337) - let box = SCNBox(width: 1, height: 2, length: 3, chamferRadius: 0) - let boxNode = SCNNode(geometry: box) - - boxNode.boundingBox = (min, max) - let nodeBoundingBox = boxNode.boundingBox - - expectEqual(nodeBoundingBox.max.x, max.x) - expectEqual(nodeBoundingBox.min.x, -max.x) - expectEqual(nodeBoundingBox.max.y, max.y) - expectEqual(nodeBoundingBox.min.y, -max.y) - expectEqual(nodeBoundingBox.max.z, max.z) - expectEqual(nodeBoundingBox.min.z, -max.z) - } - - SceneKitTests.test("SCNBoundingVolume.boundingSphere/getter") { - let box = SCNBox(width: 2 * 2, height: 3 * 2, length: 6 * 2, chamferRadius: 0) - let boundingSphere = box.boundingSphere - - // 2^2 + 3^2 + 6^2 = 7^2 - expectEqual(boundingSphere.radius, 7.0) - } - } -} - -runAllTests() - diff --git a/validation-test/stdlib/SpriteKit.swift b/validation-test/stdlib/SpriteKit.swift deleted file mode 100644 index a90e91a3e919c..0000000000000 --- a/validation-test/stdlib/SpriteKit.swift +++ /dev/null @@ -1,87 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: objc_interop - -import StdlibUnittest - -import Foundation -import SpriteKit - -var SpriteKitTests = TestSuite("SpriteKit") - -// Check that the subscript is there. -@available(OSX,introduced: 10.10) -@available(iOS,introduced: 8.0) -@available(tvOS,introduced: 8.0) -@available(watchOS,introduced: 2.0) -func testSubscript(_ node: SKNode) { - var result = node["me"] - expectType(Array.self, &result) -} - -SpriteKitTests.test("SKColor/TypeEquivalence") { - // SKColor is NSColor on OS X and UIColor on iOS. -#if os(OSX) - expectEqualType(NSColor.self, SKColor.self) -#elseif os(iOS) || os(tvOS) || os(watchOS) - expectEqualType(UIColor.self, SKColor.self) -#else - _UnknownOSError() -#endif -} - -SpriteKitTests.test("getRed(_:green:blue:alpha:)") { - var r: CGFloat = 0.0 - var g: CGFloat = 0.0 - var b: CGFloat = 0.0 - var a: CGFloat = 0.0 - let color = SKColor.red - color.getRed(&r, green: &g, blue: &b, alpha: &a) - expectEqual(1.0, r) - expectEqual(0.0, g) - expectEqual(0.0, b) - expectEqual(1.0, a) -} - -if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { - SpriteKitTests.test("SKNode.setValue(_:forAttribute:)") { - let node = SKSpriteNode() - let attrVal = SKAttributeValue(float: 2.0) - node.setValue(attrVal, forAttribute: "test") - expectEqual(node.attributeValues["test"], attrVal) - } - - SpriteKitTests.test("SKWarpGeometryGrid/init") { - var warpGrid = SKWarpGeometryGrid(columns: 1, rows: 1) - - expectEqual(warpGrid.sourcePosition(at: 0).x, 0.0) - warpGrid = warpGrid.replacingBySourcePositions(positions: [float2(1.0), float2(2.0), float2(3.0), float2(4.0)]) - expectEqual(warpGrid.sourcePosition(at: 0).x, 1.0) - - expectEqual(warpGrid.destPosition(at: 0).x, 0.0) - warpGrid = warpGrid.replacingByDestinationPositions(positions: [float2(1.0), float2(2.0), float2(3.0), float2(4.0)]) - expectEqual(warpGrid.destPosition(at: 0).x, 1.0) - - warpGrid = SKWarpGeometryGrid(columns: 1, rows: 1, destinationPositions: [float2(1.0), float2(2.0), float2(3.0), float2(4.0)]) - expectEqual(warpGrid.destPosition(at: 0).x, 1.0) - expectEqual(warpGrid.sourcePosition(at: 0).x, 0.0) - - warpGrid = SKWarpGeometryGrid(columns: 1, rows: 1, sourcePositions: [float2(1.0), float2(2.0), float2(3.0), float2(4.0)]) - expectEqual(warpGrid.destPosition(at: 0).x, 0.0) - expectEqual(warpGrid.sourcePosition(at: 0).x, 1.0) - - warpGrid = SKWarpGeometryGrid(columns: 1, rows: 1, sourcePositions: [float2(2.0), float2(1.0), float2(3.0), float2(4.0)], destinationPositions: [float2(1.0), float2(2.0), float2(3.0), float2(4.0)]) - expectEqual(warpGrid.destPosition(at: 0).x, 1.0) - expectEqual(warpGrid.sourcePosition(at: 0).x, 2.0) - } - - SpriteKitTests.test("SKWarpGeometryGrid/properties") { - func checkTheAPIsAreAvailable(grid: SKWarpGeometryGrid) { - _ = grid.replacingBySourcePositions(positions: []) - _ = grid.replacingByDestinationPositions(positions: []) - } - } -} - -runAllTests() diff --git a/validation-test/stdlib/UnsafeBufferPointer.swift.gyb b/validation-test/stdlib/UnsafeBufferPointer.swift.gyb index 2ed995338afec..fc20dfb6bd2a6 100644 --- a/validation-test/stdlib/UnsafeBufferPointer.swift.gyb +++ b/validation-test/stdlib/UnsafeBufferPointer.swift.gyb @@ -362,7 +362,7 @@ UnsafeMutableBufferPointerTestSuite.test("withContiguous(Mutable)StorageIfAvaila } UnsafeMutableBufferPointerTestSuite.test("Slice.withContiguousStorageIfAvailable") { - guard #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) else { + guard #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) else { return } diff --git a/validation-test/stdlib/WatchKit.swift b/validation-test/stdlib/WatchKit.swift deleted file mode 100644 index 59076305ed24b..0000000000000 --- a/validation-test/stdlib/WatchKit.swift +++ /dev/null @@ -1,37 +0,0 @@ -// RUN: %target-run-simple-swift -// REQUIRES: executable_test - -// REQUIRES: objc_interop -// REQUIRES: OS=watchos - -import StdlibUnittest - - -import WatchKit - -var WatchKitTests = TestSuite("WatchKit") - -if #available(iOS 8.2, *) { -// This is a very weak test, but we can't do better without spawning a GUI app. -WatchKitTests.test("WKInterfaceController/reloadRootControllers(_:)") { - WKInterfaceController.reloadRootControllers(withNamesAndContexts: []) -} - -// This is a very weak test, but we can't do better without spawning a GUI app. -WatchKitTests.test("WKInterfaceController/presentController(_:)") { - let curried = WKInterfaceController.presentController(withNamesAndContexts:) - typealias ExpectedType = - (WKInterfaceController) -> ([(name: String, context: AnyObject)]) -> Void - let checkType: ExpectedType = curried - _blackHole(checkType) - - // FIXME: can't write the following line: rdar://20985062 - // expectType(ExpectedType.self, &curried) - - let curried2 = WKInterfaceController.presentController(withNamesAndContexts:) as ExpectedType -} - -} // #available(iOS 8.2, *) - -runAllTests() -