code
stringlengths 3
10M
| language
stringclasses 31
values |
|---|---|
/home/hustccc/OS_Tutorial_Summer_of_Code/Rust_Learning_Code/csv_challenge/target/release/deps/csv_challenge-fbee5b8060c19996: src/main.rs
/home/hustccc/OS_Tutorial_Summer_of_Code/Rust_Learning_Code/csv_challenge/target/release/deps/csv_challenge-fbee5b8060c19996.d: src/main.rs
src/main.rs:
|
D
|
/Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Pods.build/Debug-iphonesimulator/Macaw.build/Objects-normal/x86_64/Rect.o : /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/export/MacawView+PDF.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAMediaTimingFillMode_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAMediaTimingFunctionName_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/MDisplayLink_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAShapeLayerLineJoin_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/MBezierPath+Extension_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/Common_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAShapeLayerLineCap_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/Graphics_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/MView_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAMediaTimingFillMode_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAMediaTimingFunctionName_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/iOS/MDisplayLink_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAShapeLayerLineJoin_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/iOS/Common_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAShapeLayerLineCap_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/iOS/Graphics_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/iOS/MView_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Arc.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/AnimationSequence.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Node.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Image.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/utils/UIImage2Image.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/Cache/AnimationCache.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Stroke.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/views/Touchable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/Cache/NodeHashable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/Cache/TransformHashable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/bindings/Variable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/AnimatableVariable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/Interpolable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/bindings/Disposable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/bindings/GroupDisposable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Drawable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/thirdparty/CGFloat+Double.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Circle.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Line.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Baseline.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Polyline.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Shape.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/PathSegmentType.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/thirdparty/NSTimer+Closure.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/thirdparty/CAAnimationClosure.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Ellipse.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Size.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/Easing.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Path.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/MDisplayLink.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Fill.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/AnimationImpl.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/views/MacawZoom.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Transform.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Align.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/LineJoin.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Polygon.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/StrokeInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/DoubleInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/ShapeInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/FillInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/TransformInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/ContentsInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/LocusInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/Animation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/CombineAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/ShapeAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/MorphingAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/TransformAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/ContentsAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/OpacityAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/TimingFunction.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Pattern.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/MoveTo.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/AspectRatio.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/LineCap.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Stop.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Group.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/AnimationProducer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/PathBuilder.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/NodeRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/ImageRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/ShapeRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/GroupRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/TextRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGParser.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/CSSParser.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/views/ShapeLayer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGSerializer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Color.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGParserError.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/MorphingGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/TransformGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/ShapeAnimationGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/CombinationAnimationGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/OpacityGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/GaussianBlur.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGCanvas.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/FuncBounds.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/PathBounds.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/utils/CGMappings.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/SceneUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/GeomUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/AnimationUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/RenderUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/utils/BoundsUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/utils/DescriptionExtensions.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/PathFunctions.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/AnimOperators.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Insets.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGConstants.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Locus.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/TransformedLocus.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Rect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/RoundRect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Effect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/AlphaEffect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/BlendEffect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/OffsetEffect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/ColorMatrixEffect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Gradient.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/RadialGradient.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/LinearGradient.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/PathSegment.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/Event.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/RotateEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/PinchEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/TouchEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/PanEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/TapEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Point.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Font.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGNodeLayout.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/layout/ContentLayout.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Text.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/RenderContext.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGView.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/views/MacawView.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/ColorMatrix.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Debug-iphonesimulator/SWXMLHash/SWXMLHash.framework/Modules/SWXMLHash.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Target\ Support\ Files/SWXMLHash/SWXMLHash-umbrella.h /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Target\ Support\ Files/Macaw/Macaw-umbrella.h /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Debug-iphonesimulator/SWXMLHash/SWXMLHash.framework/Headers/SWXMLHash-Swift.h /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Pods.build/Debug-iphonesimulator/Macaw.build/unextended-module.modulemap /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Pods.build/Debug-iphonesimulator/SWXMLHash.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Pods.build/Debug-iphonesimulator/Macaw.build/Objects-normal/x86_64/Rect~partial.swiftmodule : /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/export/MacawView+PDF.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAMediaTimingFillMode_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAMediaTimingFunctionName_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/MDisplayLink_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAShapeLayerLineJoin_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/MBezierPath+Extension_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/Common_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAShapeLayerLineCap_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/Graphics_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/MView_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAMediaTimingFillMode_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAMediaTimingFunctionName_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/iOS/MDisplayLink_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAShapeLayerLineJoin_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/iOS/Common_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAShapeLayerLineCap_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/iOS/Graphics_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/iOS/MView_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Arc.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/AnimationSequence.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Node.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Image.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/utils/UIImage2Image.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/Cache/AnimationCache.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Stroke.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/views/Touchable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/Cache/NodeHashable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/Cache/TransformHashable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/bindings/Variable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/AnimatableVariable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/Interpolable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/bindings/Disposable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/bindings/GroupDisposable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Drawable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/thirdparty/CGFloat+Double.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Circle.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Line.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Baseline.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Polyline.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Shape.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/PathSegmentType.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/thirdparty/NSTimer+Closure.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/thirdparty/CAAnimationClosure.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Ellipse.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Size.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/Easing.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Path.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/MDisplayLink.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Fill.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/AnimationImpl.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/views/MacawZoom.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Transform.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Align.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/LineJoin.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Polygon.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/StrokeInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/DoubleInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/ShapeInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/FillInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/TransformInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/ContentsInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/LocusInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/Animation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/CombineAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/ShapeAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/MorphingAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/TransformAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/ContentsAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/OpacityAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/TimingFunction.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Pattern.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/MoveTo.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/AspectRatio.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/LineCap.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Stop.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Group.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/AnimationProducer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/PathBuilder.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/NodeRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/ImageRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/ShapeRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/GroupRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/TextRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGParser.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/CSSParser.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/views/ShapeLayer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGSerializer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Color.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGParserError.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/MorphingGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/TransformGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/ShapeAnimationGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/CombinationAnimationGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/OpacityGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/GaussianBlur.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGCanvas.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/FuncBounds.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/PathBounds.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/utils/CGMappings.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/SceneUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/GeomUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/AnimationUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/RenderUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/utils/BoundsUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/utils/DescriptionExtensions.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/PathFunctions.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/AnimOperators.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Insets.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGConstants.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Locus.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/TransformedLocus.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Rect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/RoundRect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Effect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/AlphaEffect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/BlendEffect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/OffsetEffect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/ColorMatrixEffect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Gradient.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/RadialGradient.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/LinearGradient.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/PathSegment.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/Event.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/RotateEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/PinchEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/TouchEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/PanEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/TapEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Point.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Font.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGNodeLayout.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/layout/ContentLayout.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Text.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/RenderContext.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGView.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/views/MacawView.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/ColorMatrix.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Debug-iphonesimulator/SWXMLHash/SWXMLHash.framework/Modules/SWXMLHash.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Target\ Support\ Files/SWXMLHash/SWXMLHash-umbrella.h /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Target\ Support\ Files/Macaw/Macaw-umbrella.h /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Debug-iphonesimulator/SWXMLHash/SWXMLHash.framework/Headers/SWXMLHash-Swift.h /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Pods.build/Debug-iphonesimulator/Macaw.build/unextended-module.modulemap /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Pods.build/Debug-iphonesimulator/SWXMLHash.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Pods.build/Debug-iphonesimulator/Macaw.build/Objects-normal/x86_64/Rect~partial.swiftdoc : /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/export/MacawView+PDF.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAMediaTimingFillMode_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAMediaTimingFunctionName_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/MDisplayLink_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAShapeLayerLineJoin_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/MBezierPath+Extension_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/Common_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAShapeLayerLineCap_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/Graphics_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/macOS/MView_macOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAMediaTimingFillMode_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAMediaTimingFunctionName_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/iOS/MDisplayLink_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAShapeLayerLineJoin_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/iOS/Common_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/MCAShapeLayerLineCap_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/iOS/Graphics_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/iOS/MView_iOS.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Arc.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/AnimationSequence.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Node.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Image.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/utils/UIImage2Image.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/Cache/AnimationCache.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Stroke.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/views/Touchable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/Cache/NodeHashable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/Cache/TransformHashable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/bindings/Variable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/AnimatableVariable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/Interpolable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/bindings/Disposable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/bindings/GroupDisposable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Drawable.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/thirdparty/CGFloat+Double.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Circle.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Line.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Baseline.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Polyline.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Shape.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/PathSegmentType.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/thirdparty/NSTimer+Closure.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/thirdparty/CAAnimationClosure.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Ellipse.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Size.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/Easing.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Path.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/platform/MDisplayLink.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Fill.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/AnimationImpl.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/views/MacawZoom.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Transform.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Align.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/LineJoin.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Polygon.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/StrokeInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/DoubleInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/ShapeInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/FillInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/TransformInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/ContentsInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/LocusInterpolation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/Animation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/CombineAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/ShapeAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/MorphingAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/TransformAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/ContentsAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/OpacityAnimation.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/TimingFunction.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Pattern.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/MoveTo.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/AspectRatio.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/LineCap.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Stop.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Group.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/AnimationProducer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/PathBuilder.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/NodeRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/ImageRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/ShapeRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/GroupRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/TextRenderer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGParser.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/CSSParser.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/views/ShapeLayer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGSerializer.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Color.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGParserError.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/MorphingGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/TransformGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/ShapeAnimationGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/CombinationAnimationGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/types/animation_generators/OpacityGenerator.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/GaussianBlur.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGCanvas.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/FuncBounds.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/PathBounds.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/utils/CGMappings.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/SceneUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/GeomUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/AnimationUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/RenderUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/utils/BoundsUtils.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/utils/DescriptionExtensions.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/PathFunctions.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/animation/layer_animation/Extensions/AnimOperators.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Insets.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGConstants.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Locus.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/TransformedLocus.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Rect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/RoundRect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Effect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/AlphaEffect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/BlendEffect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/OffsetEffect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/ColorMatrixEffect.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Gradient.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/RadialGradient.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/LinearGradient.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/PathSegment.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/Event.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/RotateEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/PinchEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/TouchEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/PanEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/events/TapEvent.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/geom2d/Point.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/Font.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGNodeLayout.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/layout/ContentLayout.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/scene/Text.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/render/RenderContext.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/svg/SVGView.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/views/MacawView.swift /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Macaw/Source/model/draw/ColorMatrix.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Debug-iphonesimulator/SWXMLHash/SWXMLHash.framework/Modules/SWXMLHash.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Target\ Support\ Files/SWXMLHash/SWXMLHash-umbrella.h /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/Pods/Target\ Support\ Files/Macaw/Macaw-umbrella.h /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Debug-iphonesimulator/SWXMLHash/SWXMLHash.framework/Headers/SWXMLHash-Swift.h /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Pods.build/Debug-iphonesimulator/Macaw.build/unextended-module.modulemap /Users/mac/Documents/Bhupendra/RedialAnimateMenuBar/build/Pods.build/Debug-iphonesimulator/SWXMLHash.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
|
D
|
<?xml version="1.0" encoding="ASCII" standalone="no"?>
<di:SashWindowsMngr xmlns:di="http://www.eclipse.org/papyrus/0.7.0/sashdi" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmi:version="2.0">
<pageList>
<availablePage>
<emfPageIdentifier href="VAR_6_BeT-4967578645.notation#_copSALmGEeKQQp7P9cQvNQ"/>
</availablePage>
</pageList>
<sashModel currentSelection="//@sashModel/@windows.0/@children.0">
<windows>
<children xsi:type="di:TabFolder">
<children>
<emfPageIdentifier href="VAR_6_BeT-4967578645.notation#_copSALmGEeKQQp7P9cQvNQ"/>
</children>
</children>
</windows>
</sashModel>
</di:SashWindowsMngr>
|
D
|
/**
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
module dateparser;
debug(dateparser) import std.stdio;
import std.datetime;
import std.traits;
import std.typecons;
import std.compiler;
import std.regex;
import std.range;
import std.experimental.allocator.common;
import std.experimental.allocator.gc_allocator;
import dateparser.timelexer;
import dateparser.ymd;
import dateparser.parseresult;
public import dateparser.parserinfo;
private:
Parser!GCAllocator defaultParser;
static this()
{
defaultParser = new Parser!GCAllocator(new ParserInfo());
}
/**
* Parse a I[.F] seconds value into (seconds, microseconds)
*
* Params:
* value = value to parse
* Returns:
* tuple of two ints
*/
auto parseMS(R)(R s) if (
isForwardRange!R &&
!isInfinite!R &&
is(Unqual!(ElementEncodingType!R) : char))
{
import std.string : leftJustifier;
import std.algorithm.searching : canFind;
import std.algorithm.iteration : splitter;
import std.typecons : tuple;
import std.conv : parse;
import std.utf : byCodeUnit;
// auto decoding special case
static if (isNarrowString!R)
auto value = s.byCodeUnit;
else
alias value = s;
if (!(value.save.canFind('.')))
{
return tuple(parse!int(value), 0);
}
else
{
auto splitValue = value.splitter('.');
auto secs = splitValue.front;
splitValue.popFront();
auto msecs = splitValue.front.leftJustifier(6, '0');
return tuple(
parse!int(secs),
parse!int(msecs)
);
}
}
void setAttribute(P, T)(ref P p, string name, auto ref T value)
{
foreach (mem; __traits(allMembers, P))
{
static if (is(typeof(__traits(getMember, p, mem)) Q))
{
static if (is(T : Q))
{
if (mem == name)
{
__traits(getMember, p, mem) = value;
return;
}
}
}
}
assert(0, P.stringof ~ " has no member " ~ name);
}
public:
/**
This function offers a generic date/time string Parser which is able to parse
most known formats to represent a date and/or time.
This function attempts to be forgiving with regards to unlikely input formats,
returning a `SysTime` object even for dates which are ambiguous. While other languages
have writing systems without Arabic numerals, the overwhelming majority of dates
are written with them. As such, this function does not work with other
number systems.
If an element of a date/time stamp is omitted, the following rules are applied:
$(UL
$(LI If AM or PM is left unspecified, a 24-hour clock is assumed, however,
an hour on a 12-hour clock (0 <= hour <= 12) *must* be specified if
AM or PM is specified.)
$(LI If a time zone is omitted, a SysTime is given with the timezone of the
host machine.)
)
Missing information is allowed, and what ever is given is applied on top of
the `defaultDate` parameter, which defaults to January 1, 1 AD at midnight.
E.g. a string of `"10:00 AM"` with a `defaultDate` of
`SysTime(Date(2016, 1, 1))` will yield `SysTime(DateTime(2016, 1, 1, 10, 0, 0))`.
If your date string uses timezone names in place of UTC offsets, then timezone
information must be user provided, as there is no way to reliably get timezones
from the OS by abbreviation. But, the timezone will be properly set if an offset
is given. Timezone info and their abbreviations change constantly, so it's a
good idea to not rely on `timezoneInfos` too much.
This function allocates memory and throws on the GC. In order to reduce GC allocations,
use a custom `Parser` instance with a different allocator.
Params:
timeString = A forward range containing a date/time stamp.
ignoreTimezone = Set to false by default, time zones in parsed strings are ignored and a
SysTime with the local time zone is returned. If timezone information
is not important, setting this to true is slightly faster.
timezoneInfos = Time zone names / aliases which may be present in the
string. This argument maps time zone names (and optionally offsets
from those time zones) to time zones. This parameter is ignored if
ignoreTimezone is set.
dayFirst = Whether to interpret the first value in an ambiguous 3-integer date
(e.g. 01/05/09) as the day (`true`) or month (`false`). If
yearFirst is set to true, this distinguishes between YDM and
YMD.
yearFirst = Whether to interpret the first value in an ambiguous 3-integer date
(e.g. 01/05/09) as the year. If true, the first number is taken to
be the year, otherwise the last number is taken to be the year.
fuzzy = Whether to allow fuzzy parsing, allowing for string like "Today is
January 1, 2047 at 8:21:00AM".
defaultDate = The date to apply the given information on top of. Defaults to
January 1st, 1 AD
Returns:
A SysTime object representing the parsed string
Throws:
`ConvException` will be thrown for invalid string or unknown string format
Throws:
`TimeException` if the date string is successfully parsed but the created
date would be invalid
Throws:
`ConvOverflowException` if one of the numbers in the parsed date exceeds
`float.max`
*/
SysTime parse(Range)(Range timeString,
Flag!"ignoreTimezone" ignoreTimezone = No.ignoreTimezone,
const(TimeZone)[string] timezoneInfos = null,
Flag!"dayFirst" dayFirst = No.dayFirst,
Flag!"yearFirst" yearFirst = No.yearFirst,
Flag!"fuzzy" fuzzy = No.fuzzy,
SysTime defaultDate = SysTime(DateTime(1, 1, 1))) if (
isForwardRange!Range && !isInfinite!Range && isSomeChar!(ElementEncodingType!Range))
{
// dfmt off
return defaultParser.parse(
timeString,
ignoreTimezone,
timezoneInfos,
dayFirst,
yearFirst,
fuzzy,
defaultDate
);
}
///
unittest
{
immutable brazilTime = new SimpleTimeZone(dur!"seconds"(-10_800));
const(TimeZone)[string] timezones = ["BRST" : brazilTime];
immutable parsed = parse("Thu Sep 25 10:36:28 BRST 2003", No.ignoreTimezone, timezones);
// SysTime opEquals ignores timezones
assert(parsed == SysTime(DateTime(2003, 9, 25, 10, 36, 28)));
assert(parsed.timezone == brazilTime);
assert(parse(
"2003 10:36:28 BRST 25 Sep Thu",
No.ignoreTimezone,
timezones
) == SysTime(DateTime(2003, 9, 25, 10, 36, 28)));
assert(parse("Thu Sep 25 10:36:28") == SysTime(DateTime(1, 9, 25, 10, 36, 28)));
assert(parse("20030925T104941") == SysTime(DateTime(2003, 9, 25, 10, 49, 41)));
assert(parse("2003-09-25T10:49:41") == SysTime(DateTime(2003, 9, 25, 10, 49, 41)));
assert(parse("10:36:28") == SysTime(DateTime(1, 1, 1, 10, 36, 28)));
assert(parse("09-25-2003") == SysTime(DateTime(2003, 9, 25)));
}
/// Apply information on top of `defaultDate`
unittest
{
assert("10:36:28".parse(No.ignoreTimezone, null, No.dayFirst, No.yearFirst,
No.fuzzy, SysTime(DateTime(2016, 3, 15)))
== SysTime(DateTime(2016, 3, 15, 10, 36, 28)));
assert("August 07".parse(No.ignoreTimezone, null, No.dayFirst, No.yearFirst,
No.fuzzy, SysTime(DateTime(2016, 1, 1)))
== SysTime(Date(2016, 8, 7)));
assert("2000".parse(No.ignoreTimezone, null, No.dayFirst, No.yearFirst,
No.fuzzy, SysTime(DateTime(2016, 3, 1)))
== SysTime(Date(2000, 3, 1)));
}
/// Custom allocators
unittest
{
import std.experimental.allocator.mallocator : Mallocator;
auto customParser = new Parser!Mallocator(new ParserInfo());
assert(customParser.parse("2003-09-25T10:49:41") ==
SysTime(DateTime(2003, 9, 25, 10, 49, 41)));
}
/// Exceptions
unittest
{
import std.exception : assertThrown;
import std.conv : ConvException;
assertThrown!ConvException(parse(""));
assertThrown!ConvException(parse("AM"));
assertThrown!ConvException(parse("The quick brown fox jumps over the lazy dog"));
assertThrown!TimeException(parse("Feb 30, 2007"));
assertThrown!TimeException(parse("Jan 20, 2015 PM"));
assertThrown!ConvException(parse("13:44 AM"));
assertThrown!ConvException(parse("January 25, 1921 23:13 PM"));
}
// dfmt on
unittest
{
assert(parse("Thu Sep 10:36:28") == SysTime(DateTime(1, 9, 5, 10, 36, 28)));
assert(parse("Thu 10:36:28") == SysTime(DateTime(1, 1, 3, 10, 36, 28)));
assert(parse("Sep 10:36:28") == SysTime(DateTime(1, 9, 1, 10, 36, 28)));
assert(parse("Sep 2003") == SysTime(DateTime(2003, 9, 1)));
assert(parse("Sep") == SysTime(DateTime(1, 9, 1)));
assert(parse("2003") == SysTime(DateTime(2003, 1, 1)));
assert(parse("10:36") == SysTime(DateTime(1, 1, 1, 10, 36)));
}
unittest
{
assert(parse("Thu 10:36:28") == SysTime(DateTime(1, 1, 3, 10, 36, 28)));
assert(parse("20030925T104941") == SysTime(DateTime(2003, 9, 25, 10, 49, 41)));
assert(parse("20030925T1049") == SysTime(DateTime(2003, 9, 25, 10, 49, 0)));
assert(parse("20030925T10") == SysTime(DateTime(2003, 9, 25, 10)));
assert(parse("20030925") == SysTime(DateTime(2003, 9, 25)));
assert(parse("2003-09-25 10:49:41,502") == SysTime(DateTime(2003, 9, 25, 10,
49, 41), msecs(502)));
assert(parse("199709020908") == SysTime(DateTime(1997, 9, 2, 9, 8)));
assert(parse("19970902090807") == SysTime(DateTime(1997, 9, 2, 9, 8, 7)));
}
unittest
{
assert(parse("2003 09 25") == SysTime(DateTime(2003, 9, 25)));
assert(parse("2003 Sep 25") == SysTime(DateTime(2003, 9, 25)));
assert(parse("25 Sep 2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("25 Sep 2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("Sep 25 2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("09 25 2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("25 09 2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("10 09 2003", No.ignoreTimezone, null,
Yes.dayFirst) == SysTime(DateTime(2003, 9, 10)));
assert(parse("10 09 2003") == SysTime(DateTime(2003, 10, 9)));
assert(parse("10 09 03") == SysTime(DateTime(2003, 10, 9)));
assert(parse("10 09 03", No.ignoreTimezone, null, No.dayFirst,
Yes.yearFirst) == SysTime(DateTime(2010, 9, 3)));
assert(parse("25 09 03") == SysTime(DateTime(2003, 9, 25)));
}
unittest
{
assert(parse("03 25 Sep") == SysTime(DateTime(2003, 9, 25)));
assert(parse("2003 25 Sep") == SysTime(DateTime(2003, 9, 25)));
assert(parse("25 03 Sep") == SysTime(DateTime(2025, 9, 3)));
assert(parse("Thu Sep 25 2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("Sep 25 2003") == SysTime(DateTime(2003, 9, 25)));
}
// Naked times
unittest
{
assert(parse("10h36m28.5s") == SysTime(DateTime(1, 1, 1, 10, 36, 28), msecs(500)));
assert(parse("10h36m28s") == SysTime(DateTime(1, 1, 1, 10, 36, 28)));
assert(parse("10h36m") == SysTime(DateTime(1, 1, 1, 10, 36)));
assert(parse("10h") == SysTime(DateTime(1, 1, 1, 10, 0, 0)));
assert(parse("10 h 36") == SysTime(DateTime(1, 1, 1, 10, 36, 0)));
}
// AM vs PM
unittest
{
assert(parse("10h am") == SysTime(DateTime(1, 1, 1, 10)));
assert(parse("10h pm") == SysTime(DateTime(1, 1, 1, 22)));
assert(parse("10am") == SysTime(DateTime(1, 1, 1, 10)));
assert(parse("10pm") == SysTime(DateTime(1, 1, 1, 22)));
assert(parse("10:00 am") == SysTime(DateTime(1, 1, 1, 10)));
assert(parse("10:00 pm") == SysTime(DateTime(1, 1, 1, 22)));
assert(parse("10:00am") == SysTime(DateTime(1, 1, 1, 10)));
assert(parse("10:00pm") == SysTime(DateTime(1, 1, 1, 22)));
assert(parse("10:00a.m") == SysTime(DateTime(1, 1, 1, 10)));
assert(parse("10:00p.m") == SysTime(DateTime(1, 1, 1, 22)));
assert(parse("10:00a.m.") == SysTime(DateTime(1, 1, 1, 10)));
assert(parse("10:00p.m.") == SysTime(DateTime(1, 1, 1, 22)));
}
// ISO and ISO stripped
unittest
{
immutable zone = new SimpleTimeZone(dur!"seconds"(-10_800));
immutable parsed = parse("2003-09-25T10:49:41.5-03:00");
assert(parsed == SysTime(DateTime(2003, 9, 25, 10, 49, 41), msecs(500), zone));
assert((cast(immutable(SimpleTimeZone)) parsed.timezone).utcOffset == hours(-3));
immutable parsed2 = parse("2003-09-25T10:49:41-03:00");
assert(parsed2 == SysTime(DateTime(2003, 9, 25, 10, 49, 41), zone));
assert((cast(immutable(SimpleTimeZone)) parsed2.timezone).utcOffset == hours(-3));
assert(parse("2003-09-25T10:49:41") == SysTime(DateTime(2003, 9, 25, 10, 49, 41)));
assert(parse("2003-09-25T10:49") == SysTime(DateTime(2003, 9, 25, 10, 49)));
assert(parse("2003-09-25T10") == SysTime(DateTime(2003, 9, 25, 10)));
assert(parse("2003-09-25") == SysTime(DateTime(2003, 9, 25)));
immutable parsed3 = parse("2003-09-25T10:49:41-03:00");
assert(parsed3 == SysTime(DateTime(2003, 9, 25, 10, 49, 41), zone));
assert((cast(immutable(SimpleTimeZone)) parsed3.timezone).utcOffset == hours(-3));
immutable parsed4 = parse("20030925T104941-0300");
assert(parsed4 == SysTime(DateTime(2003, 9, 25, 10, 49, 41), zone));
assert((cast(immutable(SimpleTimeZone)) parsed4.timezone).utcOffset == hours(-3));
assert(parse("20030925T104941") == SysTime(DateTime(2003, 9, 25, 10, 49, 41)));
assert(parse("20030925T1049") == SysTime(DateTime(2003, 9, 25, 10, 49, 0)));
assert(parse("20030925T10") == SysTime(DateTime(2003, 9, 25, 10)));
assert(parse("20030925") == SysTime(DateTime(2003, 9, 25)));
}
// Dashes
unittest
{
assert(parse("2003-09-25") == SysTime(DateTime(2003, 9, 25)));
assert(parse("2003-Sep-25") == SysTime(DateTime(2003, 9, 25)));
assert(parse("25-Sep-2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("25-Sep-2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("Sep-25-2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("09-25-2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("25-09-2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("10-09-2003", No.ignoreTimezone, null,
Yes.dayFirst) == SysTime(DateTime(2003, 9, 10)));
assert(parse("10-09-2003") == SysTime(DateTime(2003, 10, 9)));
assert(parse("10-09-03") == SysTime(DateTime(2003, 10, 9)));
assert(parse("10-09-03", No.ignoreTimezone, null, No.dayFirst,
Yes.yearFirst) == SysTime(DateTime(2010, 9, 3)));
assert(parse("01-99") == SysTime(DateTime(1999, 1, 1)));
assert(parse("99-01") == SysTime(DateTime(1999, 1, 1)));
assert(parse("13-01", No.ignoreTimezone, null, Yes.dayFirst) == SysTime(DateTime(1,
1, 13)));
assert(parse("01-13") == SysTime(DateTime(1, 1, 13)));
assert(parse("01-99-Jan") == SysTime(DateTime(1999, 1, 1)));
}
// Dots
unittest
{
assert(parse("2003.09.25") == SysTime(DateTime(2003, 9, 25)));
assert(parse("2003.Sep.25") == SysTime(DateTime(2003, 9, 25)));
assert(parse("25.Sep.2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("25.Sep.2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("Sep.25.2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("09.25.2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("25.09.2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("10.09.2003", No.ignoreTimezone, null,
Yes.dayFirst) == SysTime(DateTime(2003, 9, 10)));
assert(parse("10.09.2003") == SysTime(DateTime(2003, 10, 9)));
assert(parse("10.09.03") == SysTime(DateTime(2003, 10, 9)));
assert(parse("10.09.03", No.ignoreTimezone, null, No.dayFirst,
Yes.yearFirst) == SysTime(DateTime(2010, 9, 3)));
}
// Slashes
unittest
{
assert(parse("2003/09/25") == SysTime(DateTime(2003, 9, 25)));
assert(parse("2003/Sep/25") == SysTime(DateTime(2003, 9, 25)));
assert(parse("25/Sep/2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("25/Sep/2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("Sep/25/2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("09/25/2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("25/09/2003") == SysTime(DateTime(2003, 9, 25)));
assert(parse("10/09/2003", No.ignoreTimezone, null,
Yes.dayFirst) == SysTime(DateTime(2003, 9, 10)));
assert(parse("10/09/2003") == SysTime(DateTime(2003, 10, 9)));
assert(parse("10/09/03") == SysTime(DateTime(2003, 10, 9)));
assert(parse("10/09/03", No.ignoreTimezone, null, No.dayFirst,
Yes.yearFirst) == SysTime(DateTime(2010, 9, 3)));
}
// Random formats
unittest
{
assert(parse("Wed, July 10, '96") == SysTime(DateTime(1996, 7, 10, 0, 0)));
assert(parse("1996.07.10 AD at 15:08:56 PDT",
Yes.ignoreTimezone) == SysTime(DateTime(1996, 7, 10, 15, 8, 56)));
assert(parse("1996.July.10 AD 12:08 PM") == SysTime(DateTime(1996, 7, 10, 12, 8)));
assert(parse("Tuesday, April 12, 1952 AD 3:30:42pm PST",
Yes.ignoreTimezone) == SysTime(DateTime(1952, 4, 12, 15, 30, 42)));
assert(parse("November 5, 1994, 8:15:30 am EST",
Yes.ignoreTimezone) == SysTime(DateTime(1994, 11, 5, 8, 15, 30)));
assert(parse("1994-11-05T08:15:30-05:00",
Yes.ignoreTimezone) == SysTime(DateTime(1994, 11, 5, 8, 15, 30)));
assert(parse("1994-11-05T08:15:30Z",
Yes.ignoreTimezone) == SysTime(DateTime(1994, 11, 5, 8, 15, 30)));
assert(parse("July 4, 1976") == SysTime(DateTime(1976, 7, 4)));
assert(parse("7 4 1976") == SysTime(DateTime(1976, 7, 4)));
assert(parse("4 jul 1976") == SysTime(DateTime(1976, 7, 4)));
assert(parse("7-4-76") == SysTime(DateTime(1976, 7, 4)));
assert(parse("19760704") == SysTime(DateTime(1976, 7, 4)));
assert(parse("0:01:02") == SysTime(DateTime(1, 1, 1, 0, 1, 2)));
assert(parse("12h 01m02s am") == SysTime(DateTime(1, 1, 1, 0, 1, 2)));
assert(parse("0:01:02 on July 4, 1976") == SysTime(DateTime(1976, 7, 4, 0, 1, 2)));
assert(parse("0:01:02 on July 4, 1976") == SysTime(DateTime(1976, 7, 4, 0, 1, 2)));
assert(parse("1976-07-04T00:01:02Z",
Yes.ignoreTimezone) == SysTime(DateTime(1976, 7, 4, 0, 1, 2)));
assert(parse("July 4, 1976 12:01:02 am") == SysTime(DateTime(1976, 7, 4, 0, 1,
2)));
assert(parse("Mon Jan 2 04:24:27 1995") == SysTime(DateTime(1995, 1, 2, 4, 24,
27)));
assert(parse("Tue Apr 4 00:22:12 PDT 1995",
Yes.ignoreTimezone) == SysTime(DateTime(1995, 4, 4, 0, 22, 12)));
assert(parse("04.04.95 00:22") == SysTime(DateTime(1995, 4, 4, 0, 22)));
assert(parse("Jan 1 1999 11:23:34.578") == SysTime(DateTime(1999, 1, 1, 11, 23,
34), msecs(578)));
assert(parse("950404 122212") == SysTime(DateTime(1995, 4, 4, 12, 22, 12)));
assert(parse("0:00 PM, PST", Yes.ignoreTimezone) == SysTime(DateTime(1, 1, 1, 12,
0)));
assert(parse("12:08 PM") == SysTime(DateTime(1, 1, 1, 12, 8)));
assert(parse("5:50 A.M. on June 13, 1990") == SysTime(DateTime(1990, 6, 13, 5,
50)));
assert(parse("3rd of May 2001") == SysTime(DateTime(2001, 5, 3)));
assert(parse("5th of March 2001") == SysTime(DateTime(2001, 3, 5)));
assert(parse("1st of May 2003") == SysTime(DateTime(2003, 5, 1)));
assert(parse("01h02m03") == SysTime(DateTime(1, 1, 1, 1, 2, 3)));
assert(parse("01h02") == SysTime(DateTime(1, 1, 1, 1, 2)));
assert(parse("01h02s") == SysTime(DateTime(1, 1, 1, 1, 0, 2)));
assert(parse("01m02") == SysTime(DateTime(1, 1, 1, 0, 1, 2)));
assert(parse("01m02h") == SysTime(DateTime(1, 1, 1, 2, 1)));
assert(parse("2004 10 Apr 11h30m") == SysTime(DateTime(2004, 4, 10, 11, 30)));
}
// Pertain, weekday, and month
unittest
{
assert(parse("Sep 03") == SysTime(DateTime(1, 9, 3)));
assert(parse("Sep of 03") == SysTime(DateTime(2003, 9, 1)));
assert(parse("Wed") == SysTime(DateTime(1, 1, 2)));
assert(parse("Wednesday") == SysTime(DateTime(1, 1, 2)));
assert(parse("October") == SysTime(DateTime(1, 10, 1)));
assert(parse("31-Dec-00") == SysTime(DateTime(2000, 12, 31)));
}
// Fuzzy
unittest
{
// Sometimes fuzzy parsing results in AM/PM flag being set without
// hours - if it's fuzzy it should ignore that.
auto s1 = "I have a meeting on March 1 1974.";
auto s2 = "On June 8th, 2020, I am going to be the first man on Mars";
// Also don't want any erroneous AM or PMs changing the parsed time
auto s3 = "Meet me at the AM/PM on Sunset at 3:00 AM on December 3rd, 2003";
auto s4 = "Meet me at 3:00AM on December 3rd, 2003 at the AM/PM on Sunset";
auto s5 = "Today is 25 of September of 2003, exactly at 10:49:41 with timezone -03:00.";
auto s6 = "Jan 29, 1945 14:45 AM I going to see you there?";
assert(parse(s1, No.ignoreTimezone, null, No.dayFirst, No.yearFirst,
Yes.fuzzy) == SysTime(DateTime(1974, 3, 1)));
assert(parse(s2, No.ignoreTimezone, null, No.dayFirst, No.yearFirst,
Yes.fuzzy) == SysTime(DateTime(2020, 6, 8)));
assert(parse(s3, No.ignoreTimezone, null, No.dayFirst, No.yearFirst,
Yes.fuzzy) == SysTime(DateTime(2003, 12, 3, 3)));
assert(parse(s4, No.ignoreTimezone, null, No.dayFirst, No.yearFirst,
Yes.fuzzy) == SysTime(DateTime(2003, 12, 3, 3)));
immutable zone = new SimpleTimeZone(dur!"hours"(-3));
immutable parsed = parse(s5, No.ignoreTimezone, null, No.dayFirst, No.yearFirst,
Yes.fuzzy);
assert(parsed == SysTime(DateTime(2003, 9, 25, 10, 49, 41), zone));
assert(parse(s6, No.ignoreTimezone, null, No.dayFirst, No.yearFirst,
Yes.fuzzy) == SysTime(DateTime(1945, 1, 29, 14, 45)));
}
// dfmt off
/// Custom parser info allows for international time representation
unittest
{
import std.utf : byChar;
class RusParserInfo : ParserInfo
{
this()
{
monthsAA = ParserInfo.convert([
["янв", "Январь"],
["фев", "Февраль"],
["мар", "Март"],
["апр", "Апрель"],
["май", "Май"],
["июн", "Июнь"],
["июл", "Июль"],
["авг", "Август"],
["сен", "Сентябрь"],
["окт", "Октябрь"],
["ноя", "Ноябрь"],
["дек", "Декабрь"]
]);
}
}
auto rusParser = new Parser!GCAllocator(new RusParserInfo());
immutable parsedTime = rusParser.parse("10 Сентябрь 2015 10:20");
assert(parsedTime == SysTime(DateTime(2015, 9, 10, 10, 20)));
immutable parsedTime2 = rusParser.parse("10 Сентябрь 2015 10:20"d.byChar);
assert(parsedTime2 == SysTime(DateTime(2015, 9, 10, 10, 20)));
}
// dfmt on
// Test ranges
unittest
{
import std.utf : byCodeUnit, byChar;
// forward ranges
assert("10h36m28s".byChar.parse == SysTime(
DateTime(1, 1, 1, 10, 36, 28)));
assert("Thu Sep 10:36:28".byChar.parse == SysTime(
DateTime(1, 9, 5, 10, 36, 28)));
// bidirectional ranges
assert("2003-09-25T10:49:41".byCodeUnit.parse == SysTime(
DateTime(2003, 9, 25, 10, 49, 41)));
assert("Thu Sep 10:36:28".byCodeUnit.parse == SysTime(
DateTime(1, 9, 5, 10, 36, 28)));
}
// Test different string types
unittest
{
import std.meta : AliasSeq;
import std.conv : to;
alias StringTypes = AliasSeq!(
char[], string,
wchar[], wstring,
dchar[], dstring
);
foreach (T; StringTypes)
{
assert("10h36m28s".to!T.parse == SysTime(
DateTime(1, 1, 1, 10, 36, 28)));
assert("Thu Sep 10:36:28".to!T.parse == SysTime(
DateTime(1, 9, 5, 10, 36, 28)));
assert("2003-09-25T10:49:41".to!T.parse == SysTime(
DateTime(2003, 9, 25, 10, 49, 41)));
assert("Thu Sep 10:36:28".to!T.parse == SysTime(
DateTime(1, 9, 5, 10, 36, 28)));
}
}
// Issue #1
unittest
{
assert(parse("Sat, 12 Mar 2016 01:30:59 -0900",
Yes.ignoreTimezone) == SysTime(DateTime(2016, 3, 12, 01, 30, 59)));
}
/**
* Implements the parsing functionality for the parse function. If you are
* using a custom `ParserInfo` many times in the same program, you can avoid
* unnecessary allocations by using the `Parser.parse` function directly.
*
* Params:
* Allocator = the allocator type to use
* parserInfo = the parser info to reference when parsing
*/
final class Parser(Allocator) if (
hasMember!(Allocator, "allocate") && hasMember!(Allocator, "deallocate"))
{
private const ParserInfo info;
public:
///
this(const ParserInfo parserInfo = null)
{
if (parserInfo is null)
{
info = new ParserInfo();
}
else
{
info = parserInfo;
}
}
/**
* This function has the same functionality as the free version of `parse`.
* The only difference is this will use your custom `ParserInfo` or allocator
* if provided.
*/
SysTime parse(Range)(Range timeString,
Flag!"ignoreTimezone" ignoreTimezone = No.ignoreTimezone,
const(TimeZone)[string] timezoneInfos = null,
Flag!"dayFirst" dayFirst = No.dayFirst,
Flag!"yearFirst" yearFirst = No.yearFirst,
Flag!"fuzzy" fuzzy = No.fuzzy,
SysTime defaultDate = SysTime(Date(1, 1, 1))) if (
isForwardRange!Range && !isInfinite!Range && isSomeChar!(ElementEncodingType!Range))
{
import std.conv : to, ConvException;
auto res = parseImpl(timeString, dayFirst, yearFirst, fuzzy);
if (res.badData)
throw new ConvException("Unknown string format");
if (res.year.isNull() && res.month.isNull() && res.day.isNull()
&& res.hour.isNull() && res.minute.isNull()
&& res.second.isNull() && res.weekday.isNull()
&& res.shortcutResult.isNull() && res.shortcutTimeResult.isNull())
throw new ConvException("String does not contain a date.");
if (res.shortcutResult.isNull && res.shortcutTimeResult.isNull)
{
if (!res.year.isNull)
defaultDate.year(res.year);
if (!res.day.isNull)
defaultDate.day(res.day);
if (!res.month.isNull)
defaultDate.month(to!Month(res.month));
if (!res.hour.isNull)
defaultDate.hour(res.hour);
if (!res.minute.isNull)
defaultDate.minute(res.minute);
if (!res.second.isNull)
defaultDate.second(res.second);
if (!res.microsecond.isNull)
defaultDate.fracSecs(usecs(res.microsecond));
if (!res.weekday.isNull() && (res.day.isNull || !res.day))
{
immutable delta_days = daysToDayOfWeek(
defaultDate.dayOfWeek(),
to!DayOfWeek(res.weekday)
);
defaultDate += dur!"days"(delta_days);
}
}
else if (!res.shortcutTimeResult.isNull)
defaultDate = SysTime(DateTime(Date(
defaultDate.year,
defaultDate.month,
defaultDate.day,
), res.shortcutTimeResult.get()));
if (!ignoreTimezone)
{
if (res.tzname in timezoneInfos)
defaultDate = defaultDate.toOtherTZ(
cast(immutable) timezoneInfos[res.tzname]
);
else if (res.tzname.length > 0 && (res.tzname == LocalTime().stdName
|| res.tzname == LocalTime().dstName))
defaultDate = SysTime(cast(DateTime) defaultDate);
else if (!res.tzoffset.isNull && res.tzoffset == 0)
defaultDate = SysTime(cast(DateTime) defaultDate, cast(immutable) UTC());
else if (!res.tzoffset.isNull && res.tzoffset != 0)
{
defaultDate = SysTime(
cast(DateTime) defaultDate,
new immutable SimpleTimeZone(dur!"seconds"(res.tzoffset), res.tzname)
);
}
}
else if (ignoreTimezone && !res.shortcutResult.isNull)
res.shortcutResult = SysTime(cast(DateTime) res.shortcutResult);
if (!res.shortcutResult.isNull)
return res.shortcutResult;
else
return defaultDate;
}
private:
/**
* Private method which performs the heavy lifting of parsing, called from
* `parse`.
*
* Params:
* timeString = the string to parse.
* dayFirst = Whether to interpret the first value in an ambiguous
* 3-integer date (e.g. 01/05/09) as the day (true) or month (false). If
* yearFirst is set to true, this distinguishes between YDM
* and YMD. If set to null, this value is retrieved from the
* current :class:ParserInfo object (which itself defaults to
* false).
* yearFirst = Whether to interpret the first value in an ambiguous 3-integer date
* (e.g. 01/05/09) as the year. If true, the first number is taken
* to be the year, otherwise the last number is taken to be the year.
* fuzzy = Whether to allow fuzzy parsing, allowing for string like "Today is
* January 1, 2047 at 8:21:00AM".
*/
ParseResult parseImpl(Range)(Range timeString, bool dayFirst = false,
bool yearFirst = false, bool fuzzy = false) if (isForwardRange!Range
&& !isInfinite!Range && isSomeChar!(ElementEncodingType!Range))
{
import std.algorithm.searching : canFind, countUntil;
import std.algorithm.iteration : filter;
import std.uni : isUpper;
import std.utf : byCodeUnit, byChar;
import std.conv : to, ConvException;
import containers.dynamicarray : DynamicArray;
ParseResult res;
DynamicArray!(string, Allocator, true) tokens;
static if (is(Unqual!(ElementEncodingType!Range) == dchar) ||
is(Unqual!(ElementEncodingType!Range) == wchar))
{
put(tokens, timeString.save.byChar.timeLexer);
}
else static if (isSomeString!Range && is(Unqual!(ElementEncodingType!Range) == char))
{
put(tokens, timeString.save.byCodeUnit.timeLexer);
}
else
{
put(tokens, timeString.save.timeLexer);
}
debug(dateparser) writeln("tokens: ", tokens[]);
//keep up with the last token skipped so we can recombine
//consecutively skipped tokens (-2 for when i begins at 0).
int last_skipped_token_i = -2;
//year/month/day list
YMD ymd;
//Index of the month string in ymd
ptrdiff_t mstridx = -1;
immutable size_t tokensLength = tokens.length;
debug(dateparser) writeln("tokensLength: ", tokensLength);
uint i = 0;
while (i < tokensLength)
{
//Check if it's a number
Nullable!(float, float.infinity) value;
string value_repr;
debug(dateparser) writeln("index: ", i);
debug(dateparser) writeln("tokens[i]: ", tokens[i]);
if (tokens[i][0].isNumber)
{
value_repr = tokens[i];
debug(dateparser) writeln("value_repr: ", value_repr);
value = to!float(value_repr);
}
//Token is a number
if (!value.isNull())
{
immutable tokensItemLength = tokens[i].length;
++i;
if (ymd.length == 3 && (tokensItemLength == 2
|| tokensItemLength == 4) && res.hour.isNull
&& (i >= tokensLength || (tokens[i] != ":" && info.hms(tokens[i]) == -1)))
{
debug(dateparser) writeln("branch 1");
//19990101T23[59]
auto s = tokens[i - 1];
res.hour = to!int(s[0 .. 2]);
if (tokensItemLength == 4)
{
res.minute = to!int(s[2 .. $]);
}
}
else if (tokensItemLength == 6 || (tokensItemLength > 6
&& tokens[i - 1].countUntil('.') == 6))
{
debug(dateparser) writeln("branch 2");
//YYMMDD || HHMMSS[.ss]
auto s = tokens[i - 1];
if (ymd.length == 0 && !tokens[i - 1].canFind('.'))
{
ymd.put(s[0 .. 2]);
ymd.put(s[2 .. 4]);
ymd.put(s[4 .. $]);
}
else
{
//19990101T235959[.59]
res.hour = to!int(s[0 .. 2]);
res.minute = to!int(s[2 .. 4]);
auto ms = parseMS(s[4 .. $]);
res.second = ms[0];
res.microsecond = ms[1];
}
}
else if (tokensItemLength == 8 || tokensItemLength == 12 || tokensItemLength == 14)
{
debug(dateparser) writeln("branch 3");
//YYYYMMDD
auto s = tokens[i - 1];
ymd.put(s[0 .. 4]);
ymd.put(s[4 .. 6]);
ymd.put(s[6 .. 8]);
if (tokensItemLength > 8)
{
res.hour = to!int(s[8 .. 10]);
res.minute = to!int(s[10 .. 12]);
if (tokensItemLength > 12)
{
res.second = to!int(s[12 .. $]);
}
}
}
else if ((i < tokensLength && info.hms(tokens[i]) > -1)
|| (i + 1 < tokensLength && tokens[i] == " " && info.hms(tokens[i + 1]) > -1))
{
debug(dateparser) writeln("branch 4");
//HH[ ]h or MM[ ]m or SS[.ss][ ]s
if (tokens[i] == " ")
{
++i;
}
auto idx = info.hms(tokens[i]);
while (true)
{
if (idx == 0)
{
res.hour = to!int(value.get());
if (value % 1)
res.minute = to!int(60 * (value % 1));
}
else if (idx == 1)
{
res.minute = to!int(value.get());
if (value % 1)
res.second = to!int(60 * (value % 1));
}
else if (idx == 2)
{
auto temp = parseMS(value_repr);
res.second = temp[0];
res.microsecond = temp[1];
}
++i;
if (i >= tokensLength || idx == 2)
break;
//12h00
try
{
value_repr = tokens[i];
value = to!float(value_repr);
}
catch (ConvException)
{
break;
}
++i;
++idx;
if (i < tokensLength)
{
immutable newidx = info.hms(tokens[i]);
if (newidx > -1)
idx = newidx;
}
}
}
else if (i == tokensLength && tokensLength > 3
&& tokens[i - 2] == " " && info.hms(tokens[i - 3]) > -1)
{
debug(dateparser) writeln("branch 5");
//X h MM or X m SS
immutable idx = info.hms(tokens[i - 3]) + 1;
if (idx == 1)
{
res.minute = to!int(value.get());
if (value % 1)
res.second = to!int(60 * (value % 1));
else if (idx == 2)
{
auto seconds = parseMS(value_repr);
res.second = seconds[0];
res.microsecond = seconds[1];
++i;
}
}
}
else if (i + 1 < tokensLength && tokens[i] == ":")
{
debug(dateparser) writeln("branch 6");
//HH:MM[:SS[.ss]]
static if (isSomeString!Range)
{
if (tokensLength == 5 && info.ampm(tokens[4]) == -1)
{
try
{
res.shortcutTimeResult = TimeOfDay.fromISOExtString(timeString);
return res;
}
catch (DateTimeException) {}
}
}
res.hour = to!int(value.get());
++i;
value = to!float(tokens[i]);
res.minute = to!int(value.get());
if (value % 1)
res.second = to!int(60 * (value % 1));
++i;
if (i < tokensLength && tokens[i] == ":")
{
auto temp = parseMS(tokens[i + 1]);
res.second = temp[0];
res.microsecond = temp[1];
i += 2;
}
}
else if (i < tokensLength && (tokens[i] == "-" || tokens[i] == "/"
|| tokens[i] == "."))
{
debug(dateparser) writeln("branch 7");
immutable string separator = tokens[i];
ymd.put(value_repr);
++i;
if (i < tokensLength && !info.jump(tokens[i]))
{
if (tokens[i][0].isNumber)
{
//01-01[-01]
static if (isSomeString!Range)
{
if (tokensLength >= 11)
{
try
{
res.shortcutResult = SysTime.fromISOExtString(timeString);
return res;
}
catch (DateTimeException) {}
}
}
ymd.put(tokens[i]);
}
else
{
//01-Jan[-01]
value = info.month(tokens[i]);
if (!value.isNull())
{
ymd.put(value.get());
mstridx = cast(ptrdiff_t) (ymd.length == 0 ? 0 : ymd.length - 1);
}
else
{
res.badData = true;
return res;
}
}
++i;
if (i < tokensLength && tokens[i] == separator)
{
//We have three members
++i;
value = info.month(tokens[i]);
if (value > -1)
{
ymd.put(value.get());
mstridx = ymd.length - 1;
}
else
ymd.put(tokens[i]);
++i;
}
}
}
else if (i >= tokensLength || info.jump(tokens[i]))
{
debug(dateparser) writeln("branch 8");
if (i + 1 < tokensLength && info.ampm(tokens[i + 1]) > -1)
{
//12 am
res.hour = to!int(value.get());
if (res.hour < 12 && info.ampm(tokens[i + 1]) == 1)
res.hour += 12;
else if (res.hour == 12 && info.ampm(tokens[i + 1]) == 0)
res.hour = 0;
++i;
}
else
{
//Year, month or day
ymd.put(value.get());
}
++i;
}
else if (info.ampm(tokens[i]) > -1)
{
debug(dateparser) writeln("branch 9");
//12am
res.hour = to!int(value.get());
if (res.hour < 12 && info.ampm(tokens[i]) == 1)
res.hour += 12;
else if (res.hour == 12 && info.ampm(tokens[i]) == 0)
res.hour = 0;
++i;
}
else if (!fuzzy)
{
debug(dateparser) writeln("branch 10");
res.badData = true;
return res;
}
else
{
debug(dateparser) writeln("branch 11");
++i;
}
continue;
}
//Check weekday
value = info.weekday(tokens[i]);
if (value > -1)
{
debug(dateparser) writeln("branch 12");
res.weekday = to!uint(value.get());
++i;
continue;
}
//Check month name
value = info.month(tokens[i]);
if (value > -1)
{
debug(dateparser) writeln("branch 13");
ymd.put(value.get);
assert(mstridx == -1);
mstridx = ymd.length - 1;
++i;
if (i < tokensLength)
{
if (tokens[i] == "-" || tokens[i] == "/")
{
//Jan-01[-99]
immutable separator = tokens[i];
++i;
ymd.put(tokens[i]);
++i;
if (i < tokensLength && tokens[i] == separator)
{
//Jan-01-99
++i;
ymd.put(tokens[i]);
++i;
}
}
else if (i + 3 < tokensLength && tokens[i] == " "
&& tokens[i + 2] == " " && info.pertain(tokens[i + 1]))
{
//Jan of 01
//In this case, 01 is clearly year
try
{
value = to!int(tokens[i + 3]);
//Convert it here to become unambiguous
ymd.put(convertYear(value.get.to!int()));
}
catch (ConvException) {}
i += 4;
}
}
continue;
}
//Check am/pm
value = info.ampm(tokens[i]);
if (value > -1)
{
debug(dateparser) writeln("branch 14");
//For fuzzy parsing, 'a' or 'am' (both valid English words)
//may erroneously trigger the AM/PM flag. Deal with that
//here.
bool valIsAMPM = true;
//If there's already an AM/PM flag, this one isn't one.
if (fuzzy && !res.ampm.isNull())
valIsAMPM = false;
//If AM/PM is found and hour is not, raise a ValueError
if (res.hour.isNull)
{
if (fuzzy)
valIsAMPM = false;
else
throw new ConvException("No hour specified with AM or PM flag.");
}
else if (!(0 <= res.hour && res.hour <= 12))
{
//If AM/PM is found, it's a 12 hour clock, so raise
//an error for invalid range
if (fuzzy)
valIsAMPM = false;
else
throw new ConvException("Invalid hour specified for 12-hour clock.");
}
if (valIsAMPM)
{
if (value == 1 && res.hour < 12)
res.hour += 12;
else if (value == 0 && res.hour == 12)
res.hour = 0;
res.ampm = to!uint(value.get());
}
++i;
continue;
}
//Check for a timezone name
immutable upperItems = tokens[i]
.byCodeUnit
.filter!(a => !isUpper(a))
.walkLength(1);
if (!res.hour.isNull && tokens[i].length <= 5
&& res.tzname.length == 0 && res.tzoffset.isNull && upperItems == 0)
{
debug(dateparser) writeln("branch 15");
res.tzname = tokens[i];
++i;
//Check for something like GMT+3, or BRST+3. Notice
//that it doesn't mean "I am 3 hours after GMT", but
//"my time +3 is GMT". If found, we reverse the
//logic so that timezone parsing code will get it
//right.
if (i < tokensLength && (tokens[i][0] == '+' || tokens[i][0] == '-'))
{
tokens[i] = tokens[i][0] == '+' ? "-" : "+";
res.tzoffset = 0;
if (info.utczone(res.tzname))
{
//With something like GMT+3, the timezone
//is *not* GMT.
res.tzname = [];
}
}
continue;
}
//Check for a numbered timezone
if (!res.hour.isNull && (tokens[i] == "+" || tokens[i] == "-"))
{
debug(dateparser) writeln("branch 16");
immutable int signal = tokens[i] == "+" ? 1 : -1;
++i;
immutable size_t tokensItemLength = tokens[i].length;
if (tokensItemLength == 4)
{
//-0300
res.tzoffset = to!int(tokens[i][0 .. 2]) * 3600 + to!int(tokens[i][2 .. $]) * 60;
}
else if (i + 1 < tokensLength && tokens[i + 1] == ":")
{
//-03:00
res.tzoffset = to!int(tokens[i]) * 3600 + to!int(tokens[i + 2]) * 60;
i += 2;
}
else if (tokensItemLength <= 2)
{
//-[0]3
res.tzoffset = to!int(tokens[i][0 .. 2]) * 3600;
}
else
{
res.badData = true;
return res;
}
++i;
res.tzoffset *= signal;
//Look for a timezone name between parenthesis
if (i + 3 < tokensLength)
{
immutable notUpperItems = tokens[i + 2]
.byCodeUnit
.filter!(a => !isUpper(a))
.walkLength(1);
if (info.jump(tokens[i]) && tokens[i + 1] == "("
&& tokens[i + 3] == ")" && 3 <= tokens[i + 2].length
&& tokens[i + 2].length <= 5 && notUpperItems == 0)
{
//-0300 (BRST)
res.tzname = tokens[i + 2];
i += 4;
}
}
continue;
}
//Check jumps
if (!(info.jump(tokens[i]) || fuzzy))
{
debug(dateparser) writeln("branch 17");
res.badData = true;
return res;
}
last_skipped_token_i = i;
++i;
}
auto ymdResult = ymd.resolveYMD(tokens[], mstridx, yearFirst, dayFirst);
// year
if (ymdResult[0] > -1)
{
res.year = ymdResult[0];
res.centurySpecified = ymd.centurySpecified;
}
// month
if (ymdResult[1] > 0)
res.month = ymdResult[1];
// day
if (ymdResult[2] > 0)
res.day = ymdResult[2];
info.validate(res);
return res;
}
}
|
D
|
struct S { ... } // S has postblit or destructor
S s; // default construction of s
S t = s; // t is copy-constructed from s
t = s; // t is assigned from s
t.opAssign(s);
ref S opAssign(S s)
{
S tmp = this; // bitcopy this into tmp
this = s; // bitcopy s into this
tmp.__dtor(); // call destructor on tmp
return this;
}
struct S
{
int[] buf;
int a;
ref S opAssign(ref const S s)
{
a = s.a;
return this;
}
this(this)
{
buf = buf.dup;
}
}
|
D
|
/**
Copyright: Copyright (c) 2017-2018 Andrey Penechko.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: Andrey Penechko.
*/
module voxelman.world.mesh.sidemeshers.slope;
import voxelman.log;
import voxelman.container.buffer;
import voxelman.math;
import voxelman.geometry;
import voxelman.world.block;
import voxelman.world.mesh.chunkmesh;
import voxelman.world.mesh.config;
import voxelman.world.mesh.sidemeshers.utils;
import voxelman.world.mesh.tables.slope;
void meshSlopeSideOccluded(CubeSide side, ubyte[4] cornerOcclusion, SideParams d)
{
immutable float mult = shadowMultipliers[side];
// apply fake lighting
float r = mult * d.color.r;
float g = mult * d.color.g;
float b = mult * d.color.b;
// Ambient occlusion multipliers
//float vert0AoMult = occlusionTable[cornerOcclusion[0]];
//float vert1AoMult = occlusionTable[cornerOcclusion[1]];
//float vert2AoMult = occlusionTable[cornerOcclusion[2]];
//float vert3AoMult = occlusionTable[cornerOcclusion[3]];
ubyte vert0AoMult = cast(ubyte)(255 * occlusionTable[cornerOcclusion[0]]);
ubyte vert1AoMult = cast(ubyte)(255 * occlusionTable[cornerOcclusion[1]]);
ubyte vert2AoMult = cast(ubyte)(255 * occlusionTable[cornerOcclusion[2]]);
ubyte vert3AoMult = cast(ubyte)(255 * occlusionTable[cornerOcclusion[3]]);
immutable ubyte[4] finalColors = [vert0AoMult, vert1AoMult, vert2AoMult, vert3AoMult];
immutable ubyte[2][4] uvs = [d.uv, [d.uv[0], cast(ubyte)(d.uv[1]+1)], [cast(ubyte)(d.uv[0]+1), cast(ubyte)(d.uv[1]+1)], [cast(ubyte)(d.uv[0]+1), d.uv[1]]];
//static if (AO_DEBUG_ENABLED)
// immutable ubyte[3][4] finalColors = getDebugAOColors(cornerOcclusion);
//else
// immutable ubyte[3][4] finalColors = [
// [cast(ubyte)(vert0AoMult * r), cast(ubyte)(vert0AoMult * g), cast(ubyte)(vert0AoMult * b)],
// [cast(ubyte)(vert1AoMult * r), cast(ubyte)(vert1AoMult * g), cast(ubyte)(vert1AoMult * b)],
// [cast(ubyte)(vert2AoMult * r), cast(ubyte)(vert2AoMult * g), cast(ubyte)(vert2AoMult * b)],
// [cast(ubyte)(vert3AoMult * r), cast(ubyte)(vert3AoMult * g), cast(ubyte)(vert3AoMult * b)]];
ubyte[3] indicies = slopeFaceIndicies[d.rotation][side];
ubyte[3] colorIndicies = slopeColorIndicies[d.rotation];
MeshVertex[] buf = d.buffer.voidPut(3);
buf[0].set(
cubeVerticies[indicies[0]][0] + d.blockPos.x,
cubeVerticies[indicies[0]][1] + d.blockPos.y,
cubeVerticies[indicies[0]][2] + d.blockPos.z,
uvs[colorIndicies[0]],
finalColors[colorIndicies[0]]);
buf[1].set(
cubeVerticies[indicies[1]][0] + d.blockPos.x,
cubeVerticies[indicies[1]][1] + d.blockPos.y,
cubeVerticies[indicies[1]][2] + d.blockPos.z,
uvs[colorIndicies[1]],
finalColors[colorIndicies[1]]);
buf[2].set(
cubeVerticies[indicies[2]][0] + d.blockPos.x,
cubeVerticies[indicies[2]][1] + d.blockPos.y,
cubeVerticies[indicies[2]][2] + d.blockPos.z,
uvs[colorIndicies[2]],
finalColors[colorIndicies[2]]);
}
|
D
|
# FIXED
gpio_if.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/example/common/gpio_if.c
gpio_if.obj: C:/TI/ccsv6/tools/compiler/arm_15.12.3.LTS/include/stdio.h
gpio_if.obj: C:/TI/ccsv6/tools/compiler/arm_15.12.3.LTS/include/linkage.h
gpio_if.obj: C:/TI/ccsv6/tools/compiler/arm_15.12.3.LTS/include/stdarg.h
gpio_if.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/inc/hw_types.h
gpio_if.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/inc/hw_ints.h
gpio_if.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/inc/hw_memmap.h
gpio_if.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/inc/hw_apps_rcm.h
gpio_if.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/driverlib/interrupt.h
gpio_if.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/driverlib/pin.h
gpio_if.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/driverlib/gpio.h
gpio_if.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/driverlib/prcm.h
gpio_if.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/driverlib/rom.h
gpio_if.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/driverlib/rom_map.h
gpio_if.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/driverlib/rom_patch.h
gpio_if.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/example/common/gpio_if.h
C:/TI/CC3200SDK_1.2.0/cc3200-sdk/example/common/gpio_if.c:
C:/TI/ccsv6/tools/compiler/arm_15.12.3.LTS/include/stdio.h:
C:/TI/ccsv6/tools/compiler/arm_15.12.3.LTS/include/linkage.h:
C:/TI/ccsv6/tools/compiler/arm_15.12.3.LTS/include/stdarg.h:
C:/TI/CC3200SDK_1.2.0/cc3200-sdk/inc/hw_types.h:
C:/TI/CC3200SDK_1.2.0/cc3200-sdk/inc/hw_ints.h:
C:/TI/CC3200SDK_1.2.0/cc3200-sdk/inc/hw_memmap.h:
C:/TI/CC3200SDK_1.2.0/cc3200-sdk/inc/hw_apps_rcm.h:
C:/TI/CC3200SDK_1.2.0/cc3200-sdk/driverlib/interrupt.h:
C:/TI/CC3200SDK_1.2.0/cc3200-sdk/driverlib/pin.h:
C:/TI/CC3200SDK_1.2.0/cc3200-sdk/driverlib/gpio.h:
C:/TI/CC3200SDK_1.2.0/cc3200-sdk/driverlib/prcm.h:
C:/TI/CC3200SDK_1.2.0/cc3200-sdk/driverlib/rom.h:
C:/TI/CC3200SDK_1.2.0/cc3200-sdk/driverlib/rom_map.h:
C:/TI/CC3200SDK_1.2.0/cc3200-sdk/driverlib/rom_patch.h:
C:/TI/CC3200SDK_1.2.0/cc3200-sdk/example/common/gpio_if.h:
|
D
|
INSTANCE OrkScout_BDTPatroullie_03 (Mst_Default_OrcScout)
{
//----- Monster -----
name = "Ork Späher";
guild = GIL_ORC;
id = 10011;
voice = 18;
level = 20;
Npctype = NPCTYPE_MAIN;
fight_tactic = FAI_ORC;
Mdl_SetVisual (self, "Orc.mds");
// Body-Mesh Body-Tex Skin-Color Head-MMS Head-Tex Teeth-Tex ARMOR
Mdl_SetVisualBody (self, "Orc_BodyScout", DEFAULT, DEFAULT, "Orc_HeadWarrior", DEFAULT, DEFAULT, -1);
attribute[ATR_STRENGTH] = 150;
EquipItem (self, ItMw_2H_OrcAxe_01);
aivar[AIV_FightDistCancel] = FIGHT_DIST_CANCEL;
daily_routine = Rtn_Start_10011;
};
FUNC VOID Rtn_Start_10011()
{
TA_Stand_WP_Orc (04,00,22,00,"WP_ORKPATROULLIE");
TA_Sleep_Orc (22,00,04,00,"WP_ORKPATROULLIE");
};
|
D
|
import api.util;
import api.c;
import api.classes, api.methods, api.enums;
import api.doc;
import language;
import language.d;
import asdf;
import std.string : toLower, chompPrefix;
import std.stdio : writeln, writefln;
import std.file : exists, readText, mkdirRecurse, isDir, writeFile = write, dirEntries, SpanMode, rmdirRecurse;
import std.path : buildPath, dirName, extension, stripExtension, baseName;
import std.format : format;
import std.getopt : defaultGetoptPrinter, getopt, GetoptResult;
import std.range : empty;
void usage(GetoptResult opt)
{
defaultGetoptPrinter("Usage: [OPTION]... [outputDir]\n", opt.options);
writeln();
}
int main(string[] args)
{
string gdnativeJson;
string classesJson = "api.json";
string godotSource;
bool overwrite = false;
auto opt = args.getopt(
"gdnative|g", "GDNative API JSON (default: gdnative_api.json)", &gdnativeJson,
"classes|c", "Classes API JSON (default: api.json)", &classesJson,
"source|s", "Godot source directory, for documentation (also sets gdnative if unset)", &godotSource,
"overwrite|o", "Overwrite outputDir unconditionally", &overwrite
);
writeln(args);
if(opt.helpWanted)
{
usage(opt);
return 0;
}
Language lang = getDLanguage();
if(gdnativeJson.empty)
{
if(godotSource) gdnativeJson = buildPath(godotSource, "modules", "gdnative", "gdnative_api.json");
else gdnativeJson = "gdnative_api.json";
}
if(!gdnativeJson.exists)
{
usage(opt);
writefln("GDNative API file %s doesn't exist", gdnativeJson);
return 1;
}
if(!classesJson.exists)
{
usage(opt);
writefln("Class API file %s doesn't exist", classesJson);
return 1;
}
string outputDir;
if(args.length >= 2) outputDir = args[1];
else
{
outputDir = args[0].dirName.buildPath("classes");
writefln("Outputting to default directory %s",outputDir);
}
if(outputDir.exists)
{
if(!outputDir.isDir)
{
usage(opt);
writefln("Error: '%s' is not a directory", outputDir);
return 1;
}
bool shouldOverwrite = overwrite;
// check if it looks like the API directory
if(outputDir.buildPath("godot", "c", "api.d").exists) shouldOverwrite = true;
if(!shouldOverwrite)
{
usage(opt);
writefln("Error: output directory %s already exists. Pass '-o' to overwrite it.", outputDir);
return 1;
}
writefln("Overwriting existing output directory %s", outputDir);
rmdirRecurse(outputDir);
}
outputDir.mkdirRecurse;
Api gdnativeApi = gdnativeJson.readText.deserialize!(Api);
auto cPath = buildPath(outputDir, "godot", "c", "api.d");
if(!cPath.dirName.exists) cPath.dirName.mkdirRecurse;
writeFile(cPath, gdnativeApi.source);
ClassList classList;
classList.classes = classesJson.readText.deserialize!(GodotClass[]);
foreach(c; classList.classes)
{
classList.dictionary[c.name] = c;
c.parent = &classList;
}
foreach(c; classList.classes) if(c.base_class)
{
c.base_class_ptr = classList.dictionary.get(c.base_class, null);
foreach(b; GodotClass.BaseRange(c.base_class_ptr))
{
import std.algorithm.searching : canFind;
if(b.name.godot == "Object") break; // don't include godot.object
if(!c.used_classes.canFind(b.name)) c.used_classes ~= b.name;
}
c.base_class_ptr.descendant_ptrs ~= c;
}
foreach(e; Type.enums)
{
import std.algorithm.searching : canFind;
auto c = e.enumParent ? e.enumParent.objectClass : null;
if(c && !c.enums.canFind!(ge => c.name.d~"."~ge.name == e.d))
{
c.missingEnums ~= e;
}
}
/+
Break constness for methods overridden by non-const methods in descendents.
This kind of overload is a compile-time error in D.
Note that Godot doesn't have overloads differing in argument types.
+/
foreach(c; classList.classes)
{
foreach(mi, m; c.methods)
{
auto b = c.base_class_ptr;
while(b)
{
foreach(bmi, bm; b.methods)
{
if(bm.name == m.name)
{
if(m.is_const != bm.is_const) bm.is_const = m.is_const = false;
}
}
b = b.base_class_ptr;
}
}
}
// add documentation XMLs
if(!godotSource.empty && godotSource.exists)
{
string[] paths = [buildPath(godotSource, "doc", "classes")];
if(buildPath(godotSource, "modules").exists)
{
foreach(de; dirEntries(buildPath(godotSource, "modules"), SpanMode.shallow))
{
auto p = buildPath(de.name, "doc_classes");
if(p.exists) paths ~= p;
}
}
foreach(p; paths) foreach(de; dirEntries(p, SpanMode.shallow)) if(de.isFile && de.extension.toLower == ".xml")
{
if(Type* t = de.name.baseName.stripExtension.escapeType in Type.typesByDName) if(t.objectClass)
{
parseClassDoc(t.objectClass, de.name.readText);
}
}
}
foreach(c; classList.classes)
{
// output files for the selected lang
foreach(const cof; lang.classOutputFiles)
{
string[2] arr = cof.generator(c);
if(!arr[0].empty)
{
string p = buildPath(outputDir, arr[0]);
string dir = dirName(p);
if(!dir.exists) mkdirRecurse(dir);
writeFile(p, arr[1]);
}
}
}
return 0;
}
|
D
|
/home/zbf/workspace/git/RTAP/target/debug/deps/semver_parser-da07f49658f995ae.rmeta: /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/lib.rs /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/version.rs /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/range.rs /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/common.rs /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/recognize.rs
/home/zbf/workspace/git/RTAP/target/debug/deps/libsemver_parser-da07f49658f995ae.rlib: /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/lib.rs /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/version.rs /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/range.rs /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/common.rs /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/recognize.rs
/home/zbf/workspace/git/RTAP/target/debug/deps/semver_parser-da07f49658f995ae.d: /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/lib.rs /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/version.rs /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/range.rs /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/common.rs /home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/recognize.rs
/home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/lib.rs:
/home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/version.rs:
/home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/range.rs:
/home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/common.rs:
/home/zbf/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/semver-parser-0.7.0/src/recognize.rs:
|
D
|
a vehicle carrying many passengers
|
D
|
/*
* Copyright Andrej Mitrovic 2013 - 2020.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
module dtk.tests.slider;
version(unittest):
import dtk;
import dtk.utils;
import dtk.tests.globals;
import std.format;
unittest
{
auto testWindow = new Window(app.mainWindow, 200, 200);
testWindow.position = Point(500, 500);
auto slider = new Slider(app.mainWindow, Angle.horizontal, 200);
slider.pack();
assert(slider.angle == Angle.horizontal);
assert(slider.length == 200);
assert(slider.minValue > -1.0 && slider.minValue < 1.0);
assert(slider.maxValue > 99.0 && slider.maxValue < 101.0);
assert(slider.value == 0.0);
slider.angle = Angle.vertical;
assert(slider.angle == Angle.vertical);
slider.length = 100;
assert(slider.length == 100);
slider.minValue = 20.0;
assert(slider.minValue > 19.0 && slider.minValue < 21.0);
slider.maxValue = 50.0;
assert(slider.maxValue > 49.0 && slider.maxValue < 51.0);
slider.value = 35;
assert(slider.value > 34.0 && slider.value < 36.0);
size_t callCount;
size_t expectedCallCount;
float value = 0;
slider.onSliderEvent ~= (scope SliderEvent event)
{
assert(event.slider is slider);
assert(event.slider.value > value - 1 && event.slider.value < value + 1);
++callCount;
};
value = 40;
slider.value = 40;
++expectedCallCount;
assert(callCount == expectedCallCount, format("%s != %s", callCount, expectedCallCount));
app.testRun();
}
|
D
|
not likely to be true or to occur or to have occurred
has little chance of being the case or coming about
having a probability too low to inspire belief
|
D
|
/**********************************************************************************
* Released under the MIT license <http://www.opensource.org/licenses/mit-license.php>
* For licensing details see the included LICENSE file.
*********************/
/***********************************************************************************
* Code parsing module.
*********************/
module dasm.parser;
import std.conv : to;
import std.array : front, popFront, appender;
debug import std.stdio;
debug import utils.testing;
import utils.exception : MyException;
import utils.ctfe : contains, ETuple, indexOf, toUpper;
import dasm.lexical;
import dasm.ast;
/***********************************************************************************
* Exception thrown on a syntactic error.
*********************/
class SyntacticError : MyException {
public this(string what, uint line, string file) {
super(file~"("~to!string(line)~"): "~what);
}
}
/***********************************************************************************
* Mismatched token exception..
*********************/
class MismatchError : SyntacticError {
public this(string token, uint line, string file) {
super("Mismatched `"~token~"'.", line, file);
}
}
/***********************************************************************************
* A class doing the parsing. Lexes a string into a stream of tokens and then parses
* them into an AST.
*********************/
class Parser {
private:
/***********************************************************************************
* Extended syntax tokens.
*********************/
enum ESyntax : string {
Keyword = "@", ///Sticks a keyword to an expression.
Quote = "'", ///Quoting: '(#whatever)
Quasiquote = "`", ///Quasiquoting.
Embed = "$", ///'(some expression $with_embedded_symbol
/// $(* and expression))
///"A string with an $embedded-variable"
}
string[] stringBank; ///Stores string literals for convinient parsing later on.
uint lineCount; /// For preprocess();
uint lineNumber; /// For parse();
string fileName; /// For parse();
/***********************************************************************************
* Removes comments, substitutes syntactic sugars, etc.
****************************************/
string preprocess(in string input)
body {
stringBank.clear;
/***********************************************************************************
* Adds some metadata - line numbers.
* TODO: Escape sequences \" etc.
*********************/
string addMetadata(in string input) {
auto spc = Lexical.Space;
auto c = Lexical.CommentStart;
auto output = appender!string(""~c~"LINE"~spc~to!string(lineCount++)~spc);
output.reserve(input.length);
auto s = (input~Lexical.EndOfFile).ptr;
bool inAString = false;
bool addCount = false;
while(*s) {
output.put(*s);
if(*s == Lexical.EndOfLine) {
if(!inAString) output.put(""~spc~c~"LINE"~spc~to!string(lineCount++)~spc);
else {
addCount = true;
lineCount++;
}
}
else if(*s == Syntax.StringDelim) {
if(!(inAString && s[-1] && s[-1] == '\\')) {
inAString = !inAString;
}
if(!inAString && addCount) {
addCount = false;
output.put(""~spc~c~"LINE"~spc~to!string(lineCount-1)~spc);
}
}
s++;
}
return output.data;
}
/***********************************************************************************
* Stores string literals in stringBank to ease parsing.
*********************/
string stringCollapse(in string input) {
auto output = appender!string();
output.reserve(input.length);
auto hexes = "0123456789ABCDEF";
auto escapeSequences = ['\\':'\\', 'n':'\n', 't':'\t', '$':'$', 'v':'\v', 'r':'\r', '"':'"'];
auto s = (input~Lexical.EndOfFile).ptr;
while(*s) {
if(*s == Syntax.StringDelim) {
//TODO: StringParser.
auto str = appender!string();
++s;
while(*s && *s != Syntax.StringDelim) {
if(*s == Lexical.EscapeStart) {
++s;
// Regular escape sequences.
if(*s && *s in escapeSequences) {
str.put(escapeSequences[*s++]);
}
// Hex bytes
else if(*s && *s == 'x') {
++s;
auto c = 16 * hexes.indexOf(toUpper(s[0])) + hexes.indexOf(toUpper(s[1]));
str.put(cast(char) c);
s += 2;
}
else {
throw new SyntacticError("Unknown escape sequence `\\" ~ *s ~ "'.",
lineNumber,
fileName);
}
}
else str.put(*s++);
}
++s;
output.put(Syntax.StringDelim~to!string(stringBank.length)~Lexical.Space);
stringBank ~= str.data;
}
else output.put(*s++);
}
return output.data;
}
/***********************************************************************************
* Removes comments.
*********************/
string commentCollapse(in string input) {
auto output = appender!string();
output.reserve(input.length);
auto s = (input~Lexical.EndOfFile).ptr;
while(*s) {
if(*s == Lexical.CommentStart) {
if(s[1] && contains(cast(string) [Lexical.CommentStart,
Lexical.Space,
Lexical.Bang],
s[1]))
while(*s && *s != Lexical.EndOfLine) s++;
}
output.put(*s++);
}
return output.data;
}
/***********************************************************************************
* Adds spaces and expands scope brackets into regular ones.
*********************/
string syntaxExpand(in string input) {
auto expanded = appender!string();
expanded.reserve(input.length);
auto s = (input~Lexical.EndOfFile).ptr;
string syntax = [Syntax.LTuple, Syntax.RTuple, //Tuple parentesis
Syntax.LVector,Syntax.RVector, //Vector parentesis
Syntax.LSet, Syntax.RSet, //Set parentesis
Syntax.StringDelim]; //String delimiter.
while(*s) {
if(contains(syntax, *s)) expanded.put(""~Lexical.Space~s[0 .. 1]~Lexical.Space);
else expanded.put(s[0 .. 1]);
s++;
}
auto output = appender!string();
output.reserve(expanded.data.length);
s = (expanded.data~Lexical.EndOfFile).ptr;
string prefix = [Lexical.CommentStart, //Sexp comment.
ESyntax.Keyword[0], //. -> nothing. //TODO
ESyntax.Quote[0], //' -> (quote )
ESyntax.Quasiquote[0], //` -> (qquote )
ESyntax.Embed[0]]; //$ -> (embed )
bool jollyRogger = true;
while(*s) {
if(*s <= Lexical.Space) {
output.put(s[0 .. 1]);
jollyRogger = true;
}
else if(jollyRogger && contains(prefix, *s))
output.put(""~Lexical.Space~s[0 .. 1]~Lexical.Space);
else {
output.put(s[0 .. 1]);
jollyRogger = false;
}
s++;
}
return output.data;
}
auto output = appender!string();
auto s = (syntaxExpand(commentCollapse(stringCollapse(addMetadata(input))))~Lexical.EndOfFile).ptr;
while(*s && *s < 0x21) s++; //Spaces, spaces everywhere.
while(*s) {
switch(*s) {
case Lexical.Space: //Spaces.
output.put(*s++);
while(*s && *s <= Lexical.Space) s++;
continue;
case 0x0: .. case 0x1F: //Whitespaces
s++;
continue;
default: break;
}
output.put(*s++);
}
if(output.data.length && output.data[$-1] == Lexical.Space) return output.data[0 .. $-1];
return output.data;
}
unittest {
auto t = TestCase("Parser.preprocess");
auto i = new Parser();
void test(int line = __LINE__)(string input, string expected) {
auto actual = i.preprocess(input);
t.equals(actual, expected, line);
}
void test1(int line = __LINE__)(string input, string expected) {
i.preprocess(input);
t.equals(i.stringBank[0], expected, line);
}
//TODO: FIXME: Unittests should be Syntax-independant.
///Whitespaces:
test(" \n\r Leading whitespaces.",
"# LINE 0 # LINE 1 Leading whitespaces.");
test("Trailing whitespaces. \n\t \r\n",
"# LINE 2 Trailing whitespaces. # LINE 3 # LINE 4");
test("Lots\t\na white\r\nspaces \nand\t shit.",
"# LINE 5 Lots # LINE 6 a white # LINE 7 spaces # LINE 8 and shit.");
test("Lots\t\na white\r\nspaces \" \nand a string\".",
"# LINE 9 Lots # LINE 10 a white # LINE 11 spaces \" 0 # LINE 12 .");
test("Some multi\nline str\ning without comments.",
"# LINE 13 Some multi # LINE 14 line str # LINE 15 ing without comments.");
///Parenteses:
test("String (with parenteses (all over)).",
"# LINE 16 String ( with parenteses ( all over ) ) .");
test("String (with [different] {parens (all)} over).",
"# LINE 17 String ( with [ different ] { parens ( all ) } over ) .");
///Comments:
test("Some string with a # line comment\n.",
"# LINE 18 Some string with a # LINE 19 .");
test("Some string ##with a line\n comment.",
"# LINE 20 Some string # LINE 21 comment.");
test("Some string #(with Expression) comment.",
"# LINE 22 Some string # ( with Expression ) comment.");
test("Some string #{with Set} comment.",
"# LINE 23 Some string # { with Set } comment.");
test("Some string #(with an (Expression embedded in a) Expression) comment.",
"# LINE 24 Some string # ( with an ( Expression embedded in a ) Expression ) comment.");
test("String with a single #word comment.",
"# LINE 25 String with a single # word comment.");
test("[Expression with a single word #comment.]",
"# LINE 26 [ Expression with a single word # comment. ]");
test("{Expression with (a)#comment rigth #next} to a paren.",
"# LINE 27 { Expression with ( a ) # comment rigth # next } to a paren.");
///Strings and comments:
test("String with a \"#(comment in a string), lol.\"",
"# LINE 28 String with a \" 0");
test("A #\"string commented out\".",
"# LINE 29 A # \" 0 .");
test("Some string \"with an \nembeded \tstring\" in it.",
"# LINE 30 Some string \" 0 # LINE 31 in it.");
test("\"Comment rigth next to a string.\"#comment",
"# LINE 32 \" 0 # comment");
test("#Comment_rigth\"next to a string.\"",
"# LINE 33 # Comment_rigth \" 0");
///Expression embedding and escape sequences:
test1(`"\tString with\nescape sequences.\r\n"`, "\tString with\nescape sequences.\r\n");
test1(`"String with an embeded \"string\".`, "String with an embeded \"string\".");
test1(`"$Strings with simple $embeds in it"`, "$0 with simple $1 in it");
test1(`"$String-with? more $(complex 3.14 2.71) embeds."`, "$0 more $1 embeds.");
test1(`"$(Really {complex} embed (with multiple (parens) [and whatnot]))"`, "$0");
test1(`"${Same deal (but {with another [set of]} parens.)}"`, "$0");
test1(`"$[Same () thing for [ a {list}]]"`, "$0");
///Keywords dispatch:
//TODO: Shit, those line numbers are a pain in the ass when adding new tests.
test("String with @keywords in it.",
"# LINE 41 String with @ keywords in it.");
test("(Expression with @keywords (and @other expressions)@in it.)",
"# LINE 42 ( Expression with @ keywords ( and @ other expressions ) @ in it. )");
test("(@keyword rigth next to)@a paren.",
"# LINE 43 ( @ keyword rigth next to ) @ a paren.");
///General fun:
test("not@keyword.",
"# LINE 44 not@keyword.");
test("not#a#comment#",
"# LINE 45 not#a#comment#");
test("not$an$embed$",
"# LINE 46 not$an$embed$");
test("not`a`qquote`",
"# LINE 47 not`a`qquote`");
test("not'a'quote'",
"# LINE 48 not'a'quote'");
}
/***********************************************************************************
* Turns a single statement into several tokens.
*********************/
string[] tokenize(in string input)
body {
auto tokens = appender!(string[]);
string token;
string parens = [Syntax.LTuple, Syntax.RTuple, //Tuple parentesis
Syntax.LVector,Syntax.RVector, //Vector parentesis
Syntax.LSet, Syntax.RSet]; //Set parentesis
auto s = (input~Lexical.EndOfFile).ptr;
while(*s) {
if(*s == ' ') {
if(token != "") {
tokens.put(token);
token = "";
}
}
else if(contains(parens, *s)) tokens.put(s[0 .. 1]);
else token ~= *s;
s++;
}
if(token != "") tokens.put(token);
return tokens.data;
}
unittest {
auto t = TestCase("Parser.tokenize");
auto i = new Parser();
void test(int line = __LINE__)(string input, string[] expected) {
auto actual = i.tokenize(input);
t.equals(actual, expected, line);
}
test("A simple string.", ["A", "simple", "string."]);
test("( A simple statement. )", ["(", "A", "simple", "statement.", ")"]);
test("( Not so ( simple statement ( at ) ) all. )",
["(", "Not", "so", "(", "simple", "statement", "(", "at", ")", ")", "all.", ")"]);
test("( Many [ different { parens } and ] other ) things.",
["(", "Many", "[", "different", "{", "parens", "}", "and", "]", "other", ")", "things." ]);
}
/***********************************************************************************
* Parses a stream of tokens into a single AST.
*********************/
Expression parse(ref string[] tokens) {
if(!tokens.length) return null;
auto token = tokens.front;
tokens.popFront;
//All kinds of parenthesis.
immutable(char)[immutable(char)] parens = [Syntax.LTuple : Syntax.RTuple,
Syntax.LVector: Syntax.RVector,
Syntax.LSet : Syntax.RSet];
immutable(char)[immutable(char)] antyparens = [Syntax.RTuple : Syntax.LTuple,
Syntax.RVector :Syntax.LVector,
Syntax.RSet : Syntax.LSet];
//Extended syntax.
string[string] expandables = [ESyntax.Quote : Keywords.Quote,
ESyntax.Quasiquote : Keywords.Quasiquote,
ESyntax.Embed : Keywords.Embed];
if(token == ""~Syntax.StringDelim) {
auto index = tokens.front; //The next token is _always_ the offset in string bank.
tokens.popFront;
return new String(stringBank[to!uint(index)], lineNumber, fileName);
}
if(token == ESyntax.Keyword) {
if(tokens.length) {
auto keyword = parse(tokens);
if((keyword.type & Type.Symbol) && !(keyword.type & Type.String)) {
if(tokens.length) {
auto expr = parse(tokens);
expr.keywords(keyword.toString);
return expr;
}
}
else throw new SyntacticError("Invalid keyword '"~keyword.toString~"'.", lineNumber, fileName);
}
}
if(token == ""~Lexical.CommentStart) { //Deletes the following expression from the token stream.
if(tokens.length) {
auto str = parse(tokens).toString; //It still does the syntactic analyzis,
if(str == "LINE") {
lineNumber = to!uint(tokens.front);
tokens.popFront;
}
}
return null; //as this is ment solely for debugging.
}
if(contains(expandables.keys, token)) {
auto symbol = new Symbol(expandables[token], lineNumber, fileName);
auto expr = parse(tokens);
return new Tuple([symbol, expr ? expr : new Tuple([], lineNumber, fileName)]);
}
if(contains(parens.keys, token[0])) {
auto delimiter = cast(immutable(char))parens[token[0]];
Expression[] collection;
do {
if(!tokens.length) throw new MismatchError(token, lineNumber, fileName);
if(tokens.front == ""~delimiter) break;
if(auto e = parse(tokens)) collection ~= e;
} while(true);
tokens.popFront; //Remove the delimiter from the token stream.
switch(delimiter) {
case Syntax.RTuple:
return new Tuple(collection, lineNumber, fileName);
case Syntax.RVector:
return new Vector(collection, lineNumber, fileName);
case Syntax.RSet:
return new Set(collection, lineNumber, fileName);
default: assert(0);
}
}
if(contains(antyparens.keys, token[0])) throw new MismatchError(token, lineNumber, fileName);
//The last possible case - a symbol or a number.
try { //BUG FIXME with a rake or something. Seriously?
auto badShit = ["-", "in", "In", "IN", "iN", "I", "i"]; //Or shall I say "bat-shit".
if(contains(badShit, token))
throw new Exception("A Phobos bug workarround.");
auto value = to!real(token);
return new Number(value, lineNumber, fileName);
}
catch(Exception) return new Symbol(token, lineNumber, fileName);
}
public:
/***********************************************************************************
* Parses a string into an array of ASTs each representing independant statement.
*********************/
Expression[] parse(in string input, in string fileName) {
this.fileName = fileName;
this.lineCount = 1; //TODO: reset it from outside.
auto output = appender!(Expression[]);
auto tokens = tokenize(preprocess(input));
while(tokens.length) {
if(auto e = parse(tokens)) output.put(e);
}
return output.data;
}
}
|
D
|
/Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Crypto.build/Cipher/AuthenticatedCipherAlgorithm.swift.o : /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Utilities/Base32.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/RSA/RSA.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/MAC/HMAC.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/MAC/OTP.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Utilities/Deprecated.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/RSA/RSAPadding.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/CipherAlgorithm.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/OpenSSLCipherAlgorithm.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/AuthenticatedCipherAlgorithm.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Digest/DigestAlgorithm.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Random/CryptoRandom.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/Cipher.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/AuthenticatedCipher.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/OpenSSLStreamCipher.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Utilities/CryptoError.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Utilities/Exports.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Digest/Digest.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/BCrypt/BCryptDigest.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/RSA/RSAKey.swift /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/XPC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/IOKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-macos.swiftinterface /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Random.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /usr/local/Cellar/libressl/3.0.2/include/openssl/asn1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/tls1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dtls1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pkcs12.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl2.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pem2.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl23.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl3.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509v3.h /usr/local/Cellar/libressl/3.0.2/include/openssl/md5.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pkcs7.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509.h /usr/local/Cellar/libressl/3.0.2/include/openssl/sha.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ecdsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/rsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/obj_mac.h /usr/local/Cellar/libressl/3.0.2/include/openssl/hmac.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ec.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /usr/local/Cellar/libressl/3.0.2/include/openssl/rand.h /usr/local/Cellar/libressl/3.0.2/include/openssl/conf.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslconf.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dh.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ecdh.h /usr/local/Cellar/libressl/3.0.2/include/openssl/lhash.h /usr/local/Cellar/libressl/3.0.2/include/openssl/stack.h /usr/local/Cellar/libressl/3.0.2/include/openssl/safestack.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/CCryptoOpenSSL/include/c_crypto_openssl.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pem.h /usr/local/Cellar/libressl/3.0.2/include/openssl/bn.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /usr/local/Cellar/libressl/3.0.2/include/openssl/bio.h /usr/local/Cellar/libressl/3.0.2/include/openssl/crypto.h /usr/local/Cellar/libressl/3.0.2/include/openssl/srtp.h /usr/local/Cellar/libressl/3.0.2/include/openssl/evp.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ossl_typ.h /usr/local/Cellar/libressl/3.0.2/include/openssl/buffer.h /usr/local/Cellar/libressl/3.0.2/include/openssl/err.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslfeatures.h /usr/local/Cellar/libressl/3.0.2/include/openssl/objects.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslv.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509_vfy.h /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/CBase32/include/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/CBcrypt/include/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio-zlib-support/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio-ssl-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Crypto.build/Cipher/AuthenticatedCipherAlgorithm~partial.swiftmodule : /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Utilities/Base32.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/RSA/RSA.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/MAC/HMAC.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/MAC/OTP.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Utilities/Deprecated.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/RSA/RSAPadding.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/CipherAlgorithm.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/OpenSSLCipherAlgorithm.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/AuthenticatedCipherAlgorithm.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Digest/DigestAlgorithm.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Random/CryptoRandom.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/Cipher.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/AuthenticatedCipher.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/OpenSSLStreamCipher.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Utilities/CryptoError.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Utilities/Exports.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Digest/Digest.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/BCrypt/BCryptDigest.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/RSA/RSAKey.swift /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/XPC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/IOKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-macos.swiftinterface /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Random.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /usr/local/Cellar/libressl/3.0.2/include/openssl/asn1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/tls1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dtls1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pkcs12.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl2.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pem2.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl23.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl3.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509v3.h /usr/local/Cellar/libressl/3.0.2/include/openssl/md5.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pkcs7.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509.h /usr/local/Cellar/libressl/3.0.2/include/openssl/sha.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ecdsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/rsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/obj_mac.h /usr/local/Cellar/libressl/3.0.2/include/openssl/hmac.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ec.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /usr/local/Cellar/libressl/3.0.2/include/openssl/rand.h /usr/local/Cellar/libressl/3.0.2/include/openssl/conf.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslconf.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dh.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ecdh.h /usr/local/Cellar/libressl/3.0.2/include/openssl/lhash.h /usr/local/Cellar/libressl/3.0.2/include/openssl/stack.h /usr/local/Cellar/libressl/3.0.2/include/openssl/safestack.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/CCryptoOpenSSL/include/c_crypto_openssl.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pem.h /usr/local/Cellar/libressl/3.0.2/include/openssl/bn.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /usr/local/Cellar/libressl/3.0.2/include/openssl/bio.h /usr/local/Cellar/libressl/3.0.2/include/openssl/crypto.h /usr/local/Cellar/libressl/3.0.2/include/openssl/srtp.h /usr/local/Cellar/libressl/3.0.2/include/openssl/evp.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ossl_typ.h /usr/local/Cellar/libressl/3.0.2/include/openssl/buffer.h /usr/local/Cellar/libressl/3.0.2/include/openssl/err.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslfeatures.h /usr/local/Cellar/libressl/3.0.2/include/openssl/objects.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslv.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509_vfy.h /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/CBase32/include/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/CBcrypt/include/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio-zlib-support/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio-ssl-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Crypto.build/Cipher/AuthenticatedCipherAlgorithm~partial.swiftdoc : /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Utilities/Base32.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/RSA/RSA.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/MAC/HMAC.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/MAC/OTP.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Utilities/Deprecated.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/RSA/RSAPadding.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/CipherAlgorithm.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/OpenSSLCipherAlgorithm.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/AuthenticatedCipherAlgorithm.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Digest/DigestAlgorithm.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Random/CryptoRandom.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/Cipher.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/AuthenticatedCipher.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Cipher/OpenSSLStreamCipher.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Utilities/CryptoError.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Utilities/Exports.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/Digest/Digest.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/BCrypt/BCryptDigest.swift /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/Crypto/RSA/RSAKey.swift /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/XPC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/IOKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-macos.swiftinterface /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Random.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /usr/local/Cellar/libressl/3.0.2/include/openssl/asn1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/tls1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dtls1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pkcs12.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl2.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pem2.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl23.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl3.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509v3.h /usr/local/Cellar/libressl/3.0.2/include/openssl/md5.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pkcs7.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509.h /usr/local/Cellar/libressl/3.0.2/include/openssl/sha.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ecdsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/rsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/obj_mac.h /usr/local/Cellar/libressl/3.0.2/include/openssl/hmac.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ec.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /usr/local/Cellar/libressl/3.0.2/include/openssl/rand.h /usr/local/Cellar/libressl/3.0.2/include/openssl/conf.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslconf.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dh.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ecdh.h /usr/local/Cellar/libressl/3.0.2/include/openssl/lhash.h /usr/local/Cellar/libressl/3.0.2/include/openssl/stack.h /usr/local/Cellar/libressl/3.0.2/include/openssl/safestack.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/CCryptoOpenSSL/include/c_crypto_openssl.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pem.h /usr/local/Cellar/libressl/3.0.2/include/openssl/bn.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /usr/local/Cellar/libressl/3.0.2/include/openssl/bio.h /usr/local/Cellar/libressl/3.0.2/include/openssl/crypto.h /usr/local/Cellar/libressl/3.0.2/include/openssl/srtp.h /usr/local/Cellar/libressl/3.0.2/include/openssl/evp.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ossl_typ.h /usr/local/Cellar/libressl/3.0.2/include/openssl/buffer.h /usr/local/Cellar/libressl/3.0.2/include/openssl/err.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslfeatures.h /usr/local/Cellar/libressl/3.0.2/include/openssl/objects.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslv.h /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509_vfy.h /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/CBase32/include/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/crypto/Sources/CBcrypt/include/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio-zlib-support/module.modulemap /Users/christian/GitHub/vapor/HelloVapor/.build/checkouts/swift-nio-ssl-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
|
D
|
import std.stdio : writeln;
char[] encrypt(char[] input, char shift) {
auto result = input.dup;
result[] -= 'a';
result[] += shift;
result[] %= 26;
result[] += 'a';
return result;
}
void main() {
// static size
int[8] staticArr;
// dynamic size (allocated to heap)
int size = 8;
int[] dynamicArr = new int[size];
// manipulation
int[] arr = [1, 2, 3];
arr[] *= 2;
assert(arr == [2, 4, 6]);
char[] toBeEncrypted = ['w', 'e', 'l', 'c', 'o', 'm', 'e', 't', 'o', 'd'];
writeln("before: ", toBeEncrypted);
auto encrypted = encrypt(toBeEncrypted, 16);
writeln("after: ", encrypted);
assert(encrypted == ['m', 'u', 'b', 's', 'e', 'c', 'u', 'j', 'e', 't']);
}
|
D
|
/Users/Juli/Documents/Swift/Eventy/Build/Intermediates.noindex/IBDesignables/Intermediates.noindex/Eventy.build/Debug-iphonesimulator/Eventy.build/Objects-normal/x86_64/Event.o : /Users/Juli/Documents/Swift/Eventy/Eventy/AppDelegate.swift /Users/Juli/Documents/Swift/Eventy/Eventy/EventTableViewCell.swift /Users/Juli/Documents/Swift/Eventy/Eventy/DateControl.swift /Users/Juli/Documents/Swift/Eventy/Eventy/EventTableViewController.swift /Users/Juli/Documents/Swift/Eventy/Eventy/AddEventViewController.swift /Users/Juli/Documents/Swift/Eventy/Eventy/Event.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/os.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/os.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/Juli/Documents/Swift/Eventy/Build/Intermediates.noindex/IBDesignables/Intermediates.noindex/Eventy.build/Debug-iphonesimulator/Eventy.build/Objects-normal/x86_64/Event~partial.swiftmodule : /Users/Juli/Documents/Swift/Eventy/Eventy/AppDelegate.swift /Users/Juli/Documents/Swift/Eventy/Eventy/EventTableViewCell.swift /Users/Juli/Documents/Swift/Eventy/Eventy/DateControl.swift /Users/Juli/Documents/Swift/Eventy/Eventy/EventTableViewController.swift /Users/Juli/Documents/Swift/Eventy/Eventy/AddEventViewController.swift /Users/Juli/Documents/Swift/Eventy/Eventy/Event.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/os.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/os.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/Juli/Documents/Swift/Eventy/Build/Intermediates.noindex/IBDesignables/Intermediates.noindex/Eventy.build/Debug-iphonesimulator/Eventy.build/Objects-normal/x86_64/Event~partial.swiftdoc : /Users/Juli/Documents/Swift/Eventy/Eventy/AppDelegate.swift /Users/Juli/Documents/Swift/Eventy/Eventy/EventTableViewCell.swift /Users/Juli/Documents/Swift/Eventy/Eventy/DateControl.swift /Users/Juli/Documents/Swift/Eventy/Eventy/EventTableViewController.swift /Users/Juli/Documents/Swift/Eventy/Eventy/AddEventViewController.swift /Users/Juli/Documents/Swift/Eventy/Eventy/Event.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/os.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/os.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
|
D
|
instance DIA_MARIA_EXIT(C_INFO)
{
npc = bau_910_maria;
nr = 999;
condition = dia_maria_exit_condition;
information = dia_maria_exit_info;
permanent = TRUE;
description = DIALOG_ENDE;
};
func int dia_maria_exit_condition()
{
return TRUE;
};
func void dia_maria_exit_info()
{
AI_StopProcessInfos(self);
};
instance DIA_MARIA_HALLO(C_INFO)
{
npc = bau_910_maria;
nr = 1;
condition = dia_maria_hallo_condition;
information = dia_maria_hallo_info;
permanent = FALSE;
description = "Kdo jsi?";
};
func int dia_maria_hallo_condition()
{
return TRUE;
};
func void dia_maria_hallo_info()
{
AI_Output(other,self,"DIA_Maria_Hallo_15_00"); //Kdo jsi?
AI_Output(self,other,"DIA_Maria_Hallo_17_01"); //Jsem Onarova žena, Maria.
AI_Output(self,other,"DIA_Maria_Hallo_17_02"); //Co tady chceš?
};
instance DIA_MARIA_UMSEHEN(C_INFO)
{
npc = bau_910_maria;
nr = 2;
condition = dia_maria_umsehen_condition;
information = dia_maria_umsehen_info;
permanent = FALSE;
description = "Jen jsem si to chtěl tady prohlédnout.";
};
func int dia_maria_umsehen_condition()
{
if(Npc_KnowsInfo(other,dia_maria_hallo))
{
return TRUE;
};
};
func void dia_maria_umsehen_info()
{
AI_Output(other,self,"DIA_Maria_Umsehen_15_00"); //Jen jsem si to chtěl tady prohlédnout.
AI_Output(self,other,"DIA_Maria_Umsehen_17_01"); //S tolika chlapama na farmě se teď nemůžu uvnitř domu moc zdržovat.
AI_Output(self,other,"DIA_Maria_Umsehen_17_02"); //Prostě sem jen tak vpadli.
};
instance DIA_MARIA_SOELDNER(C_INFO)
{
npc = bau_910_maria;
nr = 3;
condition = dia_maria_soeldner_condition;
information = dia_maria_soeldner_info;
permanent = FALSE;
description = "Obtěžují tě ti žoldáci?";
};
func int dia_maria_soeldner_condition()
{
if(Npc_KnowsInfo(other,dia_maria_umsehen))
{
return TRUE;
};
};
func void dia_maria_soeldner_info()
{
AI_Output(other,self,"DIA_Maria_Soeldner_15_00"); //Obtěžují tě ti žoldáci?
if((hero.guild == GIL_SLD) || (hero.guild == GIL_DJG))
{
AI_Output(self,other,"DIA_Maria_Soeldner_17_01"); //Hele, zapomeň na to, co jsem právě řekla - je tu teď mnohem bezpečněji, co se ti chlapi objevili.
}
else
{
AI_Output(self,other,"DIA_Maria_Soeldner_17_02"); //No, přinejmenším je tu teď, co jsou tu žoldáci, mnohem bezpečněji.
};
AI_Output(self,other,"DIA_Maria_Soeldner_17_03"); //Dokud jsme tu byli sami, pokaždé přišla domobrana z města a sebrala naši úrodu.
AI_Output(self,other,"DIA_Maria_Soeldner_17_04"); //Sebrali nejlepší část úrody. A taky si vzali pár ovcí. Nedali nám za to vůbec nic.
AI_Output(self,other,"DIA_Maria_Soeldner_17_05"); //Někteří z těch ničemů se tu dokonce odvážili krást.
if(hero.guild == GIL_MIL)
{
AI_Output(self,other,"DIA_Maria_Soeldner_17_06"); //Nevysvětluj si to nijak zle, vojáku. Vím, že takoví nejsou všichni.
};
};
instance DIA_MARIA_MISSION(C_INFO)
{
npc = bau_910_maria;
nr = 4;
condition = dia_maria_mission_condition;
information = dia_maria_mission_info;
permanent = FALSE;
description = "Tak co ti ukradli?";
};
func int dia_maria_mission_condition()
{
if(Npc_KnowsInfo(other,dia_maria_soeldner) && (MIS_MARIA_BRINGPLATE != LOG_SUCCESS))
{
return TRUE;
};
};
func void dia_maria_mission_info()
{
AI_Output(other,self,"DIA_Maria_Mission_15_00"); //Tak co ti ukradli?
AI_Output(self,other,"DIA_Maria_Mission_17_01"); //Většinou zlato a stříbro. Taky nám sebrali svatební dar. Zlatý tác.
if(other.guild != GIL_MIL)
{
AI_Output(self,other,"DIA_Maria_Mission_17_02"); //Vsadím se, že teď se na něm usazuje prach v truhle nějakého mizerného městského strážného.
};
MIS_MARIA_BRINGPLATE = LOG_RUNNING;
};
instance DIA_MARIA_BRINGPLATE(C_INFO)
{
npc = bau_910_maria;
nr = 5;
condition = dia_maria_bringplate_condition;
information = dia_maria_bringplate_info;
permanent = FALSE;
description = "Mám u sebe zlatý talíř. Není náhodou tvůj?";
};
func int dia_maria_bringplate_condition()
{
if(Npc_HasItems(other,itmi_mariasgoldplate) > 0)
{
return TRUE;
};
};
func void dia_maria_bringplate_info()
{
b_giveinvitems(other,self,itmi_mariasgoldplate,1);
AI_Output(other,self,"DIA_Maria_BringPlate_15_00"); //Mám u sebe zlatý talíř. Není náhodou tvůj?
AI_Output(self,other,"DIA_Maria_BringPlate_17_01"); //Ano! To je on! Tisíceré díky!
MIS_MARIA_BRINGPLATE = LOG_SUCCESS;
b_giveplayerxp(XP_MARIA_TELLER);
};
var int maria_belohnung;
instance DIA_MARIA_BELOHNUNG(C_INFO)
{
npc = bau_910_maria;
nr = 6;
condition = dia_maria_belohnung_condition;
information = dia_maria_belohnung_info;
permanent = TRUE;
description = "A co takhle nějakou odměnu?";
};
func int dia_maria_belohnung_condition()
{
if((MIS_MARIA_BRINGPLATE == LOG_SUCCESS) && (MARIA_BELOHNUNG == FALSE))
{
return TRUE;
};
};
func void dia_maria_belohnung_info()
{
AI_Output(other,self,"DIA_Maria_Belohnung_15_00"); //A co takhle nějakou odměnu?
if((other.guild == GIL_SLD) || Npc_KnowsInfo(other,dia_onar_howmuch))
{
AI_Output(self,other,"DIA_Maria_Belohnung_17_01"); //Pracuješ pro mého manžela jako žoldnéř, ne?
AI_Output(other,self,"DIA_Maria_Belohnung_15_02"); //Správně.
AI_Output(self,other,"DIA_Maria_Belohnung_17_03"); //Kolik ti platí?
b_say_gold(other,self,SOLD);
AI_Output(self,other,"DIA_Maria_Belohnung_17_04"); //To tedy moc není. Zajdi za ním a řekni mu, ať ti přidá.
AI_Output(other,self,"DIA_Maria_Belohnung_15_05"); //A myslíš, že to udělá?
AI_Output(self,other,"DIA_Maria_Belohnung_17_06"); //Ví, co by se stalo, kdyby ne. Věř mi.
MARIA_MEHRGOLD = TRUE;
MARIA_BELOHNUNG = TRUE;
}
else if(other.guild == GIL_NONE)
{
AI_Output(self,other,"DIA_Maria_Belohnung_17_07"); //Chceš se tady na farmě nechat najmout jako žoldák?
Info_ClearChoices(dia_maria_belohnung);
Info_AddChoice(dia_maria_belohnung,"Ne - vážně ne.",dia_maria_belohnung_gold);
Info_AddChoice(dia_maria_belohnung,"Ano.",dia_maria_belohnung_sold);
}
else
{
b_giveinvitems(self,other,itmi_gold,50);
MARIA_BELOHNUNG = TRUE;
AI_Output(self,other,"DIA_Maria_Belohnung_17_08"); //Tady, vezmi si to. Zasloužíš si to.
};
};
func void dia_maria_belohnung_gold()
{
AI_Output(other,self,"DIA_Maria_Belohnung_Gold_15_00"); //Ne - vážně ne.
b_giveinvitems(self,other,itmi_gold,50);
MARIA_BELOHNUNG = TRUE;
AI_Output(self,other,"DIA_Maria_Belohnung_Gold_17_01"); //Tak si na oplátku vezmi tohle zlato. Zasloužil sis to.
Info_ClearChoices(dia_maria_belohnung);
};
func void dia_maria_belohnung_sold()
{
AI_Output(other,self,"DIA_Maria_Belohnung_SOLD_15_00"); //Ano.
AI_Output(self,other,"DIA_Maria_Belohnung_SOLD_17_01"); //Dobrá, pokud tady pracuješ, tak dohlédnu na to, abys dostával slušný žold.
AI_Output(self,other,"DIA_Maria_Belohnung_SOLD_17_02"); //Vrať se, až si s mým manželem promluvíš o tvém platu.
Info_ClearChoices(dia_maria_belohnung);
};
instance DIA_MARIA_ABOUTONAR(C_INFO)
{
npc = bau_910_maria;
nr = 7;
condition = dia_maria_aboutonar_condition;
information = dia_maria_aboutonar_info;
permanent = FALSE;
description = "Řekni mi něco o Onarovi.";
};
func int dia_maria_aboutonar_condition()
{
if(Npc_KnowsInfo(other,dia_maria_hallo))
{
return TRUE;
};
};
func void dia_maria_aboutonar_info()
{
AI_Output(other,self,"DIA_Maria_AboutOnar_15_00"); //Řekni mi něco o Onarovi.
AI_Output(self,other,"DIA_Maria_AboutOnar_17_01"); //Je to fajn chlap. Trochu nabručený a hodně netrpělivý, ale všichni máme své chyby.
AI_Output(self,other,"DIA_Maria_AboutOnar_17_02"); //Řekla jsem svému muži, proč ty vojáky necháš se sebou takhle zacházet?
AI_Output(self,other,"DIA_Maria_AboutOnar_17_03"); //Dělej něco, říkám.
AI_Output(self,other,"DIA_Maria_AboutOnar_17_04"); //Tak najal žoldnéře. Teď se cítím jako uprostřed války.
AI_Output(self,other,"DIA_Maria_AboutOnar_17_05"); //Ale mi vlastně jsme ve válce, nebo ne?
};
instance DIA_MARIA_PERM(C_INFO)
{
npc = bau_910_maria;
nr = 8;
condition = dia_maria_perm_condition;
information = dia_maria_perm_info;
permanent = FALSE;
description = "Stalo se poslední dobou něco zajímavého?";
};
func int dia_maria_perm_condition()
{
if(Npc_KnowsInfo(other,dia_maria_hallo))
{
return TRUE;
};
};
func void dia_maria_perm_info()
{
AI_Output(other,self,"DIA_Maria_PERM_15_00"); //Stalo se poslední dobou něco zajímavého?
if(KAPITEL <= 2)
{
AI_Output(self,other,"DIA_Maria_PERM_17_01"); //Prošli tudy paladinové.
AI_Output(self,other,"DIA_Maria_PERM_17_02"); //Nejdřív jsme si mysleli, že přišli napadnout farmu, ale ve skutečnosti měli namířeno do Hornického údolí.
};
if(KAPITEL == 3)
{
AI_Output(self,other,"DIA_Maria_PERM_17_03"); //Wasili načapal před pár dny v noci zloděje. Jinak je tady klid.
};
if(KAPITEL >= 4)
{
AI_Output(self,other,"DIA_Maria_PERM_17_04"); //Je to tu mnohem klidnější, co někteří ze žoldnéřů odešli.
};
};
instance DIA_MARIA_PICKPOCKET(C_INFO)
{
npc = bau_910_maria;
nr = 900;
condition = dia_maria_pickpocket_condition;
information = dia_maria_pickpocket_info;
permanent = TRUE;
description = PICKPOCKET_60_FEMALE;
};
func int dia_maria_pickpocket_condition()
{
return c_beklauen(60,110);
};
func void dia_maria_pickpocket_info()
{
Info_ClearChoices(dia_maria_pickpocket);
Info_AddChoice(dia_maria_pickpocket,DIALOG_BACK,dia_maria_pickpocket_back);
Info_AddChoice(dia_maria_pickpocket,DIALOG_PICKPOCKET,dia_maria_pickpocket_doit);
};
func void dia_maria_pickpocket_doit()
{
b_beklauen();
Info_ClearChoices(dia_maria_pickpocket);
};
func void dia_maria_pickpocket_back()
{
Info_ClearChoices(dia_maria_pickpocket);
};
|
D
|
instance Mod_7636_MIL_Miliz_MT (Npc_Default)
{
// ------ NSC ------
name = Name_Miliz;
guild = GIL_OUT;
id = 7636;
voice = 0;
flags = 0;
npctype = NPCTYPE_nw_miliz;
// ------ Attribute ------
B_SetAttributesToChapter (self, 3);
// ------ Kampf-Taktik ------
fight_tactic = FAI_HUMAN_STRONG;
// ------ Equippte Waffen ------
EquipItem (self, ItMw_Milizschwert);
// ------ Inventory ------
B_CreateAmbientInv (self);
// ------ visuals ------
B_SetNpcVisual (self, MALE, "Hum_Head_Bald", Face_N_Mordrag, BodyTex_N, ITAR_MIL_L);
Mdl_SetModelFatness (self,0);
Mdl_ApplyOverlayMds (self, "Humans_Militia.mds");
// ------ NSC-relevante Talente vergeben ------
B_GiveNpcTalents (self);
// ------ Kampf-Talente ------
B_SetFightSkills (self, 40);
// ------ TA anmelden ------
daily_routine = Rtn_Start_7636;
};
FUNC VOID Rtn_Start_7636()
{
TA_Sit_Campfire (08,00,23,00,"CASTLE_27");
TA_Sit_Campfire (23,00,08,00,"CASTLE_27");
};
FUNC VOID Rtn_GuideToOrks_7636 ()
{
TA_Guide_Player (23,30,08,30,"CASTLE_36");
TA_Guide_Player (08,30,23,30,"CASTLE_36");
};
|
D
|
module drake.worldModel.mesh;
struct Mesh(T) {
Vector3!T[] verts;
Vector3!T[] norms;
ushort[] tris;
Material* mat;
this(const Material * mat) {
verts.
material = mat;
}
// TODO: implement
Vector3!T intersect(const ref Vector3!T focal_point, const ref Vector3!T view_point, T *tee) const {
// Vector3<double> direction = Vector3<double>(
// view_point[0] - focal_point[0],
// view_point[1] - focal_point[1],
// view_point[2] - focal_point[2]);
//
//
// //cout << "VP magnitude: " << view_point->size() << endl;
// //cout << "view point: " << (*view_point)[0] << ", " << (*view_point)[1] << ", " << (*view_point)[2] << endl;
//
//
//
// Vector3<double> line = Vector3<double>(
// vertices[0][0] - focal_point[0],
// vertices[0][1] - focal_point[1],
// vertices[0][2] - focal_point[2]);
//
// //vector<double> * dir = normalize(direction);
// //vector<double> * ln = normalize(line);
// double T = line.dot(normal)/direction.dot(normal);
// *tee = T;
// //cout << T << " = " << dot_product(line, n) << "/" << dot_product(direction, n) << endl;
// // ((*focal_point)[0] - vertices[0].get_x())/((*direction)[0]);
// Vector3<double> p = Vector3<double>(
// focal_point[0] + (direction[0]*T),
// focal_point[1] + (direction[1]*T),
// focal_point[2] + (direction[2]*T));
//
// //cout << "p: " << (*p)[0] << ", " << (*p)[1] << ", " << (*p)[2] << endl;
//
//
// /*double min = (*n)[0];
// int index;
// for (int i = 1; i < 3; i++) {
// if ((*n)[i] < min) {
// index = i;
// min = (*n)[i];
// }
// }
//
// vector<double> * m = make_perpendicular(n);
// vector<double> * u = cross_product(n, m);
// u = normalize(u);
// */
// //n->~vector();
// return p;
// //return is_inside(&p);//results;
// //return true;
}
// TODO: add back in
// bool Face::isInside(Vector3<double> & p) const {
// //cout << "p: " << (*p)[0] << ", " << (*p)[1] << ", " << (*p)[2] << endl;
// int index1;
// int index2;
// //const vector<double> * n = &normal;
// if (abs(normal[2]) > abs(normal[0]) && abs(normal[2]) > abs(normal[1])) {
// index1=0;
// index2=1;
// }
// else if (abs(normal[1]) > abs(normal[0])) {
// index1=0;
// index2=2;
// }
// else {
// index1=1;
// index2=2;
// }
// int count = 0;
// for (size_t i = 0; i < vertices.size(); i++) {
// int next = (i + 1) % vertices.size();
// //cout << "p: " << (*p)[0] << ", " << (*p)[1] << ", " << (*p)[2] << endl;
//
// vector<double> vertex1;
// vertex1.push_back(vertices[i][0]);
// vertex1.push_back(vertices[i][1]);
// vertex1.push_back(vertices[i][2]);
// //cout << "vertex1: " << vertex1[index1] << ", " << vertex1[index2] << endl;
//
// vector<double> vertex2;
// vertex2.push_back(vertices[next][0]);
// vertex2.push_back(vertices[next][1]);
// vertex2.push_back(vertices[next][2]);
// //cout << "vertex2: " << vertex2[index1] << ", " << vertex2[index2] << endl;
//
// if (abs(vertex2[index2] - vertex1[index2]) > 0.000001) {
// double t = (p[index2] - vertex1[index2])/(vertex2[index2] - vertex1[index2]);
// // cout << t << " = (" << (*p)[index2] << " - " << vertex1[index2] << ")/(" << vertex2[index2] << " - " << vertex1[index2] << ")" << endl;
// double x = vertex1[index1] + t*(vertex2[index1] - vertex1[index1]);
// // cout << x << " = " << vertex1[index1] << " + " << t << "*(" << vertex2[index1] << " - " << vertex1[index1] << ")" << endl;
//
// double max_y = max(vertex1[index2], vertex2[index2]);
// double min_y = min(vertex1[index2], vertex2[index2]);
// //cout << "index1: " << index1 << " index2: " << index2 << endl;
// //cout << "p_size: " << p->size() << endl;
// // cout << "x: " << x << " (*p)[index1] " << (*p)[index1] << " (*p)[index2] " << (*p)[index2] << " min_y " << min_y << " (*p)[index2] " << (*p)[index2] << " max_y " << max_y << endl;
// if (x > p[index1] && p[index2] > min_y && p[index2] <= max_y) {
// count++;
// }
// }
// }
// //cout << "count: " << count << endl;
// //n->~vector();
// return !(count % 2 == 0);
// }
//
// TODO: implement
Vector3!T normal() const {
// Vector3<double> a = Vector3<double>(
// vertices[1][0] - vertices[0][0],
// vertices[1][1] - vertices[0][1],
// vertices[1][2] - vertices[0][2]);
//
// Vector3<double> b = Vector3<double>(
// vertices[2][0] - vertices[1][0],
// vertices[2][1] - vertices[1][1],
// vertices[2][2] - vertices[1][2]);
//
// Vector3<double> n = a.cross(b);
//
// //TODO fix this test
// if (abs(n[0]) < .00001 && abs(n[1]) < .00001 && abs(n[2]) < .00001) {
// //cerr << "First three points of face are linear!" << endl;
// //return false;
// //exit(1);
// }
//
// normal = n.normal();
// return true;
}
// TODO: add back in
// bool Face::test_coplanarity(Vector3<double> vert) {
// Vector3<double> a = Vector3<double>(
// vert[0] - vertices[0][0],
// vert[1] - vertices[0][1],
// vert[2] - vertices[0][2]);
//
// double test = a.dot(normal);//a[0]*(*normal)[0] + a[1]*(*normal)[1] + a[2]*(*normal)[2];
//
// if (abs(test) < .0001) {
// return true;
// }
//
// else return false;
// }
// TODO: add back in
// vector<int> * Face::colorDiffuse(const Vector3<double> point, const vector<int> * light_color, double cos) {
// if (material->hasTexture()) {
// //cout << textureVertices.size() << endl;
// Vector3<double> first = Vector3<double> (
// vertices[0][0],
// vertices[0][1],
// vertices[0][2]);
//
// Vector3<double> second = Vector3<double> (
// vertices[1][0],
// vertices[1][1],
// vertices[1][2]);
//
// Vector3<double> third = Vector3<double>(
// vertices[2][0],
// vertices[2][1],
// vertices[2][2]);
//
// Vector3<double> one = first - second;
// Vector3<double> two = third - second;
//
// double lengthOne = one.magnitude();
// double lengthTwo = two.magnitude();
//
// //cout << (*one)[0] << ", " << (*one)[1] << ", " << (*one)[2] << endl;
// //cout << (*two)[0] << ", " << (*two)[1] << ", " << (*two)[2] << endl;
//
// Vector3<double> pointVector = point - second;
//
// double dotOne = one.normal().dot(pointVector);
// double dotTwo = two.normal().dot(pointVector);
//
// /* Vector3<double> texOne = Vector3<double> (
// (*textureVertices[0])[0],
// (*textureVertices[0])[1],
// 0);
//
// Vector3<double> texTwo = Vector3<double> (
// (*textureVertices[1])[0],
// (*textureVertices[1])[1],
// 0);
//
// Vector3<double> texThree = Vector3<double> (
// (*textureVertices[2])[0],
// (*textureVertices[2])[1],
// 0);
// */
//
// //if (textureVertices.count(1)) {
//
// //}
// //else return material->color_diffuse(light_color, cos);
// //if (textureVertices.count(2)) {
//
// //}
// //else return material->color_diffuse(light_color, cos);
//
// //Vector3<double> firstAxis = texOne - texTwo;
// //Vector3<double> secondAxis = texThree - texTwo;
//
// //double lengthAxisOne = firstAxis.magnitude();
// //double lengthAxisTwo = secondAxis.magnitude();
//
// double distOne = dotOne/lengthOne;
// double distTwo = dotTwo/lengthTwo;
// // cout << "success!! " << endl;
//
// // cout << "one: " << lengthOne << endl;
// // cout << "two: " << lengthTwo << endl;
//
// // return material->color_diffuse(light_color, cos, distOne, distTwo);
// //vector<double> * pointVector2 = subtract(
// //double AxisOneDot = dot_product(first,Axis
//
// }
//
// return material->color_diffuse(light_color, cos);
//
//
// }
// output
string toString() const {
string output = "mesh:";
foreach(Vector3!T vert; vertices) {
output ~= "\n\t" ~vert;
}
return output;
}
void toString(scope void delegate(const(char)[]) sink, FormatSpec!char fmt) const {
put(sink, "mesh:");
foreach(Vector3!T vert; vertices) {
put(sink, "\n\t");
put(sink, vert);
}
}
}
//////////////////
// Unit Tests //
//////////////////
|
D
|
/Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/HNote.build/Debug-iphoneos/HNote.build/Objects-normal/arm64/SidebarTableView.o : /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/AppDelegate.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/EWPopMenu/MenuTableViewCell.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/coreData/CoreDataManager.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/NoteContentController.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/RichTextController.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/ViewController.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/SettingViewController.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/NoteItem+CoreDataProperties.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/NoteItem+CoreDataClass.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/EWPopMenu/PopMenu.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/view/SidebarTableView.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/view/NotesTableView.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/view/SidebarTableCellView.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/view/NotesTableCellView.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/EWPopMenu/PopMenuView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.apinotesc /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/Debug-iphoneos/MarkdownView/MarkdownView.framework/Modules/MarkdownView.swiftmodule/arm64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/SwiftOnoneSupport.swiftmodule /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/Debug-iphoneos/MarkdownView/MarkdownView.framework/Headers/MarkdownView-umbrella.h /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/Debug-iphoneos/MarkdownView/MarkdownView.framework/Headers/MarkdownView-Swift.h /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/Debug-iphoneos/MarkdownView/MarkdownView.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/CoreData.framework/Headers/CoreData.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/WebKit.framework/Headers/WebKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/HNote.build/Debug-iphoneos/HNote.build/Objects-normal/arm64/SidebarTableView~partial.swiftmodule : /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/AppDelegate.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/EWPopMenu/MenuTableViewCell.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/coreData/CoreDataManager.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/NoteContentController.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/RichTextController.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/ViewController.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/SettingViewController.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/NoteItem+CoreDataProperties.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/NoteItem+CoreDataClass.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/EWPopMenu/PopMenu.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/view/SidebarTableView.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/view/NotesTableView.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/view/SidebarTableCellView.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/view/NotesTableCellView.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/EWPopMenu/PopMenuView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.apinotesc /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/Debug-iphoneos/MarkdownView/MarkdownView.framework/Modules/MarkdownView.swiftmodule/arm64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/SwiftOnoneSupport.swiftmodule /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/Debug-iphoneos/MarkdownView/MarkdownView.framework/Headers/MarkdownView-umbrella.h /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/Debug-iphoneos/MarkdownView/MarkdownView.framework/Headers/MarkdownView-Swift.h /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/Debug-iphoneos/MarkdownView/MarkdownView.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/CoreData.framework/Headers/CoreData.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/WebKit.framework/Headers/WebKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/HNote.build/Debug-iphoneos/HNote.build/Objects-normal/arm64/SidebarTableView~partial.swiftdoc : /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/AppDelegate.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/EWPopMenu/MenuTableViewCell.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/coreData/CoreDataManager.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/NoteContentController.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/RichTextController.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/ViewController.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/SettingViewController.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/NoteItem+CoreDataProperties.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/NoteItem+CoreDataClass.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/EWPopMenu/PopMenu.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/view/SidebarTableView.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/view/NotesTableView.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/view/SidebarTableCellView.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/view/NotesTableCellView.swift /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/HNote/EWPopMenu/PopMenuView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.apinotesc /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/Debug-iphoneos/MarkdownView/MarkdownView.framework/Modules/MarkdownView.swiftmodule/arm64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/SwiftOnoneSupport.swiftmodule /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/Debug-iphoneos/MarkdownView/MarkdownView.framework/Headers/MarkdownView-umbrella.h /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/Debug-iphoneos/MarkdownView/MarkdownView.framework/Headers/MarkdownView-Swift.h /Users/hongweihui/Desktop/IOS大作业_洪伟辉_18126278/HNote/build/Debug-iphoneos/MarkdownView/MarkdownView.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/CoreData.framework/Headers/CoreData.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/WebKit.framework/Headers/WebKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
|
D
|
instance NWKR(C_Item)
{
name = "Landkarte Khorinis mit Fundorten der Kräuter";
mainflag = ITEM_KAT_DOCS;
flags = ITEM_MISSION | ITEM_MULTI;
value = 0;
visual = "ItWr_Map_01.3DS";
material = MAT_LEATHER;
scemeName = "MAP";
on_state[0] = use_map_nwkr;
description = name;
text[0] = "Kronstöckl, Goblinbeeren und Drachenwurzeln";
text[1] = "Heilwurzel, Feuerwurzel, Snapperkraut und Feldknöterich";
text[5] = "Wert: ";
count[5] = value;
};
func void use_map_nwkr()
{
var int Document;
Document = Doc_CreateMap();
Doc_SetPages(Document,1);
Doc_SetPage(Document,0,"MAP_NW_KR.tga",TRUE);
Doc_SetLevel(Document,"NewWorld\NewWorld.zen");
Doc_SetLevelCoords(Document,-28000,50500,95500,-42500);
Doc_Show(Document);
};
instance NWTR(C_Item)
{
name = "Landkarte Khorinis mit Fundorten der Tränke";
mainflag = ITEM_KAT_DOCS;
flags = ITEM_MISSION | ITEM_MULTI;
value = 0;
visual = "ItWr_Map_01.3DS";
material = MAT_LEATHER;
scemeName = "MAP";
on_state[0] = use_map_nwtr;
description = name;
text[0] = "Elixier des Lebens, des Geistes, der Geschicklichkeit und der Stärke";
text[1] = "";
text[5] = "Wert: ";
count[5] = value;
};
func void use_map_nwtr()
{
var int Document;
Document = Doc_CreateMap();
Doc_SetPages(Document,1);
Doc_SetPage(Document,0,"MAP_NW_TR.tga",TRUE);
Doc_SetLevel(Document,"NewWorld\NewWorld.zen");
Doc_SetLevelCoords(Document,-28000,50500,95500,-42500);
Doc_Show(Document);
};
instance NWST(C_Item)
{
name = "Landkarte Khorinis mit Fundorten der Steintafeln";
mainflag = ITEM_KAT_DOCS;
flags = ITEM_MISSION | ITEM_MULTI;
value = 0;
visual = "ItWr_Map_01.3DS";
material = MAT_LEATHER;
scemeName = "MAP";
on_state[0] = use_map_nwst;
description = name;
text[0] = "Talenttafeln, Attributstafeln und Alte Steintafeln";
text[1] = "";
text[5] = "Wert: ";
count[5] = value;
};
func void use_map_nwst()
{
var int Document;
Document = Doc_CreateMap();
Doc_SetPages(Document,1);
Doc_SetPage(Document,0,"MAP_NW_ST.tga",TRUE);
Doc_SetLevel(Document,"NewWorld\NewWorld.zen");
Doc_SetLevelCoords(Document,-28000,50500,95500,-42500);
Doc_Show(Document);
};
instance OWKR(C_Item)
{
name = "Landkarte Minental mit Fundorten der Kräuter";
mainflag = ITEM_KAT_DOCS;
flags = ITEM_MISSION | ITEM_MULTI;
value = 0;
visual = "ItWr_Map_01.3DS";
material = MAT_LEATHER;
scemeName = "MAP";
on_state[0] = use_map_owkr;
description = name;
text[0] = "Goblinbeeren, Heilwurzeln, Feuerkraut, Snapperkraut und Feldknöterich";
text[1] = "";
text[5] = "Wert: ";
count[5] = value;
};
func void use_map_owkr()
{
var int Document;
Document = Doc_CreateMap();
Doc_SetPages(Document,1);
Doc_SetPage(Document,0,"MAP_OW_KR.tga",TRUE);
Doc_SetLevel(Document,"OldWorld\OldWorld.zen");
Doc_SetLevelCoords(Document,-78500,47500,54000,-53000);
Doc_Show(Document);
};
instance OWTR(C_Item)
{
name = "Landkarte Minental mit Fundorten der Tränke";
mainflag = ITEM_KAT_DOCS;
flags = ITEM_MISSION | ITEM_MULTI;
value = 0;
visual = "ItWr_Map_01.3DS";
material = MAT_LEATHER;
scemeName = "MAP";
on_state[0] = use_map_owtr;
description = name;
text[0] = "Elixier des Geistes, der Stärke oder der Geschicklichkeit";
text[1] = "";
text[5] = "Wert: ";
count[5] = value;
};
func void use_map_owtr()
{
var int Document;
Document = Doc_CreateMap();
Doc_SetPages(Document,1);
Doc_SetPage(Document,0,"MAP_OW_TR.tga",TRUE);
Doc_SetLevel(Document,"OldWorld\OldWorld.zen");
Doc_SetLevelCoords(Document,-78500,47500,54000,-53000);
Doc_Show(Document);
};
instance OWST(C_Item)
{
name = "Landkarte Minental mit Fundorten der Steintafeln";
mainflag = ITEM_KAT_DOCS;
flags = ITEM_MISSION | ITEM_MULTI;
value = 0;
visual = "ItWr_Map_01.3DS";
material = MAT_LEATHER;
scemeName = "MAP";
on_state[0] = use_map_owst;
description = name;
text[0] = "Talenttafeln, Attributstafeln und Alte Steintafeln";
text[1] = "";
text[5] = "Wert: ";
count[5] = value;
};
func void use_map_owst()
{
var int Document;
Document = Doc_CreateMap();
Doc_SetPages(Document,1);
Doc_SetPage(Document,0,"MAP_OW_ST.tga",TRUE);
Doc_SetLevel(Document,"OldWorld\OldWorld.zen");
Doc_SetLevelCoords(Document,-78500,47500,54000,-53000);
Doc_Show(Document);
};
instance AWTR(C_Item)
{
name = "Landkarte Jharkendar mit Tränken";
mainflag = ITEM_KAT_DOCS;
flags = ITEM_MISSION | ITEM_MULTI;
value = 0;
visual = "ItWr_Map_01.3DS";
material = MAT_LEATHER;
scemeName = "MAP";
on_state[0] = use_map_awtr;
description = name;
text[0] = "Essenz des Geistes und Elixier des Lebens";
text[1] = "";
text[5] = "Wert: ";
count[5] = value;
};
func void use_map_awtr()
{
var int Document;
Document = Doc_CreateMap();
Doc_SetPages(Document,1);
Doc_SetPage(Document,0,"MAP_AW_TR.tga",TRUE);
Doc_SetLevel(Document,"Addon\AddonWorld.zen");
Doc_SetLevelCoords(Document,-47783,36300,43949,-32300);
Doc_Show(Document);
};
instance AWKR(C_Item)
{
name = "Landkarte Jharkendar mit Kräuter";
mainflag = ITEM_KAT_DOCS;
flags = ITEM_MISSION | ITEM_MULTI;
value = 0;
visual = "ItWr_Map_01.3DS";
material = MAT_LEATHER;
scemeName = "MAP";
on_state[0] = use_map_awkr;
description = name;
text[0] = "Kronstöckel, Heilwurzel, Feuerwurzel, Snapperkraut und Feldknöterich";
text[1] = "";
text[5] = "Wert: ";
count[5] = value;
};
func void use_map_awkr()
{
var int Document;
Document = Doc_CreateMap();
Doc_SetPages(Document,1);
Doc_SetPage(Document,0,"MAP_AW_KR.tga",TRUE);
Doc_SetLevel(Document,"Addon\AddonWorld.zen");
Doc_SetLevelCoords(Document,-47783,36300,43949,-32300);
Doc_Show(Document);
};
instance AWST(C_Item)
{
name = "Landkarte Jharkendar mit Steintafeln";
mainflag = ITEM_KAT_DOCS;
flags = ITEM_MISSION | ITEM_MULTI;
value = 0;
visual = "ItWr_Map_01.3DS";
material = MAT_LEATHER;
scemeName = "MAP";
on_state[0] = use_map_awst;
description = name;
text[0] = "Talenttafeln, Attributstafeln und Alte Steintafeln";
text[1] = "";
text[5] = "Wert: ";
count[5] = value;
};
func void use_map_awst()
{
var int Document;
Document = Doc_CreateMap();
Doc_SetPages(Document,1);
Doc_SetPage(Document,0,"MAP_AW_ST.tga",TRUE);
Doc_SetLevel(Document,"Addon\AddonWorld.zen");
Doc_SetLevelCoords(Document,-47783,36300,43949,-32300);
Doc_Show(Document);
};
|
D
|
/*
* This file is part of gtkD.
*
* gtkD is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* gtkD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with gtkD; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// generated automatically - do not change
// find conversion definition on APILookup.txt
// implement new conversion functionalities on the wrap.utils pakage
/*
* Conversion parameters:
* inFile =
* outPack = gda
* outFile = ProviderInfo
* strct = GdaProviderInfo
* realStrct=
* ctorStrct=
* clss = ProviderInfo
* interf =
* class Code: Yes
* interface Code: No
* template for:
* extend =
* implements:
* prefixes:
* - gda_provider_
* omit structs:
* omit prefixes:
* omit code:
* omit signals:
* imports:
* - gtkD.glib.Str
* - gtkD.glib.ListG
* structWrap:
* - GdaProviderInfo* -> ProviderInfo
* module aliases:
* local aliases:
* overrides:
*/
module gtkD.gda.ProviderInfo;
public import gtkD.gdac.gdatypes;
private import gtkD.gdac.gda;
private import gtkD.glib.ConstructionException;
private import gtkD.glib.Str;
private import gtkD.glib.ListG;
/**
* Description
* The functions in this section allow applications an easy access to the libgda
* configuration, thus making them able to access the list of data sources
* configured in the system, for instance.
*/
public class ProviderInfo
{
/** the main Gtk struct */
protected GdaProviderInfo* gdaProviderInfo;
public GdaProviderInfo* getProviderInfoStruct()
{
return gdaProviderInfo;
}
/** the main Gtk struct as a void* */
protected void* getStruct()
{
return cast(void*)gdaProviderInfo;
}
/**
* Sets our main struct and passes it to the parent class
*/
public this (GdaProviderInfo* gdaProviderInfo)
{
if(gdaProviderInfo is null)
{
this = null;
return;
}
this.gdaProviderInfo = gdaProviderInfo;
}
/** */
this (ListG glist) {
this.gdaProviderInfo = cast(GdaProviderInfo *) glist.data;
}
/** */
string id() { return Str.toString(this.gdaProviderInfo.id); }
/** */
string location() { return Str.toString(this.gdaProviderInfo.location); }
/** */
string description() { return Str.toString(this.gdaProviderInfo.description); }
/** */
ListG gda_params() { return new ListG(this.gdaProviderInfo.gdaParams); }
/**
*/
/**
* Returns:
*/
public static GType infoGetType()
{
// GType gda_provider_info_get_type (void);
return gda_provider_info_get_type();
}
/**
* Creates a new GdaProviderInfo structure from an existing one.
* Returns: a newly allocated GdaProviderInfo with contains a copy of information in src.
*/
public ProviderInfo infoCopy()
{
// GdaProviderInfo* gda_provider_info_copy (GdaProviderInfo *src);
auto p = gda_provider_info_copy(gdaProviderInfo);
if(p is null)
{
return null;
}
return new ProviderInfo(cast(GdaProviderInfo*) p);
}
/**
* Deallocates all memory associated to the given GdaProviderInfo.
*/
public void infoFree()
{
// void gda_provider_info_free (GdaProviderInfo *provider_info);
gda_provider_info_free(gdaProviderInfo);
}
}
|
D
|
module UnrealScript.UnrealEd.GenericBrowserType_RenderTexture;
import ScriptClasses;
import UnrealScript.Helpers;
import UnrealScript.UnrealEd.GenericBrowserType_Texture;
extern(C++) interface GenericBrowserType_RenderTexture : GenericBrowserType_Texture
{
public extern(D):
private static __gshared ScriptClass mStaticClass;
@property final static ScriptClass StaticClass() { mixin(MGSCC("Class UnrealEd.GenericBrowserType_RenderTexture")); }
private static __gshared GenericBrowserType_RenderTexture mDefaultProperties;
@property final static GenericBrowserType_RenderTexture DefaultProperties() { mixin(MGDPC("GenericBrowserType_RenderTexture", "GenericBrowserType_RenderTexture UnrealEd.Default__GenericBrowserType_RenderTexture")); }
}
|
D
|
// Written in the D programming language.
/**
This is a submodule of $(MREF std, algorithm).
It contains generic comparison algorithms.
$(SCRIPT inhibitQuickIndex = 1;)
$(BOOKTABLE Cheat Sheet,
$(TR $(TH Function Name) $(TH Description))
$(T2 among,
Checks if a value is among a set of values, e.g.
`if (v.among(1, 2, 3)) // `v` is 1, 2 or 3`)
$(T2 castSwitch,
`(new A()).castSwitch((A a)=>1,(B b)=>2)` returns `1`.)
$(T2 clamp,
`clamp(1, 3, 6)` returns `3`. `clamp(4, 3, 6)` returns `4`.)
$(T2 cmp,
`cmp("abc", "abcd")` is `-1`, `cmp("abc", "aba")` is `1`,
and `cmp("abc", "abc")` is `0`.)
$(T2 either,
Return first parameter `p` that passes an `if (p)` test, e.g.
`either(0, 42, 43)` returns `42`.)
$(T2 equal,
Compares ranges for element-by-element equality, e.g.
`equal([1, 2, 3], [1.0, 2.0, 3.0])` returns `true`.)
$(T2 isPermutation,
`isPermutation([1, 2], [2, 1])` returns `true`.)
$(T2 isSameLength,
`isSameLength([1, 2, 3], [4, 5, 6])` returns `true`.)
$(T2 levenshteinDistance,
`levenshteinDistance("kitten", "sitting")` returns `3` by using
the $(LINK2 https://en.wikipedia.org/wiki/Levenshtein_distance,
Levenshtein distance algorithm).)
$(T2 levenshteinDistanceAndPath,
`levenshteinDistanceAndPath("kitten", "sitting")` returns
`tuple(3, "snnnsni")` by using the
$(LINK2 https://en.wikipedia.org/wiki/Levenshtein_distance,
Levenshtein distance algorithm).)
$(T2 max,
`max(3, 4, 2)` returns `4`.)
$(T2 min,
`min(3, 4, 2)` returns `2`.)
$(T2 mismatch,
`mismatch("oh hi", "ohayo")` returns `tuple(" hi", "ayo")`.)
$(T2 predSwitch,
`2.predSwitch(1, "one", 2, "two", 3, "three")` returns `"two"`.)
)
Copyright: Andrei Alexandrescu 2008-.
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP erdani.com, Andrei Alexandrescu)
Source: $(PHOBOSSRC std/algorithm/comparison.d)
Macros:
T2=$(TR $(TDNW $(LREF $1)) $(TD $+))
*/
module std.algorithm.comparison;
import std.functional : unaryFun, binaryFun, lessThan, greaterThan;
import std.range.primitives;
import std.traits;
import std.meta : allSatisfy, anySatisfy;
import std.typecons : tuple, Tuple, Flag, Yes;
import std.internal.attributes : betterC;
/**
Find `value` _among `values`, returning the 1-based index
of the first matching value in `values`, or `0` if `value`
is not _among `values`. The predicate `pred` is used to
compare values, and uses equality by default.
Params:
pred = The predicate used to compare the values.
value = The value to search for.
values = The values to compare the value to.
Returns:
0 if value was not found among the values, otherwise the index of the
found value plus one is returned.
See_Also:
$(REF_ALTTEXT find, find, std,algorithm,searching) and $(REF_ALTTEXT canFind, canFind, std,algorithm,searching) for finding a value in a
range.
*/
uint among(alias pred = (a, b) => a == b, Value, Values...)
(Value value, Values values)
if (Values.length != 0)
{
foreach (uint i, ref v; values)
{
import std.functional : binaryFun;
if (binaryFun!pred(value, v)) return i + 1;
}
return 0;
}
/// Ditto
template among(values...)
if (isExpressionTuple!values)
{
uint among(Value)(Value value)
if (!is(CommonType!(Value, values) == void))
{
switch (value)
{
foreach (uint i, v; values)
case v:
return i + 1;
default:
return 0;
}
}
}
///
@safe @nogc @betterC unittest
{
assert(3.among(1, 42, 24, 3, 2));
if (auto pos = "bar".among("foo", "bar", "baz"))
assert(pos == 2);
else
assert(false);
// 42 is larger than 24
assert(42.among!((lhs, rhs) => lhs > rhs)(43, 24, 100) == 2);
}
/**
Alternatively, `values` can be passed at compile-time, allowing for a more
efficient search, but one that only supports matching on equality:
*/
@safe @nogc @betterC unittest
{
assert(3.among!(2, 3, 4));
assert("bar".among!("foo", "bar", "baz") == 2);
}
@safe unittest
{
import std.meta : AliasSeq;
if (auto pos = 3.among(1, 2, 3))
assert(pos == 3);
else
assert(false);
assert(!4.among(1, 2, 3));
auto position = "hello".among("hello", "world");
assert(position);
assert(position == 1);
alias values = AliasSeq!("foo", "bar", "baz");
auto arr = [values];
assert(arr[0 .. "foo".among(values)] == ["foo"]);
assert(arr[0 .. "bar".among(values)] == ["foo", "bar"]);
assert(arr[0 .. "baz".among(values)] == arr);
assert("foobar".among(values) == 0);
if (auto pos = 3.among!(1, 2, 3))
assert(pos == 3);
else
assert(false);
assert(!4.among!(1, 2, 3));
position = "hello".among!("hello", "world");
assert(position);
assert(position == 1);
static assert(!__traits(compiles, "a".among!("a", 42)));
static assert(!__traits(compiles, (Object.init).among!(42, "a")));
}
// Used in castSwitch to find the first choice that overshadows the last choice
// in a tuple.
private template indexOfFirstOvershadowingChoiceOnLast(choices...)
{
alias firstParameterTypes = Parameters!(choices[0]);
alias lastParameterTypes = Parameters!(choices[$ - 1]);
static if (lastParameterTypes.length == 0)
{
// If the last is null-typed choice, check if the first is null-typed.
enum isOvershadowing = firstParameterTypes.length == 0;
}
else static if (firstParameterTypes.length == 1)
{
// If the both first and last are not null-typed, check for overshadowing.
enum isOvershadowing =
is(firstParameterTypes[0] == Object) // Object overshadows all other classes!(this is needed for interfaces)
|| is(lastParameterTypes[0] : firstParameterTypes[0]);
}
else
{
// If the first is null typed and the last is not - the is no overshadowing.
enum isOvershadowing = false;
}
static if (isOvershadowing)
{
enum indexOfFirstOvershadowingChoiceOnLast = 0;
}
else
{
enum indexOfFirstOvershadowingChoiceOnLast =
1 + indexOfFirstOvershadowingChoiceOnLast!(choices[1..$]);
}
}
/**
Executes and returns one of a collection of handlers based on the type of the
switch object.
The first choice that `switchObject` can be casted to the type
of argument it accepts will be called with `switchObject` casted to that
type, and the value it'll return will be returned by `castSwitch`.
If a choice's return type is void, the choice must throw an exception, unless
all the choices are void. In that case, castSwitch itself will return void.
Throws: If none of the choice matches, a `SwitchError` will be thrown. $(D
SwitchError) will also be thrown if not all the choices are void and a void
choice was executed without throwing anything.
Params:
choices = The `choices` needs to be composed of function or delegate
handlers that accept one argument. There can also be a choice that
accepts zero arguments. That choice will be invoked if the $(D
switchObject) is null.
switchObject = the object against which the tests are being made.
Returns:
The value of the selected choice.
Note: `castSwitch` can only be used with object types.
*/
auto castSwitch(choices...)(Object switchObject)
{
import core.exception : SwitchError;
import std.format : format;
// Check to see if all handlers return void.
enum areAllHandlersVoidResult = {
bool result = true;
foreach (index, choice; choices)
{
result &= is(ReturnType!choice : void); // void or noreturn
}
return result;
}();
if (switchObject !is null)
{
// Checking for exact matches:
const classInfo = typeid(switchObject);
foreach (index, choice; choices)
{
static assert(isCallable!choice,
"A choice handler must be callable");
alias choiceParameterTypes = Parameters!choice;
static assert(choiceParameterTypes.length <= 1,
"A choice handler can not have more than one argument.");
static if (choiceParameterTypes.length == 1)
{
alias CastClass = choiceParameterTypes[0];
static assert(is(CastClass == class) || is(CastClass == interface),
"A choice handler can have only class or interface typed argument.");
// Check for overshadowing:
immutable indexOfOvershadowingChoice =
indexOfFirstOvershadowingChoiceOnLast!(choices[0 .. index + 1]);
static assert(indexOfOvershadowingChoice == index,
"choice number %d(type %s) is overshadowed by choice number %d(type %s)".format(
index + 1, CastClass.stringof, indexOfOvershadowingChoice + 1,
Parameters!(choices[indexOfOvershadowingChoice])[0].stringof));
if (classInfo == typeid(CastClass))
{
static if (is(ReturnType!(choice) == void))
{
choice(cast(CastClass) switchObject);
static if (areAllHandlersVoidResult)
{
return;
}
else
{
throw new SwitchError("Handlers that return void should throw");
}
}
else
{
return choice(cast(CastClass) switchObject);
}
}
}
}
// Checking for derived matches:
foreach (choice; choices)
{
alias choiceParameterTypes = Parameters!choice;
static if (choiceParameterTypes.length == 1)
{
if (auto castedObject = cast(choiceParameterTypes[0]) switchObject)
{
static if (is(ReturnType!(choice) == void))
{
choice(castedObject);
static if (areAllHandlersVoidResult)
{
return;
}
else
{
throw new SwitchError("Handlers that return void should throw");
}
}
else
{
return choice(castedObject);
}
}
}
}
}
else // If switchObject is null:
{
// Checking for null matches:
foreach (index, choice; choices)
{
static if (Parameters!(choice).length == 0)
{
immutable indexOfOvershadowingChoice =
indexOfFirstOvershadowingChoiceOnLast!(choices[0 .. index + 1]);
// Check for overshadowing:
static assert(indexOfOvershadowingChoice == index,
"choice number %d(null reference) is overshadowed by choice number %d(null reference)".format(
index + 1, indexOfOvershadowingChoice + 1));
if (switchObject is null)
{
static if (is(ReturnType!(choice) == void))
{
choice();
static if (areAllHandlersVoidResult)
{
return;
}
else
{
throw new SwitchError("Handlers that return void should throw");
}
}
else
{
return choice();
}
}
}
}
}
// In case nothing matched:
throw new SwitchError("Input not matched by any choice");
}
///
@system unittest
{
import std.algorithm.iteration : map;
import std.format : format;
class A
{
int a;
this(int a) {this.a = a;}
@property int i() { return a; }
}
interface I { }
class B : I { }
Object[] arr = [new A(1), new B(), null];
auto results = arr.map!(castSwitch!(
(A a) => "A with a value of %d".format(a.a),
(I i) => "derived from I",
() => "null reference",
))();
// A is handled directly:
assert(results[0] == "A with a value of 1");
// B has no handler - it is handled by the handler of I:
assert(results[1] == "derived from I");
// null is handled by the null handler:
assert(results[2] == "null reference");
}
/// Using with void handlers:
@system unittest
{
import std.exception : assertThrown;
class A { }
class B { }
// Void handlers are allowed if they throw:
assertThrown!Exception(
new B().castSwitch!(
(A a) => 1,
(B d) { throw new Exception("B is not allowed!"); }
)()
);
// Void handlers are also allowed if all the handlers are void:
new A().castSwitch!(
(A a) { },
(B b) { assert(false); },
)();
}
@system unittest
{
import core.exception : SwitchError;
import std.exception : assertThrown;
interface I { }
class A : I { }
class B { }
// Nothing matches:
assertThrown!SwitchError((new A()).castSwitch!(
(B b) => 1,
() => 2,
)());
// Choices with multiple arguments are not allowed:
static assert(!__traits(compiles,
(new A()).castSwitch!(
(A a, B b) => 0,
)()));
// Only callable handlers allowed:
static assert(!__traits(compiles,
(new A()).castSwitch!(
1234,
)()));
// Only object arguments allowed:
static assert(!__traits(compiles,
(new A()).castSwitch!(
(int x) => 0,
)()));
// Object overshadows regular classes:
static assert(!__traits(compiles,
(new A()).castSwitch!(
(Object o) => 0,
(A a) => 1,
)()));
// Object overshadows interfaces:
static assert(!__traits(compiles,
(new A()).castSwitch!(
(Object o) => 0,
(I i) => 1,
)()));
// No multiple null handlers allowed:
static assert(!__traits(compiles,
(new A()).castSwitch!(
() => 0,
() => 1,
)()));
// No non-throwing void handlers allowed(when there are non-void handlers):
assertThrown!SwitchError((new A()).castSwitch!(
(A a) {},
(B b) => 2,
)());
// All-void handlers work for the null case:
null.castSwitch!(
(Object o) { assert(false); },
() { },
)();
// Throwing void handlers work for the null case:
assertThrown!Exception(null.castSwitch!(
(Object o) => 1,
() { throw new Exception("null"); },
)());
}
@system unittest
{
interface I { }
class B : I { }
class C : I { }
assert((new B()).castSwitch!(
(B b) => "class B",
(I i) => "derived from I",
) == "class B");
assert((new C()).castSwitch!(
(B b) => "class B",
(I i) => "derived from I",
) == "derived from I");
}
// https://issues.dlang.org/show_bug.cgi?id=22384
@system unittest
{
// Use explicit methods to enforce return types
static void objectSkip(Object) {}
static void defaultSkip() {}
static noreturn objectError(Object) { assert(false); }
static noreturn defaultError() { assert(false); }
{
alias test = castSwitch!(objectSkip, defaultError);
static assert(is(ReturnType!test == void));
}{
alias test = castSwitch!(objectError, defaultSkip);
static assert(is(ReturnType!test == void));
}{
alias test = castSwitch!(objectError, defaultError);
static assert(is(ReturnType!test == noreturn));
}
// Also works with non-void handlers
static int objectValue(Object) { return 1;}
static int defaultValue() { return 2; }
{
alias test = castSwitch!(objectValue, defaultError);
static assert(is(ReturnType!test == int));
}{
alias test = castSwitch!(objectError, defaultValue);
static assert(is(ReturnType!test == int));
}
// No confusion w.r.t. void callbacks
alias FP = void function();
static FP objectFunc(Object) { return &defaultSkip; }
static FP defaultFunc() { return &defaultSkip; }
{
alias test = castSwitch!(objectFunc, defaultError);
static assert(is(ReturnType!test == FP));
}{
alias test = castSwitch!(objectError, defaultFunc);
static assert(is(ReturnType!test == FP));
}
}
/** Clamps `val` into the given bounds. Result has the same type as `val`.
Params:
val = The value to _clamp.
lower = The _lower bound of the _clamp.
upper = The _upper bound of the _clamp.
Returns:
`lower` if `val` is less than `lower`, `upper` if `val` is greater than
`upper`, and `val` in all other cases. Comparisons are made
correctly (using $(REF lessThan, std,functional) and the return value
is converted to the return type using the standard integer coversion rules
$(REF greaterThan, std,functional)) even if the signedness of `T1`, `T2`,
and `T3` are different.
*/
T1 clamp(T1, T2, T3)(T1 val, T2 lower, T3 upper)
{
static assert(is(T2 : T1), "T2 of type '", T2.stringof
, "' must be implicitly convertible to type of T1 '"
, T1.stringof, "'");
static assert(is(T3 : T1), "T3 of type '", T3.stringof
, "' must be implicitly convertible to type of T1 '"
, T1.stringof, "'");
assert(!lower.greaterThan(upper), "Lower can't be greater than upper.");
// `if (is(typeof(val.lessThan(lower) ? lower : val.greaterThan(upper) ? upper : val) : T1))
// because of https://issues.dlang.org/show_bug.cgi?id=16235.
// Once that is fixed, we can simply use the ternary in both the template constraint
// and the template body
if (val.lessThan(lower))
return lower;
else if (val.greaterThan(upper))
return upper;
return val;
}
///
@safe @nogc @betterC unittest
{
assert(clamp(2, 1, 3) == 2);
assert(clamp(0, 1, 3) == 1);
assert(clamp(4, 1, 3) == 3);
assert(clamp(1, 1, 1) == 1);
assert(clamp(5, -1, 2u) == 2);
auto x = clamp(42, uint.max, uint.max);
static assert(is(typeof(x) == int));
assert(x == -1);
}
@safe unittest
{
int a = 1;
short b = 6;
double c = 2;
static assert(is(typeof(clamp(c,a,b)) == double));
assert(clamp(c, a, b) == c);
assert(clamp(a-c, a, b) == a);
assert(clamp(b+c, a, b) == b);
// mixed sign
a = -5;
uint f = 5;
static assert(is(typeof(clamp(f, a, b)) == uint));
assert(clamp(f, a, b) == f);
// similar type deduction for (u)long
static assert(is(typeof(clamp(-1L, -2L, 2UL)) == long));
// user-defined types
import std.datetime : Date;
assert(clamp(Date(1982, 1, 4), Date(1012, 12, 21), Date(2012, 12, 21)) == Date(1982, 1, 4));
assert(clamp(Date(1982, 1, 4), Date.min, Date.max) == Date(1982, 1, 4));
// UFCS style
assert(Date(1982, 1, 4).clamp(Date.min, Date.max) == Date(1982, 1, 4));
// Stability
struct A {
int x, y;
int opCmp(ref const A rhs) const { return (x > rhs.x) - (x < rhs.x); }
}
A x, lo, hi;
x.y = 42;
assert(x.clamp(lo, hi).y == 42);
}
// https://issues.dlang.org/show_bug.cgi?id=23268
@safe pure nothrow @nogc unittest
{
static assert(__traits(compiles, clamp(short.init, short.init, cast(const) short.init)));
}
// cmp
/**********************************
Performs a lexicographical comparison on two
$(REF_ALTTEXT input ranges, isInputRange, std,range,primitives).
Iterating `r1` and `r2` in lockstep, `cmp` compares each element
`e1` of `r1` with the corresponding element `e2` in `r2`. If one
of the ranges has been finished, `cmp` returns a negative value
if `r1` has fewer elements than `r2`, a positive value if `r1`
has more elements than `r2`, and `0` if the ranges have the same
number of elements.
If the ranges are strings, `cmp` performs UTF decoding
appropriately and compares the ranges one code point at a time.
A custom predicate may be specified, in which case `cmp` performs
a three-way lexicographical comparison using `pred`. Otherwise
the elements are compared using `opCmp`.
Params:
pred = Predicate used for comparison. Without a predicate
specified the ordering implied by `opCmp` is used.
r1 = The first range.
r2 = The second range.
Returns:
`0` if the ranges compare equal. A negative value if `r1` is a prefix of `r2` or
the first differing element of `r1` is less than the corresponding element of `r2`
according to `pred`. A positive value if `r2` is a prefix of `r1` or the first
differing element of `r2` is less than the corresponding element of `r1`
according to `pred`.
Note:
An earlier version of the documentation incorrectly stated that `-1` is the
only negative value returned and `1` is the only positive value returned.
Whether that is true depends on the types being compared.
*/
auto cmp(R1, R2)(R1 r1, R2 r2)
if (isInputRange!R1 && isInputRange!R2)
{
alias E1 = ElementEncodingType!R1;
alias E2 = ElementEncodingType!R2;
static if (isDynamicArray!R1 && isDynamicArray!R2
&& __traits(isUnsigned, E1) && __traits(isUnsigned, E2)
&& E1.sizeof == 1 && E2.sizeof == 1
// Both or neither must auto-decode.
&& (is(immutable E1 == immutable char) == is(immutable E2 == immutable char)))
{
// dstrcmp algorithm is correct for both ubyte[] and for char[].
import core.internal.string : dstrcmp;
return dstrcmp(cast(const char[]) r1, cast(const char[]) r2);
}
else static if (!(isSomeString!R1 && isSomeString!R2))
{
for (;; r1.popFront(), r2.popFront())
{
static if (is(typeof(r1.front.opCmp(r2.front)) R))
alias Result = R;
else
alias Result = int;
if (r2.empty) return Result(!r1.empty);
if (r1.empty) return Result(-1);
static if (is(typeof(r1.front.opCmp(r2.front))))
{
auto c = r1.front.opCmp(r2.front);
if (c != 0) return c;
}
else
{
auto a = r1.front, b = r2.front;
if (auto result = (b < a) - (a < b)) return result;
}
}
}
else
{
static if (typeof(r1[0]).sizeof == typeof(r2[0]).sizeof)
{
return () @trusted
{
auto p1 = r1.ptr, p2 = r2.ptr,
pEnd = p1 + min(r1.length, r2.length);
for (; p1 != pEnd; ++p1, ++p2)
{
if (*p1 != *p2) return cast(int) *p1 - cast(int) *p2;
}
static if (typeof(r1[0]).sizeof >= 2 && size_t.sizeof <= uint.sizeof)
return cast(int) r1.length - cast(int) r2.length;
else
return int(r1.length > r2.length) - int(r1.length < r2.length);
}();
}
else
{
import std.utf : decode;
for (size_t i1, i2;;)
{
if (i1 == r1.length) return -int(i2 < r2.length);
if (i2 == r2.length) return int(1);
immutable c1 = decode(r1, i1),
c2 = decode(r2, i2);
if (c1 != c2) return cast(int) c1 - cast(int) c2;
}
}
}
}
/// ditto
int cmp(alias pred, R1, R2)(R1 r1, R2 r2)
if (isInputRange!R1 && isInputRange!R2)
{
static if (!(isSomeString!R1 && isSomeString!R2))
{
for (;; r1.popFront(), r2.popFront())
{
if (r2.empty) return !r1.empty;
if (r1.empty) return -1;
auto a = r1.front, b = r2.front;
if (binaryFun!pred(a, b)) return -1;
if (binaryFun!pred(b, a)) return 1;
}
}
else
{
import std.utf : decode;
for (size_t i1, i2;;)
{
if (i1 == r1.length) return -int(i2 < r2.length);
if (i2 == r2.length) return 1;
immutable c1 = decode(r1, i1),
c2 = decode(r2, i2);
if (c1 != c2)
{
if (binaryFun!pred(c2, c1)) return 1;
if (binaryFun!pred(c1, c2)) return -1;
}
}
}
}
///
pure @safe unittest
{
int result;
result = cmp("abc", "abc");
assert(result == 0);
result = cmp("", "");
assert(result == 0);
result = cmp("abc", "abcd");
assert(result < 0);
result = cmp("abcd", "abc");
assert(result > 0);
result = cmp("abc"d, "abd");
assert(result < 0);
result = cmp("bbc", "abc"w);
assert(result > 0);
result = cmp("aaa", "aaaa"d);
assert(result < 0);
result = cmp("aaaa", "aaa"d);
assert(result > 0);
result = cmp("aaa", "aaa"d);
assert(result == 0);
result = cmp("aaa"d, "aaa"d);
assert(result == 0);
result = cmp(cast(int[])[], cast(int[])[]);
assert(result == 0);
result = cmp([1, 2, 3], [1, 2, 3]);
assert(result == 0);
result = cmp([1, 3, 2], [1, 2, 3]);
assert(result > 0);
result = cmp([1, 2, 3], [1L, 2, 3, 4]);
assert(result < 0);
result = cmp([1L, 2, 3], [1, 2]);
assert(result > 0);
}
/// Example predicate that compares individual elements in reverse lexical order
pure @safe unittest
{
int result;
result = cmp!"a > b"("abc", "abc");
assert(result == 0);
result = cmp!"a > b"("", "");
assert(result == 0);
result = cmp!"a > b"("abc", "abcd");
assert(result < 0);
result = cmp!"a > b"("abcd", "abc");
assert(result > 0);
result = cmp!"a > b"("abc"d, "abd");
assert(result > 0);
result = cmp!"a > b"("bbc", "abc"w);
assert(result < 0);
result = cmp!"a > b"("aaa", "aaaa"d);
assert(result < 0);
result = cmp!"a > b"("aaaa", "aaa"d);
assert(result > 0);
result = cmp!"a > b"("aaa", "aaa"d);
assert(result == 0);
result = cmp("aaa"d, "aaa"d);
assert(result == 0);
result = cmp!"a > b"(cast(int[])[], cast(int[])[]);
assert(result == 0);
result = cmp!"a > b"([1, 2, 3], [1, 2, 3]);
assert(result == 0);
result = cmp!"a > b"([1, 3, 2], [1, 2, 3]);
assert(result < 0);
result = cmp!"a > b"([1, 2, 3], [1L, 2, 3, 4]);
assert(result < 0);
result = cmp!"a > b"([1L, 2, 3], [1, 2]);
assert(result > 0);
}
// cmp for string with custom predicate fails if distinct chars can compare equal
// https://issues.dlang.org/show_bug.cgi?id=18286
@nogc nothrow pure @safe unittest
{
static bool ltCi(dchar a, dchar b)// less than, case insensitive
{
import std.ascii : toUpper;
return toUpper(a) < toUpper(b);
}
static assert(cmp!ltCi("apple2", "APPLE1") > 0);
static assert(cmp!ltCi("apple1", "APPLE2") < 0);
static assert(cmp!ltCi("apple", "APPLE1") < 0);
static assert(cmp!ltCi("APPLE", "apple1") < 0);
static assert(cmp!ltCi("apple", "APPLE") == 0);
}
// for non-string ranges check that opCmp is evaluated only once per pair.
// https://issues.dlang.org/show_bug.cgi?id=18280
@nogc nothrow @safe unittest
{
static int ctr = 0;
struct S
{
int opCmp(ref const S rhs) const
{
++ctr;
return 0;
}
bool opEquals(T)(T o) const { return false; }
size_t toHash() const { return 0; }
}
immutable S[4] a;
immutable S[4] b;
immutable result = cmp(a[], b[]);
assert(result == 0, "neither should compare greater than the other!");
assert(ctr == a.length, "opCmp should be called exactly once per pair of items!");
}
nothrow pure @safe @nogc unittest
{
import std.array : staticArray;
// Test cmp when opCmp returns float.
struct F
{
float value;
float opCmp(const ref F rhs) const
{
return value - rhs.value;
}
bool opEquals(T)(T o) const { return false; }
size_t toHash() const { return 0; }
}
auto result = cmp([F(1), F(2), F(3)].staticArray[], [F(1), F(2), F(3)].staticArray[]);
assert(result == 0);
assert(is(typeof(result) == float));
result = cmp([F(1), F(3), F(2)].staticArray[], [F(1), F(2), F(3)].staticArray[]);
assert(result > 0);
result = cmp([F(1), F(2), F(3)].staticArray[], [F(1), F(2), F(3), F(4)].staticArray[]);
assert(result < 0);
result = cmp([F(1), F(2), F(3)].staticArray[], [F(1), F(2)].staticArray[]);
assert(result > 0);
}
nothrow pure @safe unittest
{
// Parallelism (was broken by inferred return type "immutable int")
import std.parallelism : task;
auto t = task!cmp("foo", "bar");
}
// equal
/**
Compares two or more ranges for equality, as defined by predicate `pred`
(which is `==` by default).
*/
template equal(alias pred = "a == b")
{
/++
Compares two or more ranges for equality. The ranges may have
different element types, as long as all are comparable by means of
the `pred`.
Performs $(BIGOH min(rs[0].length, rs[1].length, ...)) evaluations of `pred`. However, if
`equal` is invoked with the default predicate, the implementation may take the liberty
to use faster implementations that have the theoretical worst-case
$(BIGOH max(rs[0].length, rs[1].length, ...)).
At least one of the ranges must be finite. If one range involved is infinite, the result is
(statically known to be) `false`.
If the ranges have different kinds of UTF code unit (`char`, `wchar`, or
`dchar`), then they are compared using UTF decoding to avoid
accidentally integer-promoting units.
Params:
rs = The ranges to be compared.
Returns:
`true` if and only if all ranges compare _equal element
for element, according to binary predicate `pred`.
+/
bool equal(Ranges...)(Ranges rs)
if (rs.length > 1
&& allSatisfy!(isInputRange, Ranges)
&& !allSatisfy!(isInfinite, Ranges)
&& is(typeof(binaryFun!pred(rs[0].front, rs[1].front)))
&& (rs.length == 2 || is(typeof(equal!pred(rs[1 .. $])) == bool))
)
{
alias ElementEncodingTypes = staticMap!(ElementEncodingType, Ranges);
enum differentSize(T) = T.sizeof != ElementEncodingTypes[0].sizeof;
enum useCodePoint = allSatisfy!(isSomeChar, ElementEncodingTypes) &&
anySatisfy!(differentSize, ElementEncodingTypes);
enum bool comparableWithEq(alias r) = is(typeof(rs[0] == r));
static if (anySatisfy!(isInfinite, Ranges))
{
return false;
}
else static if (useCodePoint)
{
import std.utf : byDchar;
static bool allByDchar(size_t done, Ranges...)(auto ref Ranges rs)
{
static if (done == rs.length)
return equalLoop(rs);
else
return allByDchar!(done + 1)(rs[0 .. done], rs[done].byDchar, rs[done + 1 .. $]);
}
return allByDchar!0(rs);
}
else static if (is(typeof(pred) == string) && pred == "a == b" &&
allSatisfy!(isArray, Ranges) && allSatisfy!(comparableWithEq, rs))
{
static foreach (r; rs[1 .. $])
if (rs[0] != r)
return false;
return true;
}
// if one of the arguments is a string and the other isn't, then auto-decoding
// can be avoided if they have the same ElementEncodingType
// TODO: generalize this
else static if (rs.length == 2 && is(typeof(pred) == string) && pred == "a == b" &&
isAutodecodableString!(Ranges[0]) != isAutodecodableString!(Ranges[1]) &&
is(immutable ElementEncodingType!(Ranges[0]) == immutable ElementEncodingType!(Ranges[1])))
{
import std.utf : byCodeUnit;
static if (isAutodecodableString!(Ranges[0]))
return equal(rs[0].byCodeUnit, rs[1]);
else
return equal(rs[1].byCodeUnit, rs[0]);
}
else
{
static foreach (i, R; Ranges)
{
static if (hasLength!R)
{
static if (!is(typeof(firstLength)))
{
// Found the first range that has length
auto firstLength = rs[i].length;
}
else
{
// Compare the length of the current range against the first with length
if (firstLength != rs[i].length)
return false;
}
}
}
return equalLoop(rs);
}
}
private bool equalLoop(Rs...)(ref Rs rs)
{
for (; !rs[0].empty; rs[0].popFront)
static foreach (r; rs[1 .. $])
if (r.empty || !binaryFun!pred(rs[0].front, r.front))
return false;
else
r.popFront;
static foreach (r; rs[1 .. $])
if (!r.empty)
return false;
return true;
}
}
///
@safe @nogc unittest
{
import std.algorithm.comparison : equal;
import std.math.operations : isClose;
int[4] a = [ 1, 2, 4, 3 ];
assert(!equal(a[], a[1..$]));
assert(equal(a[], a[]));
assert(equal!((a, b) => a == b)(a[], a[]));
// different types
double[4] b = [ 1.0, 2, 4, 3];
assert(!equal(a[], b[1..$]));
assert(equal(a[], b[]));
// predicated: ensure that two vectors are approximately equal
double[4] c = [ 1.0000000005, 2, 4, 3];
assert(equal!isClose(b[], c[]));
}
@safe @nogc unittest
{
import std.algorithm.comparison : equal;
import std.math.operations : isClose;
auto s1 = "abc", s2 = "abc"w;
assert(equal(s1, s2, s2));
assert(equal(s1, s2, s2, s1));
assert(!equal(s1, s2, s2[1 .. $]));
int[4] a = [ 1, 2, 4, 3 ];
assert(!equal(a[], a[1..$], a[]));
assert(equal(a[], a[], a[]));
assert(equal!((a, b) => a == b)(a[], a[], a[]));
// different types
double[4] b = [ 1.0, 2, 4, 3];
assert(!equal(a[], b[1..$], b[]));
assert(equal(a[], b[], a[], b[]));
// predicated: ensure that two vectors are approximately equal
double[4] c = [ 1.0000000005, 2, 4, 3];
assert(equal!isClose(b[], c[], b[]));
}
/++
Tip: `equal` can itself be used as a predicate to other functions.
This can be very useful when the element type of a range is itself a
range. In particular, `equal` can be its own predicate, allowing
range of range (of range...) comparisons.
+/
@safe unittest
{
import std.algorithm.comparison : equal;
import std.range : iota, chunks;
assert(equal!(equal!equal)(
[[[0, 1], [2, 3]], [[4, 5], [6, 7]]],
iota(0, 8).chunks(2).chunks(2)
));
}
@safe unittest
{
import std.algorithm.iteration : map;
import std.internal.test.dummyrange : ReferenceForwardRange,
ReferenceInputRange, ReferenceInfiniteForwardRange;
import std.math.operations : isClose;
// various strings
assert(equal("æøå", "æøå")); //UTF8 vs UTF8
assert(!equal("???", "æøå")); //UTF8 vs UTF8
assert(equal("æøå"w, "æøå"d)); //UTF16 vs UTF32
assert(!equal("???"w, "æøå"d));//UTF16 vs UTF32
assert(equal("æøå"d, "æøå"d)); //UTF32 vs UTF32
assert(!equal("???"d, "æøå"d));//UTF32 vs UTF32
assert(!equal("hello", "world"));
// same strings, but "explicit non default" comparison (to test the non optimized array comparison)
assert( equal!("a == b")("æøå", "æøå")); //UTF8 vs UTF8
assert(!equal!("a == b")("???", "æøå")); //UTF8 vs UTF8
assert( equal!("a == b")("æøå"w, "æøå"d)); //UTF16 vs UTF32
assert(!equal!("a == b")("???"w, "æøå"d));//UTF16 vs UTF32
assert( equal!("a == b")("æøå"d, "æøå"d)); //UTF32 vs UTF32
assert(!equal!("a == b")("???"d, "æøå"d));//UTF32 vs UTF32
assert(!equal!("a == b")("hello", "world"));
//Array of string
assert(equal(["hello", "world"], ["hello", "world"]));
assert(!equal(["hello", "world"], ["hello"]));
assert(!equal(["hello", "world"], ["hello", "Bob!"]));
//Should not compile, because "string == dstring" is illegal
static assert(!is(typeof(equal(["hello", "world"], ["hello"d, "world"d]))));
//However, arrays of non-matching string can be compared using equal!equal. Neat-o!
equal!equal(["hello", "world"], ["hello"d, "world"d]);
//Tests, with more fancy map ranges
int[] a = [ 1, 2, 4, 3 ];
assert(equal([2, 4, 8, 6], map!"a*2"(a)));
double[] b = [ 1.0, 2, 4, 3];
double[] c = [ 1.0000000005, 2, 4, 3];
assert(equal!isClose(map!"a*2"(b), map!"a*2"(c)));
assert(!equal([2, 4, 1, 3], map!"a*2"(a)));
assert(!equal([2, 4, 1], map!"a*2"(a)));
assert(!equal!isClose(map!"a*3"(b), map!"a*2"(c)));
//Tests with some fancy reference ranges.
ReferenceInputRange!int cir = new ReferenceInputRange!int([1, 2, 4, 3]);
ReferenceForwardRange!int cfr = new ReferenceForwardRange!int([1, 2, 4, 3]);
assert(equal(cir, a));
cir = new ReferenceInputRange!int([1, 2, 4, 3]);
assert(equal(cir, cfr.save));
assert(equal(cfr.save, cfr.save));
cir = new ReferenceInputRange!int([1, 2, 8, 1]);
assert(!equal(cir, cfr));
//Test with an infinite range
auto ifr = new ReferenceInfiniteForwardRange!int;
assert(!equal(a, ifr));
assert(!equal(ifr, a));
//Test InputRange without length
assert(!equal(ifr, cir));
assert(!equal(cir, ifr));
}
@safe @nogc pure unittest
{
import std.utf : byChar, byDchar, byWchar;
assert(equal("æøå".byChar, "æøå"));
assert(equal("æøå".byChar, "æøå"w));
assert(equal("æøå".byChar, "æøå"d));
assert(equal("æøå", "æøå".byChar));
assert(equal("æøå"w, "æøå".byChar));
assert(equal("æøå"d, "æøå".byChar));
assert(equal("æøå".byWchar, "æøå"));
assert(equal("æøå".byWchar, "æøå"w));
assert(equal("æøå".byWchar, "æøå"d));
assert(equal("æøå", "æøå".byWchar));
assert(equal("æøå"w, "æøå".byWchar));
assert(equal("æøå"d, "æøå".byWchar));
assert(equal("æøå".byDchar, "æøå"));
assert(equal("æøå".byDchar, "æøå"w));
assert(equal("æøå".byDchar, "æøå"d));
assert(equal("æøå", "æøå".byDchar));
assert(equal("æøå"w, "æøå".byDchar));
assert(equal("æøå"d, "æøå".byDchar));
}
@safe @nogc pure unittest
{
struct R(bool _empty) {
enum empty = _empty;
@property char front(){assert(0);}
void popFront(){assert(0);}
}
alias I = R!false;
static assert(!__traits(compiles, I().equal(I())));
// strings have fixed length so don't need to compare elements
assert(!I().equal("foo"));
assert(!"bar".equal(I()));
alias E = R!true;
assert(E().equal(E()));
assert(E().equal(""));
assert("".equal(E()));
assert(!E().equal("foo"));
assert(!"bar".equal(E()));
}
// levenshteinDistance
/**
Encodes $(HTTP realityinteractive.com/rgrzywinski/archives/000249.html,
edit operations) necessary to transform one sequence into
another. Given sequences `s` (source) and `t` (target), a
sequence of `EditOp` encodes the steps that need to be taken to
convert `s` into `t`. For example, if `s = "cat"` and $(D
"cars"), the minimal sequence that transforms `s` into `t` is:
skip two characters, replace 't' with 'r', and insert an 's'. Working
with edit operations is useful in applications such as spell-checkers
(to find the closest word to a given misspelled word), approximate
searches, diff-style programs that compute the difference between
files, efficient encoding of patches, DNA sequence analysis, and
plagiarism detection.
*/
enum EditOp : char
{
/** Current items are equal; no editing is necessary. */
none = 'n',
/** Substitute current item in target with current item in source. */
substitute = 's',
/** Insert current item from the source into the target. */
insert = 'i',
/** Remove current item from the target. */
remove = 'r'
}
///
@safe unittest
{
with(EditOp)
{
assert(levenshteinDistanceAndPath("foo", "foobar")[1] == [none, none, none, insert, insert, insert]);
assert(levenshteinDistanceAndPath("banana", "fazan")[1] == [substitute, none, substitute, none, none, remove]);
}
}
private struct Levenshtein(Range, alias equals, CostType = size_t)
{
EditOp[] path()
{
import std.algorithm.mutation : reverse;
EditOp[] result;
size_t i = rows - 1, j = cols - 1;
// restore the path
while (i || j)
{
auto cIns = j == 0 ? CostType.max : matrix(i,j - 1);
auto cDel = i == 0 ? CostType.max : matrix(i - 1,j);
auto cSub = i == 0 || j == 0
? CostType.max
: matrix(i - 1,j - 1);
switch (min_index(cSub, cIns, cDel))
{
case 0:
result ~= matrix(i - 1,j - 1) == matrix(i,j)
? EditOp.none
: EditOp.substitute;
--i;
--j;
break;
case 1:
result ~= EditOp.insert;
--j;
break;
default:
result ~= EditOp.remove;
--i;
break;
}
}
reverse(result);
return result;
}
~this() {
FreeMatrix();
}
private:
CostType _deletionIncrement = 1,
_insertionIncrement = 1,
_substitutionIncrement = 1;
CostType[] _matrix;
size_t rows, cols;
// Treat _matrix as a rectangular array
ref CostType matrix(size_t row, size_t col) { return _matrix[row * cols + col]; }
void AllocMatrix(size_t r, size_t c) @trusted {
import core.checkedint : mulu;
bool overflow;
const rc = mulu(r, c, overflow);
assert(!overflow, "Overflow during multiplication to determine number "
~ " of matrix elements");
rows = r;
cols = c;
if (_matrix.length < rc)
{
import core.exception : onOutOfMemoryError;
import core.stdc.stdlib : realloc;
const nbytes = mulu(rc, _matrix[0].sizeof, overflow);
assert(!overflow, "Overflow during multiplication to determine "
~ " number of bytes of matrix");
auto m = cast(CostType *) realloc(_matrix.ptr, nbytes);
if (!m)
onOutOfMemoryError();
_matrix = m[0 .. r * c];
InitMatrix();
}
}
void FreeMatrix() @trusted {
import core.stdc.stdlib : free;
free(_matrix.ptr);
_matrix = null;
}
void InitMatrix() {
foreach (r; 0 .. rows)
matrix(r,0) = r * _deletionIncrement;
foreach (c; 0 .. cols)
matrix(0,c) = c * _insertionIncrement;
}
static uint min_index(CostType i0, CostType i1, CostType i2)
{
if (i0 <= i1)
{
return i0 <= i2 ? 0 : 2;
}
else
{
return i1 <= i2 ? 1 : 2;
}
}
CostType distanceWithPath(Range s, Range t)
{
auto slen = walkLength(s.save), tlen = walkLength(t.save);
AllocMatrix(slen + 1, tlen + 1);
foreach (i; 1 .. rows)
{
auto sfront = s.front;
auto tt = t.save;
foreach (j; 1 .. cols)
{
auto cSub = matrix(i - 1,j - 1)
+ (equals(sfront, tt.front) ? 0 : _substitutionIncrement);
tt.popFront();
auto cIns = matrix(i,j - 1) + _insertionIncrement;
auto cDel = matrix(i - 1,j) + _deletionIncrement;
switch (min_index(cSub, cIns, cDel))
{
case 0:
matrix(i,j) = cSub;
break;
case 1:
matrix(i,j) = cIns;
break;
default:
matrix(i,j) = cDel;
break;
}
}
s.popFront();
}
return matrix(slen,tlen);
}
CostType distanceLowMem(Range s, Range t, CostType slen, CostType tlen)
{
CostType lastdiag, olddiag;
AllocMatrix(slen + 1, 1);
foreach (y; 1 .. slen + 1)
{
_matrix[y] = y;
}
foreach (x; 1 .. tlen + 1)
{
auto tfront = t.front;
auto ss = s.save;
_matrix[0] = x;
lastdiag = x - 1;
foreach (y; 1 .. rows)
{
olddiag = _matrix[y];
auto cSub = lastdiag + (equals(ss.front, tfront) ? 0 : _substitutionIncrement);
ss.popFront();
auto cIns = _matrix[y - 1] + _insertionIncrement;
auto cDel = _matrix[y] + _deletionIncrement;
switch (min_index(cSub, cIns, cDel))
{
case 0:
_matrix[y] = cSub;
break;
case 1:
_matrix[y] = cIns;
break;
default:
_matrix[y] = cDel;
break;
}
lastdiag = olddiag;
}
t.popFront();
}
return _matrix[slen];
}
}
/**
Returns the $(HTTP wikipedia.org/wiki/Levenshtein_distance, Levenshtein
distance) between `s` and `t`. The Levenshtein distance computes
the minimal amount of edit operations necessary to transform `s`
into `t`. Performs $(BIGOH s.length * t.length) evaluations of $(D
equals) and occupies $(BIGOH min(s.length, t.length)) storage.
Params:
equals = The binary predicate to compare the elements of the two ranges.
s = The original range.
t = The transformation target
Returns:
The minimal number of edits to transform s into t.
Does not allocate GC memory.
*/
size_t levenshteinDistance(alias equals = (a,b) => a == b, Range1, Range2)
(Range1 s, Range2 t)
if (isForwardRange!(Range1) && isForwardRange!(Range2))
{
alias eq = binaryFun!(equals);
for (;;)
{
if (s.empty) return t.walkLength;
if (t.empty) return s.walkLength;
if (eq(s.front, t.front))
{
s.popFront();
t.popFront();
continue;
}
static if (isBidirectionalRange!(Range1) && isBidirectionalRange!(Range2))
{
if (eq(s.back, t.back))
{
s.popBack();
t.popBack();
continue;
}
}
break;
}
auto slen = walkLength(s.save);
auto tlen = walkLength(t.save);
if (slen == 1 && tlen == 1)
{
return eq(s.front, t.front) ? 0 : 1;
}
if (slen < tlen)
{
Levenshtein!(Range1, eq, size_t) lev;
return lev.distanceLowMem(s, t, slen, tlen);
}
else
{
Levenshtein!(Range2, eq, size_t) lev;
return lev.distanceLowMem(t, s, tlen, slen);
}
}
///
@safe unittest
{
import std.algorithm.iteration : filter;
import std.uni : toUpper;
assert(levenshteinDistance("cat", "rat") == 1);
assert(levenshteinDistance("parks", "spark") == 2);
assert(levenshteinDistance("abcde", "abcde") == 0);
assert(levenshteinDistance("abcde", "abCde") == 1);
assert(levenshteinDistance("kitten", "sitting") == 3);
assert(levenshteinDistance!((a, b) => toUpper(a) == toUpper(b))
("parks", "SPARK") == 2);
assert(levenshteinDistance("parks".filter!"true", "spark".filter!"true") == 2);
assert(levenshteinDistance("ID", "I♥D") == 1);
}
@safe @nogc nothrow unittest
{
assert(levenshteinDistance("cat"d, "rat"d) == 1);
}
/// ditto
size_t levenshteinDistance(alias equals = (a,b) => a == b, Range1, Range2)
(auto ref Range1 s, auto ref Range2 t)
if (isConvertibleToString!Range1 || isConvertibleToString!Range2)
{
import std.meta : staticMap;
alias Types = staticMap!(convertToString, Range1, Range2);
return levenshteinDistance!(equals, Types)(s, t);
}
@safe unittest
{
static struct S { string s; alias s this; }
assert(levenshteinDistance(S("cat"), S("rat")) == 1);
assert(levenshteinDistance("cat", S("rat")) == 1);
assert(levenshteinDistance(S("cat"), "rat") == 1);
}
@safe @nogc nothrow unittest
{
static struct S { dstring s; alias s this; }
assert(levenshteinDistance(S("cat"d), S("rat"d)) == 1);
assert(levenshteinDistance("cat"d, S("rat"d)) == 1);
assert(levenshteinDistance(S("cat"d), "rat"d) == 1);
}
/**
Returns the Levenshtein distance and the edit path between `s` and
`t`.
Params:
equals = The binary predicate to compare the elements of the two ranges.
s = The original range.
t = The transformation target
Returns:
Tuple with the first element being the minimal amount of edits to transform s into t and
the second element being the sequence of edits to effect this transformation.
Allocates GC memory for the returned EditOp[] array.
*/
Tuple!(size_t, EditOp[])
levenshteinDistanceAndPath(alias equals = (a,b) => a == b, Range1, Range2)
(Range1 s, Range2 t)
if (isForwardRange!(Range1) && isForwardRange!(Range2))
{
Levenshtein!(Range1, binaryFun!(equals)) lev;
auto d = lev.distanceWithPath(s, t);
return tuple(d, lev.path());
}
///
@safe unittest
{
string a = "Saturday", b = "Sundays";
auto p = levenshteinDistanceAndPath(a, b);
assert(p[0] == 4);
assert(equal(p[1], "nrrnsnnni"));
}
@safe unittest
{
assert(levenshteinDistance("a", "a") == 0);
assert(levenshteinDistance("a", "b") == 1);
assert(levenshteinDistance("aa", "ab") == 1);
assert(levenshteinDistance("aa", "abc") == 2);
assert(levenshteinDistance("Saturday", "Sunday") == 3);
assert(levenshteinDistance("kitten", "sitting") == 3);
}
/// ditto
Tuple!(size_t, EditOp[])
levenshteinDistanceAndPath(alias equals = (a,b) => a == b, Range1, Range2)
(auto ref Range1 s, auto ref Range2 t)
if (isConvertibleToString!Range1 || isConvertibleToString!Range2)
{
import std.meta : staticMap;
alias Types = staticMap!(convertToString, Range1, Range2);
return levenshteinDistanceAndPath!(equals, Types)(s, t);
}
@safe unittest
{
static struct S { string s; alias s this; }
assert(levenshteinDistanceAndPath(S("cat"), S("rat"))[0] == 1);
assert(levenshteinDistanceAndPath("cat", S("rat"))[0] == 1);
assert(levenshteinDistanceAndPath(S("cat"), "rat")[0] == 1);
}
// max
/**
Iterates the passed arguments and returns the maximum value.
Params:
args = The values to select the maximum from. At least two arguments must
be passed, and they must be comparable with `<`.
Returns:
The maximum of the passed-in values. The type of the returned value is
the type among the passed arguments that is able to store the largest value.
If at least one of the arguments is NaN, the result is an unspecified value.
See $(REF maxElement, std,algorithm,searching) for examples on how to cope
with NaNs.
See_Also:
$(REF maxElement, std,algorithm,searching)
*/
auto max(T...)(T args)
if (T.length >= 2 && !is(CommonType!T == void))
{
// Get left-hand side of the comparison.
static if (T.length == 2)
alias a = args[0];
else
auto a = max(args[0 .. ($ + 1) / 2]);
alias T0 = typeof(a);
// Get right-hand side.
static if (T.length <= 3)
alias b = args[$ - 1];
else
auto b = max(args[($ + 1) / 2 .. $]);
alias T1 = typeof(b);
static assert(is(typeof(a < b)),
"Invalid arguments: Cannot compare types " ~ T0.stringof ~
" and " ~ T1.stringof ~ " for ordering.");
// Compute the returned type.
static if (is(typeof(mostNegative!T0 < mostNegative!T1)))
// Both are numeric (or character or Boolean), so we choose the one with the highest maximum.
// (We use mostNegative for num/bool/char testing purposes even if it's not used otherwise.)
alias Result = Select!(T1.max > T0.max, T1, T0);
else
// At least one is non-numeric, so just go with the common type.
alias Result = CommonType!(T0, T1);
// Perform the computation.
import std.functional : lessThan;
immutable chooseB = lessThan!(T0, T1)(a, b);
return cast(Result) (chooseB ? b : a);
}
/// ditto
T max(T, U)(T a, U b)
if (is(T == U) && is(typeof(a < b)))
{
/* Handle the common case without all the template expansions
* of the general case
*/
return a < b ? b : a;
}
///
@safe @betterC @nogc unittest
{
int a = 5;
short b = 6;
double c = 2;
auto d = max(a, b);
assert(is(typeof(d) == int));
assert(d == 6);
auto e = min(a, b, c);
assert(is(typeof(e) == double));
assert(e == 2);
}
@safe unittest // not @nogc due to `Date`
{
int a = 5;
short b = 6;
double c = 2;
auto d = max(a, b);
static assert(is(typeof(d) == int));
assert(d == 6);
auto e = max(a, b, c);
static assert(is(typeof(e) == double));
assert(e == 6);
// mixed sign
a = -5;
uint f = 5;
static assert(is(typeof(max(a, f)) == uint));
assert(max(a, f) == 5);
//Test user-defined types
import std.datetime : Date;
assert(max(Date(2012, 12, 21), Date(1982, 1, 4)) == Date(2012, 12, 21));
assert(max(Date(1982, 1, 4), Date(2012, 12, 21)) == Date(2012, 12, 21));
assert(max(Date(1982, 1, 4), Date.min) == Date(1982, 1, 4));
assert(max(Date.min, Date(1982, 1, 4)) == Date(1982, 1, 4));
assert(max(Date(1982, 1, 4), Date.max) == Date.max);
assert(max(Date.max, Date(1982, 1, 4)) == Date.max);
assert(max(Date.min, Date.max) == Date.max);
assert(max(Date.max, Date.min) == Date.max);
}
// min
/**
Iterates the passed arguments and returns the minimum value.
Params:
args = The values to select the minimum from. At least two arguments must
be passed, and they must be comparable with `<`.
Returns:
The minimum of the passed-in values. The type of the returned value is
the type among the passed arguments that is able to store the smallest value.
If at least one of the arguments is NaN, the result is an unspecified value.
See $(REF minElement, std,algorithm,searching) for examples on how to cope
with NaNs.
See_Also:
$(REF minElement, std,algorithm,searching)
*/
auto min(T...)(T args)
if (T.length >= 2 && !is(CommonType!T == void))
{
// Get the left-hand side of the comparison.
static if (T.length <= 2)
alias a = args[0];
else
auto a = min(args[0 .. ($ + 1) / 2]);
alias T0 = typeof(a);
// Get the right-hand side.
static if (T.length <= 3)
alias b = args[$ - 1];
else
auto b = min(args[($ + 1) / 2 .. $]);
alias T1 = typeof(b);
static assert(is(typeof(a < b)),
"Invalid arguments: Cannot compare types " ~ T0.stringof ~
" and " ~ T1.stringof ~ " for ordering.");
// Compute the returned type.
static if (is(typeof(mostNegative!T0 < mostNegative!T1)))
// Both are numeric (or character or Boolean), so we choose the one with the lowest minimum.
// If they have the same minimum, choose the one with the smallest size.
// If both mostNegative and sizeof are equal, go for stability: pick the type of the first one.
alias Result = Select!(mostNegative!T1 < mostNegative!T0 ||
mostNegative!T1 == mostNegative!T0 && T1.sizeof < T0.sizeof,
T1, T0);
else
// At least one is non-numeric, so just go with the common type.
alias Result = CommonType!(T0, T1);
// Engage!
import std.functional : lessThan;
immutable chooseB = lessThan!(T1, T0)(b, a);
return cast(Result) (chooseB ? b : a);
}
/// ditto
T min(T, U)(T a, U b)
if (is(T == U) && is(typeof(a < b)))
{
/* Handle the common case without all the template expansions
* of the general case
*/
return b < a ? b : a;
}
///
@safe @nogc @betterC unittest
{
int a = 5;
short b = 6;
double c = 2;
auto d = min(a, b);
static assert(is(typeof(d) == int));
assert(d == 5);
auto e = min(a, b, c);
static assert(is(typeof(e) == double));
assert(e == 2);
ulong f = 0xffff_ffff_ffff;
const uint g = min(f, 0xffff_0000);
assert(g == 0xffff_0000);
dchar h = 100;
uint i = 101;
static assert(is(typeof(min(h, i)) == dchar));
static assert(is(typeof(min(i, h)) == uint));
assert(min(h, i) == 100);
}
/**
With arguments of mixed signedness, the return type is the one that can
store the lowest values.
*/
@safe @nogc @betterC unittest
{
int a = -10;
uint f = 10;
static assert(is(typeof(min(a, f)) == int));
assert(min(a, f) == -10);
}
/// User-defined types that support comparison with < are supported.
@safe unittest // not @nogc due to `Date`
{
import std.datetime;
assert(min(Date(2012, 12, 21), Date(1982, 1, 4)) == Date(1982, 1, 4));
assert(min(Date(1982, 1, 4), Date(2012, 12, 21)) == Date(1982, 1, 4));
assert(min(Date(1982, 1, 4), Date.min) == Date.min);
assert(min(Date.min, Date(1982, 1, 4)) == Date.min);
assert(min(Date(1982, 1, 4), Date.max) == Date(1982, 1, 4));
assert(min(Date.max, Date(1982, 1, 4)) == Date(1982, 1, 4));
assert(min(Date.min, Date.max) == Date.min);
assert(min(Date.max, Date.min) == Date.min);
}
// min must be stable: when in doubt, return the first argument.
@safe unittest
{
assert(min(1.0, double.nan) == 1.0);
assert(min(double.nan, 1.0) is double.nan);
static struct A {
int x;
string y;
int opCmp(const A a) const { return int(x > a.x) - int(x < a.x); }
}
assert(min(A(1, "first"), A(1, "second")) == A(1, "first"));
}
// mismatch
/**
Sequentially compares elements in `rs` in lockstep, and
stops at the first mismatch (according to `pred`, by default
equality). Returns a tuple with the reduced ranges that start with the
two mismatched values. Performs $(BIGOH min(r[0].length, r[1].length, ...))
evaluations of `pred`.
*/
Tuple!(Ranges)
mismatch(alias pred = (a, b) => a == b, Ranges...)(Ranges rs)
if (rs.length >= 2 && allSatisfy!(isInputRange, Ranges))
{
loop: for (; !rs[0].empty; rs[0].popFront)
{
static foreach (r; rs[1 .. $])
{
if (r.empty || !binaryFun!pred(rs[0].front, r.front))
break loop;
r.popFront;
}
}
return tuple(rs);
}
///
@safe @nogc unittest
{
int[6] x = [ 1, 5, 2, 7, 4, 3 ];
double[6] y = [ 1.0, 5, 2, 7.3, 4, 8 ];
auto m = mismatch(x[], y[]);
assert(m[0] == x[3 .. $]);
assert(m[1] == y[3 .. $]);
auto m2 = mismatch(x[], y[], x[], y[]);
assert(m2[0] == x[3 .. $]);
assert(m2[1] == y[3 .. $]);
assert(m2[2] == x[3 .. $]);
assert(m2[3] == y[3 .. $]);
}
@safe @nogc unittest
{
import std.range : only;
int[3] a = [ 1, 2, 3 ];
int[4] b = [ 1, 2, 4, 5 ];
auto mm = mismatch(a[], b[]);
assert(equal(mm[0], only(3)));
assert(equal(mm[1], only(4, 5)));
}
/**
Returns one of a collection of expressions based on the value of the switch
expression.
`choices` needs to be composed of pairs of test expressions and return
expressions. Each test-expression is compared with `switchExpression` using
`pred`(`switchExpression` is the first argument) and if that yields true -
the return expression is returned.
Both the test and the return expressions are lazily evaluated.
Params:
switchExpression = The first argument for the predicate.
choices = Pairs of test expressions and return expressions. The test
expressions will be the second argument for the predicate, and the return
expression will be returned if the predicate yields true with $(D
switchExpression) and the test expression as arguments. May also have a
default return expression, that needs to be the last expression without a test
expression before it. A return expression may be of void type only if it
always throws.
Returns: The return expression associated with the first test expression that
made the predicate yield true, or the default return expression if no test
expression matched.
Throws: If there is no default return expression and the predicate does not
yield true with any test expression - `SwitchError` is thrown. $(D
SwitchError) is also thrown if a void return expression was executed without
throwing anything.
*/
auto predSwitch(alias pred = "a == b", T, R ...)(T switchExpression, lazy R choices)
{
import core.exception : SwitchError;
alias predicate = binaryFun!(pred);
foreach (index, ChoiceType; R)
{
//The even places in `choices` are for the predicate.
static if (index % 2 == 1)
{
if (predicate(switchExpression, choices[index - 1]()))
{
static if (is(typeof(choices[index]()) == void))
{
choices[index]();
throw new SwitchError("Choices that return void should throw");
}
else
{
return choices[index]();
}
}
}
}
//In case nothing matched:
static if (R.length % 2 == 1) //If there is a default return expression:
{
static if (is(typeof(choices[$ - 1]()) == void))
{
choices[$ - 1]();
throw new SwitchError("Choices that return void should throw");
}
else
{
return choices[$ - 1]();
}
}
else //If there is no default return expression:
{
throw new SwitchError("Input not matched by any pattern");
}
}
///
@safe unittest
{
string res = 2.predSwitch!"a < b"(
1, "less than 1",
5, "less than 5",
10, "less than 10",
"greater or equal to 10");
assert(res == "less than 5");
//The arguments are lazy, which allows us to use predSwitch to create
//recursive functions:
int factorial(int n)
{
return n.predSwitch!"a <= b"(
-1, {throw new Exception("Can not calculate n! for n < 0");}(),
0, 1, // 0! = 1
n * factorial(n - 1) // n! = n * (n - 1)! for n >= 0
);
}
assert(factorial(3) == 6);
//Void return expressions are allowed if they always throw:
import std.exception : assertThrown;
assertThrown!Exception(factorial(-9));
}
@system unittest
{
import core.exception : SwitchError;
import std.exception : assertThrown;
//Nothing matches - with default return expression:
assert(20.predSwitch!"a < b"(
1, "less than 1",
5, "less than 5",
10, "less than 10",
"greater or equal to 10") == "greater or equal to 10");
//Nothing matches - without default return expression:
assertThrown!SwitchError(20.predSwitch!"a < b"(
1, "less than 1",
5, "less than 5",
10, "less than 10",
));
//Using the default predicate:
assert(2.predSwitch(
1, "one",
2, "two",
3, "three",
) == "two");
//Void return expressions must always throw:
assertThrown!SwitchError(1.predSwitch(
0, "zero",
1, {}(), //A void return expression that doesn't throw
2, "two",
));
}
/**
Checks if two or more ranges have the same number of elements. This function is
optimized to always take advantage of the `length` member of either range
if it exists.
If all ranges have a `length` member or at least one is infinite,
`_isSameLength`'s complexity is $(BIGOH 1). Otherwise, complexity is
$(BIGOH n), where `n` is the smallest of the lengths of ranges with unknown
length.
Infinite ranges are considered of the same length. An infinite range has never
the same length as a finite range.
Params:
rs = two or more $(REF_ALTTEXT input ranges, isInputRange, std,range,primitives)
Returns:
`true` if both ranges have the same length, `false` otherwise.
*/
bool isSameLength(Ranges...)(Ranges rs)
if (allSatisfy!(isInputRange, Ranges))
{
static if (anySatisfy!(isInfinite, Ranges))
{
return allSatisfy!(isInfinite, Ranges);
}
else static if (anySatisfy!(hasLength, Ranges))
{
// Compute the O(1) length
auto baselineLength = size_t.max;
static foreach (i, R; Ranges)
{
static if (hasLength!R)
{
if (baselineLength == size_t.max)
baselineLength = rs[i].length;
else if (rs[i].length != baselineLength)
return false;
}
}
// Iterate all ranges without known length
foreach (_; 0 .. baselineLength)
static foreach (i, R; Ranges)
{
static if (!hasLength!R)
{
// All must be non-empty
if (rs[i].empty)
return false;
rs[i].popFront;
}
}
static foreach (i, R; Ranges)
{
static if (!hasLength!R)
{
// All must be now empty
if (!rs[i].empty)
return false;
}
}
return true;
}
else
{
// All have unknown length, iterate in lockstep
for (;;)
static foreach (i, r; rs)
{
if (r.empty)
{
// One is empty, so all must be empty
static if (i != 0)
{
return false;
}
else
{
static foreach (j, r1; rs[1 .. $])
if (!r1.empty)
return false;
return true;
}
}
r.popFront;
}
}
}
///
@safe nothrow pure unittest
{
assert(isSameLength([1, 2, 3], [4, 5, 6]));
assert(isSameLength([1, 2, 3], [4, 5, 6], [7, 8, 9]));
assert(isSameLength([0.3, 90.4, 23.7, 119.2], [42.6, 23.6, 95.5, 6.3]));
assert(isSameLength("abc", "xyz"));
assert(isSameLength("abc", "xyz", [1, 2, 3]));
int[] a;
int[] b;
assert(isSameLength(a, b));
assert(isSameLength(a, b, a, a, b, b, b));
assert(!isSameLength([1, 2, 3], [4, 5]));
assert(!isSameLength([1, 2, 3], [4, 5, 6], [7, 8]));
assert(!isSameLength([0.3, 90.4, 23.7], [42.6, 23.6, 95.5, 6.3]));
assert(!isSameLength("abcd", "xyz"));
assert(!isSameLength("abcd", "xyz", "123"));
assert(!isSameLength("abcd", "xyz", "1234"));
}
// Test CTFE
@safe @nogc pure @betterC unittest
{
static assert(isSameLength([1, 2, 3], [4, 5, 6]));
static assert(isSameLength([1, 2, 3], [4, 5, 6], [7, 8, 9]));
static assert(!isSameLength([0.3, 90.4, 23.7], [42.6, 23.6, 95.5, 6.3]));
static assert(!isSameLength([1], [0.3, 90.4], [42]));
}
@safe @nogc pure unittest
{
import std.range : only;
assert(isSameLength(only(1, 2, 3), only(4, 5, 6)));
assert(isSameLength(only(1, 2, 3), only(4, 5, 6), only(7, 8, 9)));
assert(isSameLength(only(0.3, 90.4, 23.7, 119.2), only(42.6, 23.6, 95.5, 6.3)));
assert(!isSameLength(only(1, 3, 3), only(4, 5)));
assert(!isSameLength(only(1, 3, 3), only(1, 3, 3), only(4, 5)));
assert(!isSameLength(only(1, 3, 3), only(4, 5), only(1, 3, 3)));
}
@safe nothrow pure unittest
{
import std.internal.test.dummyrange;
auto r1 = new ReferenceInputRange!int([1, 2, 3]);
auto r2 = new ReferenceInputRange!int([4, 5, 6]);
assert(isSameLength(r1, r2));
auto r3 = new ReferenceInputRange!int([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Input) r4;
assert(isSameLength(r3, r4));
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Input) r5;
auto r6 = new ReferenceInputRange!int([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
assert(isSameLength(r5, r6));
auto r7 = new ReferenceInputRange!int([1, 2]);
auto r8 = new ReferenceInputRange!int([4, 5, 6]);
assert(!isSameLength(r7, r8));
auto r9 = new ReferenceInputRange!int([1, 2, 3, 4, 5, 6, 7, 8]);
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Input) r10;
assert(!isSameLength(r9, r10));
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Input) r11;
auto r12 = new ReferenceInputRange!int([1, 2, 3, 4, 5, 6, 7, 8]);
assert(!isSameLength(r11, r12));
import std.algorithm.iteration : filter;
assert(isSameLength(filter!"a >= 1"([1, 2, 3]), [4, 5, 6]));
assert(!isSameLength(filter!"a > 1"([1, 2, 3]), [4, 5, 6]));
assert(isSameLength(filter!"a > 1"([1, 2, 3]), filter!"a > 4"([4, 5, 6])));
assert(isSameLength(filter!"a > 1"([1, 2, 3]),
filter!"a > 4"([4, 5, 6]), filter!"a >= 5"([4, 5, 6])));
}
// Still functional but not documented anymore.
alias AllocateGC = Flag!"allocateGC";
/**
Checks if both ranges are permutations of each other.
This function can allocate if the `Yes.allocateGC` flag is passed. This has
the benefit of have better complexity than the `Yes.allocateGC` option. However,
this option is only available for ranges whose equality can be determined via each
element's `toHash` method. If customized equality is needed, then the `pred`
template parameter can be passed, and the function will automatically switch to
the non-allocating algorithm. See $(REF binaryFun, std,functional) for more details on
how to define `pred`.
Non-allocating forward range option: $(BIGOH n^2)
Non-allocating forward range option with custom `pred`: $(BIGOH n^2)
Allocating forward range option: amortized $(BIGOH r1.length) + $(BIGOH r2.length)
Params:
pred = an optional parameter to change how equality is defined
allocateGC = `Yes.allocateGC`/`No.allocateGC`
r1 = A finite $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
r2 = A finite $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
Returns:
`true` if all of the elements in `r1` appear the same number of times in `r2`.
Otherwise, returns `false`.
*/
bool isPermutation(Flag!"allocateGC" allocateGC, Range1, Range2)
(Range1 r1, Range2 r2)
if (allocateGC == Yes.allocateGC &&
isForwardRange!Range1 &&
isForwardRange!Range2 &&
!isInfinite!Range1 &&
!isInfinite!Range2)
{
alias E1 = Unqual!(ElementType!Range1);
alias E2 = Unqual!(ElementType!Range2);
if (!isSameLength(r1.save, r2.save))
{
return false;
}
// Skip the elements at the beginning where r1.front == r2.front,
// they are in the same order and don't need to be counted.
while (!r1.empty && !r2.empty && r1.front == r2.front)
{
r1.popFront();
r2.popFront();
}
if (r1.empty && r2.empty)
{
return true;
}
int[CommonType!(E1, E2)] counts;
foreach (item; r1)
{
++counts[item];
}
foreach (item; r2)
{
if (--counts[item] < 0)
{
return false;
}
}
return true;
}
/// ditto
bool isPermutation(alias pred = "a == b", Range1, Range2)
(Range1 r1, Range2 r2)
if (is(typeof(binaryFun!(pred))) &&
isForwardRange!Range1 &&
isForwardRange!Range2 &&
!isInfinite!Range1 &&
!isInfinite!Range2)
{
import std.algorithm.searching : count;
alias predEquals = binaryFun!(pred);
alias E1 = Unqual!(ElementType!Range1);
alias E2 = Unqual!(ElementType!Range2);
if (!isSameLength(r1.save, r2.save))
{
return false;
}
// Skip the elements at the beginning where r1.front == r2.front,
// they are in the same order and don't need to be counted.
while (!r1.empty && !r2.empty && predEquals(r1.front, r2.front))
{
r1.popFront();
r2.popFront();
}
if (r1.empty && r2.empty)
{
return true;
}
size_t r1_count;
size_t r2_count;
// At each element item, when computing the count of item, scan it while
// also keeping track of the scanning index. If the first occurrence
// of item in the scanning loop has an index smaller than the current index,
// then you know that the element has been seen before
size_t index;
outloop: for (auto r1s1 = r1.save; !r1s1.empty; r1s1.popFront, index++)
{
auto item = r1s1.front;
r1_count = 0;
r2_count = 0;
size_t i;
for (auto r1s2 = r1.save; !r1s2.empty; r1s2.popFront, i++)
{
auto e = r1s2.front;
if (predEquals(e, item) && i < index)
{
continue outloop;
}
else if (predEquals(e, item))
{
++r1_count;
}
}
r2_count = r2.save.count!pred(item);
if (r1_count != r2_count)
{
return false;
}
}
return true;
}
///
@safe pure unittest
{
import std.typecons : Yes;
assert(isPermutation([1, 2, 3], [3, 2, 1]));
assert(isPermutation([1.1, 2.3, 3.5], [2.3, 3.5, 1.1]));
assert(isPermutation("abc", "bca"));
assert(!isPermutation([1, 2], [3, 4]));
assert(!isPermutation([1, 1, 2, 3], [1, 2, 2, 3]));
assert(!isPermutation([1, 1], [1, 1, 1]));
// Faster, but allocates GC handled memory
assert(isPermutation!(Yes.allocateGC)([1.1, 2.3, 3.5], [2.3, 3.5, 1.1]));
assert(!isPermutation!(Yes.allocateGC)([1, 2], [3, 4]));
}
// Test @nogc inference
@safe @nogc pure unittest
{
static immutable arr1 = [1, 2, 3];
static immutable arr2 = [3, 2, 1];
assert(isPermutation(arr1, arr2));
static immutable arr3 = [1, 1, 2, 3];
static immutable arr4 = [1, 2, 2, 3];
assert(!isPermutation(arr3, arr4));
}
@safe pure unittest
{
import std.internal.test.dummyrange;
auto r1 = new ReferenceForwardRange!int([1, 2, 3, 4]);
auto r2 = new ReferenceForwardRange!int([1, 2, 4, 3]);
assert(isPermutation(r1, r2));
auto r3 = new ReferenceForwardRange!int([1, 2, 3, 4]);
auto r4 = new ReferenceForwardRange!int([4, 2, 1, 3]);
assert(isPermutation!(Yes.allocateGC)(r3, r4));
auto r5 = new ReferenceForwardRange!int([1, 2, 3]);
auto r6 = new ReferenceForwardRange!int([4, 2, 1, 3]);
assert(!isPermutation(r5, r6));
auto r7 = new ReferenceForwardRange!int([4, 2, 1, 3]);
auto r8 = new ReferenceForwardRange!int([1, 2, 3]);
assert(!isPermutation!(Yes.allocateGC)(r7, r8));
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Random) r9;
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Random) r10;
assert(isPermutation(r9, r10));
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Random) r11;
DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Random) r12;
assert(isPermutation!(Yes.allocateGC)(r11, r12));
alias mytuple = Tuple!(int, int);
assert(isPermutation!"a[0] == b[0]"(
[mytuple(1, 4), mytuple(2, 5)],
[mytuple(2, 3), mytuple(1, 2)]
));
}
/**
Get the _first argument `a` that passes an `if (unaryFun!pred(a))` test. If
no argument passes the test, return the last argument.
Similar to behaviour of the `or` operator in dynamic languages such as Lisp's
`(or ...)` and Python's `a or b or ...` except that the last argument is
returned upon no match.
Simplifies logic, for instance, in parsing rules where a set of alternative
matchers are tried. The _first one that matches returns it match result,
typically as an abstract syntax tree (AST).
Bugs:
Lazy parameters are currently, too restrictively, inferred by DMD to
always throw even though they don't need to be. This makes it impossible to
currently mark `either` as `nothrow`. See issue at $(BUGZILLA 12647).
Returns:
The _first argument that passes the test `pred`.
*/
CommonType!(T, Ts) either(alias pred = a => a, T, Ts...)(T first, lazy Ts alternatives)
if (alternatives.length >= 1 &&
!is(CommonType!(T, Ts) == void) &&
allSatisfy!(ifTestable, T, Ts))
{
alias predFun = unaryFun!pred;
if (predFun(first)) return first;
foreach (e; alternatives[0 .. $ - 1])
if (predFun(e)) return e;
return alternatives[$ - 1];
}
///
@safe pure @betterC unittest
{
const a = 1;
const b = 2;
auto ab = either(a, b);
static assert(is(typeof(ab) == const(int)));
assert(ab == a);
auto c = 2;
const d = 3;
auto cd = either!(a => a == 3)(c, d); // use predicate
static assert(is(typeof(cd) == int));
assert(cd == d);
auto e = 0;
const f = 2;
auto ef = either(e, f);
static assert(is(typeof(ef) == int));
assert(ef == f);
}
///
@safe pure unittest
{
immutable p = 1;
immutable q = 2;
auto pq = either(p, q);
static assert(is(typeof(pq) == immutable(int)));
assert(pq == p);
assert(either(3, 4) == 3);
assert(either(0, 4) == 4);
assert(either(0, 0) == 0);
assert(either("", "a") == "");
}
///
@safe pure unittest
{
string r = null;
assert(either(r, "a") == "a");
assert(either("a", "") == "a");
immutable s = [1, 2];
assert(either(s, s) == s);
assert(either([0, 1], [1, 2]) == [0, 1]);
assert(either([0, 1], [1]) == [0, 1]);
assert(either("a", "b") == "a");
static assert(!__traits(compiles, either(1, "a")));
static assert(!__traits(compiles, either(1.0, "a")));
static assert(!__traits(compiles, either('a', "a")));
}
|
D
|
module android.java.java.security.cert.PKIXCertPathChecker;
public import android.java.java.security.cert.PKIXCertPathChecker_d_interface;
import arsd.jni : ImportExportImpl;
mixin ImportExportImpl!PKIXCertPathChecker;
import import3 = android.java.java.lang.Class;
import import0 = android.java.java.util.Set;
|
D
|
// Issue 16594
import core.stdc.stdio;
shared static ~this()
{
__gshared int count;
if (count++) fprintf(stderr, "dtor_called_more_than_once");
else throw new Exception("static_dtor_exception");
}
void main()
{
}
|
D
|
instance Info_Sld_8_EXIT(C_Info)
{
nr = 999;
condition = Info_Sld_8_EXIT_Condition;
information = Info_Sld_8_EXIT_Info;
permanent = 1;
description = "KONIEC";
};
func int Info_Sld_8_EXIT_Condition()
{
return 1;
};
func void Info_Sld_8_EXIT_Info()
{
AI_StopProcessInfos(self);
};
instance Info_Sld_8_EinerVonEuchWerden(C_Info)
{
nr = 4;
condition = Info_Sld_8_EinerVonEuchWerden_Condition;
information = Info_Sld_8_EinerVonEuchWerden_Info;
permanent = 1;
description = "Nie przydałby się wam dodatkowy człowiek?";
};
func int Info_Sld_8_EinerVonEuchWerden_Condition()
{
if((Npc_GetTrueGuild(other) != GIL_SLD) && (Npc_GetTrueGuild(other) != GIL_KDW) && !C_NpcBelongsToOldCamp(other) && !C_NpcBelongsToPsiCamp(other))
{
return TRUE;
};
};
func void Info_Sld_8_EinerVonEuchWerden_Info()
{
AI_Output(other,self,"Info_Sld_8_EinerVonEuchWerden_15_00"); //Nie przydałby się wam dodatkowy człowiek?
AI_Output(self,other,"Info_Sld_8_EinerVonEuchWerden_08_01"); //Lee nie przyjmuje ludzi, którzy nie spędzili tu kilku lat i nie maja dużego doświadczenia.
AI_Output(self,other,"Info_Sld_8_EinerVonEuchWerden_08_02"); //Jeśli chcesz zostać w Obozie musisz najpierw postawić się Szkodnikom.
};
instance Info_Sld_8_WichtigePersonen(C_Info)
{
nr = 3;
condition = Info_Sld_8_WichtigePersonen_Condition;
information = Info_Sld_8_WichtigePersonen_Info;
permanent = 1;
description = "Kto tu dowodzi?";
};
func int Info_Sld_8_WichtigePersonen_Condition()
{
return 1;
};
func void Info_Sld_8_WichtigePersonen_Info()
{
var C_Npc Lee;
var C_Npc Cronos;
AI_Output(other,self,"Info_Sld_8_WichtigePersonen_15_00"); //Kto tu dowodzi?
AI_Output(self,other,"Info_Sld_8_WichtigePersonen_08_01"); //Wszyscy Najemnicy słuchają Lee. Szef zawarł umowę z Magami - my ich ochraniamy, a oni pomogą nam stąd zwiać!
AI_Output(other,self,"Info_Sld_8_WichtigePersonen_15_02"); //A więc w rzeczywistości rządzą tu Magowie?
AI_Output(self,other,"Info_Sld_8_WichtigePersonen_08_03"); //Nie, obozem NIKT tak naprawdę nie rządzi. Większość z mieszkających tu ludzi nie chciała bądź nie mogła mieszkać w Starym Obozie.
AI_Output(self,other,"Info_Sld_8_WichtigePersonen_08_04"); //Każdy dba tu o własny interes. Zgadzamy się tylko co do jednego: lepiej już usypać z rudy wielki kopiec i wysadzić go w powietrze, niż wchodzić w układy z królem, niech mu ziemia ciężką będzie.
Lee = Hlp_GetNpc(Sld_700_Lee);
Lee.aivar[AIV_FINDABLE] = TRUE;
Cronos = Hlp_GetNpc(KDW_604_Cronos);
Cronos.aivar[AIV_FINDABLE] = TRUE;
};
instance Info_Sld_8_DasLager(C_Info)
{
nr = 2;
condition = Info_Sld_8_DasLager_Condition;
information = Info_Sld_8_DasLager_Info;
permanent = 1;
description = "Co możesz mi opowiedzieć o tym obozie?";
};
func int Info_Sld_8_DasLager_Condition()
{
if(!C_NpcBelongsToNewCamp(other))
{
return 1;
};
};
func void Info_Sld_8_DasLager_Info()
{
var C_Npc Cronos;
AI_Output(other,self,"Info_Sld_8_DasLager_15_00"); //Co możesz mi opowiedzieć o tym obozie?
AI_Output(self,other,"Info_Sld_8_DasLager_08_01"); //Uważaj na siebie! W Obozie aż roi się od morderców i rabusiów!
AI_Output(self,other,"Info_Sld_8_DasLager_08_02"); //Mamy tutaj kilka niepisanych praw. Pierwsze: tylko Najemnicy mogą wchodzić do strefy Magów.
AI_Output(self,other,"Info_Sld_8_DasLager_08_03"); //Drugie: zanim zbliżysz się do kopca rudy, wykop sobie wygodny grób. Trzecie: nie pokazuj się w knajpie na jeziorze.
AI_Output(self,other,"Info_Sld_8_DasLager_08_04"); //Widzisz, to jest lokal Szkodników, a oni nie lubią jak pokazują się tam żółtodzioby takie jak ty.
Cronos = Hlp_GetNpc(KDW_604_Cronos);
Cronos.aivar[AIV_FINDABLE] = TRUE;
};
instance Info_Sld_8_DieLage(C_Info)
{
nr = 1;
condition = Info_Sld_8_DieLage_Condition;
information = Info_Sld_8_DieLage_Info;
permanent = 1;
description = "Jak leci?";
};
func int Info_Sld_8_DieLage_Condition()
{
return 1;
};
func void Info_Sld_8_DieLage_Info()
{
var C_Npc Cronos;
AI_Output(other,self,"Info_Sld_8_DieLage_15_00"); //Jak leci?
AI_Output(self,other,"Info_Sld_8_DieLage_08_01"); //Jak zwykle. Pilnujemy, żeby nikt nie zbliżył się do Magów ani do rudy.
Cronos = Hlp_GetNpc(KDW_604_Cronos);
Cronos.aivar[AIV_FINDABLE] = TRUE;
};
instance Info_Sld_8_Krautprobe(C_Info)
{
nr = 5;
condition = Info_Sld_8_Krautprobe_Condition;
information = Info_Sld_8_Krautprobe_Info;
permanent = 1;
description = "Mam przy sobie trochę bagiennego ziela? Może chcesz trochę kupić?";
};
func int Info_Sld_8_Krautprobe_Condition()
{
if(((BaalKagan_VerteilKraut == LOG_RUNNING) || (BaalKagan_VerteilKraut == LOG_SUCCESS)) && (self.aivar[AIV_DEALDAY] <= Wld_GetDay()))
{
return TRUE;
};
};
func void Info_Sld_8_Krautprobe_Info()
{
AI_Output(other,self,"Info_Sld_8_Krautprobe_15_00"); //Mam przy sobie trochę bagiennego ziela? Może chcesz je kupić?
if((Npc_HasItems(other,ItMiJoint_1) > 0) || (Npc_HasItems(other,ItMiJoint_2) > 0) || (Npc_HasItems(other,ItMiJoint_3) > 0))
{
if(Npc_HasItems(other,ItMiJoint_1))
{
B_GiveInvItems(other,self,ItMiJoint_1,1);
}
else if(Npc_HasItems(other,ItMiJoint_2))
{
B_GiveInvItems(other,self,ItMiJoint_2,1);
}
else if(Npc_HasItems(other,ItMiJoint_3))
{
B_GiveInvItems(other,self,ItMiJoint_3,1);
};
AI_Output(self,other,"Info_Sld_8_Krautprobe_08_01"); //Czemu nie? Dam ci za nie 10 bryłek rudy.
AI_Output(self,other,"Info_Sld_8_Krautprobe_08_02"); //Pogadaj jeszcze z resztą chłopaków. Oni pewnie też będą zainteresowani.
CreateInvItems(self,ItMiNugget,10);
B_GiveInvItems(self,other,ItMiNugget,10);
NC_Joints_verteilt = NC_Joints_verteilt + 1;
self.aivar[AIV_DEALDAY] = Wld_GetDay() + 1;
}
else
{
AI_Output(self,other,"Info_Sld_8_Krautprobe_No_Joint_08_00"); //Nie tak szybko. Najpierw pokaż ziele! Nie masz, co?!
};
};
func void B_AssignAmbientInfos_Sld_8(var C_Npc slf)
{
B_AssignFindNpc_NC(slf);
Info_Sld_8_EXIT.npc = Hlp_GetInstanceID(slf);
Info_Sld_8_EinerVonEuchWerden.npc = Hlp_GetInstanceID(slf);
Info_Sld_8_WichtigePersonen.npc = Hlp_GetInstanceID(slf);
Info_Sld_8_DasLager.npc = Hlp_GetInstanceID(slf);
Info_Sld_8_DieLage.npc = Hlp_GetInstanceID(slf);
Info_Sld_8_Krautprobe.npc = Hlp_GetInstanceID(slf);
};
|
D
|
instance BDT_1067_Bandit_L(Npc_Default)
{
name[0] = NAME_Bandit;
guild = GIL_BDT;
id = 1067;
voice = 10;
flags = 0;
npcType = NPCTYPE_AMBIENT;
aivar[AIV_EnemyOverride] = TRUE;
B_SetAttributesToChapter(self,1);
fight_tactic = FAI_HUMAN_COWARD;
EquipItem(self,ItMw_1h_Bau_Mace);
B_CreateAmbientInv(self);
B_SetNpcVisual(self,MALE,"Hum_Head_FatBald",Face_N_Normal20,BodyTex_N,ItAr_BDT_M);
Mdl_SetModelFatness(self,0);
Mdl_ApplyOverlayMds(self,"Humans_Relaxed.mds");
B_GiveNpcTalents(self);
B_SetFightSkills(self,30);
daily_routine = Rtn_Start_1067;
};
func void Rtn_Start_1067()
{
TA_Sleep(0,0,12,0,"NW_CASTLEMINE_TOWER_08");
TA_Sleep(12,0,0,0,"NW_CASTLEMINE_TOWER_08");
};
|
D
|
/* Written by Walter Bright
* www.digitalmars.com
* Placed into Public Domain
*/
// Identify the compiler used and its various features.
module std.compiler;
const
{
// Vendor specific string naming the compiler
char[] name = "Digital Mars D";
// Master list of D compiler vendors
enum Vendor
{
DigitalMars = 1
}
// Which vendor we are
Vendor vendor = Vendor.DigitalMars;
// The vendor specific version number, as in
// version_major.version_minor
uint version_major = 0;
uint version_minor = 0;
// The version of the D Programming Language Specification
// Supported by the compiler
uint D_major = 0;
uint D_minor = 0;
}
|
D
|
module UnrealScript.TribesGame.GFxTrPage_ServerAddTime;
import ScriptClasses;
import UnrealScript.Helpers;
import UnrealScript.TribesGame.GFxTrAction;
import UnrealScript.TribesGame.GFxTrPage;
import UnrealScript.GFxUI.GFxObject;
extern(C++) interface GFxTrPage_ServerAddTime : GFxTrPage
{
public extern(D):
private static __gshared ScriptClass mStaticClass;
@property final static ScriptClass StaticClass() { mixin(MGSCC("Class TribesGame.GFxTrPage_ServerAddTime")); }
private static __gshared GFxTrPage_ServerAddTime mDefaultProperties;
@property final static GFxTrPage_ServerAddTime DefaultProperties() { mixin(MGDPC("GFxTrPage_ServerAddTime", "GFxTrPage_ServerAddTime TribesGame.Default__GFxTrPage_ServerAddTime")); }
static struct Functions
{
private static __gshared
{
ScriptFunction mInitialize;
ScriptFunction mSpecialAction;
ScriptFunction mModifyAction;
ScriptFunction mTakeFocus;
ScriptFunction mPopupData;
ScriptFunction mPopupComplete;
ScriptFunction mFillData;
ScriptFunction mFillOption;
ScriptFunction mCheckDescription;
ScriptFunction mFillDescription;
ScriptFunction mShowModel;
ScriptFunction mCheckPricing;
ScriptFunction mFillPricing;
}
public @property static final
{
ScriptFunction Initialize() { mixin(MGF("mInitialize", "Function TribesGame.GFxTrPage_ServerAddTime.Initialize")); }
ScriptFunction SpecialAction() { mixin(MGF("mSpecialAction", "Function TribesGame.GFxTrPage_ServerAddTime.SpecialAction")); }
ScriptFunction ModifyAction() { mixin(MGF("mModifyAction", "Function TribesGame.GFxTrPage_ServerAddTime.ModifyAction")); }
ScriptFunction TakeFocus() { mixin(MGF("mTakeFocus", "Function TribesGame.GFxTrPage_ServerAddTime.TakeFocus")); }
ScriptFunction PopupData() { mixin(MGF("mPopupData", "Function TribesGame.GFxTrPage_ServerAddTime.PopupData")); }
ScriptFunction PopupComplete() { mixin(MGF("mPopupComplete", "Function TribesGame.GFxTrPage_ServerAddTime.PopupComplete")); }
ScriptFunction FillData() { mixin(MGF("mFillData", "Function TribesGame.GFxTrPage_ServerAddTime.FillData")); }
ScriptFunction FillOption() { mixin(MGF("mFillOption", "Function TribesGame.GFxTrPage_ServerAddTime.FillOption")); }
ScriptFunction CheckDescription() { mixin(MGF("mCheckDescription", "Function TribesGame.GFxTrPage_ServerAddTime.CheckDescription")); }
ScriptFunction FillDescription() { mixin(MGF("mFillDescription", "Function TribesGame.GFxTrPage_ServerAddTime.FillDescription")); }
ScriptFunction ShowModel() { mixin(MGF("mShowModel", "Function TribesGame.GFxTrPage_ServerAddTime.ShowModel")); }
ScriptFunction CheckPricing() { mixin(MGF("mCheckPricing", "Function TribesGame.GFxTrPage_ServerAddTime.CheckPricing")); }
ScriptFunction FillPricing() { mixin(MGF("mFillPricing", "Function TribesGame.GFxTrPage_ServerAddTime.FillPricing")); }
}
}
@property final auto ref
{
int PurchaseIndex() { mixin(MGPC("int", 360)); }
int FocusIndex() { mixin(MGPC("int", 356)); }
}
final:
void Initialize()
{
(cast(ScriptObject)this).ProcessEvent(Functions.Initialize, cast(void*)0, cast(void*)0);
}
void SpecialAction(GFxTrAction Action)
{
ubyte params[4];
params[] = 0;
*cast(GFxTrAction*)params.ptr = Action;
(cast(ScriptObject)this).ProcessEvent(Functions.SpecialAction, params.ptr, cast(void*)0);
}
int ModifyAction(int ActionIndex, GFxObject DataList)
{
ubyte params[12];
params[] = 0;
*cast(int*)params.ptr = ActionIndex;
*cast(GFxObject*)¶ms[4] = DataList;
(cast(ScriptObject)this).ProcessEvent(Functions.ModifyAction, params.ptr, cast(void*)0);
return *cast(int*)¶ms[8];
}
int TakeFocus(int ActionIndex, GFxObject DataList)
{
ubyte params[12];
params[] = 0;
*cast(int*)params.ptr = ActionIndex;
*cast(GFxObject*)¶ms[4] = DataList;
(cast(ScriptObject)this).ProcessEvent(Functions.TakeFocus, params.ptr, cast(void*)0);
return *cast(int*)¶ms[8];
}
void PopupData(GFxObject Obj)
{
ubyte params[4];
params[] = 0;
*cast(GFxObject*)params.ptr = Obj;
(cast(ScriptObject)this).ProcessEvent(Functions.PopupData, params.ptr, cast(void*)0);
}
void PopupComplete(int Action, ScriptString TextInput)
{
ubyte params[16];
params[] = 0;
*cast(int*)params.ptr = Action;
*cast(ScriptString*)¶ms[4] = TextInput;
(cast(ScriptObject)this).ProcessEvent(Functions.PopupComplete, params.ptr, cast(void*)0);
}
void FillData(GFxObject DataList)
{
ubyte params[4];
params[] = 0;
*cast(GFxObject*)params.ptr = DataList;
(cast(ScriptObject)this).ProcessEvent(Functions.FillData, params.ptr, cast(void*)0);
}
GFxObject FillOption(int ActionIndex)
{
ubyte params[8];
params[] = 0;
*cast(int*)params.ptr = ActionIndex;
(cast(ScriptObject)this).ProcessEvent(Functions.FillOption, params.ptr, cast(void*)0);
return *cast(GFxObject*)¶ms[4];
}
void CheckDescription(GFxObject DataList)
{
ubyte params[4];
params[] = 0;
*cast(GFxObject*)params.ptr = DataList;
(cast(ScriptObject)this).ProcessEvent(Functions.CheckDescription, params.ptr, cast(void*)0);
}
GFxObject FillDescription(GFxObject DataList)
{
ubyte params[8];
params[] = 0;
*cast(GFxObject*)params.ptr = DataList;
(cast(ScriptObject)this).ProcessEvent(Functions.FillDescription, params.ptr, cast(void*)0);
return *cast(GFxObject*)¶ms[4];
}
void ShowModel()
{
(cast(ScriptObject)this).ProcessEvent(Functions.ShowModel, cast(void*)0, cast(void*)0);
}
bool CheckPricing(GFxObject DataList)
{
ubyte params[8];
params[] = 0;
*cast(GFxObject*)params.ptr = DataList;
(cast(ScriptObject)this).ProcessEvent(Functions.CheckPricing, params.ptr, cast(void*)0);
return *cast(bool*)¶ms[4];
}
GFxObject FillPricing(GFxObject DataList)
{
ubyte params[8];
params[] = 0;
*cast(GFxObject*)params.ptr = DataList;
(cast(ScriptObject)this).ProcessEvent(Functions.FillPricing, params.ptr, cast(void*)0);
return *cast(GFxObject*)¶ms[4];
}
}
|
D
|
/**
* This module defines logging functions for Pebble watches.
*/
module pebble.logging;
@nogc:
nothrow:
/// An opaque type for data logging.
struct DataLoggingSession {}
/// A reference to a data logging session on Pebble OS.
deprecated("Use DataLoggingSession* instead of DataLoggingSessionRef")
alias void* DataLoggingSessionRef;
/**
* The different types of session data that Pebble supports. This type
* describes the type of a singular item in the data session. Every item in
* a given session is the same type and size.
*/
enum DataLoggingItemType {
/**
* Array of bytes. Remember that this is the type of a single item in the
* logging session, so using this type means you'll be logging multiple
* byte arrays (each a fixed length described by item_length) for
* the duration of the session.
*/
byte_array = 0,
/**
* Unsigned integer. This may be a 1, 2, or 4 byte integer depending on
* the item_length parameter
*/
_uint = 2,
/**
* Signed integer. This may be a 1, 2, or 4 byte integer depending on
* the item_length parameter
*/
_int = 3
}
///
alias DATA_LOGGING_BYTE_ARRAY = DataLoggingItemType.byte_array;
///
alias DATA_LOGGING_UINT = DataLoggingItemType._uint;
///
alias DATA_LOGGING_INT = DataLoggingItemType._int;
/**
* Enumerated values describing the possible outcomes of data logging
* operations
*/
enum DataLoggingResult {
/// Successful operation.
success = 0,
/// Someone else is writing to this logging session.
busy = 1,
/// No more space to save data.
full = 2,
/// The logging session does not exist.
not_found = 3,
/// The logging session was made inactive.
closed = 4,
/// An invalid parameter was passed to one of the functions.
invalid_params = 5
}
///
alias DATA_LOGGING_SUCCESS = DataLoggingResult.success;
///
alias DATA_LOGGING_BUSY = DataLoggingResult.busy;
///
alias DATA_LOGGING_FULL = DataLoggingResult.full;
///
alias DATA_LOGGING_NOT_FOUND = DataLoggingResult.not_found;
///
alias DATA_LOGGING_CLOSED = DataLoggingResult.closed;
///
alias DATA_LOGGING_INVALID_PARAMS = DataLoggingResult.invalid_params;
/**
* Create a new data logging session.
*
* Params:
* tag = A tag associated with the logging session.
* item_type = The type of data stored in this logging session
* item_length = The size of a single data item in bytes
* resume = true if we want to look for a logging session of the same tag and
* resume logging to it. If this is false and a session with the specified
* tag exists, that session will be closed and a new session will be
* opened.
*
* Returns: An opaque reference to the data logging session.
*/
extern(C) DataLoggingSession* data_logging_create
(uint tag, DataLoggingItemType item_type, ushort item_length, bool resume);
/**
* Finish up a data logging_session. Logging data is kept until it has
* successfully been transferred over to the phone, but no data may be added
* to the session after this function is called.
*
* Params:
* logging_session = a reference to the data logging session previously
* allocated using data_logging_create
*/
extern(C) void data_logging_finish(DataLoggingSession* logging_session);
/**
* Add data to the data logging session. If a phone is available,
* the data is sent directly to the phone. Otherwise, it is saved to the
* watch storage until the watch is connected to a phone.
*
* Params:
* logging_session = A reference to the data logging session you want to add
* the data to.
* data = A pointer to the data buffer that contains multiple items.
* num_items = The number of items to log. This means data must be at least
* (num_items * item_length) long in bytes.
*
* Returns: DATA_LOGGING_SUCCESS on success.
* Returns: DATA_LOGGING_NOT_FOUND if the logging session is invalid.
* Returns: DATA_LOGGING_CLOSED if the session is not active.
* Returns: DATA_LOGGING_BUSY if the session is not available for writing.
* Returns: DATA_LOGGING_INVALID_PARAMS if num_items is 0 or data is NULL.
*/
extern(C) DataLoggingResult data_logging_log
(DataLoggingSession* logging_session, const(void)* data, uint num_items);
/// Suggested log level values
enum AppLogLevel: ubyte {
error = 1,
warning = 50,
info = 100,
_debug = 200,
verbose = 255
}
///
alias APP_LOG_LEVEL_ERROR = AppLogLevel.error;
///
alias APP_LOG_LEVEL_WARNING = AppLogLevel.warning;
///
alias APP_LOG_LEVEL_INFO = AppLogLevel.info;
///
alias APP_LOG_LEVEL_DEBUG = AppLogLevel._debug;
///
alias APP_LOG_LEVEL_VERBOSE = AppLogLevel.verbose;
/**
* Log an app message.
*
* See_Also: snprinf for defaults about the C formatting string.
*
* Params:
* log_level = The log level.
* src_filename = The source file where the log originates from.
* src_line_number = The line number in the source file where the log
* originates from.
* fmt = A C formatting string
* ... = The arguments for the formatting string
*/
extern(C) void app_log(AppLogLevel log_level, const(char)* src_filename,
int src_line_number, const(char)* fmt, ...);
// TODO: Implement more arguments than just the format string.
/**
* This function matches the helper macro which comes with Pebble.
*
* Params:
* level = The log level to log output as
* fmt = A C formatting string
* args = The arguments for the formatting string
*/
void APP_LOG(AppLogLevel log_level, const(char)* fmt,
int src_line_number = __LINE__, const(char)* src_filename = __FILE__.ptr) {
app_log(log_level, src_filename, src_line_number, fmt);
}
|
D
|
module basics.user;
/* User settings read from the user config file. This file differs from the
* global config file, see globconf.d. Whenever the user file doesn't exist,
* the default values from static this() are used.
*/
import std.typecons; // rebindable
import std.algorithm; // sort filenames before outputting them
import std.conv;
import enumap;
import basics.alleg5;
import basics.globals;
import basics.globconf;
import basics.help;
import file.filename;
import file.date;
import file.io;
import file.language;
import file.log; // when writing to disk fails
import file.useropt;
import hardware.keynames;
import hardware.keyset;
import net.ac;
import net.phyu;
import net.style;
private Result[Filename] results;
// These is only for iteration during option saving/loading.
// Outside of this module, refer to options by their static variable name.
private AbstractUserOption[string] _optvecLoad;
private AbstractUserOption[] _optvecSave;
private auto newOpt(T)(string fileKey, Lang lang, T defaultVal)
{
assert (fileKey !in _optvecLoad);
static if (is (T == Filename))
auto ret = new UserOptionFilename(fileKey, lang, defaultVal);
else
auto ret = new UserOption!T(fileKey, lang, defaultVal);
_optvecLoad[fileKey] = ret;
_optvecSave ~= ret;
return ret;
}
private auto newOpt(T)(string fileKey, T defaultVal)
{
return newOpt(fileKey, Lang.min, defaultVal);
}
@property bool languageIsEnglish()
{
assert (fileLanguage !is null);
assert (fileLanguage.value !is null);
return fileLanguage.value == basics.globals.fileLanguageEnglish;
}
UserOptionFilename fileLanguage;
UserOption!int optionGroup;
UserOption!int mouseSpeed;
UserOption!int scrollSpeedEdge;
UserOption!int scrollSpeedClick;
UserOption!bool fastMovementFreesMouse;
UserOption!bool avoidBuilderQueuing;
UserOption!bool avoidBatterToExploder;
UserOption!bool replayAfterFrameBack;
UserOption!int pausedAssign; // 0 = nothing (allows multiple assignments),
// 1 = advance 1 frame, 2 = unpause
UserOption!bool screenWindowed;
UserOption!int screenWindowedX;
UserOption!int screenWindowedY;
UserOption!bool paintTorusSeams;
UserOption!bool showButtonHotkeys;
UserOption!bool ingameTooltips;
UserOption!bool showFPS;
UserOption!int guiColorRed;
UserOption!int guiColorGreen;
UserOption!int guiColorBlue;
UserOption!int soundVolume;
UserOptionFilename singleLastLevel;
UserOptionFilename networkLastLevel;
UserOptionFilename replayLastLevel;
UserOption!int networkLastStyle;
UserOption!bool replayAutoSolutions;
UserOption!bool replayAutoMulti;
UserOption!int editorGridSelected;
UserOption!int editorGridCustom;
UserOptionFilename editorLastDirTerrain;
UserOptionFilename editorLastDirSteel;
UserOptionFilename editorLastDirHatch;
UserOptionFilename editorLastDirGoal;
UserOptionFilename editorLastDirHazard;
UserOption!KeySet
keyScroll,
keyPriorityInvert,
keyZoomIn,
keyZoomOut,
keyForceLeft,
keyForceRight,
keyPause,
keyFrameBackMany,
keyFrameBackOne,
keyFrameAheadOne,
keyFrameAheadMany,
keySpeedFast,
keySpeedTurbo,
keyRestart,
keyStateLoad,
keyStateSave,
keyNuke,
keyChat,
keySpecTribe,
keyPingGoals,
keyGameExit,
keyMenuOkay,
keyMenuEdit,
keyMenuNewLevel,
keyMenuExport,
keyMenuDelete,
keyMenuSearch,
keyMenuUpDir,
keyMenuUpBy1,
keyMenuUpBy5,
keyMenuDownBy1,
keyMenuDownBy5,
keyMenuExit,
keyMenuMainSingle,
keyMenuMainNetwork,
keyMenuMainReplays,
keyMenuMainOptions,
keyEditorLeft,
keyEditorRight,
keyEditorUp,
keyEditorDown,
keyEditorSave,
keyEditorSaveAs,
keyEditorCopy,
keyEditorDelete,
keyEditorGrid,
keyEditorSelectAll,
keyEditorSelectFrame,
keyEditorSelectAdd,
keyEditorGroup,
keyEditorUngroup,
keyEditorBackground,
keyEditorForeground,
keyEditorMirror,
keyEditorRotate,
keyEditorDark,
keyEditorAddTerrain,
keyEditorAddSteel,
keyEditorAddHatch,
keyEditorAddGoal,
keyEditorAddHazard,
keyEditorExit,
keyEditorMenuConstants,
keyEditorMenuTopology,
keyEditorMenuLooks,
keyEditorMenuSkills;
Enumap!(Ac, UserOption!KeySet) keySkill;
@property const(Ac[14]) skillSort() { return _skillSort; }
private Ac[14] _skillSort = [
Ac.walker,
Ac.jumper,
Ac.runner,
Ac.climber,
Ac.floater,
Ac.batter,
Ac.exploder,
Ac.blocker,
Ac.cuber,
Ac.builder,
Ac.platformer,
Ac.basher,
Ac.miner,
Ac.digger
];
static this()
{
assert (! fileLanguage);
assert (fileLanguageEnglish);
fileLanguage = newOpt("LANGUAGE", Lang.optionLanguage, fileLanguageEnglish);
optionGroup = newOpt("OPTION_GROUP", 0);
mouseSpeed = newOpt("MOUSE_SPEED", Lang.optionMouseSpeed, mouseStandardDivisor);
scrollSpeedEdge = newOpt("SCROLL_SPEED_EDGE", Lang.optionScrollSpeedEdge, mouseStandardDivisor);
scrollSpeedClick = newOpt("SCROLL_SPEED_CLICK", Lang.optionScrollSpeedClick, mouseStandardDivisor / 2);
version (linux) {
fastMovementFreesMouse = newOpt("FAST_MOVEMENT_FREES_MOUSE",
Lang.optionFastMovementFreesMouse, false);
}
else {
fastMovementFreesMouse = newOpt("FAST_MOVEMENT_FREES_MOUSE",
Lang.optionFastMovementFreesMouse, true);
}
avoidBuilderQueuing = newOpt("AVOID_BUILDER_QUEUING", Lang.optionAvoidBuilderQueuing, true);
avoidBatterToExploder = newOpt("AVOID_BATTER_TO_EXPLODER", Lang.optionAvoidBatterToExploder, false);
replayAfterFrameBack = newOpt("REPLAY_AFTER_FRAME_BACK", Lang.optionReplayAfterFrameBack, true);
pausedAssign = newOpt("PAUSED_ASSIGN", Lang.optionPausedAssign, 1);
screenWindowed = newOpt("SCREEN_WINDOWED", Lang.optionScreenWindowed, false);
screenWindowedX = newOpt("SCREEN_WINDOWED_X", Lang.optionScreenWindowedRes, 640);
screenWindowedY = newOpt("SCREEN_WINDOWED_Y", 480);
paintTorusSeams = newOpt("PAINT_TORUS_SEAMS", Lang.optionPaintTorusSeams, true);
showButtonHotkeys = newOpt("SHOW_BUTTON_HOTKEYS", Lang.optionShowButtonHotkeys, true);
ingameTooltips = newOpt("INGAME_TOOLTIPS", Lang.optionIngameTooltips, true);
showFPS = newOpt("SHOW_FRAMES_PER_SECOND", Lang.optionShowFPS, false);
guiColorRed = newOpt("GUI_COLOR_RED", Lang.optionGuiColorRed, 0x60);
guiColorGreen = newOpt("GUI_COLOR_GREEN", Lang.optionGuiColorGreen, 0x80);
guiColorBlue = newOpt("GUI_COLOR_BLUE", Lang.optionGuiColorBlue, 0xB0);
soundVolume = newOpt("SOUND_VOLUME", Lang.optionSoundVolume, 10);
singleLastLevel = newOpt("SINGLE_LAST_LEVEL", fileSingleplayerFirstLevel);
networkLastLevel = newOpt("NETWORK_LAST_LEVEL", dirLevelsNetwork);
replayLastLevel = newOpt("REPLAY_LAST_LEVEL", dirReplays);
networkLastStyle = newOpt("NETWORK_LAST_STYLE", Style.red.to!int);
replayAutoSolutions = newOpt("REPLAY_AUTO_SAVE_SOLUTIONS", Lang.optionReplayAutoSolutions, true);
replayAutoMulti = newOpt("REPLAY_AUTO_SAVE_MULTI", Lang.optionReplayAutoMulti, true);
editorLastDirTerrain = newOpt("EDITOR_LAST_DIR_TERRAIN", Lang.addTerrain, dirImages);
editorLastDirSteel = newOpt("EDITOR_LAST_DIR_STEEL", Lang.addSteel, dirImages);
editorLastDirHatch = newOpt("EDITOR_LAST_DIR_HATCH", Lang.addHatch, dirImages);
editorLastDirGoal = newOpt("EDITOR_LAST_DIR_GOAL", Lang.addGoal, dirImages);
editorLastDirHazard = newOpt("EDITOR_LAST_DIR_HAZARD", Lang.addHazard, dirImages);
editorGridSelected = newOpt("EDITOR_GRID_SELECTED", 1);
editorGridCustom = newOpt("EDITOR_GRID_CUSTOM", Lang.optionEdGridCustom, 8);
void newSkillKey(Ac ac, int singleKey)
{
keySkill[ac] = newOpt(ac.acToString, KeySet(singleKey));
}
newSkillKey(Ac.walker, ALLEGRO_KEY_D);
newSkillKey(Ac.jumper, ALLEGRO_KEY_R);
newSkillKey(Ac.runner, ALLEGRO_KEY_LSHIFT);
newSkillKey(Ac.climber, ALLEGRO_KEY_Z);
newSkillKey(Ac.floater, ALLEGRO_KEY_Q);
newSkillKey(Ac.batter, ALLEGRO_KEY_C);
newSkillKey(Ac.exploder, ALLEGRO_KEY_V);
newSkillKey(Ac.blocker, ALLEGRO_KEY_X);
newSkillKey(Ac.cuber, ALLEGRO_KEY_B);
newSkillKey(Ac.builder, ALLEGRO_KEY_A);
newSkillKey(Ac.platformer, ALLEGRO_KEY_T);
newSkillKey(Ac.basher, ALLEGRO_KEY_E);
newSkillKey(Ac.miner, ALLEGRO_KEY_G);
newSkillKey(Ac.digger, ALLEGRO_KEY_W);
auto newKey(string str, Lang lang, int key)
{
return newOpt(str, lang, KeySet(key));
}
auto newKey2(string str, Lang lang, int key1, int key2)
{
return newOpt(str, lang, KeySet(KeySet(key1), KeySet(key2)));
}
// Global keys -- these work in editor and game
keyScroll = newKey("KEY_HOLD_TO_SCROLL", Lang.optionKeyScroll, keyRMB);
keyPriorityInvert = newKey("KEY_PRIORITY_INVERT", Lang.optionKeyPriorityInvert, keyRMB);
keyZoomIn = newKey("KEY_ZOOM_IN", Lang.optionKeyZoomIn, hardware.keynames.keyWheelUp);
keyZoomOut = newKey("KEY_ZOOM_OUT", Lang.optionKeyZoomOut, hardware.keynames.keyWheelDown);
// Game keys
keyForceLeft = newKey2("KEY_FORCE_LEFT", Lang.optionKeyForceLeft, ALLEGRO_KEY_S, ALLEGRO_KEY_LEFT);
keyForceRight = newKey2("KEY_FORCE_RIGHT", Lang.optionKeyForceRight, ALLEGRO_KEY_F, ALLEGRO_KEY_RIGHT);
keyPause = newKey2("KEY_PAUSE", Lang.optionKeyPause, ALLEGRO_KEY_SPACE, keyMMB);
keyFrameBackMany = newKey("KEY_SPEED_BACK_MANY", Lang.optionKeyFrameBackMany, ALLEGRO_KEY_1);
keyFrameBackOne = newKey("KEY_SPEED_BACK_ONE", Lang.optionKeyFrameBackOne, ALLEGRO_KEY_2);
keyFrameAheadOne = newKey("KEY_SPEED_AHEAD_ONE", Lang.optionKeyFrameAheadOne, ALLEGRO_KEY_3);
keyFrameAheadMany = newKey("KEY_SPEED_AHEAD_MANY", Lang.optionKeyFrameAheadMany, ALLEGRO_KEY_6);
keySpeedFast = newKey("KEY_SPEED_FAST", Lang.optionKeySpeedFast, ALLEGRO_KEY_4);
keySpeedTurbo = newKey("KEY_SPEED_TURBO", Lang.optionKeySpeedTurbo, ALLEGRO_KEY_5);
keyRestart = newKey("KEY_RESTART", Lang.optionKeyRestart, ALLEGRO_KEY_F1);
keyStateLoad = newKey("KEY_STATE_LOAD", Lang.optionKeyStateLoad, ALLEGRO_KEY_F2);
keyStateSave = newKey("KEY_STATE_SAVE", Lang.optionKeyStateSave, ALLEGRO_KEY_F3);
keyNuke = newKey("KEY_NUKE", Lang.optionKeyNuke, ALLEGRO_KEY_F12);
keySpecTribe = newKey("KEY_SPECTATE_NEXT_PLAYER", Lang.optionKeySpecTribe, ALLEGRO_KEY_TAB);
keyPingGoals = newOpt("KEY_PING_GOALS", Lang.optionKeyPingGoals, KeySet());
keyChat = newKey("KEY_CHAT", Lang.optionKeyChat, ALLEGRO_KEY_ENTER);
keyGameExit = newKey("KEY_GAME_EXIT", Lang.winGameTitle, ALLEGRO_KEY_ESCAPE);
keyMenuOkay = newKey("KEY_MENU_OKAY", Lang.optionKeyMenuOkay, ALLEGRO_KEY_SPACE);
keyMenuEdit = newKey("KEY_MENU_EDIT", Lang.optionKeyMenuEdit, ALLEGRO_KEY_F);
keyMenuNewLevel = newKey("KEY_MENU_NEW_LEVEL", Lang.optionKeyMenuNewLevel, ALLEGRO_KEY_F1);
keyMenuExport = newKey("KEY_MENU_EXPORT", Lang.optionKeyMenuExport, ALLEGRO_KEY_R);
keyMenuDelete = newKey2("KEY_MENU_DELETE", Lang.optionKeyMenuDelete, ALLEGRO_KEY_G, ALLEGRO_KEY_DELETE);
keyMenuSearch = newKey("KEY_MENU_SEARCH", Lang.browserSearch, ALLEGRO_KEY_SLASH);
keyMenuUpDir = newKey("KEY_MENU_UP_DIR", Lang.optionKeyMenuUpDir, ALLEGRO_KEY_A);
keyMenuUpBy1 = newKey2("KEY_MENU_UP_1", Lang.optionKeyMenuUpBy1, ALLEGRO_KEY_S, ALLEGRO_KEY_UP);
keyMenuUpBy5 = newKey("KEY_MENU_UP_5", Lang.optionKeyMenuUpBy5, ALLEGRO_KEY_W);
keyMenuDownBy1 = newKey2("KEY_MENU_DOWN_1", Lang.optionKeyMenuDownBy1, ALLEGRO_KEY_D, ALLEGRO_KEY_DOWN);
keyMenuDownBy5 = newKey("KEY_MENU_DOWN_5", Lang.optionKeyMenuDownBy5, ALLEGRO_KEY_E);
keyMenuExit = newKey("KEY_MENU_EXIT", Lang.optionKeyMenuExit, ALLEGRO_KEY_ESCAPE);
keyMenuMainSingle = newKey("KEY_MENU_MAIN_SINGLE", Lang.browserSingleTitle, ALLEGRO_KEY_F);
keyMenuMainNetwork = newKey("KEY_MENU_MAIN_NETWORK", Lang.winLobbyTitle, ALLEGRO_KEY_D);
keyMenuMainReplays = newKey("KEY_MENU_MAIN_REPLAY", Lang.browserReplayTitle, ALLEGRO_KEY_S);
keyMenuMainOptions = newKey("KEY_MENU_MAIN_OPTIONS", Lang.optionTitle, ALLEGRO_KEY_A);
keyEditorLeft = newKey2("KEY_EDITOR_LEFT", Lang.optionEdLeft, ALLEGRO_KEY_S, ALLEGRO_KEY_LEFT);
keyEditorRight = newKey2("KEY_EDITOR_RIGHT", Lang.optionEdRight, ALLEGRO_KEY_F, ALLEGRO_KEY_RIGHT);
keyEditorUp = newKey2("KEY_EDITOR_UP", Lang.optionEdUp, ALLEGRO_KEY_E, ALLEGRO_KEY_UP);
keyEditorDown = newKey2("KEY_EDITOR_DOWN", Lang.optionEdDown, ALLEGRO_KEY_D, ALLEGRO_KEY_DOWN);
keyEditorSave = newOpt("KEY_EDITOR_SAVE", Lang.optionEdSave, KeySet());
keyEditorSaveAs = newOpt("KEY_EDITOR_SAVE_AS", Lang.optionEdSaveAs, KeySet());
keyEditorCopy = newKey("KEY_EDITOR_COPY", Lang.optionEdCopy, ALLEGRO_KEY_A);
keyEditorDelete = newKey2("KEY_EDITOR_DELETE", Lang.optionEdDelete, ALLEGRO_KEY_G, ALLEGRO_KEY_DELETE);
keyEditorGrid = newKey("KEY_EDITOR_GRID", Lang.optionEdGrid, ALLEGRO_KEY_C);
keyEditorSelectAll = newKey("KEY_EDITOR_SELECT_ALL", Lang.optionEdSelectAll, ALLEGRO_KEY_ALT);
keyEditorSelectFrame = newKey("KEY_EDITOR_SELECT_FRAME", Lang.optionEdSelectFrame, ALLEGRO_KEY_LSHIFT);
keyEditorSelectAdd = newKey("KEY_EDITOR_SELECT_ADD", Lang.optionEdSelectAdd, ALLEGRO_KEY_V);
keyEditorGroup = newKey("KEY_EDITOR_GROUP", Lang.optionEdGroup, ALLEGRO_KEY_Q);
keyEditorUngroup = newOpt("KEY_EDITOR_UNGROUP", Lang.optionEdUngroup, KeySet());
keyEditorForeground = newKey("KEY_EDITOR_FOREGROUND", Lang.optionEdForeground, ALLEGRO_KEY_T);
keyEditorBackground = newKey("KEY_EDITOR_BACKGROUND", Lang.optionEdBackground, ALLEGRO_KEY_B);
keyEditorMirror = newKey("KEY_EDITOR_MIRROR", Lang.optionEdMirror, ALLEGRO_KEY_W);
keyEditorRotate = newKey("KEY_EDITOR_ROTATE", Lang.optionEdRotate, ALLEGRO_KEY_R);
keyEditorDark = newKey("KEY_EDITOR_DARK", Lang.optionEdDark, ALLEGRO_KEY_X);
keyEditorAddTerrain = newKey("KEY_EDITOR_ADD_TERRAIN", Lang.optionEdAddTerrain, ALLEGRO_KEY_SPACE);
keyEditorAddSteel = newKey("KEY_EDITOR_ADD_STEEL", Lang.optionEdAddSteel, ALLEGRO_KEY_TAB);
keyEditorAddHatch = newKey("KEY_EDITOR_ADD_HATCH", Lang.optionEdAddHatch, ALLEGRO_KEY_1);
keyEditorAddGoal = newKey("KEY_EDITOR_ADD_GOAL", Lang.optionEdAddGoal, ALLEGRO_KEY_2);
keyEditorAddHazard = newKey("KEY_EDITOR_ADD_HAZARD", Lang.optionEdAddHazard, ALLEGRO_KEY_4);
keyEditorMenuConstants = newKey("KEY_EDITOR_MENU_CONSTANTS", Lang.winConstantsTitle, ALLEGRO_KEY_5);
keyEditorMenuTopology = newKey("KEY_EDITOR_MENU_TOPOLOGY", Lang.winTopologyTitle, ALLEGRO_KEY_6);
keyEditorMenuLooks = newKey("KEY_EDITOR_MENU_LOOKS", Lang.winLooksTitle, ALLEGRO_KEY_7);
keyEditorMenuSkills = newKey("KEY_EDITOR_MENU_SKILLS", Lang.winSkillsTitle, ALLEGRO_KEY_8);
keyEditorExit = newKey("KEY_EDITOR_EXIT", Lang.commonExit, ALLEGRO_KEY_ESCAPE);
_optvecLoad.rehash();
}
// ############################################################################
class Result {
const(Date) built;
int lixSaved;
int skillsUsed;
Phyu phyusUsed;
this (const(Date) bu)
{
built = bu;
}
int opEquals(in Result rhs) const
{
return built == rhs.built
&& lixSaved == rhs.lixSaved
&& skillsUsed == rhs.skillsUsed
&& phyusUsed == rhs.phyusUsed;
}
// Returns < 0 on a worse rhs result, > 0 for a better rhs result.
// The user wouldn't want to replace an old solving result with
// a new-built-using non-solving result.
// To check in results into the database of solved levels, use
// setLevelResult() from this module.
int opCmp(in Result rhs) const
{
if (lixSaved != rhs.lixSaved)
return lixSaved - rhs.lixSaved; // more lix saved is better
if (skillsUsed != rhs.skillsUsed)
return rhs.skillsUsed - skillsUsed; // fewer skills used is better
if (phyusUsed != rhs.phyusUsed)
return rhs.phyusUsed - phyusUsed; // less time taken is better
return built.opCmp(rhs.built); // newer result better
}
unittest {
Result a = new Result(Date.now());
Result b = new Result(Date.now());
a.lixSaved = 4;
b.lixSaved = 5;
assert (b > a);
b.lixSaved = 4;
assert (a >= b);
b.phyusUsed = 1;
assert (a > b);
}
}
const(Result) getLevelResult(in Filename fn)
{
Result* ret = (rebindable!(const Filename)(fn) in results);
return ret ? (*ret) : null;
}
void setLevelResult(
in Filename _fn,
Result r,
) {
auto fn = rebindable!(const Filename)(_fn);
auto savedResult = (fn in results);
if (savedResult is null
|| savedResult.built != r.built
|| *savedResult < r)
results[fn] = r;
}
// ############################################################################
private Filename userFileName()
{
return new VfsFilename(dirDataUser.dirRootless
~ basics.help.escapeStringForFilename(userName)
~ filenameExtConfig);
}
void load()
{
if (userName == null)
// This happens upon first start after installation.
// Don't try to load anything, and don't log anything.
return;
IoLine[] lines;
try
lines = fillVectorFromFile(userFileName());
catch (Exception e) {
log("Can't load user configuration for `" ~ userName ~ "':");
log(" -> " ~ e.msg);
log(" -> Falling back to the unescaped filename `"
~ userName ~ filenameExtConfig ~ "'.");
try {
lines = fillVectorFromFile(new VfsFilename(
dirDataUser.dirRootless ~ userName ~ filenameExtConfig));
}
catch (Exception e) {
log(" -> " ~ e.msg);
log(" -> " ~ "Falling back to the default user configuration.");
lines = null;
}
}
results = null;
foreach (i; lines) {
if (i.type == '<') {
import std.string;
auto fn = rebindable!(const Filename)(new VfsFilename(
// Backwards compat for renaming Simple to Lovely:
// Load all old user results. We would save with the new name.
// Remove the call to replace during early 2018.
i.text1.replace("lemforum/Simple/", "lemforum/Lovely/")
));
Result read = new Result(new Date(i.text2));
read.lixSaved = i.nr1;
read.skillsUsed = i.nr2;
read.phyusUsed = Phyu(i.nr3);
Result* old = (fn in results);
if (! old || *old < read)
results[fn] = read;
}
else if (auto opt = i.text1 in _optvecLoad)
opt.set(i);
// Backwards compatibility: Before 0.6.2, I had hacked in two hotkeys
// for pause that saved to different variables. Load this other var.
else if (i.nr1 != 0 && i.text1 == "KEY_PAUSE2")
keyPause.value = KeySet(keyPause.value, KeySet(i.nr1));
}
}
nothrow void save()
{
if (userName == null) {
log("User name is empty. User configuration will not be saved.");
return;
}
try {
auto f = userFileName.openForWriting();
foreach (opt; _optvecSave)
f.writeln(opt.ioLine);
f.writeln();
foreach (key, r; results)
f.writeln(IoLine.Angle(key.rootless,
r.lixSaved, r.skillsUsed, r.phyusUsed, r.built.toString));
}
catch (Exception e) {
log("Can't save user configuration for `" ~ userName ~ "':");
log(" -> " ~ e.msg);
}
}
|
D
|
/******************************************************************************
Tests the reading of the legacy buckets.
Copyright: (c) 2016 Sociomantic Labs. All rights reserved.
******************************************************************************/
module integrationtest.versioning.cases.TestLegacy;
import integrationtest.versioning.DlsVersioningCase;
import ocean.core.array.Search;
import ocean.transition;
/******************************************************************************
Check if the legacy records can be read.
*******************************************************************************/
class GetAllLegacy: DlsVersioningCase
{
this ( )
{
this.test_channel = "legacy";
}
override public Description description ( )
{
Description desc;
desc.priority = 100;
desc.name = "GetAll over the legacy channel";
return desc;
}
public override void run ( )
{
// A single bucket file in the legacy format is copied into the test DLS
// node's data folder (see DlsVersioningRunner.copyFiles()). We can then
// perform tests to check that the DLS can read it properly.
// The layout of the legacy channel
cstring[][hash_t] records =
[
0x0000000057275806: ["Hello there"],
0x0000000057275809: ["I'm a legacy channel"],
0x000000005727580c: ["Nice to meet you finaly"],
0x0000000057275810: ["Oh, yes indeed."]
];
// Do a GetAll to retrieve them all
auto fetched = this.dls.getAll(this.test_channel);
// Confirm the results
test!("==")(fetched.length, records.length);
bool[hash_t] checked;
foreach (k, vals; fetched)
{
auto local_vals = k in records;
test(local_vals.length == vals.length, "GetAll returned wrong key");
foreach (val; vals)
{
test!("==")((*local_vals).contains(val), true);
}
test(!(k in checked), "GetAll returned the same key twice");
checked[k] = true;
}
}
}
|
D
|
/Users/radibarq/developer/NasaInArabic/build/NasaInArabic.build/Debug-iphonesimulator/NasaInArabic.build/Objects-normal/x86_64/AppStoreViewController1.o : /Users/radibarq/developer/NasaInArabic/NasaInArabic/AppStoreViewController1.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Source.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/\ Article.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/AppDelegate.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Tag.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Global.swift /Users/radibarq/developer/NasaInArabic/CachingPlayerItem.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/WebViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ArticleTableViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/MoreTableViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ArticleViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ImageArticleViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ProfileViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/CategoriesCollectionViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ArticlesCollectionViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/AlbumsCollectionViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/VideosCollectionViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/VideoViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/TabBarViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/AboutUsViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/CategoriesViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Contributor.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Contributors.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Hero/Hero.framework/Modules/Hero.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Player/Player.framework/Modules/Player.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YouTubePlayer/YouTubePlayer.framework/Modules/YouTubePlayer.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Cards/Cards.framework/Modules/Cards.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YoutubeKit/YoutubeKit.framework/Modules/YoutubeKit.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/CollectionKit/CollectionKit.framework/Modules/CollectionKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ModelIO.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/simd.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreAudio.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/MediaPlayer.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/MetalKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImage+GIF.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImage-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Hero/Hero.framework/Headers/Hero-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Player/Player.framework/Headers/Player-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YouTubePlayer/YouTubePlayer.framework/Headers/YouTubePlayer-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Cards/Cards.framework/Headers/Cards-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YoutubeKit/YoutubeKit.framework/Headers/YoutubeKit-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/CollectionKit/CollectionKit.framework/Headers/CollectionKit-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImage+ForceDecode.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/NSImage+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIButton+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/NSButton+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIView+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImageView+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImageView+HighlightedWebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDImageCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageFrame.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/NSData+ImageContentType.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDImageCacheConfig.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageOperation.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIView+WebCacheOperation.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageDownloaderOperation.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageTransition.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDAnimatedImageRep.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageDownloader.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageGIFCoder.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageImageIOCoder.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageCoder.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageManager.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageCodersManager.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImagePrefetcher.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageCoderHelper.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImage+MultiFormat.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageCompat.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Hero/Hero.framework/Headers/Hero-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Player/Player.framework/Headers/Player-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YouTubePlayer/YouTubePlayer.framework/Headers/YouTubePlayer-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Cards/Cards.framework/Headers/Cards-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YoutubeKit/YoutubeKit.framework/Headers/YoutubeKit-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/CollectionKit/CollectionKit.framework/Headers/CollectionKit-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Hero/Hero.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Player/Player.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YouTubePlayer/YouTubePlayer.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Cards/Cards.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YoutubeKit/YoutubeKit.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/CollectionKit/CollectionKit.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/MessageUI.framework/Headers/MessageUI.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/ModelIO.framework/Headers/ModelIO.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreMedia.framework/Headers/CoreMedia.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/AVFoundation.framework/Headers/AVFoundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/MediaPlayer.framework/Headers/MediaPlayer.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/WebKit.framework/Headers/WebKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/MetalKit.framework/Headers/MetalKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/MediaToolbox.framework/Headers/MediaToolbox.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/AudioToolbox.framework/Headers/AudioToolbox.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/radibarq/developer/NasaInArabic/build/NasaInArabic.build/Debug-iphonesimulator/NasaInArabic.build/Objects-normal/x86_64/AppStoreViewController1~partial.swiftmodule : /Users/radibarq/developer/NasaInArabic/NasaInArabic/AppStoreViewController1.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Source.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/\ Article.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/AppDelegate.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Tag.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Global.swift /Users/radibarq/developer/NasaInArabic/CachingPlayerItem.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/WebViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ArticleTableViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/MoreTableViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ArticleViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ImageArticleViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ProfileViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/CategoriesCollectionViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ArticlesCollectionViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/AlbumsCollectionViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/VideosCollectionViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/VideoViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/TabBarViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/AboutUsViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/CategoriesViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Contributor.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Contributors.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Hero/Hero.framework/Modules/Hero.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Player/Player.framework/Modules/Player.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YouTubePlayer/YouTubePlayer.framework/Modules/YouTubePlayer.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Cards/Cards.framework/Modules/Cards.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YoutubeKit/YoutubeKit.framework/Modules/YoutubeKit.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/CollectionKit/CollectionKit.framework/Modules/CollectionKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ModelIO.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/simd.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreAudio.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/MediaPlayer.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/MetalKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImage+GIF.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImage-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Hero/Hero.framework/Headers/Hero-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Player/Player.framework/Headers/Player-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YouTubePlayer/YouTubePlayer.framework/Headers/YouTubePlayer-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Cards/Cards.framework/Headers/Cards-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YoutubeKit/YoutubeKit.framework/Headers/YoutubeKit-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/CollectionKit/CollectionKit.framework/Headers/CollectionKit-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImage+ForceDecode.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/NSImage+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIButton+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/NSButton+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIView+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImageView+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImageView+HighlightedWebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDImageCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageFrame.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/NSData+ImageContentType.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDImageCacheConfig.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageOperation.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIView+WebCacheOperation.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageDownloaderOperation.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageTransition.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDAnimatedImageRep.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageDownloader.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageGIFCoder.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageImageIOCoder.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageCoder.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageManager.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageCodersManager.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImagePrefetcher.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageCoderHelper.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImage+MultiFormat.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageCompat.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Hero/Hero.framework/Headers/Hero-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Player/Player.framework/Headers/Player-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YouTubePlayer/YouTubePlayer.framework/Headers/YouTubePlayer-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Cards/Cards.framework/Headers/Cards-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YoutubeKit/YoutubeKit.framework/Headers/YoutubeKit-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/CollectionKit/CollectionKit.framework/Headers/CollectionKit-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Hero/Hero.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Player/Player.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YouTubePlayer/YouTubePlayer.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Cards/Cards.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YoutubeKit/YoutubeKit.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/CollectionKit/CollectionKit.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/MessageUI.framework/Headers/MessageUI.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/ModelIO.framework/Headers/ModelIO.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreMedia.framework/Headers/CoreMedia.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/AVFoundation.framework/Headers/AVFoundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/MediaPlayer.framework/Headers/MediaPlayer.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/WebKit.framework/Headers/WebKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/MetalKit.framework/Headers/MetalKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/MediaToolbox.framework/Headers/MediaToolbox.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/AudioToolbox.framework/Headers/AudioToolbox.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/radibarq/developer/NasaInArabic/build/NasaInArabic.build/Debug-iphonesimulator/NasaInArabic.build/Objects-normal/x86_64/AppStoreViewController1~partial.swiftdoc : /Users/radibarq/developer/NasaInArabic/NasaInArabic/AppStoreViewController1.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Source.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/\ Article.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/AppDelegate.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Tag.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Global.swift /Users/radibarq/developer/NasaInArabic/CachingPlayerItem.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/WebViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ArticleTableViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/MoreTableViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ArticleViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ImageArticleViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ProfileViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/CategoriesCollectionViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/ArticlesCollectionViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/AlbumsCollectionViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/VideosCollectionViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/VideoViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/TabBarViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/AboutUsViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/CategoriesViewController.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Contributor.swift /Users/radibarq/developer/NasaInArabic/NasaInArabic/Contributors.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Hero/Hero.framework/Modules/Hero.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Player/Player.framework/Modules/Player.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YouTubePlayer/YouTubePlayer.framework/Modules/YouTubePlayer.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Cards/Cards.framework/Modules/Cards.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YoutubeKit/YoutubeKit.framework/Modules/YoutubeKit.swiftmodule/x86_64.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/CollectionKit/CollectionKit.framework/Modules/CollectionKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ModelIO.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/simd.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreAudio.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/MediaPlayer.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/MetalKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImage+GIF.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImage-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Hero/Hero.framework/Headers/Hero-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Player/Player.framework/Headers/Player-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YouTubePlayer/YouTubePlayer.framework/Headers/YouTubePlayer-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Cards/Cards.framework/Headers/Cards-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YoutubeKit/YoutubeKit.framework/Headers/YoutubeKit-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/CollectionKit/CollectionKit.framework/Headers/CollectionKit-umbrella.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImage+ForceDecode.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/NSImage+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIButton+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/NSButton+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIView+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImageView+WebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImageView+HighlightedWebCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDImageCache.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageFrame.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/NSData+ImageContentType.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDImageCacheConfig.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageOperation.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIView+WebCacheOperation.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageDownloaderOperation.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageTransition.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDAnimatedImageRep.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageDownloader.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageGIFCoder.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageImageIOCoder.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageCoder.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageManager.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageCodersManager.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImagePrefetcher.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageCoderHelper.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/UIImage+MultiFormat.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Headers/SDWebImageCompat.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Hero/Hero.framework/Headers/Hero-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Player/Player.framework/Headers/Player-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YouTubePlayer/YouTubePlayer.framework/Headers/YouTubePlayer-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Cards/Cards.framework/Headers/Cards-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YoutubeKit/YoutubeKit.framework/Headers/YoutubeKit-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/CollectionKit/CollectionKit.framework/Headers/CollectionKit-Swift.h /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/SDWebImage/SDWebImage.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Hero/Hero.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Player/Player.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YouTubePlayer/YouTubePlayer.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/Cards/Cards.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/YoutubeKit/YoutubeKit.framework/Modules/module.modulemap /Users/radibarq/developer/NasaInArabic/build/Debug-iphonesimulator/CollectionKit/CollectionKit.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/MessageUI.framework/Headers/MessageUI.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/ModelIO.framework/Headers/ModelIO.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreMedia.framework/Headers/CoreMedia.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/AVFoundation.framework/Headers/AVFoundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/MediaPlayer.framework/Headers/MediaPlayer.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/WebKit.framework/Headers/WebKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/MetalKit.framework/Headers/MetalKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/MediaToolbox.framework/Headers/MediaToolbox.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/AudioToolbox.framework/Headers/AudioToolbox.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
|
D
|
/**
Json-Rpc 2.0 protocol implementation.
This module has 3 entry point:
$(UL
$(LI `RawJsonRpcAutoClient`)
$(LI `HttpJsonRpcAutoClient`)
$(LI `TcpJsonRpcAutoClient`)
)
Copyright: © 2018 Eliott Dumeix
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
*/
module rpc.protocol.json;
public import rpc.core;
import std.typecons: Nullable, nullable;
import vibe.data.json;
import vibe.core.log;
import autointf : InterfaceInfo;
import std.traits : hasUDA;
/** Json-Rpc 2.0 error.
*/
class JsonRpcError
{
public:
/// Error code
int code;
/// Error message
string message;
/// Optional json data
@optional Json data;
/// Default constructor.
this() @safe nothrow {}
/// Standard error constructor.
this(StdCodes code)
@safe nothrow {
this.code = code;
this.message = CODES_MESSAGE[this.code];
}
///
static enum StdCodes
{
parseError = -32700, /// Parse error
invalidRequest = -32600, /// Invalid request
methodNotFound = -32601, /// Method not found
invalidParams = -32602, /// Invalid params
internalError = -32603 /// Internal error
}
///
private static immutable string[int] CODES_MESSAGE;
static this()
@safe {
CODES_MESSAGE[StdCodes.parseError] = "Parse error";
CODES_MESSAGE[StdCodes.invalidRequest] = "Invalid Request";
CODES_MESSAGE[StdCodes.methodNotFound] = "Method not found";
CODES_MESSAGE[StdCodes.invalidParams] = "Invalid params";
CODES_MESSAGE[StdCodes.internalError] = "Internal error";
}
}
/** A Json-Rpc request that use TId as id type.
*/
class JsonRpcRequest(TId): IRpcRequest!TId
{
public:
///
override @property TId requestId() { return id; }
/// json rpc string
string jsonrpc;
/// Json rpc method
string method;
// id
@optional TId id;
// Parameters
@optional Nullable!Json params;
///
this() @safe
{
params = Nullable!Json.init;
}
/// Create a new json request.
static JsonRpcRequest!TId make(T)(TId id, string method, T params)
{
import vibe.data.json : serializeToJson;
auto request = new JsonRpcRequest!TId();
request.id = id;
request.method = method;
request.params = serializeToJson!T(params);
return request;
}
/// ditto
static JsonRpcRequest!TId make(TId id, string method)
{
auto request = new JsonRpcRequest!TId();
request.id = id;
request.method = method;
return request;
}
///
bool hasParams() @safe
{
return !params.isNull;
}
/// Convert to Json.
Json toJson() const @safe
{
Json json = Json.emptyObject;
json["jsonrpc"] = "2.0";
json["method"] = method;
json["id"] = id;
if (!params.isNull)
json["params"] = params.get;
return json;
}
/// Parse from Json.
static JsonRpcRequest fromJson(Json src) @safe
{
JsonRpcRequest request = new JsonRpcRequest();
request.jsonrpc = src["jsonrpc"].to!string;
request.method = src["method"].to!string;
if (src["id"].type != Json.Type.undefined)
request.id = src["id"].to!TId;
if (src["params"].type != Json.Type.undefined)
request.params = src["params"].nullable;
return request;
}
/// Convert to a Json string.
override string toString() const @safe
{
return toJson().toString();
}
/// Parse from a Json string.
static JsonRpcRequest fromString(string src) @safe
{
return fromJson(parseJson(src));
}
}
///
@("Test JsonRpcRequest")
unittest
{
import vibe.data.json;
auto r1 = new JsonRpcRequest!int();
auto json = Json.emptyObject;
json["foo"] = 42;
r1.method = "foo";
r1.toString().should == `{"method":"foo","id":0,"jsonrpc":"2.0"}`;
auto r2 = new JsonRpcRequest!int();
r2.method = "foo";
r2.params = json;
r2.toString().should == `{"params":{"foo":42},"method":"foo","id":0,"jsonrpc":"2.0"}`;
auto r3 = deserializeJson!(JsonRpcRequest!int)(r1.toString());
r3.id.should == r1.id;
r3.params.should == r1.params;
r3.method.should == r1.method;
// string id:
auto r10 = new JsonRpcRequest!string();
r10.method = "foo";
r10.id = "bar";
r10.toString().should == `{"method":"foo","id":"bar","jsonrpc":"2.0"}`;
}
/** A Json-Rpc response with an id of type TId.
*/
class JsonRpcResponse(TId): IRpcResponse
{
public:
///
string jsonrpc;
/// id
Nullable!TId id;
/// Optional result.
@optional Nullable!Json result;
/// Optional error.
@optional Nullable!JsonRpcError error;
///
this() @safe nothrow
{
result = Nullable!Json.init;
error = Nullable!JsonRpcError.init;
}
/// Tells if the response is an error.
bool isError() @safe nothrow
{
return !error.isNull;
}
/// Tells if the response is in success.
bool isSuccess() @safe nothrow
{
return !result.isNull;
}
/// Convert to Json.
Json toJson() const @safe
{
Json json = Json.emptyObject;
json["jsonrpc"] = "2.0";
// the id must be 'null' in case of parse error
if (!id.isNull)
json["id"] = id.get;
else
json["id"] = null;
if (!result.isNull)
json["result"] = result.get;
if (!error.isNull)
json["error"] = serializeToJson!(const(JsonRpcError))(error.get);
return json;
}
/// Parse from Json.
static JsonRpcResponse fromJson(Json src) @safe
{
JsonRpcResponse request = new JsonRpcResponse();
request.jsonrpc = src["jsonrpc"].to!string;
if (src["id"].type != Json.Type.undefined)
{
if (src["id"].type == Json.Type.null_)
request.id.nullify;
else
request.id = src["id"].to!TId;
}
if (src["result"].type != Json.Type.undefined)
request.result = src["result"].nullable;
if (src["error"].type != Json.Type.undefined)
request.error = deserializeJson!JsonRpcError(src["error"]).nullable;
return request;
}
/// Convert to Json string.
override string toString() const @safe
{
return toJson().toString();
}
/// Parse from Json string.
static JsonRpcResponse fromString(string src) @safe
{
return fromJson(parseJson(src));
}
}
///
@("Test JsonRpcResponse")
unittest
{
auto r1 = new JsonRpcResponse!int();
Json json = "hello";
r1.result = json;
r1.id = 42;
r1.toString().should == `{"result":"hello","id":42,"jsonrpc":"2.0"}`;
auto error = new JsonRpcError();
error.code = -32600;
error.message = "Invalid Request";
auto r2 = new JsonRpcResponse!int();
r2.error = error;
r2.id = 1;
r2.toString().should == `{"error":{"code":-32600,"message":"Invalid Request"},"id":1,"jsonrpc":"2.0"}`;
}
/// Encapsulate a json-rpc error response.
class JsonRpcMethodException: RpcException
{
import std.conv: to;
this(JsonRpcError error) @safe
{
if (error.data.type == Json.Type.object)
super(error.message ~ " (" ~ to!string(error.code) ~ "): " ~ error.data.toString());
else
super(error.message ~ " (" ~ to!string(error.code) ~ ")");
}
this(string msg) @safe
{
super(msg);
}
}
/// Exception to be used inside rpc handler, to throw user defined json-rpc error.
class JsonRpcUserException: RpcException
{
import vibe.data.json;
public:
int code;
Json data;
this(T)(int code, string msg, T data) @safe
{
super(msg);
this.code = code;
this.data = serializeToJson(data);
}
}
///
package class RawJsonRpcClient(TId,
TReq: JsonRpcRequest!TId=JsonRpcRequest!TId,
TResp: JsonRpcResponse!TId=JsonRpcResponse!TId) :
RawRpcClient!(TId, TReq, TResp)
{
import core.time : Duration;
import vibe.data.json;
import vibe.stream.operations: readAllUTF8;
import vibe.core.stream: InputStream, OutputStream;
private:
IIdGenerator!TId _idGenerator;
TResp[TId] _pendingResponse;
public:
this(OutputStream ostream, InputStream istream) @safe
{
super(ostream, istream);
_idGenerator = new IdGenerator!TId();
}
/** Send a request with an auto-generated id.
Throws:
JSONException
*/
TResp sendRequestAndWait(TReq request, Duration timeout = Duration.max()) @safe
{
request.id = _idGenerator.getNextId();
_ostream.write(request.toString());
return waitForResponse(request.id, timeout);
}
// Process the input stream once.
override void tick() @safe
{
string rawJson = _istream.readAllUTF8();
Json json = parseJson(rawJson);
void process(Json jsonObject)
{
auto response = deserializeJson!TResp(jsonObject);
_pendingResponse[response.id] = response;
}
// batch of commands
if (json.type == Json.Type.array)
{
foreach(object; json.byValue)
{
process(object);
}
}
else
{
process(json);
}
}
protected:
TResp waitForResponse(TId id, Duration timeout) @safe
{
import std.conv: to;
// check if response already received
if (id in _pendingResponse)
{
scope(exit) _pendingResponse.remove(id);
return _pendingResponse[id];
}
else
{
throw new RpcTimeoutException("No reponse");
}
}
}
/// Represents a Json rpc client.
alias IJsonRpcClient(TId, TReq: JsonRpcRequest!TId, TResp: JsonRpcResponse!TId) = IRpcClient!(TId, TReq, TResp);
/// An http json-rpc client
package alias HttpJsonRpcClient(TId,
TReq: JsonRpcRequest!TId=JsonRpcRequest!TId,
TResp: JsonRpcResponse!TId=JsonRpcResponse!TId) = HttpRpcClient!(TId, TReq, TResp);
///
package class TcpJsonRpcClient(TId,
TReq: JsonRpcRequest!TId=JsonRpcRequest!TId,
TResp: JsonRpcResponse!TId=JsonRpcResponse!TId): IJsonRpcClient!(TId, TReq, TResp)
{
import vibe.core.net : TCPConnection, TCPListener, connectTCP;
import vibe.stream.operations : readLine;
import core.time;
import std.conv: to;
private:
string _host;
ushort _port;
bool _connected;
IIdGenerator!TId _idGenerator;
JsonRpcResponse!TId[TId] _pendingResponse;
TCPConnection _conn;
RpcInterfaceSettings _settings;
public:
@property bool connected() { return _connected; }
this(string host, ushort port, RpcInterfaceSettings settings)
{
_host = host;
_port = port;
_settings = settings;
this.connect();
_idGenerator = new IdGenerator!TId();
}
bool connect() @safe nothrow
in {
assert(!_connected);
}
do {
try {
_conn = connectTCP(_host, _port);
_connected = true;
} catch (Exception e) {
_connected = false;
}
return _connected;
}
/// auto-generate id
TResp sendRequestAndWait(TReq request, core.time.Duration timeout = core.time.Duration.max()) @safe
{
if (!_connected)
throw new RpcNotConnectedException("tcp client not connected ! call connect() first.");
request.id = _idGenerator.getNextId();
logTrace("tcp send request: %s", request);
_conn.write(request.toString() ~ _settings.linesep);
if (_conn.waitForData(timeout)) {
char[] raw = cast(char[]) _conn.readLine(size_t.max, _settings.linesep);
string json = to!string(raw);
logTrace("tcp server request response: %s", json);
auto response = deserializeJson!TResp(json);
return response;
}
else
throw new RpcTimeoutException("waitForData timeout");
}
@disable void tick() @safe {}
}
/// Represents a Json rpc server.
alias IJsonRpcServer(TId,
TReq: JsonRpcRequest!TId=JsonRpcRequest!TId,
TResp: JsonRpcResponse!TId=JsonRpcResponse!TId) =
IRpcServer!(TId, TReq, TResp);
///
alias JsonRpcRequestHandler(TId, TReq=JsonRpcRequest!TId, TResp=JsonRpcResponse!TId) =
RpcRequestHandler!(TReq, TResp);
///
class RawJsonRpcServer(TId, TReq=JsonRpcRequest!TId, TResp=JsonRpcResponse!TId):
RawRpcServer!(TId, TReq, TResp),
IRpcServerOutput!TResp
{
import vibe.stream.operations: readAllUTF8;
import vibe.core.stream: InputStream, OutputStream;
alias RequestHandler = JsonRpcRequestHandler!(TId, TReq, TResp);
private:
RequestHandler[string] _requestHandler;
public:
this(OutputStream ostream, InputStream istream) @safe
{
super(ostream, istream);
}
void registerRequestHandler(string method, RequestHandler handler)
{
_requestHandler[method] = handler;
}
void sendResponse(TResp reponse) @safe
{
_ostream.write(reponse.toString());
}
void tick() @safe
{
string rawJson = _istream.readAllUTF8();
Json json = parseJson(rawJson);
void process(Json jsonObject)
{
auto request = deserializeJson!TReq(jsonObject);
if (request.method in _requestHandler)
{
_requestHandler[request.method](request, this);
}
}
// batch of commands
if (json.type == Json.Type.array)
{
foreach(object; json.byValue)
{
process(object);
}
}
else
{
process(json);
}
}
}
/// An http json-rpc client
class HttpJsonRpcServer(TId,
TReq: JsonRpcRequest!TId=JsonRpcRequest!TId,
TResp: JsonRpcResponse!TId=JsonRpcResponse!TId):
HttpRpcServer!(TId, TReq, TResp)
{
import vibe.data.json: JSONException;
import vibe.http.router: URLRouter;
this(URLRouter router, string path)
{
super(router, path);
}
override RpcRespHandler createReponseHandler(HTTPServerResponse res)
@safe nothrow {
return new class RpcRespHandler
{
override void sendResponse(TResp reponse) @safe nothrow
{
logTrace("post request response: %s", reponse);
try {
res.writeJsonBody(reponse.toJson());
} catch (Exception e) {
logCritical("unable to send response: %s", e.msg);
// TODO: add a delgate to allow the user to handle error
}
}
};
}
@disable void tick() @safe {}
protected override TResp buildResponseFromException(Exception e) @safe nothrow
{
auto response = new TResp();
if (is(typeof(e) == JSONException))
{
response.error = new JsonRpcError(JsonRpcError.StdCodes.parseError);
return response;
}
else
{
response.error = new JsonRpcError(JsonRpcError.StdCodes.internalError);
return response;
}
}
void registerInterface(I)(I instance, RpcInterfaceSettings settings = null)
{
import std.algorithm : filter, map, all;
import std.array : array;
import std.range : front;
import vibe.internal.meta.uda : findFirstUDA;
alias Info = InterfaceInfo!I;
foreach (i, Func; Info.Methods) {
enum methodNameAtt = findFirstUDA!(RpcMethodAttribute, Func);
enum smethod = Info.staticMethods[i];
auto handler = jsonRpcMethodHandler!(TId, TReq, TResp, Func, i, I)(instance);
// select rpc name (attribute or function name):
static if (methodNameAtt.found)
this.registerRequestHandler(methodNameAtt.value.method, handler);
else
this.registerRequestHandler(smethod.name, handler);
}
}
}
///
class TcpJsonRpcServer(TId,
TReq: JsonRpcRequest!TId=JsonRpcRequest!TId,
TResp: JsonRpcResponse!TId=JsonRpcResponse!TId): IJsonRpcServer!(TId, TReq, TResp)
{
import vibe.core.net : TCPConnection, TCPListener, listenTCP;
import vibe.stream.operations : readLine;
import std.conv : to;
private:
class ResponseWriter: JsonRpcRespHandler
{
private TCPConnection _conn;
this(TCPConnection conn)
{
_conn = conn;
}
void sendResponse(TResp reponse)
@safe {
logTrace("tcp request response: %s", reponse);
try {
_conn.write(reponse.toString() ~ _settings.linesep);
} catch (Exception e) {
logTrace("unable to send response: %s", e.msg);
// TODO: add a delgate to allow the user to handle error
}
}
}
class TCPClient
{
private:
TCPConnection _connection;
JsonRpcRequestHandler!(TId, TReq, TResp)[string] _requestHandler;
public /*properties*/:
@property auto conn() { return _connection; }
public:
this(TCPConnection connection)
{
_connection = connection;
}
void run() @safe nothrow
{
try {
auto writer = new ResponseWriter(_connection);
while (!_connection.empty) {
auto json = cast(const(char)[])_connection.readLine(size_t.max, _settings.linesep);
logTrace("tcp request received: %s", json);
this.process(json.to!string, writer);
}
} catch (Exception e) {
logError("Failed to read from client: %s", e.msg);
if (_settings !is null)
_settings.errorHandler(e);
}
}
void process(string data, JsonRpcRespHandler respHandler) @safe
{
Json json = parseJson(data);
void process(Json jsonObject)
{
auto request = deserializeJson!TReq(jsonObject);
if (request.method in _requestHandler)
{
_requestHandler[request.method](request, respHandler);
}
}
// batch of commands
if (json.type == Json.Type.array)
{
foreach(object; json.byValue)
{
process(object);
}
}
else
{
process(json);
}
}
void registerRequestHandler(string method, JsonRpcRequestHandler!(TId, TReq, TResp) handler) @safe nothrow
{
_requestHandler[method] = handler;
}
void registerInterface(I)(I instance) @safe nothrow
{
import std.algorithm : filter, map, all;
import std.array : array;
import std.range : front;
alias Info = InterfaceInfo!I;
foreach (i, Func; Info.Methods) {
enum smethod = Info.staticMethods[i];
// normal handler
auto handler = jsonRpcMethodHandler!(TId, TReq, TResp, Func, i)(instance);
this.registerRequestHandler(smethod.name, handler);
}
}
}
alias FactoryDel(I) = I delegate(TCPConnection);
alias NewClientDel = void delegate(TCPClient) @safe nothrow;
alias JsonRpcRespHandler = IRpcServerOutput!TResp;
JsonRpcRequestHandler!(TId, TReq, TResp)[string] _requestHandler;
RpcInterfaceSettings _settings;
NewClientDel[] _newClientDelegates;
public:
this(ushort port, RpcInterfaceSettings settings = new RpcInterfaceSettings())
{
_settings = settings;
listenTCP(port, (conn) @safe nothrow {
logTrace("new client: %s", conn);
auto client = new TCPClient(conn);
foreach(newClientDel; _newClientDelegates)
newClientDel(client);
client.run();
conn.close();
});
}
void registerInterface(I)(I instance)
{
_newClientDelegates ~= (client) @safe nothrow {
client.registerInterface!I(instance);
};
}
void registerInterface(I)(FactoryDel!I factory)
{
_newClientDelegates ~= (client) {
// instanciate an API for each client:
I instance = factory(client.conn);
client.registerInterface!I(instance);
};
}
@disable void tick() @safe {}
void registerRequestHandler(string method, JsonRpcRequestHandler!(TId, TReq, TResp) handler)
{
_requestHandler[method] = handler;
}
void process(string data, JsonRpcRespHandler respHandler)
{
Json json = parseJson(data);
void process(Json jsonObject)
{
auto request = deserializeJson!TReq(jsonObject);
if (request.method in _requestHandler)
{
_requestHandler[request.method](request, respHandler);
}
}
// batch of commands
if (json.type == Json.Type.array)
{
foreach(object; json.byValue)
{
process(object);
}
}
else
{
process(json);
}
}
}
/// Return an handler to match a json-rpc request on an interface method.
package JsonRpcRequestHandler!(TId, TReq, TResp) jsonRpcMethodHandler(TId, TReq, TResp, alias Func, size_t n, T)(T inst)
{
import std.traits;
import std.meta : AliasSeq;
import std.string : format;
import vibe.utils.string : sanitizeUTF8;
import vibe.internal.meta.funcattr : IsAttributedParameter, computeAttributedParameterCtx;
import vibe.internal.meta.traits : derivedMethod;
import vibe.internal.meta.uda : findFirstUDA;
enum Method = __traits(identifier, Func);
alias PTypes = ParameterTypeTuple!Func;
alias PDefaults = ParameterDefaultValueTuple!Func;
alias CFuncRaw = derivedMethod!(T, Func);
static if (AliasSeq!(CFuncRaw).length > 0) alias CFunc = CFuncRaw;
else alias CFunc = Func;
alias RT = ReturnType!(FunctionTypeOf!Func);
static const sroute = InterfaceInfo!T.staticMethods[n];
enum objectParamAtt = findFirstUDA!(RpcMethodObjectParams, Func);
void handler(TReq req, IRpcServerOutput!TResp serv) @safe
{
auto response = new TResp();
response.id = req.id;
PTypes params;
// build a custom json error object tobe sent in json rpc error response.
Json buildErrorData(string details)
@safe {
auto json = Json.emptyObject;
json["details"] = details;
json["request"] = req.toJson();
return json;
}
try {
// check params consistency beetween rpc-request and function parameters
static if (PTypes.length > 1 && !objectParamAtt.found)
{
// we expect a json array
if (req.params.type != Json.Type.array)
{
response.error = new JsonRpcError(JsonRpcError.StdCodes.invalidParams);
response.error.data = buildErrorData("Expected a json array for params");
serv.sendResponse(response);
return;
}
// req.params is a json array
else if (req.params.length != PTypes.length)
{
response.error = new JsonRpcError(JsonRpcError.StdCodes.invalidParams);
response.error.data = buildErrorData("Missing params");
serv.sendResponse(response);
return;
}
}
else if (PTypes.length > 1 && objectParamAtt.found)
{
// in object mode, check param count
if (req.params.type == Json.Type.object)
{
if (req.params.length != PTypes.length)
{
response.error = new JsonRpcError(JsonRpcError.StdCodes.invalidParams);
response.error.data = buildErrorData("Missing entry in params");
serv.sendResponse(response);
return;
}
}
}
foreach (i, PT; PTypes) {
enum sparam = sroute.parameters[i];
static if (!objectParamAtt.found)
{
enum pname = sparam.name;
auto fieldname = sparam.name;
params[i] = deserializeJson!PT(req.params[i]);
}
else
{
enum pname = sparam.name;
if (pname in objectParamAtt.value.names)
params[i] = deserializeJson!PT(req.params[objectParamAtt.value.names[pname]]);
else
params[i] = deserializeJson!PT(req.params[pname]);
}
}
} catch (Exception e) {
// handleException(e, HTTPStatus.badRequest);
return;
}
try {
import vibe.internal.meta.funcattr;
static if (!__traits(compiles, () @safe { __traits(getMember, inst, Method)(params); }))
pragma(msg, "Non-@safe methods are deprecated in REST interfaces - Mark "~T.stringof~"."~Method~" as @safe.");
static if (is(RT == void)) {
// TODO: return null
} else {
auto ret = () @trusted { return __traits(getMember, inst, Method)(params); } (); // TODO: remove after deprecation period
static if (!__traits(compiles, () @safe { evaluateOutputModifiers!Func(ret, req, res); } ()))
pragma(msg, "Non-@safe @after evaluators are deprecated - annotate @after evaluator function for "~T.stringof~"."~Method~" as @safe.");
static if (!__traits(compiles, () @safe { res.writeJsonBody(ret); }))
pragma(msg, "Non-@safe serialization of REST return types deprecated - ensure that "~RT.stringof~" is safely serializable.");
() @trusted {
// build reponse
response.id = req.id;
response.result = serializeToJson(ret);
serv.sendResponse(response);
}();
}
}
// catch user-defined json-rpc errors.
catch (JsonRpcUserException e)
{
response.error = new JsonRpcError();
response.error.code = e.code;
response.error.message = e.msg;
response.error.data = e.data;
serv.sendResponse(response);
return;
}
catch (Exception e) {
response.error = new JsonRpcError();
response.error.code = 0;
response.error.message = e.msg;
serv.sendResponse(response);
return;
}
}
return &handler;
}
/** Base class for creating a Json RPC automatic client.
*/
package class JsonRpcAutoClient(I,
TId,
TReq: JsonRpcRequest!TId=JsonRpcRequest!TId,
TResp: JsonRpcResponse!TId=JsonRpcResponse!TId)
{
import std.traits;
protected:
IRpcClient!(TId, TReq, TResp) _client;
RpcInterfaceSettings _settings;
ReturnType!Func executeMethod(alias Func, ARGS...)(ARGS args) @safe
{
import vibe.internal.meta.uda : findFirstUDA;
import std.traits;
import std.array : appender;
import core.time;
import vibe.data.json;
// retrieve some compile time informations
// alias Info = RpcInterface!I;
alias RT = ReturnType!Func;
alias PTT = ParameterTypeTuple!Func;
alias PTN = ParameterIdentifierTuple!Func;
enum objectParamAtt = findFirstUDA!(RpcMethodObjectParams, Func);
enum methodNameAtt = findFirstUDA!(RpcMethodAttribute, Func);
// parameters are rendered as array if annotated with @rpcArrayParams
enum bool paramsAsArray = hasRpcArrayParams!Func || (PTT.length > 1);
try
{
auto jsonParams = Json.undefined;
// Render params as unique param or array
static if (!objectParamAtt.found)
{
// if several params, then build an a json array
static if (paramsAsArray)
jsonParams = Json.emptyArray;
// fill the json array or the unique value
static foreach (i, PT; PTT) {
static if (paramsAsArray)
jsonParams.appendArrayElement(serializeToJson(args[i]));
else
jsonParams = serializeToJson(args[i]);
}
}
// render params as a json object by using the param name
// for the key or the uda if exists
else
{
jsonParams = Json.emptyObject;
// fill object
static foreach (i, PT; PTT) {
if (PTN[i] in objectParamAtt.value.names)
jsonParams[objectParamAtt.value.names[PTN[i]]] = serializeToJson(args[i]);
else
jsonParams[PTN[i]] = serializeToJson(args[i]);
}
}
static if (!is(RT == void))
RT jret;
// create a json-rpc request
auto request = new TReq();
static if (methodNameAtt.found)
request.method = methodNameAtt.value.method;
else
request.method = __traits(identifier, Func);
request.params = jsonParams; // set rpc call params
auto response = _client.sendRequestAndWait(request, _settings.responseTimeout); // send packet and wait
if (response.isError())
{
throw new JsonRpcMethodException(response.error);
}
// void return type
static if (is(RT == void))
{
}
else
{
return deserializeJson!RT(response.result);
}
}
catch (JSONException e)
{
throw new RpcParsingException(e.msg, e);
}
catch (Exception e)
{
throw new RpcException(e.msg, e);
}
}
public:
this(IRpcClient!(TId, TReq, TResp) client, RpcInterfaceSettings settings)
{
_client = client;
_settings = settings;
}
@property auto client() @safe { return _client; }
}
///
package class JsonRpcAutoAttributeClient(I) : I
{
import autointf;
private:
// compile-time
// Extract RPC id type from attribute:
static if (hasUDA!(I, RpcIdTypeAttribute!int))
alias TId = int;
else static if (hasUDA!(I, RpcIdTypeAttribute!string))
alias TId = string;
else
alias TId = int;
protected:
alias TReq = JsonRpcRequest!TId;
alias TResp = JsonRpcResponse!TId;
alias AutoClient(I) = JsonRpcAutoClient!(I, TId, TReq, TResp);
alias RpcClient = IRpcClient!(TId, TReq, TResp);
AutoClient!I _autoClient;
pragma(inline, true)
ReturnType!Func executeMethod(alias Func, ARGS...)(ARGS args) @safe
{
return _autoClient.executeMethod!(Func, ARGS)(args);
}
public:
this(RpcClient client, RpcInterfaceSettings settings) @safe
{
_autoClient = new AutoClient!I(client, settings);
}
pragma(inline, true)
@property auto client() @safe { return _autoClient.client; }
mixin(autoImplementMethods!(I, executeMethod)());
}
/** Used to create an auto-implemented raw Rpc client from an interface.
---
auto input = `{"jsonrpc":"2.0","id":2,"result":` ~ to!string(getValue!int) ~ "}";
auto istream = createMemoryStream(input.toBytes());
auto ostream = createMemoryOutputStream();
auto api = new RawJsonRpcAutoClient!IAPI(ostream, istream);
// test the client side:
// inputstream not processed: timeout
api.add(1, 2).shouldThrowExactly!RpcException;
ostream.str.should.be == JsonRpcRequest!int.make(1, "add", [1, 2]).toString();
// process input stream
api.client.tick();
// client must send a reponse
api.add(1, 2).should.be == getValue!int;
---
*/
class RawJsonRpcAutoClient(I) : JsonRpcAutoAttributeClient!I
{
import vibe.core.stream: InputStream, OutputStream;
public:
this(OutputStream ostream, InputStream istream, RpcInterfaceSettings settings = new RpcInterfaceSettings()) @safe
{
super(new RawJsonRpcClient!TId(ostream, istream), settings);
}
}
/** Used to create an auto-implemented Http Rpc client from an interface.
---
interface IAPI
{
void send(string data);
}
auto client = new HttpJsonRpcAutoClient!IAPI("http://127.0.0.1:8080/rpc_2");
client.send("data");
---
*/
class HttpJsonRpcAutoClient(I) : JsonRpcAutoAttributeClient!I
{
public:
this(string host, RpcInterfaceSettings settings = new RpcInterfaceSettings()) @safe
{
super(new HttpJsonRpcClient!TId(host), settings);
}
}
/** Used to create an auto-implemented Tcp Rpc client from an interface.
---
interface IAPI
{
void send(string data);
}
auto client = new TcpJsonRpcAutoClient!IAPI("http://127.0.0.1:8080/rpc_2");
client.send("data");
---
*/
class TcpJsonRpcAutoClient(I) : JsonRpcAutoAttributeClient!I
{
public:
this(string host, ushort port, RpcInterfaceSettings settings = new RpcInterfaceSettings()) @safe
{
super(new TcpJsonRpcClient!TId(host, port, settings), settings);
}
}
|
D
|
module webkit2webextension.DOMHTMLTableColElement;
private import glib.Str;
private import webkit2webextension.DOMHTMLElement;
private import webkit2webextension.c.functions;
public import webkit2webextension.c.types;
/** */
public class DOMHTMLTableColElement : DOMHTMLElement
{
/** the main Gtk struct */
protected WebKitDOMHTMLTableColElement* webKitDOMHTMLTableColElement;
/** Get the main Gtk struct */
public WebKitDOMHTMLTableColElement* getDOMHTMLTableColElementStruct(bool transferOwnership = false)
{
if (transferOwnership)
ownedRef = false;
return webKitDOMHTMLTableColElement;
}
/** the main Gtk struct as a void* */
protected override void* getStruct()
{
return cast(void*)webKitDOMHTMLTableColElement;
}
/**
* Sets our main struct and passes it to the parent class.
*/
public this (WebKitDOMHTMLTableColElement* webKitDOMHTMLTableColElement, bool ownedRef = false)
{
this.webKitDOMHTMLTableColElement = webKitDOMHTMLTableColElement;
super(cast(WebKitDOMHTMLElement*)webKitDOMHTMLTableColElement, ownedRef);
}
/** */
public static GType getType()
{
return webkit_dom_html_table_col_element_get_type();
}
/**
*
*
* Deprecated: Use JavaScriptCore API instead
*
* Returns: A #gchar
*/
public string getAlign()
{
auto retStr = webkit_dom_html_table_col_element_get_align(webKitDOMHTMLTableColElement);
scope(exit) Str.freeString(retStr);
return Str.toString(retStr);
}
/**
*
*
* Deprecated: Use JavaScriptCore API instead
*
* Returns: A #gchar
*/
public string getCh()
{
auto retStr = webkit_dom_html_table_col_element_get_ch(webKitDOMHTMLTableColElement);
scope(exit) Str.freeString(retStr);
return Str.toString(retStr);
}
/**
*
*
* Deprecated: Use JavaScriptCore API instead
*
* Returns: A #gchar
*/
public string getChOff()
{
auto retStr = webkit_dom_html_table_col_element_get_ch_off(webKitDOMHTMLTableColElement);
scope(exit) Str.freeString(retStr);
return Str.toString(retStr);
}
/**
*
*
* Deprecated: Use JavaScriptCore API instead
*
* Returns: A #glong
*/
public glong getSpan()
{
return webkit_dom_html_table_col_element_get_span(webKitDOMHTMLTableColElement);
}
/**
*
*
* Deprecated: Use JavaScriptCore API instead
*
* Returns: A #gchar
*/
public string getVAlign()
{
auto retStr = webkit_dom_html_table_col_element_get_v_align(webKitDOMHTMLTableColElement);
scope(exit) Str.freeString(retStr);
return Str.toString(retStr);
}
/**
*
*
* Deprecated: Use JavaScriptCore API instead
*
* Returns: A #gchar
*/
public string getWidth()
{
auto retStr = webkit_dom_html_table_col_element_get_width(webKitDOMHTMLTableColElement);
scope(exit) Str.freeString(retStr);
return Str.toString(retStr);
}
/**
*
*
* Deprecated: Use JavaScriptCore API instead
*
* Params:
* value = A #gchar
*/
public void setAlign(string value)
{
webkit_dom_html_table_col_element_set_align(webKitDOMHTMLTableColElement, Str.toStringz(value));
}
/**
*
*
* Deprecated: Use JavaScriptCore API instead
*
* Params:
* value = A #gchar
*/
public void setCh(string value)
{
webkit_dom_html_table_col_element_set_ch(webKitDOMHTMLTableColElement, Str.toStringz(value));
}
/**
*
*
* Deprecated: Use JavaScriptCore API instead
*
* Params:
* value = A #gchar
*/
public void setChOff(string value)
{
webkit_dom_html_table_col_element_set_ch_off(webKitDOMHTMLTableColElement, Str.toStringz(value));
}
/**
*
*
* Deprecated: Use JavaScriptCore API instead
*
* Params:
* value = A #glong
*/
public void setSpan(glong value)
{
webkit_dom_html_table_col_element_set_span(webKitDOMHTMLTableColElement, value);
}
/**
*
*
* Deprecated: Use JavaScriptCore API instead
*
* Params:
* value = A #gchar
*/
public void setVAlign(string value)
{
webkit_dom_html_table_col_element_set_v_align(webKitDOMHTMLTableColElement, Str.toStringz(value));
}
/**
*
*
* Deprecated: Use JavaScriptCore API instead
*
* Params:
* value = A #gchar
*/
public void setWidth(string value)
{
webkit_dom_html_table_col_element_set_width(webKitDOMHTMLTableColElement, Str.toStringz(value));
}
}
|
D
|
; Copyright (C) 2008 The Android Open Source Project
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
.source T_div_int_2.java
.class public dot.junit.opcodes.div_int.d.T_div_int_2
.super java/lang/Object
.method public <init>()V
.limit regs 1
invoke-direct {v0}, java/lang/Object/<init>()V
return-void
.end method
.method public run(II)I
.limit regs 4
const-wide v1, 3.1415
div-int v0, v3, v1
return v0
.end method
|
D
|
/*
* hunt-proton: AMQP Protocol library for D programming language.
*
* Copyright (C) 2018-2019 HuntLabs
*
* Website: https://www.huntlabs.net/
*
* Licensed under the Apache-2.0 License.
*
*/
module hunt.proton.amqp.UnsignedLong;
import hunt.math;
import hunt.Number;
import std.algorithm.comparison;
import std.conv : to;
import hunt.logging;
import std.concurrency : initOnce;
class UnsignedLong : Number
{
static UnsignedLong[] cachedValues ;
static BigInteger TWO_TO_THE_SIXTY_FOUR;
static BigInteger LONG_MAX_VALUE;
static UnsignedLong ZERO;
static UnsignedLong[] initCachedValues()
{
UnsignedLong[] cachedVal = new UnsignedLong[256];
for(int i = 0; i<256; i++)
{
cachedValues[i] = new UnsignedLong(i);
}
return cachedVal;
}
//static UnsignedLong[] cachedValues() {
// __gshared UnsignedLong[] inst;
// return initOnce!inst(initCachedValues);
//}
static this()
{
cachedValues = new UnsignedLong[256];
for(int i = 0; i<256; i++)
{
cachedValues[i] = new UnsignedLong(i);
}
UnsignedLong.TWO_TO_THE_SIXTY_FOUR = new BigInteger([1,0,0,0,0,0,0,0,0]);
UnsignedLong.LONG_MAX_VALUE = BigInteger.valueOf(0x7FFFFFFFFFFFFFFF);
UnsignedLong.ZERO = cachedValues[0];
}
private long _underlying;
this(long underlying)
{
_underlying = underlying;
}
override
public int intValue()
{
return cast(int) _underlying;
}
override
public long longValue()
{
return _underlying;
}
public BigInteger bigIntegerValue()
{
if(_underlying >= 0L)
{
return BigInteger.valueOf(_underlying);
}
else
{
return TWO_TO_THE_SIXTY_FOUR.add(BigInteger.valueOf(_underlying));
}
}
override
public float floatValue()
{
return cast(float) (longValue());
}
override
public double doubleValue()
{
return cast(double) (longValue());
}
override bool opEquals(Object o)
{
if (this is o)
{
return true;
}
if (o is null || (cast(UnsignedLong)o is null))
{
return false;
}
UnsignedLong that = cast(UnsignedLong)o;
if (_underlying != that._underlying)
{
return false;
}
return true;
}
override int opCmp(Object o)
{
UnsignedLong that = cast(UnsignedLong)(o);
return cast(int)(longValue() - that.longValue());
}
//override size_t toHash() @trusted nothrow {
// size_t hashcode = 0;
// hashcode = price * 20;
// hashcode += hashOf(item);
// return hashcode;
//}
override
public size_t toHash() @trusted nothrow
{
return cast(size_t)(_underlying ^ (_underlying >>> 32));
}
//
//public string toString()
//{
// return String.valueOf(bigIntegerValue());
//}
public static UnsignedLong valueOf(long underlying)
{
if((underlying & 0xFFL) == underlying)
{
return cachedValues[cast(int)(underlying)];
}
else
{
return new UnsignedLong(underlying);
}
}
public static UnsignedLong valueOf(string value)
{
BigInteger bigInt = new BigInteger(value);
return valueOf(bigInt);
}
public static UnsignedLong valueOf(BigInteger bigInt)
{
if(bigInt.signum() == -1 || bigInt.bitLength() > 64)
{
// throw new NumberFormatException("Value \""+bigInt+"\" lies outside the range [0 - 2^64).");
logError("Value lies outside the range [0 - 2^64).");
return null;
}
else if(bigInt.compareTo(LONG_MAX_VALUE)>=0)
{
return UnsignedLong.valueOf(bigInt.longValue());
}
else
{
return UnsignedLong.valueOf(TWO_TO_THE_SIXTY_FOUR.subtract(bigInt).negate().longValue());
}
}
override
byte byteValue()
{
return 1;
}
override short shortValue()
{
return 1;
}
override string toString()
{
return "";
}
}
|
D
|
// SemiTwist D Tools
// Run Unittests
// Written in the D programming language.
/++
Author:
$(WEB www.semitwist.com, Nick Sabalausky)
This runs the SemiTwist D Tools unit tests.
This has been tested to work with DMD 2.058 through 2.062
+/
module semitwist.apps.tests.unittests.main;
import semitwist.cmd.all;
version(unittest) {} else import std.stdio;
void main()
{
flushAsserts();
version(unittest) {}
else
{
writeln("This is the release build of the SemiTwistDTools unittests.");
writeln("Naturally, it doesn't do anything.");
writeln();
writeln("Run 'semitwist-unittests-debug' instead.");
}
}
|
D
|
instance PAL_255_Ritter (Npc_Default)
{
// ------ NSC ------
name = NAME_RITTER;
guild = GIL_PAL;
id = 255;
voice = 9;
flags = 0; //NPC_FLAG_IMMORTAL oder 0
npctype = NPCTYPE_OCAMBIENT;
// ------ Attribute ------
B_SetAttributesToChapter (self, 4); //setzt Attribute und LEVEL entsprechend dem angegebenen Kapitel (1-6)
// ------ Kampf-Taktik ------
fight_tactic = FAI_HUMAN_STRONG; // MASTER / STRONG / COWARD
// ------ Equippte Waffen ------ //Munition wird automatisch generiert, darf aber angegeben werden
EquipItem (self, ItMw_1h_Pal_Sword);
EquipItem (self, ItRw_Mil_Crossbow);
// ------ Inventory ------
B_CreateAmbientInv (self);
// ------ visuals ------ //Muss NACH Attributen kommen, weil in B_SetNpcVisual die Breite abh. v. STR skaliert wird
B_SetNpcVisual (self, MALE, "Hum_Head_Bald", Face_P_Normal_Fletcher, BodyTex_P, ITAR_PAL_M);
Mdl_SetModelFatness (self, 0);
Mdl_ApplyOverlayMds (self, "Humans_Militia.mds"); // Tired / Militia / Mage / Arrogance / Relaxed
// ------ NSC-relevante Talente vergeben ------
B_GiveNpcTalents (self);
// ------ Kampf-Talente ------ //Der enthaltene B_AddFightSkill setzt Talent-Ani abhängig von TrefferChance% - alle Kampftalente werden gleichhoch gesetzt
B_SetFightSkills (self, 65); //Grenzen für Talent-Level liegen bei 30 und 60
// ------ TA anmelden ------
daily_routine = Rtn_Start_255;
};
FUNC VOID Rtn_Start_255 ()
{
TA_Practice_Sword (08,00,19,00,"OC_TRAIN_01");
TA_Sit_Campfire (19,00,08,00,"OC_CAMPFIRE_OUT_01");
};
|
D
|
/home/serlog/Escritorio/Raúl/Semestre-2020-II/Paralelos/parallel_computing/lab1/target/rls/debug/deps/standback-369edbc6b9d1a216.rmeta: /home/serlog/.cargo/registry/src/github.com-1ecc6299db9ec823/standback-0.2.10/src/lib.rs /home/serlog/.cargo/registry/src/github.com-1ecc6299db9ec823/standback-0.2.10/src/v1_46.rs
/home/serlog/Escritorio/Raúl/Semestre-2020-II/Paralelos/parallel_computing/lab1/target/rls/debug/deps/libstandback-369edbc6b9d1a216.rlib: /home/serlog/.cargo/registry/src/github.com-1ecc6299db9ec823/standback-0.2.10/src/lib.rs /home/serlog/.cargo/registry/src/github.com-1ecc6299db9ec823/standback-0.2.10/src/v1_46.rs
/home/serlog/Escritorio/Raúl/Semestre-2020-II/Paralelos/parallel_computing/lab1/target/rls/debug/deps/standback-369edbc6b9d1a216.d: /home/serlog/.cargo/registry/src/github.com-1ecc6299db9ec823/standback-0.2.10/src/lib.rs /home/serlog/.cargo/registry/src/github.com-1ecc6299db9ec823/standback-0.2.10/src/v1_46.rs
/home/serlog/.cargo/registry/src/github.com-1ecc6299db9ec823/standback-0.2.10/src/lib.rs:
/home/serlog/.cargo/registry/src/github.com-1ecc6299db9ec823/standback-0.2.10/src/v1_46.rs:
|
D
|
/**
* Compiler implementation of the
* $(LINK2 http://www.dlang.org, D programming language).
*
* Copyright: Copyright (C) 1999-2019 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 http://www.digitalmars.com, Walter Bright)
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/staticassert.d, _staticassert.d)
* Documentation: https://dlang.org/phobos/dmd_staticassert.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/staticassert.d
*/
module dmd.staticassert;
import dmd.dscope;
import dmd.dsymbol;
import dmd.expression;
import dmd.globals;
import dmd.id;
import dmd.identifier;
import dmd.mtype;
import dmd.visitor;
/***********************************************************
*/
extern (C++) final class StaticAssert : Dsymbol
{
Expression exp;
Expression msg;
extern (D) this(const ref Loc loc, Expression exp, Expression msg)
{
super(Id.empty);
this.loc = loc;
this.exp = exp;
this.msg = msg;
}
override Dsymbol syntaxCopy(Dsymbol s)
{
assert(!s);
return new StaticAssert(loc, exp.syntaxCopy(), msg ? msg.syntaxCopy() : null);
}
override void addMember(Scope* sc, ScopeDsymbol sds)
{
// we didn't add anything
}
override bool oneMember(Dsymbol* ps, Identifier ident)
{
//printf("StaticAssert::oneMember())\n");
*ps = null;
return true;
}
override const(char)* kind() const
{
return "static assert";
}
override void accept(Visitor v)
{
v.visit(this);
}
}
|
D
|
module SecureEngineCustomVMs;
// ******************************************************************************
// Header: SecureEngineCustomVMs64.d
// Description: D macros definitions
//
// Author/s: Oreans Technologies
// (c) 2015 Oreans Technologies
//
// --- File generated automatically from Oreans VM Generator (16/6/2015) ---
// ******************************************************************************
// ******************************************************************************
// Macros definition
// ******************************************************************************
version (D_InlineAsm_X64)
{
const VM_TIGER_WHITE_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x67, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_TIGER_WHITE_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0xF7, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_TIGER_RED_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x68, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_TIGER_RED_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0xF8, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_TIGER_BLACK_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x69, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_TIGER_BLACK_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0xF9, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_FISH_WHITE_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x6B, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_FISH_WHITE_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0xFB, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_FISH_RED_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x6D, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_FISH_RED_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0xFD, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_FISH_BLACK_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x6F, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_FISH_BLACK_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0xFF, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_PUMA_WHITE_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x71, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_PUMA_WHITE_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x01, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_PUMA_RED_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x73, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_PUMA_RED_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x03, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_PUMA_BLACK_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x75, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_PUMA_BLACK_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x05, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_SHARK_WHITE_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x77, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_SHARK_WHITE_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x07, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_SHARK_RED_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x79, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_SHARK_RED_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x09, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_SHARK_BLACK_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x7B, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_SHARK_BLACK_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x0B, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_DOLPHIN_WHITE_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x87, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_DOLPHIN_WHITE_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x17, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_DOLPHIN_RED_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x89, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_DOLPHIN_RED_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x19, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_DOLPHIN_BLACK_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x8B, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_DOLPHIN_BLACK_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x1B, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_EAGLE_WHITE_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x93, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_EAGLE_WHITE_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x23, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_EAGLE_RED_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x95, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_EAGLE_RED_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x25, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_EAGLE_BLACK_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x97, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_EAGLE_BLACK_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x27, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_MUTATE_ONLY_START = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x10, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
const VM_MUTATE_ONLY_END = "asm { db 0xEB, 0x10, 0x57, 0x4C, 0x20, 0x20, 0x11, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x57, 0x4C, 0x20, 0x20;}";
}
|
D
|
/Users/yajnavalkya/Developer/Rationalize/build/Rationalize.build/Debug-iphonesimulator/Rationalize.build/Objects-normal/x86_64/SnappingSlider.o : /Users/yajnavalkya/Developer/Rationalize/Rationalize/AppDelegate.swift /Users/yajnavalkya/Developer/Rationalize/Rationalize/SnappingSlider.swift /Users/yajnavalkya/Developer/Rationalize/Rationalize/DashboardViewController.swift /Users/yajnavalkya/Developer/Rationalize/Rationalize/HouseholdTableViewController.swift /Users/yajnavalkya/Developer/Rationalize/Rationalize/ShoppingListTableViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/yajnavalkya/Developer/Rationalize/build/Rationalize.build/Debug-iphonesimulator/Rationalize.build/Objects-normal/x86_64/SnappingSlider~partial.swiftmodule : /Users/yajnavalkya/Developer/Rationalize/Rationalize/AppDelegate.swift /Users/yajnavalkya/Developer/Rationalize/Rationalize/SnappingSlider.swift /Users/yajnavalkya/Developer/Rationalize/Rationalize/DashboardViewController.swift /Users/yajnavalkya/Developer/Rationalize/Rationalize/HouseholdTableViewController.swift /Users/yajnavalkya/Developer/Rationalize/Rationalize/ShoppingListTableViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/yajnavalkya/Developer/Rationalize/build/Rationalize.build/Debug-iphonesimulator/Rationalize.build/Objects-normal/x86_64/SnappingSlider~partial.swiftdoc : /Users/yajnavalkya/Developer/Rationalize/Rationalize/AppDelegate.swift /Users/yajnavalkya/Developer/Rationalize/Rationalize/SnappingSlider.swift /Users/yajnavalkya/Developer/Rationalize/Rationalize/DashboardViewController.swift /Users/yajnavalkya/Developer/Rationalize/Rationalize/HouseholdTableViewController.swift /Users/yajnavalkya/Developer/Rationalize/Rationalize/ShoppingListTableViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
|
D
|
module prova.graphics.spritebatch;
import prova.assets;
import prova.attachables;
import prova.graphics;
import prova.math;
import prova.util;
import std.typecons;
///
final class SpriteBatch
{
/// Copy of GraphicsContext.spriteShader
ShaderProgram shaderProgram;
private bool begun;
private Mesh mesh;
private GraphicsContext context;
private RenderTarget renderTarget;
private Matrix projection;
private LinkedList!(Tuple!(Sprite, Matrix)) sprites;
///
this(GraphicsContext context)
{
shaderProgram = context.spriteShader;
sprites = new LinkedList!(Tuple!(Sprite, Matrix));
mesh = new SpriteMesh();
}
///
void begin(RenderTarget renderTarget, Matrix projection)
{
assert(!begun, "Batch should not already be started");
this.renderTarget = renderTarget;
this.projection = projection;
begun = true;
}
///
void batchSprite(AnimatedSprite sprite, Matrix transform)
{
sprite.update();
batchSprite(cast(Sprite) sprite, transform);
}
///
void batchSprite(Sprite sprite, Matrix transform)
{
assert(begun, "Batch should have started with begin(RenderTarget, Matrix projection)");
sprites.insertBack(tuple(sprite, transform));
}
/// Draws batched sprites
void end()
{
assert(begun, "Batch should have started with begin(RenderTarget, Matrix projection)");
Color lastTint;
uint lastTexture = -1;
// set the inital value for the tint
shaderProgram.setVector4("tint", lastTint);
foreach(Tuple!(Sprite, Matrix) spriteTuple; sprites) {
Sprite sprite = spriteTuple[0];
Matrix transform = spriteTuple[1];
if(sprite.texture.id != lastTexture) {
shaderProgram.setTexture(0, sprite.texture);
lastTexture = sprite.texture.id;
}
if(sprite.tint != lastTint) {
shaderProgram.setVector4("tint", sprite.tint);
lastTint = sprite.tint;
}
drawSprite(sprite, transform);
}
sprites.clear();
begun = false;
}
///
void drawSprite(Sprite sprite, Matrix transform)
{
Vector2 size = sprite.clip.getSize();
Vector3 center = size / 2;
Rect clip;
clip.left = sprite.clip.left / sprite.texture.width;
clip.top = 1 - (sprite.clip.top + sprite.clip.height) / sprite.texture.height;
clip.width = sprite.clip.width / sprite.texture.width;
clip.height = sprite.clip.height / sprite.texture.height;
Matrix offset = Matrix.identity;
offset = offset.scale(size);
offset = offset.translate(-sprite.origin - center);
shaderProgram.setMatrix("transform", projection * (transform * offset));
shaderProgram.setVector4("clip", clip);
shaderProgram.drawMesh(mesh, renderTarget, DrawMode.TRIANGLE_FAN);
}
}
|
D
|
/**
* @file pxidev.h
* @brief Gamecard PXI service.
*/
module ctru.services.pxidev;
import ctru.types;
import ctru.services.fs;
extern (C): nothrow: @nogc:
/// Card SPI wait operation type.
enum PXIDEVWaitType : ubyte
{
none = 0, ///< Do not wait.
sleep = 1, ///< Sleep for the specified number of nanoseconds.
ireq_return = 2, ///< Wait for IREQ, return if timeout.
ireq_continue = 3 ///< Wait for IREQ, continue if timeout.
}
/// Card SPI register deassertion type.
enum PXIDEVDeassertType : ubyte
{
none = 0, ///< Do not deassert.
before_wait = 1, ///< Deassert before waiting.
after_wait = 2 ///< Deassert after waiting.
}
/// Card SPI transfer buffer.
struct PXIDEV_SPIBuffer
{
void* ptr; ///< Data pointer.
uint size; ///< Data size.
ubyte transferOption; ///< Transfer options. See @ref pxiDevMakeTransferOption
ulong waitOperation; ///< Wait operation. See @ref pxiDevMakeWaitOperation
}
/// Initializes pxi:dev.
Result pxiDevInit();
/// Shuts down pxi:dev.
void pxiDevExit();
/**
* @brief Creates a packed card SPI transfer option value.
* @param baudRate Baud rate to use when transferring.
* @param busMode Bus mode to use when transferring.
* @return A packed card SPI transfer option value.
*/
pragma(inline, true)
ubyte pxiDevMakeTransferOption(
FSCardSPIBaudRate baudRate,
FSCardSPIBusMode busMode)
{
return (baudRate & 0x3F) | ((busMode & 0x3) << 6);
}
/**
* @brief Creates a packed card SPI wait operation value.
* @param waitTypnbe Type of wait to perform.
* @param deassertType Type of register deassertion to perform.
* @param timeout Timeout, in nanoseconds, to wait, if applicable.
* @return A packed card SPI wait operation value.
*/
pragma(inline, true)
ulong pxiDevMakeWaitOperation(
PXIDEVWaitType waitType,
PXIDEVDeassertType deassertType,
ulong timeout)
{
return (waitType & 0xF) | ((deassertType & 0xF) << 4) | ((timeout & 0xFFFFFFFFFFFFFF) << 8);
}
/**
* @brief Performs multiple card SPI writes and reads.
* @param header Header to lead the transfers with. Must be, at most, 8 bytes in size.
* @param writeBuffer1 Buffer to make first transfer from.
* @param readBuffer1 Buffer to receive first response to.
* @param writeBuffer2 Buffer to make second transfer from.
* @param readBuffer2 Buffer to receive second response to.
* @param footer Footer to follow the transfers with. Must be, at most, 8 bytes in size. Wait operation is unused.
*/
Result PXIDEV_SPIMultiWriteRead(PXIDEV_SPIBuffer* header, PXIDEV_SPIBuffer* writeBuffer1, PXIDEV_SPIBuffer* readBuffer1, PXIDEV_SPIBuffer* writeBuffer2, PXIDEV_SPIBuffer* readBuffer2, PXIDEV_SPIBuffer* footer);
/**
* @brief Performs a single card SPI write and read.
* @param bytesRead Pointer to output the number of bytes received to.
* @param initialWaitOperation Wait operation to perform before transferring data.
* @param writeBuffer Buffer to transfer data from.
* @param readBuffer Buffer to receive data to.
*/
Result PXIDEV_SPIWriteRead(uint* bytesRead, ulong initialWaitOperation, PXIDEV_SPIBuffer* writeBuffer, PXIDEV_SPIBuffer* readBuffer);
|
D
|
a female tiger
|
D
|
module android.java.android.media.AudioManager_AudioPlaybackCallback;
public import android.java.android.media.AudioManager_AudioPlaybackCallback_d_interface;
import arsd.jni : ImportExportImpl;
mixin ImportExportImpl!AudioManager_AudioPlaybackCallback;
import import1 = android.java.java.lang.Class;
|
D
|
/**
* Copyright:
* (C) 2016 Martin Brzenska
*
* License:
* Distributed under the terms of the MIT license.
* Consult the provided LICENSE.md file for details
*/
module libdominator;
public import libdominator.Attribute;
public import libdominator.Dominator;
public import libdominator.Node;
public import libdominator.Filter;
public import libdominator.Output;
|
D
|
uncastrated adult male horse
constituting the full quantity or extent
constituting the undiminished entirety
(of leaves or petals) having a smooth edge
(used of domestic animals) sexually competent
|
D
|
/**
* This is a low-level messaging API upon which more structured or restrictive
* APIs may be built. The general idea is that every messageable entity is
* represented by a common handle type (called a Cid in this implementation),
* which allows messages to be sent to in-process threads, on-host processes,
* and foreign-host processes using the same interface. This is an important
* aspect of scalability because it allows the components of a program to be
* spread across available resources with few to no changes to the actual
* implementation.
*
* Right now, only in-process threads are supported and referenced by a more
* specialized handle called a Tid. It is effectively a subclass of Cid, with
* additional features specific to in-process messaging.
*
* Synposis:
* ---
* import std.stdio;
* import std.concurrency;
*
* void spawnedFunc(Tid tid)
* {
* // Receive a message from the owner thread.
* receive(
* (int i) { writeln("Received the number ", i);}
* );
*
* // Send a message back to the owner thread
* // indicating success.
* send(tid, true);
* }
*
* void main()
* {
* // Start spawnedFunc in a new thread.
* auto tid = spawn(&spawnedFunc, thisTid);
*
* // Send the number 42 to this new thread.
* send(tid, 42);
*
* // Receive the result code.
* auto wasSuccessful = receiveOnly!(bool);
* assert(wasSuccessful);
* writeln("Successfully printed number.");
* }
* ---
*
* Copyright: Copyright Sean Kelly 2009 - 2010.
* License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
* Authors: Sean Kelly
* Source: $(PHOBOSSRC std/_concurrency.d)
*/
/* Copyright Sean Kelly 2009 - 2010.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
module std.concurrency;
public
{
import core.atomic;
import core.sync.barrier;
import core.sync.condition;
import core.sync.mutex;
import core.sync.rwmutex;
import core.sync.semaphore;
import std.variant;
}
private
{
import core.thread;
import std.algorithm;
import std.exception;
import std.range;
import std.range;
import std.traits;
import std.typecons;
import std.typetuple;
template hasLocalAliasing(T...)
{
static if( !T.length )
enum hasLocalAliasing = false;
else
enum hasLocalAliasing = (std.traits.hasLocalAliasing!(T[0]) && !is(T[0] == Tid)) ||
std.concurrency.hasLocalAliasing!(T[1 .. $]);
}
enum MsgType
{
standard,
priority,
linkDead,
}
struct Message
{
MsgType type;
Variant data;
this(T...)( MsgType t, T vals )
if( T.length < 1 )
{
static assert( false, "messages must contain at least one item" );
}
this(T...)( MsgType t, T vals )
if( T.length == 1 )
{
type = t;
data = vals[0];
}
this(T...)( MsgType t, T vals )
if( T.length > 1 )
{
type = t;
data = Tuple!(T)( vals );
}
@property auto convertsTo(T...)()
{
static if( T.length == 1 )
return is( T[0] == Variant ) ||
data.convertsTo!(T);
else
return data.convertsTo!(Tuple!(T));
}
@property auto get(T...)()
{
static if( T.length == 1 )
{
static if( is( T[0] == Variant ) )
return data;
else
return data.get!(T);
}
else
{
return data.get!(Tuple!(T));
}
}
auto map(Op)( Op op )
{
alias ParameterTypeTuple!(Op) Args;
static if( Args.length == 1 )
{
static if( is( Args[0] == Variant ) )
return op( data );
else
return op( data.get!(Args) );
}
else
{
return op( data.get!(Tuple!(Args)).expand );
}
}
}
void checkops(T...)( T ops )
{
foreach( i, t1; T )
{
static assert( isFunctionPointer!t1 || isDelegate!t1 );
alias ParameterTypeTuple!(t1) a1;
alias ReturnType!(t1) r1;
static if( i < T.length - 1 && is( r1 == void ) )
{
static assert( a1.length != 1 || !is( a1[0] == Variant ),
"function with arguments " ~ a1.stringof ~
" occludes successive function" );
foreach( t2; T[i+1 .. $] )
{
static assert( isFunctionPointer!t2 || isDelegate!t2 );
alias ParameterTypeTuple!(t2) a2;
static assert( !is( a1 == a2 ),
"function with arguments " ~ a1.stringof ~
" occludes successive function" );
}
}
}
}
MessageBox mbox;
bool[Tid] links;
Tid owner;
}
shared static this()
{
// NOTE: Normally, mbox is initialized by spawn() or thisTid(). This
// doesn't support the simple case of calling only receive() in main
// however. To ensure that this works, initialize the main thread's
// mbox field here (as shared static ctors are run once on startup
// by the main thread).
mbox = new MessageBox;
}
static ~this()
{
if( mbox !is null )
{
mbox.close();
auto me = thisTid;
foreach( tid; links.keys )
_send( MsgType.linkDead, tid, me );
if( owner != Tid.init )
_send( MsgType.linkDead, owner, me );
}
}
//////////////////////////////////////////////////////////////////////////////
// Exceptions
//////////////////////////////////////////////////////////////////////////////
/**
* Thrown on calls to $(D receiveOnly) if a message other than the type
* the receiving thread expected is sent.
*/
class MessageMismatch : Exception
{
this( string msg = "Unexpected message type" )
{
super( msg );
}
}
/**
* Thrown on calls to $(D receive) if the thread that spawned the receiving
* thread has terminated and no more messages exist.
*/
class OwnerTerminated : Exception
{
this( Tid t, string msg = "Owner terminated" )
{
super( msg );
tid = t;
}
Tid tid;
}
/**
* Thrown if a linked thread has terminated.
*/
class LinkTerminated : Exception
{
this( Tid t, string msg = "Link terminated" )
{
super( msg );
tid = t;
}
Tid tid;
}
/**
* Thrown if a message was sent to a thread via
* $(XREF concurrency, prioritySend) and the receiver does not have a handler
* for a message of this type.
*/
class PriorityMessageException : Exception
{
this( Variant vals )
{
super( "Priority message" );
message = vals;
}
/**
* The message that was sent.
*/
Variant message;
}
/**
* Thrown on mailbox crowding if the mailbox is configured with
* $(D OnCrowding.throwException).
*/
class MailboxFull : Exception
{
this( Tid t, string msg = "Mailbox full" )
{
super( msg );
tid = t;
}
Tid tid;
}
//////////////////////////////////////////////////////////////////////////////
// Thread ID
//////////////////////////////////////////////////////////////////////////////
/**
* An opaque type used to represent a logical local process.
*/
struct Tid
{
void send(T...)( T vals )
{
static assert( !hasLocalAliasing!(T),
"Aliases to mutable thread-local data not allowed." );
_send( this, vals );
}
private:
this( MessageBox m )
{
mbox = m;
}
MessageBox mbox;
}
/**
* Returns the caller's Tid.
*/
@property Tid thisTid()
{
if( mbox )
return Tid( mbox );
mbox = new MessageBox;
return Tid( mbox );
}
//////////////////////////////////////////////////////////////////////////////
// Thread Creation
//////////////////////////////////////////////////////////////////////////////
/**
* Executes the supplied function in a new context represented by $(D Tid). The
* calling context is designated as the owner of the new context. When the
* owner context terminated an $(D OwnerTerminated) message will be sent to the
* new context, causing an $(D OwnerTerminated) exception to be thrown on
* $(D receive()).
*
* Params:
* fn = The function to execute.
* args = Arguments to the function.
*
* Returns:
* A Tid representing the new context.
*
* Notes:
* $(D args) must not have unshared aliasing. In other words, all arguments
* to $(D fn) must either be $(D shared) or $(D immutable) or have no
* pointer indirection. This is necessary for enforcing isolation among
* threads.
*
* Example:
* ---
* import std.stdio;
*
* void f1(string str)
* {
* writeln(str);
* }
*
* void f2(char[] str)
* {
* writeln(str);
* }
*
* void main()
* {
* auto str = "Hello, world";
*
* // Works: string is immutable.
* auto tid1 = spawn(&f1, str);
*
* // Fails: char[] has mutable aliasing.
* auto tid2 = spawn(&f2, str.dup);
* }
* ---
*/
Tid spawn(T...)( void function(T) fn, T args )
{
static assert( !hasLocalAliasing!(T),
"Aliases to mutable thread-local data not allowed." );
return _spawn( false, fn, args );
}
/**
* Executes the supplied function in a new context represented by Tid. This
* new context is linked to the calling context so that if either it or the
* calling context terminates a LinkTerminated message will be sent to the
* other, causing a LinkTerminated exception to be thrown on receive(). The
* owner relationship from spawn() is preserved as well, so if the link
* between threads is broken, owner termination will still result in an
* OwnerTerminated exception to be thrown on receive().
*
* Params:
* fn = The function to execute.
* args = Arguments to the function.
*
* Returns:
* A Tid representing the new context.
*/
Tid spawnLinked(T...)( void function(T) fn, T args )
{
static assert( !hasLocalAliasing!(T),
"Aliases to mutable thread-local data not allowed." );
return _spawn( true, fn, args );
}
/*
*
*/
private Tid _spawn(T...)( bool linked, void function(T) fn, T args )
{
// TODO: MessageList and &exec should be shared.
auto spawnTid = Tid( new MessageBox );
auto ownerTid = thisTid;
void exec()
{
mbox = spawnTid.mbox;
owner = ownerTid;
fn( args );
}
// TODO: MessageList and &exec should be shared.
auto t = new Thread( &exec ); t.start();
links[spawnTid] = linked;
return spawnTid;
}
//////////////////////////////////////////////////////////////////////////////
// Sending and Receiving Messages
//////////////////////////////////////////////////////////////////////////////
/**
* Sends the supplied value to the context represented by tid. As with
* $(XREF concurrency, spawn), $(D T) must not have unshared aliasing.
*/
void send(T...)( Tid tid, T vals )
{
static assert( !hasLocalAliasing!(T),
"Aliases to mutable thread-local data not allowed." );
_send( tid, vals );
}
/**
* Send a message to $(D tid) but place it at the front of $(D tid)'s message
* queue instead of at the back. This function is typically used for
* out-of-band communication, to signal exceptional conditions, etc.
*/
void prioritySend(T...)( Tid tid, T vals )
{
static assert( !hasLocalAliasing!(T),
"Aliases to mutable thread-local data not allowed." );
_send( MsgType.priority, tid, vals );
}
/*
* ditto
*/
private void _send(T...)( Tid tid, T vals )
{
_send( MsgType.standard, tid, vals );
}
/*
* Implementation of send. This allows parameter checking to be different for
* both Tid.send() and .send().
*/
private void _send(T...)( MsgType type, Tid tid, T vals )
{
auto msg = Message( type, vals );
tid.mbox.put( msg );
}
/**
* Receive a message from another thread, or block if no messages of the
* specified types are available. This function works by pattern matching
* a message against a set of delegates and executing the first match found.
*
* If a delegate that accepts a $(XREF variant, Variant) is included as
* the last argument to $(D receive), it will match any message that was not
* matched by an earlier delegate. If more than one argument is sent,
* the $(D Variant) will contain a $(XREF typecons, Tuple) of all values
* sent.
*
* Example:
* ---
* import std.stdio;
* import std.variant;
*
* void spawnedFunction()
* {
* receive(
* (int i) { writeln("Received an int."); },
* (float f) { writeln("Received a float."); },
* (Variant v) { writeln("Received some other type."); }
* );
* }
* ---
*/
void receive(T...)( T ops )
{
checkops( ops );
mbox.get( ops );
}
unittest
{
assert( __traits( compiles,
{
receive( (Variant x) {} );
receive( (int x) {}, (Variant x) {} );
} ) );
assert( !__traits( compiles,
{
receive( (Variant x) {}, (int x) {} );
} ) );
assert( !__traits( compiles,
{
receive( (int x) {}, (int x) {} );
} ) );
}
// Make sure receive() works with free functions as well.
version (unittest)
{
private void receiveFunction(int x) {}
}
unittest
{
assert( __traits( compiles,
{
receive( &receiveFunction );
receive( &receiveFunction, (Variant x) {} );
} ) );
}
private template receiveOnlyRet(T...)
{
static if( T.length == 1 )
alias T[0] receiveOnlyRet;
else
alias Tuple!(T) receiveOnlyRet;
}
/**
* Receives only messages with arguments of types $(D T).
*
* Throws: $(D MessageMismatch) if a message of types other than $(D T)
* is received.
*
* Returns: The received message. If $(D T.length) is greater than one,
* the message will be packed into a $(XREF typecons, Tuple).
*
* Example:
* ---
* import std.concurrency;
* void spawnedFunc()
* {
* auto msg = receiveOnly!(int, string)();
* assert(msg[0] == 42);
* assert(msg[1] == "42");
* }
*
* void main()
* {
* auto tid = spawn(&spawnedFunc);
* send(tid, 42, "42");
* }
* ---
*/
receiveOnlyRet!(T) receiveOnly(T...)()
{
Tuple!(T) ret;
mbox.get( ( T val )
{
static if( T.length )
ret.field = val;
},
( LinkTerminated e )
{
throw e;
},
( OwnerTerminated e )
{
throw e;
},
( Variant val )
{
throw new MessageMismatch;
} );
static if( T.length == 1 )
return ret[0];
else
return ret;
}
/**
* $(RED Deprecated. It will be removed in August 2012. Please use the version
* which takes a $(CXREF time, Duration) instead.)
*/
deprecated bool receiveTimeout(T...)( long ms, T ops )
{
return receiveTimeout( dur!"msecs"( ms ), ops );
}
/++
Same as $(D receive) except that rather than wait forever for a message,
it waits until either it receives a message or the given
$(CXREF time, Duration) has passed. It returns $(D true) if it received a
message and $(D false) if it timed out waiting for one.
+/
bool receiveTimeout(T...)( Duration duration, T ops )
{
checkops( ops );
return mbox.get( duration, ops );
}
unittest
{
assert( __traits( compiles,
{
receiveTimeout( 0, (Variant x) {} );
receiveTimeout( 0, (int x) {}, (Variant x) {} );
} ) );
assert( !__traits( compiles,
{
receiveTimeout( 0, (Variant x) {}, (int x) {} );
} ) );
assert( !__traits( compiles,
{
receiveTimeout( 0, (int x) {}, (int x) {} );
} ) );
assert( __traits( compiles,
{
receiveTimeout( dur!"msecs"(10), (int x) {}, (Variant x) {} );
} ) );
}
//////////////////////////////////////////////////////////////////////////////
// MessageBox Limits
//////////////////////////////////////////////////////////////////////////////
/**
* These behaviors may be specified when a mailbox is full.
*/
enum OnCrowding
{
block, /// Wait until room is available.
throwException, /// Throw a MailboxFull exception.
ignore /// Abort the send and return.
}
private
{
bool onCrowdingBlock( Tid tid )
{
return true;
}
bool onCrowdingThrow( Tid tid )
{
throw new MailboxFull( tid );
}
bool onCrowdingIgnore( Tid tid )
{
return false;
}
}
/**
* Sets a limit on the maximum number of user messages allowed in the mailbox.
* If this limit is reached, the caller attempting to add a new message will
* execute the behavior specified by doThis. If messages is zero, the mailbox
* is unbounded.
*
* Params:
* tid = The Tid of the thread for which this limit should be set.
* messages = The maximum number of messages or zero if no limit.
* doThis = The behavior executed when a message is sent to a full
* mailbox.
*/
void setMaxMailboxSize( Tid tid, size_t messages, OnCrowding doThis )
{
final switch( doThis )
{
case OnCrowding.block:
return tid.mbox.setMaxMsgs( messages, &onCrowdingBlock );
case OnCrowding.throwException:
return tid.mbox.setMaxMsgs( messages, &onCrowdingThrow );
case OnCrowding.ignore:
return tid.mbox.setMaxMsgs( messages, &onCrowdingIgnore );
}
}
/**
* Sets a limit on the maximum number of user messages allowed in the mailbox.
* If this limit is reached, the caller attempting to add a new message will
* execute onCrowdingDoThis. If messages is zero, the mailbox is unbounded.
*
* Params:
* tid = The Tid of the thread for which this limit should be set.
* messages = The maximum number of messages or zero if no limit.
* onCrowdingDoThis = The routine called when a message is sent to a full
* mailbox.
*/
void setMaxMailboxSize( Tid tid, size_t messages, bool function(Tid) onCrowdingDoThis )
{
tid.mbox.setMaxMsgs( messages, onCrowdingDoThis );
}
//////////////////////////////////////////////////////////////////////////////
// Name Registration
//////////////////////////////////////////////////////////////////////////////
private
{
__gshared Tid[string] tidByName;
__gshared string[][Tid] namesByTid;
__gshared Mutex registryLock;
}
shared static this()
{
registryLock = new Mutex;
}
static ~this()
{
auto me = thisTid;
synchronized( registryLock )
{
if( auto allNames = me in namesByTid )
{
foreach( name; *allNames )
tidByName.remove( name );
namesByTid.remove( me );
}
}
}
/**
* Associates name with tid in a process-local map. When the thread
* represented by tid termiantes, any names associated with it will be
* automatically unregistered.
*
* Params:
* name = The name to associate with tid.
* tid = The tid register by name.
*
* Returns:
* true if the name is available and tid is not known to represent a
* defunct thread.
*/
bool register( string name, Tid tid )
{
synchronized( registryLock )
{
if( name in tidByName )
return false;
if( tid.mbox.isClosed )
return false;
namesByTid[tid] ~= name;
tidByName[name] = tid;
return true;
}
}
/**
* Removes the registered name associated with a tid.
*
* Params:
* name = The name to unregister.
*
* Returns:
* true if the name is registered, false if not.
*/
bool unregister( string name )
{
synchronized( registryLock )
{
if( auto tid = name in tidByName )
{
auto allNames = *tid in namesByTid;
auto pos = countUntil( *allNames, name );
remove!(SwapStrategy.unstable)( *allNames, pos );
tidByName.remove( name );
return true;
}
return false;
}
}
/**
* Gets the Tid associated with name.
*
* Params:
* name = The name to locate within the registry.
*
* Returns:
* The associated Tid or Tid.init if name is not registered.
*/
Tid locate( string name )
{
synchronized( registryLock )
{
if( auto tid = name in tidByName )
return *tid;
return Tid.init;
}
}
//////////////////////////////////////////////////////////////////////////////
// MessageBox Implementation
//////////////////////////////////////////////////////////////////////////////
private
{
/*
* A MessageBox is a message queue for one thread. Other threads may send
* messages to this owner by calling put(), and the owner receives them by
* calling get(). The put() call is therefore effectively shared and the
* get() call is effectively local. setMaxMsgs may be used by any thread
* to limit the size of the message queue.
*/
class MessageBox
{
this()
{
m_lock = new Mutex;
m_putMsg = new Condition( m_lock );
m_notFull = new Condition( m_lock );
m_closed = false;
}
/*
*
*/
final @property bool isClosed() const
{
synchronized( m_lock )
{
return m_closed;
}
}
/*
* Sets a limit on the maximum number of user messages allowed in the
* mailbox. If this limit is reached, the caller attempting to add
* a new message will execute call. If num is zero, there is no limit
* on the message queue.
*
* Params:
* num = The maximum size of the queue or zero if the queue is
* unbounded.
* call = The routine to call when the queue is full.
*/
final void setMaxMsgs( size_t num, bool function(Tid) call )
{
synchronized( m_lock )
{
m_maxMsgs = num;
m_onMaxMsgs = call;
}
}
/*
* If maxMsgs is not set, the message is added to the queue and the
* owner is notified. If the queue is full, the message will still be
* accepted if it is a control message, otherwise onCrowdingDoThis is
* called. If the routine returns true, this call will block until
* the owner has made space available in the queue. If it returns
* false, this call will abort.
*
* Params:
* msg = The message to put in the queue.
*
* Throws:
* An exception if the queue is full and onCrowdingDoThis throws.
*/
final void put( ref Message msg )
{
synchronized( m_lock )
{
// TODO: Generate an error here if m_closed is true, or maybe
// put a message in the caller's queue?
if( !m_closed )
{
while( true )
{
if( isPriorityMsg( msg ) )
{
m_sharedPty.put( msg );
m_putMsg.notify();
return;
}
if( !mboxFull() || isControlMsg( msg ) )
{
m_sharedBox.put( msg );
m_putMsg.notify();
return;
}
if( m_onMaxMsgs !is null && !m_onMaxMsgs( thisTid ) )
{
return;
}
m_putQueue++;
m_notFull.wait();
m_putQueue--;
}
}
}
}
/*
* Matches ops against each message in turn until a match is found.
*
* Params:
* ops = The operations to match. Each may return a bool to indicate
* whether a message with a matching type is truly a match.
*
* Returns:
* true if a message was retrieved and false if not (such as if a
* timeout occurred).
*
* Throws:
* LinkTerminated if a linked thread terminated, or OwnerTerminated
* if the owner thread terminates and no existing messages match the
* supplied ops.
*/
final bool get(T...)( scope T vals )
{
static assert( T.length );
static if( isImplicitlyConvertible!(T[0], Duration) )
{
alias TypeTuple!(T[1 .. $]) Ops;
alias vals[1 .. $] ops;
assert( vals[0] >= dur!"msecs"(0) );
enum timedWait = true;
Duration period = vals[0];
}
else
{
alias TypeTuple!(T) Ops;
alias vals[0 .. $] ops;
enum timedWait = false;
}
bool onStandardMsg( ref Message msg )
{
foreach( i, t; Ops )
{
alias ParameterTypeTuple!(t) Args;
auto op = ops[i];
if( msg.convertsTo!(Args) )
{
static if( is( ReturnType!(t) == bool ) )
{
return msg.map( op );
}
else
{
msg.map( op );
return true;
}
}
}
return false;
}
bool onLinkDeadMsg( ref Message msg )
{
assert( msg.convertsTo!(Tid) );
auto tid = msg.get!(Tid);
if( bool* depends = (tid in links) )
{
links.remove( tid );
// Give the owner relationship precedence.
if( *depends && tid != owner )
{
auto e = new LinkTerminated( tid );
auto m = Message( MsgType.standard, e );
if( onStandardMsg( m ) )
return true;
throw e;
}
}
if( tid == owner )
{
owner = Tid.init;
auto e = new OwnerTerminated( tid );
auto m = Message( MsgType.standard, e );
if( onStandardMsg( m ) )
return true;
throw e;
}
return false;
}
bool onControlMsg( ref Message msg )
{
switch( msg.type )
{
case MsgType.linkDead:
return onLinkDeadMsg( msg );
default:
return false;
}
}
bool scan( ref ListT list )
{
for( auto range = list[]; !range.empty; )
{
// Only the message handler will throw, so if this occurs
// we can be certain that the message was handled.
scope(failure) list.removeAt( range );
if( isControlMsg( range.front ) )
{
if( onControlMsg( range.front ) )
{
// Although the linkDead message is a control message,
// it can be handled by the user. Since the linkDead
// message throws if not handled, if we get here then
// it has been handled and we can return from receive.
// This is a weird special case that will have to be
// handled in a more general way if more are added.
if( !isLinkDeadMsg( range.front ) )
{
list.removeAt( range );
continue;
}
list.removeAt( range );
return true;
}
range.popFront();
continue;
}
else
{
if( onStandardMsg( range.front ) )
{
list.removeAt( range );
return true;
}
range.popFront();
continue;
}
}
return false;
}
bool pty( ref ListT list )
{
if( !list.empty )
{
auto range = list[];
if( onStandardMsg( range.front ) )
{
list.removeAt( range );
return true;
}
if( range.front.convertsTo!(Throwable) )
throw range.front.get!(Throwable);
else if( range.front.convertsTo!(shared(Throwable)) )
throw range.front.get!(shared(Throwable));
else throw new PriorityMessageException( range.front.data );
}
return false;
}
while( true )
{
ListT arrived;
if( pty( m_localPty ) ||
scan( m_localBox ) )
{
return true;
}
synchronized( m_lock )
{
updateMsgCount();
while( m_sharedPty.empty && m_sharedBox.empty )
{
// NOTE: We're notifying all waiters here instead of just
// a few because the onCrowding behavior may have
// changed and we don't want to block sender threads
// unnecessarily if the new behavior is not to block.
// This will admittedly result in spurious wakeups
// in other situations, but what can you do?
if( m_putQueue && !mboxFull() )
m_notFull.notifyAll();
static if( timedWait )
{
if( !m_putMsg.wait( period ) )
return false;
}
else
{
m_putMsg.wait();
}
}
m_localPty.put( m_sharedPty );
arrived.put( m_sharedBox );
}
if( m_localPty.empty )
{
scope(exit) m_localBox.put( arrived );
if( scan( arrived ) )
return true;
else continue;
}
m_localBox.put( arrived );
pty( m_localPty );
return true;
}
}
/*
* Called on thread termination. This routine processes any remaining
* control messages, clears out message queues, and sets a flag to
* reject any future messages.
*/
final void close()
{
void onLinkDeadMsg( ref Message msg )
{
assert( msg.convertsTo!(Tid) );
auto tid = msg.get!(Tid);
links.remove( tid );
if( tid == owner )
owner = Tid.init;
}
void sweep( ref ListT list )
{
for( auto range = list[]; !range.empty; range.popFront() )
{
if( range.front.type == MsgType.linkDead )
onLinkDeadMsg( range.front );
}
}
ListT arrived;
sweep( m_localBox );
synchronized( m_lock )
{
arrived.put( m_sharedBox );
m_closed = true;
}
m_localBox.clear();
sweep( arrived );
}
private:
//////////////////////////////////////////////////////////////////////
// Routines involving shared data, m_lock must be held.
//////////////////////////////////////////////////////////////////////
bool mboxFull()
{
return m_maxMsgs &&
m_maxMsgs <= m_localMsgs + m_sharedBox.length;
}
void updateMsgCount()
{
m_localMsgs = m_localBox.length;
}
private:
//////////////////////////////////////////////////////////////////////
// Routines involving local data only, no lock needed.
//////////////////////////////////////////////////////////////////////
pure final bool isControlMsg( ref Message msg )
{
return msg.type != MsgType.standard &&
msg.type != MsgType.priority;
}
pure final bool isPriorityMsg( ref Message msg )
{
return msg.type == MsgType.priority;
}
pure final bool isLinkDeadMsg( ref Message msg )
{
return msg.type == MsgType.linkDead;
}
private:
//////////////////////////////////////////////////////////////////////
// Type declarations.
//////////////////////////////////////////////////////////////////////
alias bool function(Tid) OnMaxFn;
alias List!(Message) ListT;
private:
//////////////////////////////////////////////////////////////////////
// Local data, no lock needed.
//////////////////////////////////////////////////////////////////////
ListT m_localBox;
ListT m_localPty;
private:
//////////////////////////////////////////////////////////////////////
// Shared data, m_lock must be held on access.
//////////////////////////////////////////////////////////////////////
Mutex m_lock;
Condition m_putMsg;
Condition m_notFull;
size_t m_putQueue;
ListT m_sharedBox;
ListT m_sharedPty;
OnMaxFn m_onMaxMsgs;
size_t m_localMsgs;
size_t m_maxMsgs;
bool m_closed;
}
/*
*
*/
struct List(T)
{
struct Range
{
@property bool empty() const
{
return !m_prev.next;
}
@property ref T front()
{
enforce( m_prev.next );
return m_prev.next.val;
}
@property void front( T val )
{
enforce( m_prev.next );
m_prev.next.val = val;
}
void popFront()
{
enforce( m_prev.next );
m_prev = m_prev.next;
}
//T moveFront()
//{
// enforce( m_prev.next );
// return move( m_prev.next.val );
//}
private this( Node* p )
{
m_prev = p;
}
private Node* m_prev;
}
/*
*
*/
void put( T val )
{
put( new Node( val ) );
}
/*
*
*/
void put( ref List!(T) rhs )
{
if( !rhs.empty )
{
put( rhs.m_first );
while( m_last.next !is null )
{
m_last = m_last.next;
m_count++;
}
rhs.m_first = null;
rhs.m_last = null;
rhs.m_count = 0;
}
}
/*
*
*/
Range opSlice()
{
return Range( cast(Node*) &m_first );
}
/*
*
*/
void removeAt( Range r )
{
assert( m_count );
Node* n = r.m_prev;
enforce( n && n.next );
if( m_last is m_first )
m_last = null;
else if( m_last is n.next )
m_last = n;
Node* todelete = n.next;
n.next = n.next.next;
//delete todelete;
m_count--;
}
/*
*
*/
@property size_t length()
{
return m_count;
}
/*
*
*/
void clear()
{
m_first = m_last = null;
m_count = 0;
}
/*
*
*/
@property bool empty()
{
return m_first is null;
}
private:
struct Node
{
Node* next;
T val;
this( T v )
{
val = v;
}
}
/*
*
*/
void put( Node* n )
{
m_count++;
if( !empty )
{
m_last.next = n;
m_last = n;
return;
}
m_first = n;
m_last = n;
}
Node* m_first;
Node* m_last;
size_t m_count;
}
}
version( unittest )
{
import std.stdio;
void testfn( Tid tid )
{
receive( (float val) { assert(0); },
(int val, int val2)
{
assert( val == 42 && val2 == 86 );
} );
receive( (Tuple!(int, int) val)
{
assert( val[0] == 42 &&
val[1] == 86 );
} );
receive( (Variant val) {} );
receive( (string val)
{
if( "the quick brown fox" != val )
return false;
return true;
},
(string val)
{
assert( false );
} );
prioritySend( tid, "done" );
}
void runTest( Tid tid )
{
send( tid, 42, 86 );
send( tid, tuple(42, 86) );
send( tid, "hello", "there" );
send( tid, "the quick brown fox" );
receive( (string val) { assert(val == "done"); } );
}
unittest
{
auto tid = spawn( &testfn, thisTid );
runTest( tid );
// Run the test again with a limited mailbox size.
tid = spawn( &testfn, thisTid );
setMaxMailboxSize( tid, 2, OnCrowding.block );
runTest( tid );
}
}
|
D
|
instance DIA_VALENTINO_EXIT(C_INFO)
{
npc = vlk_421_valentino;
nr = 999;
condition = dia_valentino_exit_condition;
information = dia_valentino_exit_info;
permanent = TRUE;
description = DIALOG_ENDE;
};
func int dia_valentino_exit_condition()
{
return TRUE;
};
func void dia_valentino_exit_info()
{
AI_StopProcessInfos(self);
};
instance DIA_VALENTINO_HALLO(C_INFO)
{
npc = vlk_421_valentino;
nr = 1;
condition = dia_valentino_hallo_condition;
information = dia_valentino_hallo_info;
permanent = FALSE;
description = "Takže copak to tu máme?";
};
func int dia_valentino_hallo_condition()
{
return TRUE;
};
func void dia_valentino_hallo_info()
{
AI_Output(other,self,"DIA_Valentino_HALLO_15_00"); //Takže copak to tu máme?
if((hero.guild == GIL_KDF) || (hero.guild == GIL_PAL))
{
AI_Output(self,other,"DIA_Valentino_HALLO_03_01"); //Jmenuji se Valentino. Snažím se, abych tento den, který mi Innos dal, neznesvětil žádnou prací.
AI_Output(other,self,"DIA_Valentino_HALLO_15_02"); //Dávej pozor na to, co říkáš.
AI_Output(self,other,"DIA_Valentino_HALLO_03_03"); //Ach, omluv mě. Nechtěl jsem Tvou Milost nijak urazit, ó, prosím za odpuštění, pane.
}
else
{
AI_Output(self,other,"DIA_Valentino_HALLO_03_04"); //Copak se neumíš chovat? To je nechutné!
AI_Output(self,other,"DIA_Valentino_HALLO_03_05"); //Pořád tahle špinavá chátra! Nemáš být náhodou někde v práci?
AI_Output(self,other,"DIA_Valentino_HALLO_03_06"); //Ale počítám, že takového ošuntělého chlápka jako ty si každý všimne, co?
AI_Output(self,other,"DIA_Valentino_HALLO_03_07"); //No, až budeš mít tolik zlata jako já, taky nebudeš muset vůbec pracovat. Ale ty nikdy takhle bohatý nebudeš.
AI_Output(other,self,"DIA_Valentino_HALLO_15_08"); //Vidím, že s tebou si užiju pořádnou srandu.
};
};
instance DIA_VALENTINO_WHOAGAIN(C_INFO)
{
npc = vlk_421_valentino;
nr = 2;
condition = dia_valentino_whoagain_condition;
information = dia_valentino_whoagain_info;
permanent = FALSE;
description = "Ptal jsem se tě, kdo jsi!";
};
func int dia_valentino_whoagain_condition()
{
if(Npc_KnowsInfo(other,dia_valentino_hallo) && (other.guild != GIL_KDF) && (other.guild != GIL_PAL))
{
return TRUE;
};
};
func void dia_valentino_whoagain_info()
{
AI_Output(other,self,"DIA_Valentino_Add_15_01"); //Ptal jsem se tě, kdo jsi!
AI_Output(self,other,"DIA_Valentino_HALLO_wasmachstdu_03_01"); //Jsem švihák Valentino. Bonviván a miláček žen!
AI_Output(self,other,"DIA_Valentino_HALLO_wasmachstdu_03_02"); //Trápení neznám, však moudrostí a zlatem oplývám a ženy mi padají k nohám, sotva mne spatří.
AI_Output(self,other,"DIA_Valentino_HALLO_wasmachstdu_03_03"); //Jestli máš problémy, nech si je pro sebe, já je nepotřebuju.
};
instance DIA_VALENTINO_MANIEREN(C_INFO)
{
npc = vlk_421_valentino;
nr = 3;
condition = dia_valentino_manieren_condition;
information = dia_valentino_manieren_info;
permanent = FALSE;
description = "Zdá se mi, že bych ti měl uštědřit menší lekci slušného chování!";
};
func int dia_valentino_manieren_condition()
{
if(Npc_KnowsInfo(other,dia_valentino_hallo) && (other.guild != GIL_PAL) && (other.guild != GIL_KDF))
{
return TRUE;
};
};
func void dia_valentino_manieren_info()
{
AI_Output(other,self,"DIA_Valentino_Add_15_02"); //Zdá se mi, že bych ti měl uštědřit menší lekci slušného chování!
AI_Output(self,other,"DIA_Valentino_HALLO_klappe_03_01"); //Mně to nevadí. Jen si mne klidně zbij. Až se zítra ráno probudím, zase mi bude dobře.
AI_Output(self,other,"DIA_Valentino_HALLO_klappe_03_02"); //Ale ty s tímhle ksichtem budeš muset chodit celý život.
};
var int valentino_lo_perm;
var int valentino_hi_perm;
instance DIA_VALENTINO_WASNUETZLICHES(C_INFO)
{
npc = vlk_421_valentino;
nr = 4;
condition = dia_valentino_wasnuetzliches_condition;
information = dia_valentino_wasnuetzliches_info;
permanent = TRUE;
description = "Chceš mi říci ještě něco jiného?";
};
func int dia_valentino_wasnuetzliches_condition()
{
if(Npc_KnowsInfo(other,dia_valentino_hallo))
{
return TRUE;
};
};
func void dia_valentino_wasnuetzliches_info()
{
AI_Output(other,self,"DIA_Valentino_Add_15_03"); //(klidně) Chceš mi říci ještě něco jiného?
if(self.aivar[AIV_DEFEATEDBYPLAYER] == TRUE)
{
b_say(self,other,"$NOTNOW");
}
else if((VALENTINO_LO_PERM == FALSE) && (other.guild != GIL_PAL) && (other.guild != GIL_KDF))
{
AI_Output(self,other,"DIA_Valentino_WASNUETZLICHES_03_01"); //Získej si věhlas, nikdy nikomu nic neslibuj, ber si, co chceš, a dávej si pozor, aby ses nedostal do sporu s domobranou.
AI_Output(self,other,"DIA_Valentino_WASNUETZLICHES_03_02"); //Nebo se žárlivými manželi, samozřejmě - ti jsou ze všech nejhorší, to ti povím.
VALENTINO_LO_PERM = TRUE;
}
else if((VALENTINO_HI_PERM == FALSE) && ((other.guild == GIL_PAL) || (other.guild == GIL_KDF)))
{
AI_Output(self,other,"DIA_Valentino_WASNUETZLICHES_03_03"); //Pro muže tvého postavení není nic nemožné. Prostě jen musíš poznat, kdy je čas k činu.
AI_Output(self,other,"DIA_Valentino_WASNUETZLICHES_03_04"); //Tak neztrácej čas a jednej!
VALENTINO_HI_PERM = TRUE;
}
else
{
AI_Output(self,other,"DIA_Valentino_WASNUETZLICHES_03_05"); //Už jsem ti řekl všechno, co potřebuješ vědět - zbytek je na tobě.
};
};
instance DIA_VALENTINO_PICKPOCKET(C_INFO)
{
npc = vlk_421_valentino;
nr = 900;
condition = dia_valentino_pickpocket_condition;
information = dia_valentino_pickpocket_info;
permanent = TRUE;
description = "(Tenhle klíč lze snadno ukrást)";
};
func int dia_valentino_pickpocket_condition()
{
if((Npc_GetTalentSkill(other,NPC_TALENT_PICKPOCKET) == 1) && (self.aivar[AIV_PLAYERHASPICKEDMYPOCKET] == FALSE) && (Npc_HasItems(self,itke_valentino) >= 1) && (other.attribute[ATR_DEXTERITY] >= (30 - THEFTDIFF)))
{
return TRUE;
};
};
func void dia_valentino_pickpocket_info()
{
Info_ClearChoices(dia_valentino_pickpocket);
Info_AddChoice(dia_valentino_pickpocket,DIALOG_BACK,dia_valentino_pickpocket_back);
Info_AddChoice(dia_valentino_pickpocket,DIALOG_PICKPOCKET,dia_valentino_pickpocket_doit);
};
func void dia_valentino_pickpocket_doit()
{
if(other.attribute[ATR_DEXTERITY] >= 30)
{
b_giveinvitems(self,other,itke_valentino,1);
self.aivar[AIV_PLAYERHASPICKEDMYPOCKET] = TRUE;
b_giveplayerxp(XP_AMBIENT);
Info_ClearChoices(dia_valentino_pickpocket);
}
else
{
AI_StopProcessInfos(self);
b_attack(self,other,AR_THEFT,1);
};
};
func void dia_valentino_pickpocket_back()
{
Info_ClearChoices(dia_valentino_pickpocket);
};
|
D
|
module android.java.android.provider.Telephony_Mms_Outbox;
public import android.java.android.provider.Telephony_Mms_Outbox_d_interface;
import arsd.jni : ImportExportImpl;
mixin ImportExportImpl!Telephony_Mms_Outbox;
import import0 = android.java.java.lang.Class;
|
D
|
module android.java.android.widget.GridLayout_Alignment_d_interface;
import arsd.jni : IJavaObjectImplementation, JavaPackageId, JavaName, IJavaObject, ImportExportImpl, JavaInterfaceMembers;
static import arsd.jni;
import import0 = android.java.java.lang.Class_d_interface;
@JavaName("GridLayout$Alignment")
final class GridLayout_Alignment : IJavaObject {
static immutable string[] _d_canCastTo = [
];
@Import import0.Class getClass();
@Import int hashCode();
@Import bool equals(IJavaObject);
@Import @JavaName("toString") string toString_();
override string toString() { return arsd.jni.javaObjectToString(this); }
@Import void notify();
@Import void notifyAll();
@Import void wait(long);
@Import void wait(long, int);
@Import void wait();
mixin IJavaObjectImplementation!(false);
public static immutable string _javaParameterString = "Landroid/widget/GridLayout$Alignment;";
}
|
D
|
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module flow.engine.impl.cmd.EvaluateConditionalEventsCmd;
import hunt.collection.Map;
import flow.common.api.FlowableException;
import flow.common.interceptor.CommandContext;
import flow.engine.impl.persistence.entity.ExecutionEntity;
import flow.engine.impl.util.CommandContextUtil;
import flow.engine.impl.cmd.NeedsActiveExecutionCmd;
/**
* @author Tijs Rademakers
*/
class EvaluateConditionalEventsCmd : NeedsActiveExecutionCmd!Object {
protected Map!(string, Object) processVariables;
protected Map!(string, Object) transientVariables;
protected bool async;
this(string processInstanceId, Map!(string, Object) processVariables) {
super(processInstanceId);
this.processVariables = processVariables;
}
this(string processInstanceId, Map!(string, Object) processVariables, Map!(string, Object) transientVariables) {
this(processInstanceId, processVariables);
this.transientVariables = transientVariables;
}
override
protected Object execute(CommandContext commandContext, ExecutionEntity execution) {
if (!execution.isProcessInstanceType()) {
throw new FlowableException("Execution is not of type process instance");
}
if (processVariables !is null) {
execution.setVariables(processVariables);
}
if (transientVariables !is null) {
execution.setTransientVariables(transientVariables);
}
CommandContextUtil.getAgenda(commandContext).planEvaluateConditionalEventsOperation(execution);
return null;
}
override
protected string getSuspendedExceptionMessage() {
return "Cannot evaluate conditions for an execution that is suspended";
}
}
|
D
|
/**
* Generate the object file for function declarations and critical sections.
*
* Copyright: Copyright (C) 1999-2022 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/glue.d, _glue.d)
* Documentation: $(LINK https://dlang.org/phobos/dmd_glue.html)
* Coverage: $(LINK https://codecov.io/gh/dlang/dmd/src/master/src/dmd/glue.d)
*/
module dmd.glue;
import core.stdc.stdio;
import core.stdc.string;
import core.stdc.stdlib;
import dmd.root.array;
import dmd.root.file;
import dmd.root.filename;
import dmd.common.outbuffer;
import dmd.root.rmem;
import dmd.root.string;
import dmd.backend.cdef;
import dmd.backend.cc;
import dmd.backend.code;
import dmd.backend.dt;
import dmd.backend.el;
import dmd.backend.global;
import dmd.backend.obj;
import dmd.backend.oper;
import dmd.backend.rtlsym;
import dmd.backend.symtab;
import dmd.backend.ty;
import dmd.backend.type;
import dmd.aggregate;
import dmd.arraytypes;
import dmd.astenums;
import dmd.blockexit;
import dmd.dclass;
import dmd.declaration;
import dmd.dmangle;
import dmd.dmdparams;
import dmd.dmodule;
import dmd.dmsc;
import dmd.dstruct;
import dmd.dsymbol;
import dmd.dtemplate;
import dmd.e2ir;
import dmd.errors;
import dmd.expression;
import dmd.func;
import dmd.globals;
import dmd.identifier;
import dmd.id;
import dmd.lib;
import dmd.mtype;
import dmd.objc_glue;
import dmd.s2ir;
import dmd.statement;
import dmd.target;
import dmd.tocsym;
import dmd.toctype;
import dmd.toir;
import dmd.toobj;
import dmd.typesem;
import dmd.utils;
alias symbols = Array!(Symbol*);
alias toSymbol = dmd.tocsym.toSymbol;
/**
* Generate code for `modules` and write objects/libraries
*
* Params:
* modules = array of `Module`s to generate code for
* libmodules = array of objects/libraries already generated (passed on command line)
* libname = {.lib,.a} file output name
* objdir = directory to write object files to
* lib = write library file instead of object file(s)
* obj = generate object files
* oneobj = write one object file instead of multiple ones
* multiobj = break one object file into multiple ones
* verbose = print progress message when generatig code
*/
void generateCodeAndWrite(Module[] modules, const(char)*[] libmodules,
const(char)[] libname, const(char)[] objdir,
bool lib, bool obj, bool oneobj, bool multiobj,
bool verbose)
{
Library library = null;
if (lib)
{
library = Library.factory();
library.setFilename(objdir, libname);
// Add input object and input library files to output library
foreach (p; libmodules)
library.addObject(p.toDString(), null);
}
if (!obj)
{
}
else if (oneobj)
{
OutBuffer objbuf;
Module firstm; // first module we generate code for
foreach (m; modules)
{
if (m.filetype == FileType.dhdr)
continue;
if (!firstm)
{
firstm = m;
obj_start(objbuf, m.srcfile.toChars());
}
if (verbose)
message("code %s", m.toChars());
genObjFile(m, false);
}
if (!global.errors && firstm)
{
obj_end(objbuf, library, firstm.objfile.toChars());
}
}
else
{
OutBuffer objbuf;
foreach (m; modules)
{
if (m.filetype == FileType.dhdr)
continue;
if (verbose)
message("code %s", m.toChars());
obj_start(objbuf, m.srcfile.toChars());
genObjFile(m, multiobj);
obj_end(objbuf, library, m.objfile.toChars());
obj_write_deferred(objbuf, library, glue.obj_symbols_towrite);
if (global.errors && !lib)
m.deleteObjFile();
}
}
if (lib && !global.errors)
library.write();
}
extern (C++):
//extern
__gshared Symbol* bzeroSymbol; /// common location for immutable zeros
struct Glue
{
elem *eictor;
Symbol *ictorlocalgot;
symbols sctors;
StaticDtorDeclarations ectorgates;
symbols sdtors;
symbols stests;
symbols ssharedctors;
SharedStaticDtorDeclarations esharedctorgates;
symbols sshareddtors;
const(char)* lastmname;
Dsymbols obj_symbols_towrite;
}
private __gshared Glue glue;
/**************************************
* Append s to list of object files to generate later.
* Only happens with multiobj.
*/
void obj_append(Dsymbol s)
{
//printf("deferred: %s\n", s.toChars());
glue.obj_symbols_towrite.push(s);
}
/*******************************
* Generating multiple object files, one per Dsymbol
* in symbols_towrite[].
* Params:
* library = library to write object files to
* symbols_towrite = array of Dsymbols
*/
extern (D)
private void obj_write_deferred(ref OutBuffer objbuf, Library library, ref Dsymbols symbols_towrite)
{
// this array can grow during the loop; do not replace with foreach
for (size_t i = 0; i < symbols_towrite.length; ++i)
{
Dsymbol s = symbols_towrite[i];
Module m = s.getModule();
const(char)* mname;
if (m)
{
mname = m.srcfile.toChars();
glue.lastmname = mname;
}
else
{
//mname = s.ident.toChars();
mname = glue.lastmname;
assert(mname);
}
obj_start(objbuf, mname);
__gshared int count;
count++; // sequence for generating names
/* Create a module that's a doppelganger of m, with just
* enough to be able to create the moduleinfo.
*/
OutBuffer idbuf;
idbuf.printf("%s.%d", m ? m.ident.toChars() : mname, count);
if (!m)
{
// it doesn't make sense to make up a module if we don't know where to put the symbol
// so output it into its own object file without ModuleInfo
objmod.initfile(idbuf.peekChars(), null, mname);
toObjFile(s, false);
objmod.termfile();
}
else
{
Identifier id = Identifier.create(idbuf.extractChars());
Module md = new Module(mname.toDString, id, 0, 0);
md.members = new Dsymbols();
md.members.push(s); // its only 'member' is s
md.doppelganger = 1; // identify this module as doppelganger
md.md = m.md;
md.aimports.push(m); // it only 'imports' m
genObjFile(md, false);
}
/* Set object file name to be source name with sequence number,
* as mangled symbol names get way too long.
*/
const(char)* fname = FileName.removeExt(mname);
OutBuffer namebuf;
uint hash = 0;
for (const(char)* p = s.toChars(); *p; p++)
hash += *p;
namebuf.printf("%s_%x_%x.%.*s", fname, count, hash,
cast(int)target.obj_ext.length, target.obj_ext.ptr);
FileName.free(cast(char *)fname);
fname = namebuf.extractChars();
//printf("writing '%s'\n", fname);
obj_end(objbuf, library, fname);
}
glue.obj_symbols_towrite.dim = 0;
}
/***********************************************
* Generate function that calls array of functions and gates.
* Params:
* m = module symbol (for name mangling purposes)
* sctors = array of functions
* ectorgates = array of gates
* id = identifier string for generator function
* Returns:
* function Symbol generated
*/
extern (D)
private Symbol *callFuncsAndGates(Module m, Symbol*[] sctors, StaticDtorDeclaration[] ectorgates,
const(char)* id)
{
if (!sctors.length && !ectorgates.length)
return null;
Symbol *sctor = null;
__gshared type *t;
if (!t)
{
/* t will be the type of the functions generated:
* extern (C) void func();
*/
t = type_function(TYnfunc, null, false, tstypes[TYvoid]);
t.Tmangle = mTYman_c;
}
localgot = null;
sctor = toSymbolX(m, id, SCglobal, t, "FZv");
cstate.CSpsymtab = &sctor.Sfunc.Flocsym;
elem *ector = null;
foreach (f; ectorgates)
{
Symbol *s = toSymbol(f.vgate);
elem *e = el_var(s);
e = el_bin(OPaddass, TYint, e, el_long(TYint, 1));
ector = el_combine(ector, e);
}
foreach (s; sctors)
{
elem *e = el_una(OPucall, TYvoid, el_var(s));
ector = el_combine(ector, e);
}
block *b = block_calloc();
b.BC = BCret;
b.Belem = ector;
sctor.Sfunc.Fstartline.Sfilename = m.arg.xarraydup.ptr;
sctor.Sfunc.Fstartblock = b;
writefunc(sctor); // hand off to backend
return sctor;
}
/**************************************
* Prepare for generating obj file.
* Params:
* objbuf = write object file contents to this
* srcfile = name of the source file
*/
private void obj_start(ref OutBuffer objbuf, const(char)* srcfile)
{
//printf("obj_start()\n");
bzeroSymbol = null;
rtlsym_reset();
clearStringTab();
version (Windows)
{
// Produce Ms COFF files by default, OMF for -m32omf
assert(objbuf.length() == 0);
switch (target.objectFormat())
{
case Target.ObjectFormat.coff: objmod = MsCoffObj_init(&objbuf, srcfile, null); break;
case Target.ObjectFormat.omf: objmod = OmfObj_init(&objbuf, srcfile, null); break;
default: assert(0);
}
}
else
{
objmod = Obj.initialize(&objbuf, srcfile, null);
}
el_reset();
cg87_reset();
out_reset();
objc.reset();
}
/****************************************
* Finish creating the object module and writing it to objbuf[].
* Then either write the object module to an actual file,
* or add it to a library.
* Params:
* objbuf = contains the generated contents of the object file
* objfilename = what to call the object module
* library = if non-null, add object module to this library
*/
private void obj_end(ref OutBuffer objbuf, Library library, const(char)* objfilename)
{
objmod.term(objfilename);
//delete objmod;
objmod = null;
if (library)
{
// Transfer ownership of image buffer to library
library.addObject(objfilename.toDString(), cast(ubyte[]) objbuf.extractSlice[]);
}
else
{
//printf("write obj %s\n", objfilename);
writeFile(Loc.initial, objfilename.toDString, objbuf[]);
// For non-libraries, the object buffer should be cleared to
// avoid repetitions.
objbuf.destroy();
}
}
bool obj_includelib(const(char)* name) nothrow
{
return objmod.includelib(name);
}
extern(D) bool obj_includelib(const(char)[] name) nothrow
{
return name.toCStringThen!(n => obj_includelib(n.ptr));
}
void obj_startaddress(Symbol *s)
{
return objmod.startaddress(s);
}
bool obj_linkerdirective(const(char)* directive)
{
return objmod.linkerdirective(directive);
}
/**************************************
* Generate .obj file for Module.
*/
private void genObjFile(Module m, bool multiobj)
{
//EEcontext *ee = env.getEEcontext();
//printf("Module.genobjfile(multiobj = %d) %s\n", multiobj, m.toChars());
glue.lastmname = m.srcfile.toChars();
objmod.initfile(glue.lastmname, null, m.toPrettyChars());
glue.eictor = null;
glue.ictorlocalgot = null;
glue.sctors.setDim(0);
glue.ectorgates.setDim(0);
glue.sdtors.setDim(0);
glue.ssharedctors.setDim(0);
glue.esharedctorgates.setDim(0);
glue.sshareddtors.setDim(0);
glue.stests.setDim(0);
if (m.doppelganger)
{
/* Generate a reference to the moduleinfo, so the module constructors
* and destructors get linked in.
*/
Module mod = m.aimports[0];
assert(mod);
if (mod.sictor || mod.sctor || mod.sdtor || mod.ssharedctor || mod.sshareddtor)
{
Symbol *s = toSymbol(mod);
//objextern(s);
//if (!s.Sxtrnnum) objextdef(s.Sident);
if (!s.Sxtrnnum)
{
//printf("%s\n", s.Sident);
//#if 0 /* This should work, but causes optlink to fail in common/newlib.asm */
// objextdef(s.Sident);
//#else
Symbol *sref = symbol_generate(SCstatic, type_fake(TYnptr));
sref.Sfl = FLdata;
auto dtb = DtBuilder(0);
dtb.xoff(s, 0, TYnptr);
sref.Sdt = dtb.finish();
outdata(sref);
//#endif
}
}
}
if (global.params.cov)
{
/* Create coverage identifier:
* uint[numlines] __coverage;
*/
m.cov = toSymbolX(m, "__coverage", SCstatic, type_fake(TYint), "Z");
m.cov.Sflags |= SFLhidden;
m.cov.Stype.Tmangle = mTYman_d;
m.cov.Sfl = FLdata;
auto dtb = DtBuilder(0);
if (m.ctfe_cov)
{
// initalize the uint[] __coverage symbol with data from ctfe.
static extern (C) int comp_uints (const scope void* a, const scope void* b)
{ return (*cast(uint*) a) - (*cast(uint*) b); }
uint[] sorted_lines = m.ctfe_cov.keys;
qsort(sorted_lines.ptr, sorted_lines.length, sorted_lines[0].sizeof,
&comp_uints);
uint lastLine = 0;
foreach (line;sorted_lines)
{
// zero fill from last line to line.
if (line)
{
assert(line > lastLine);
dtb.nzeros((line - lastLine - 1) * 4);
}
dtb.dword(m.ctfe_cov[line]);
lastLine = line;
}
// zero fill from last line to end
if (m.numlines > lastLine)
dtb.nzeros((m.numlines - lastLine) * 4);
}
else
{
dtb.nzeros(4 * m.numlines);
}
m.cov.Sdt = dtb.finish();
outdata(m.cov);
m.covb = cast(uint *)calloc((m.numlines + 32) / 32, (*m.covb).sizeof);
}
for (int i = 0; i < m.members.dim; i++)
{
auto member = (*m.members)[i];
//printf("toObjFile %s %s\n", member.kind(), member.toChars());
toObjFile(member, multiobj);
}
if (global.params.cov)
{
/* Generate
* private bit[numlines] __bcoverage;
*/
Symbol *bcov = symbol_calloc("__bcoverage");
bcov.Stype = type_fake(TYuint);
bcov.Stype.Tcount++;
bcov.Sclass = SCstatic;
bcov.Sfl = FLdata;
auto dtb = DtBuilder(0);
dtb.nbytes((m.numlines + 32) / 32 * (*m.covb).sizeof, cast(char *)m.covb);
bcov.Sdt = dtb.finish();
outdata(bcov);
free(m.covb);
m.covb = null;
/* Generate:
* _d_cover_register(uint[] __coverage, BitArray __bcoverage, string filename);
* and prepend it to the static constructor.
*/
/* t will be the type of the functions generated:
* extern (C) void func();
*/
type *t = type_function(TYnfunc, null, false, tstypes[TYvoid]);
t.Tmangle = mTYman_c;
m.sictor = toSymbolX(m, "__modictor", SCglobal, t, "FZv");
cstate.CSpsymtab = &m.sictor.Sfunc.Flocsym;
localgot = glue.ictorlocalgot;
elem *ecov = el_pair(TYdarray, el_long(TYsize_t, m.numlines), el_ptr(m.cov));
elem *ebcov = el_pair(TYdarray, el_long(TYsize_t, m.numlines), el_ptr(bcov));
if (target.os == Target.OS.Windows && target.is64bit)
{
ecov = addressElem(ecov, Type.tvoid.arrayOf(), false);
ebcov = addressElem(ebcov, Type.tvoid.arrayOf(), false);
}
elem *efilename = toEfilename(m);
if (target.os == Target.OS.Windows && target.is64bit)
efilename = addressElem(efilename, Type.tstring, true);
elem *e = el_params(
el_long(TYuchar, global.params.covPercent),
ecov,
ebcov,
efilename,
null);
e = el_bin(OPcall, TYvoid, el_var(getRtlsym(RTLSYM.DCOVER2)), e);
glue.eictor = el_combine(e, glue.eictor);
glue.ictorlocalgot = localgot;
}
// If coverage / static constructor / destructor / unittest calls
if (glue.eictor || glue.sctors.dim || glue.ectorgates.dim || glue.sdtors.dim ||
glue.ssharedctors.dim || glue.esharedctorgates.dim || glue.sshareddtors.dim || glue.stests.dim)
{
if (glue.eictor)
{
localgot = glue.ictorlocalgot;
block *b = block_calloc();
b.BC = BCret;
b.Belem = glue.eictor;
m.sictor.Sfunc.Fstartline.Sfilename = m.arg.xarraydup.ptr;
m.sictor.Sfunc.Fstartblock = b;
writefunc(m.sictor);
}
m.sctor = callFuncsAndGates(m, glue.sctors[], glue.ectorgates[], "__modctor");
m.sdtor = callFuncsAndGates(m, glue.sdtors[], null, "__moddtor");
m.ssharedctor = callFuncsAndGates(m, glue.ssharedctors[], cast(StaticDtorDeclaration[])glue.esharedctorgates[], "__modsharedctor");
m.sshareddtor = callFuncsAndGates(m, glue.sshareddtors[], null, "__modshareddtor");
m.stest = callFuncsAndGates(m, glue.stests[], null, "__modtest");
if (m.doppelganger)
genModuleInfo(m);
}
if (m.doppelganger)
{
objc.generateModuleInfo(m);
objmod.termfile();
return;
}
/* Generate module info for templates and -cov.
* Don't generate ModuleInfo if `object.ModuleInfo` is not declared or
* explicitly disabled through compiler switches such as `-betterC`.
* Don't generate ModuleInfo for C files.
*/
if (global.params.useModuleInfo && Module.moduleinfo && m.filetype != FileType.c/*|| needModuleInfo()*/)
genModuleInfo(m);
objmod.termfile();
}
/* ================================================================== */
private UnitTestDeclaration needsDeferredNested(FuncDeclaration fd)
{
while (fd && fd.isNested())
{
FuncDeclaration fdp = fd.toParent2().isFuncDeclaration();
if (!fdp)
break;
if (UnitTestDeclaration udp = fdp.isUnitTestDeclaration())
return udp.semanticRun < PASS.obj ? udp : null;
fd = fdp;
}
return null;
}
void FuncDeclaration_toObjFile(FuncDeclaration fd, bool multiobj)
{
ClassDeclaration cd = fd.parent.isClassDeclaration();
//printf("FuncDeclaration_toObjFile(%p, %s.%s)\n", fd, fd.parent.toChars(), fd.toChars());
//printf("storage_class: %llx\n", fd.storage_class);
//if (type) printf("type = %s\n", type.toChars());
version (none)
{
//printf("line = %d\n", getWhere() / LINEINC);
EEcontext *ee = env.getEEcontext();
if (ee.EEcompile == 2)
{
if (ee.EElinnum < (getWhere() / LINEINC) ||
ee.EElinnum > (endwhere / LINEINC)
)
return; // don't compile this function
ee.EEfunc = toSymbol(this);
}
}
if (fd.semanticRun >= PASS.obj) // if toObjFile() already run
return;
if (fd.type && fd.type.ty == Tfunction && (cast(TypeFunction)fd.type).next is null)
return;
// If errors occurred compiling it, such as https://issues.dlang.org/show_bug.cgi?id=6118
if (fd.type && fd.type.ty == Tfunction && (cast(TypeFunction)fd.type).next.ty == Terror)
return;
if (fd.hasSemantic3Errors)
return;
if (global.errors)
return;
if (!fd.fbody)
return;
UnitTestDeclaration ud = fd.isUnitTestDeclaration();
if (ud && !global.params.useUnitTests)
return;
if (multiobj && !fd.isStaticDtorDeclaration() && !fd.isStaticCtorDeclaration()
&& !(fd.flags & (FUNCFLAG.CRTCtor | FUNCFLAG.CRTDtor)))
{
obj_append(fd);
return;
}
if (fd.semanticRun == PASS.semanticdone)
{
/* What happened is this function failed semantic3() with errors,
* but the errors were gagged.
* Try to reproduce those errors, and then fail.
*/
fd.error("errors compiling the function");
return;
}
assert(fd.semanticRun == PASS.semantic3done);
assert(fd.ident != Id.empty);
for (FuncDeclaration fd2 = fd; fd2; )
{
if (fd2.inNonRoot())
return;
if (fd2.isNested())
fd2 = fd2.toParent2().isFuncDeclaration();
else
break;
}
if (UnitTestDeclaration udp = needsDeferredNested(fd))
{
/* Can't do unittest's out of order, they are order dependent in that their
* execution is done in lexical order.
*/
udp.deferredNested.push(fd);
//printf("%s @[%s]\n\t-. pushed to unittest @[%s]\n",
// fd.toPrettyChars(), fd.loc.toChars(), udp.loc.toChars());
return;
}
// start code generation
fd.semanticRun = PASS.obj;
if (global.params.verbose)
message("function %s", fd.toPrettyChars());
Symbol *s = toSymbol(fd);
func_t *f = s.Sfunc;
// tunnel type of "this" to debug info generation
if (AggregateDeclaration ad = fd.parent.isAggregateDeclaration())
{
.type* t = Type_toCtype(ad.getType());
if (cd)
t = t.Tnext; // skip reference
f.Fclass = cast(Classsym *)t;
}
/* This is done so that the 'this' pointer on the stack is the same
* distance away from the function parameters, so that an overriding
* function can call the nested fdensure or fdrequire of its overridden function
* and the stack offsets are the same.
*/
if (fd.isVirtual() && (fd.fensure || fd.frequire))
f.Fflags3 |= Ffakeeh;
if (fd.hasNoEH())
// Same as config.ehmethod==EH_NONE, but only for this function
f.Fflags3 |= Feh_none;
s.Sclass = target.os == Target.OS.OSX ? SCcomdat : SCglobal;
/* Make C static functions SCstatic
*/
if (fd.storage_class & STC.static_ && fd.isCsymbol())
s.Sclass = SCstatic;
for (Dsymbol p = fd.parent; p; p = p.parent)
{
if (p.isTemplateInstance())
{
// functions without D or C++ name mangling mixed in at global scope
// shouldn't have multiple definitions
const linkage = fd.resolvedLinkage();
if (p.isTemplateMixin() && (linkage == LINK.c || linkage == LINK.windows ||
linkage == LINK.objc))
{
const q = p.toParent();
if (q && q.isModule())
{
s.Sclass = SCglobal;
break;
}
}
s.Sclass = SCcomdat;
break;
}
}
if (fd.inlinedNestedCallees)
{
/* https://issues.dlang.org/show_bug.cgi?id=15333
* If fd contains inlined expressions that come from
* nested function bodies, the enclosing of the functions must be
* generated first, in order to calculate correct frame pointer offset.
*/
foreach (fdc; *fd.inlinedNestedCallees)
{
FuncDeclaration fp = fdc.toParent2().isFuncDeclaration();
if (fp && fp.semanticRun < PASS.obj)
{
toObjFile(fp, multiobj);
}
}
}
if (fd.isNested())
{
//if (!(config.flags3 & CFG3pic))
// s.Sclass = SCstatic;
f.Fflags3 |= Fnested;
/* The enclosing function must have its code generated first,
* in order to calculate correct frame pointer offset.
*/
FuncDeclaration fdp = fd.toParent2().isFuncDeclaration();
if (fdp && fdp.semanticRun < PASS.obj)
{
toObjFile(fdp, multiobj);
}
}
else
{
specialFunctions(objmod, fd);
}
symtab_t *symtabsave = cstate.CSpsymtab;
cstate.CSpsymtab = &f.Flocsym;
// Find module m for this function
Module m = null;
for (Dsymbol p = fd.parent; p; p = p.parent)
{
m = p.isModule();
if (m)
break;
}
Dsymbols deferToObj; // write these to OBJ file later
Array!(elem*) varsInScope;
Label*[void*] labels = null;
IRState irs = IRState(m, fd, &varsInScope, &deferToObj, &labels, &global.params, &target);
Symbol *shidden = null;
Symbol *sthis = null;
tym_t tyf = tybasic(s.Stype.Tty);
//printf("linkage = %d, tyf = x%x\n", linkage, tyf);
int reverse = tyrevfunc(s.Stype.Tty);
assert(fd.type.ty == Tfunction);
TypeFunction tf = cast(TypeFunction)fd.type;
RET retmethod = retStyle(tf, fd.needThis());
if (retmethod == RET.stack)
{
// If function returns a struct, put a pointer to that
// as the first argument
.type *thidden = Type_toCtype(tf.next.pointerTo());
char[5 + 10 + 1] hiddenparam = void;
__gshared uint hiddenparami; // how many we've generated so far
const(char)* name;
if (fd.isNRVO() && fd.nrvo_var)
name = fd.nrvo_var.ident.toChars();
else
{
sprintf(hiddenparam.ptr, "__HID%u", ++hiddenparami);
name = hiddenparam.ptr;
}
shidden = symbol_name(name, SCparameter, thidden);
shidden.Sflags |= SFLtrue | SFLfree;
if (fd.isNRVO() && fd.nrvo_var && fd.nrvo_var.nestedrefs.dim)
type_setcv(&shidden.Stype, shidden.Stype.Tty | mTYvolatile);
irs.shidden = shidden;
fd.shidden = shidden;
}
else
{
// Register return style cannot make nrvo.
// Auto functions keep the NRVO flag up to here,
// so we should eliminate it before entering backend.
fd.flags &= ~FUNCFLAG.NRVO;
}
if (fd.vthis)
{
assert(!fd.vthis.csym);
sthis = toSymbol(fd.vthis);
sthis.Stype = getParentClosureType(sthis, fd);
irs.sthis = sthis;
if (!(f.Fflags3 & Fnested))
f.Fflags3 |= Fmember;
}
// Estimate number of parameters, pi
size_t pi = (fd.v_arguments !is null);
if (fd.parameters)
pi += fd.parameters.dim;
if (fd.objc.selector)
pi++; // Extra argument for Objective-C selector
// Create a temporary buffer, params[], to hold function parameters
Symbol*[10] paramsbuf = void;
Symbol **params = paramsbuf.ptr; // allocate on stack if possible
if (pi + 2 > paramsbuf.length) // allow extra 2 for sthis and shidden
{
params = cast(Symbol **)Mem.check(malloc((pi + 2) * (Symbol *).sizeof));
}
// Get the actual number of parameters, pi, and fill in the params[]
pi = 0;
if (fd.v_arguments)
{
params[pi] = toSymbol(fd.v_arguments);
pi += 1;
}
if (fd.parameters)
{
foreach (i, v; *fd.parameters)
{
//printf("param[%d] = %p, %s\n", i, v, v.toChars());
assert(!v.csym);
params[pi + i] = toSymbol(v);
}
pi += fd.parameters.dim;
}
if (reverse)
{
// Reverse params[] entries
foreach (i, sptmp; params[0 .. pi/2])
{
params[i] = params[pi - 1 - i];
params[pi - 1 - i] = sptmp;
}
}
if (shidden)
{
// shidden becomes last parameter
//params[pi] = shidden;
// shidden becomes first parameter
memmove(params + 1, params, pi * (params[0]).sizeof);
params[0] = shidden;
pi++;
}
pi = objc.addSelectorParameterSymbol(fd, params, pi);
if (sthis)
{
// sthis becomes last parameter
//params[pi] = sthis;
// sthis becomes first parameter
memmove(params + 1, params, pi * (params[0]).sizeof);
params[0] = sthis;
pi++;
}
if (target.isPOSIX && fd._linkage != LINK.d && shidden && sthis)
{
/* swap shidden and sthis
*/
Symbol *sp = params[0];
params[0] = params[1];
params[1] = sp;
}
foreach (sp; params[0 .. pi])
{
sp.Sclass = SCparameter;
sp.Sflags &= ~SFLspill;
sp.Sfl = FLpara;
symbol_add(sp);
}
// Determine register assignments
if (pi)
{
FuncParamRegs fpr = FuncParamRegs.create(tyf);
foreach (sp; params[0 .. pi])
{
if (fpr.alloc(sp.Stype, sp.Stype.Tty, &sp.Spreg, &sp.Spreg2))
{
sp.Sclass = (target.os == Target.OS.Windows && target.is64bit) ? SCshadowreg : SCfastpar;
sp.Sfl = (sp.Sclass == SCshadowreg) ? FLpara : FLfast;
}
}
}
// Done with params
if (params != paramsbuf.ptr)
free(params);
params = null;
localgot = null;
Statement sbody = fd.fbody;
Blockx bx;
bx.startblock = block_calloc();
bx.curblock = bx.startblock;
bx.funcsym = s;
bx.scope_index = -1;
bx.classdec = cast(void*)cd;
bx.member = cast(void*)fd;
bx._module = cast(void*)fd.getModule();
irs.blx = &bx;
// Initialize argptr
if (fd.v_argptr)
{
// Declare va_argsave
if (target.is64bit &&
target.os & Target.OS.Posix)
{
type *t = type_struct_class("__va_argsave_t", 16, 8 * 6 + 8 * 16 + 8 * 3, null, null, false, false, true, false);
// The backend will pick this up by name
Symbol *sv = symbol_name("__va_argsave", SCauto, t);
sv.Stype.Tty |= mTYvolatile;
symbol_add(sv);
}
// Declare _argptr, but only for D files
if (!irs.Cfile)
{
Symbol *sa = toSymbol(fd.v_argptr);
symbol_add(sa);
elem *e = el_una(OPva_start, TYnptr, el_ptr(sa));
block_appendexp(irs.blx.curblock, e);
}
}
/* Doing this in semantic3() caused all kinds of problems:
* 1. couldn't reliably get the final mangling of the function name due to fwd refs
* 2. impact on function inlining
* 3. what to do when writing out .di files, or other pretty printing
*/
if (global.params.trace && !fd.isCMain() && !fd.isNaked() && !(fd.hasReturnExp & 8))
{
/* The profiler requires TLS, and TLS may not be set up yet when C main()
* gets control (i.e. OSX), leading to a crash.
*/
/* Wrap the entire function body in:
* trace_pro("funcname");
* try
* body;
* finally
* _c_trace_epi();
*/
StringExp se = StringExp.create(Loc.initial, s.Sident.ptr);
se.type = Type.tstring;
se.type = se.type.typeSemantic(Loc.initial, null);
Expressions *exps = new Expressions();
exps.push(se);
FuncDeclaration fdpro = FuncDeclaration.genCfunc(null, Type.tvoid, "trace_pro");
Expression ec = VarExp.create(Loc.initial, fdpro);
Expression e = CallExp.create(Loc.initial, ec, exps);
e.type = Type.tvoid;
Statement sp = ExpStatement.create(fd.loc, e);
FuncDeclaration fdepi = FuncDeclaration.genCfunc(null, Type.tvoid, "_c_trace_epi");
ec = VarExp.create(Loc.initial, fdepi);
e = CallExp.create(Loc.initial, ec);
e.type = Type.tvoid;
Statement sf = ExpStatement.create(fd.loc, e);
Statement stf;
if (sbody.blockExit(fd, false) == BE.fallthru)
stf = CompoundStatement.create(Loc.initial, sbody, sf);
else
stf = TryFinallyStatement.create(Loc.initial, sbody, sf);
sbody = CompoundStatement.create(Loc.initial, sp, stf);
}
if (fd.interfaceVirtual)
{
// Adjust the 'this' pointer instead of using a thunk
assert(irs.sthis);
elem *ethis = el_var(irs.sthis);
ethis = fixEthis2(ethis, fd);
elem *e = el_bin(OPminass, TYnptr, ethis, el_long(TYsize_t, fd.interfaceVirtual.offset));
block_appendexp(irs.blx.curblock, e);
}
buildClosure(fd, &irs);
if (config.ehmethod == EHmethod.EH_WIN32 && fd.isSynchronized() && cd &&
!fd.isStatic() && !sbody.usesEH() && !global.params.trace)
{
/* The "jmonitor" hack uses an optimized exception handling frame
* which is a little shorter than the more general EH frame.
*/
s.Sfunc.Fflags3 |= Fjmonitor;
}
Statement_toIR(sbody, &irs);
if (global.errors)
{
// Restore symbol table
cstate.CSpsymtab = symtabsave;
return;
}
bx.curblock.BC = BCret;
f.Fstartblock = bx.startblock;
// einit = el_combine(einit,bx.init);
if (fd.isCtorDeclaration())
{
assert(sthis);
foreach (b; BlockRange(f.Fstartblock))
{
if (b.BC == BCret)
{
elem *ethis = el_var(sthis);
ethis = fixEthis2(ethis, fd);
b.BC = BCretexp;
b.Belem = el_combine(b.Belem, ethis);
}
}
}
if (config.ehmethod == EHmethod.EH_NONE || f.Fflags3 & Feh_none)
insertFinallyBlockGotos(f.Fstartblock);
else if (config.ehmethod == EHmethod.EH_DWARF)
insertFinallyBlockCalls(f.Fstartblock);
// If static constructor
if (fd.isSharedStaticCtorDeclaration()) // must come first because it derives from StaticCtorDeclaration
{
glue.ssharedctors.push(s);
}
else if (fd.isStaticCtorDeclaration())
{
glue.sctors.push(s);
}
// If static destructor
if (fd.isSharedStaticDtorDeclaration()) // must come first because it derives from StaticDtorDeclaration
{
SharedStaticDtorDeclaration fs = fd.isSharedStaticDtorDeclaration();
assert(fs);
if (fs.vgate)
{
/* Increment destructor's vgate at construction time
*/
glue.esharedctorgates.push(fs);
}
glue.sshareddtors.shift(s);
}
else if (fd.isStaticDtorDeclaration())
{
StaticDtorDeclaration fs = fd.isStaticDtorDeclaration();
assert(fs);
if (fs.vgate)
{
/* Increment destructor's vgate at construction time
*/
glue.ectorgates.push(fs);
}
glue.sdtors.shift(s);
}
// If unit test
if (ud)
{
glue.stests.push(s);
}
if (global.errors)
{
// Restore symbol table
cstate.CSpsymtab = symtabsave;
return;
}
writefunc(s); // hand off to backend
buildCapture(fd);
// Restore symbol table
cstate.CSpsymtab = symtabsave;
if (fd.isExport())
objmod.export_symbol(s, cast(uint)Para.offset);
if (fd.flags & FUNCFLAG.CRTCtor)
objmod.setModuleCtorDtor(s, true);
if (fd.flags & FUNCFLAG.CRTDtor)
{
//See TargetC.initialize
if(target.c.crtDestructorsSupported)
{
objmod.setModuleCtorDtor(s, false);
} else
{
/*
https://issues.dlang.org/show_bug.cgi?id=22520
Apple radar: https://openradar.appspot.com/FB9733712
Apple deprecated the mechanism used to implement `crt_destructor`
on MacOS Monterey. This works around that by generating a new function
(crt_destructor_thunk_NNN, run as a constructor) which registers
the destructor-to-be using __cxa_atexit()
This workaround may need a further look at when it comes to
shared library support, however there is no bridge for
that spilt milk to flow under yet.
This relies on the Itanium ABI so is portable to any
platform it, if needed.
*/
__gshared uint nthDestructor = 0;
char* buf = cast(char*) calloc(50, 1);
assert(buf);
const ret = snprintf(buf, 100, "_dmd_crt_destructor_thunk.%u", nthDestructor++);
assert(ret >= 0 && ret < 100, "snprintf either failed or overran buffer");
//Function symbol
auto newConstructor = symbol_calloc(buf);
//Build type
newConstructor.Stype = type_function(TYnfunc, [], false, type_alloc(TYvoid));
//Tell it it's supposed to be a C function. Does it do anything? Not sure.
type_setmangle(&newConstructor.Stype, mTYman_c);
symbol_func(newConstructor);
//Global SC for now.
newConstructor.Sclass = SCstatic;
func_t* funcState = newConstructor.Sfunc;
//Init start block
funcState.Fstartblock = block_calloc();
block* startBlk = funcState.Fstartblock;
//Make that block run __cxa_atexit(&func);
auto atexitSym = getRtlsym(RTLSYM.CXA_ATEXIT);
Symbol* dso_handle = symbol_calloc("__dso_handle");
dso_handle.Stype = type_fake(TYint);
//Try to get MacOS _ prefix-ism right.
type_setmangle(&dso_handle.Stype, mTYman_c);
dso_handle.Sfl = FLextern;
dso_handle.Sclass = SCextern;
dso_handle.Stype.Tcount++;
auto handlePtr = el_ptr(dso_handle);
//Build parameter pack - __cxa_atexit(&func, null, null)
auto paramPack = el_params(handlePtr, el_long(TYnptr, 0), el_ptr(s), null);
auto exec = el_bin(OPcall, TYvoid, el_var(atexitSym), paramPack);
block_appendexp(startBlk, exec); //payload
startBlk.BC = BCgoto;
auto next = block_calloc();
startBlk.appendSucc(next);
startBlk.Bnext = next;
next.BC = BCret;
//Emit in binary
writefunc(newConstructor);
//Mark as a CONSTRUCTOR because our thunk implements the destructor
objmod.setModuleCtorDtor(newConstructor, true);
}
}
foreach (sd; *irs.deferToObj)
{
toObjFile(sd, false);
}
if (ud)
{
foreach (fdn; ud.deferredNested)
{
toObjFile(fdn, false);
}
}
if (irs.startaddress)
{
//printf("Setting start address\n");
objmod.startaddress(irs.startaddress);
}
}
/*******************************************
* Detect special functions like `main()` and do special handling for them,
* like special mangling, including libraries, setting the storage class, etc.
* `objmod` and `fd` are updated.
*
* Params:
* objmod = object module
* fd = function symbol
*/
private void specialFunctions(Obj objmod, FuncDeclaration fd)
{
const libname = finalDefaultlibname();
Symbol* s = fd.toSymbol(); // backend symbol corresponding to fd
// Pull in RTL startup code (but only once)
if (fd.isMain() && onlyOneMain(fd.loc))
{
final switch (target.objectFormat())
{
case Target.ObjectFormat.elf:
case Target.ObjectFormat.macho:
objmod.external_def("_main");
break;
case Target.ObjectFormat.coff:
objmod.external_def("main");
break;
case Target.ObjectFormat.omf:
objmod.external_def("_main");
objmod.external_def("__acrtused_con");
break;
}
if (libname)
obj_includelib(libname);
s.Sclass = SCglobal;
return;
}
else if (fd.isRtInit())
{
final switch (target.objectFormat())
{
case Target.ObjectFormat.elf:
case Target.ObjectFormat.macho:
case Target.ObjectFormat.coff:
objmod.ehsections(); // initialize exception handling sections
break;
case Target.ObjectFormat.omf:
break;
}
return;
}
void includeWinLibs(bool cmain, const(char)* omflib)
{
if (target.objectFormat() == Target.ObjectFormat.coff)
{
if (!cmain)
objmod.includelib("uuid");
if (driverParams.mscrtlib.length && driverParams.mscrtlib[0])
obj_includelib(driverParams.mscrtlib);
objmod.includelib("OLDNAMES");
}
else if (target.objectFormat() == Target.ObjectFormat.omf)
{
if (cmain)
{
objmod.external_def("__acrtused_con"); // bring in C startup code
objmod.includelib("snn.lib"); // bring in C runtime library
}
else
{
objmod.external_def(omflib);
}
}
}
if (fd.isCMain())
{
includeWinLibs(true, "");
s.Sclass = SCglobal;
}
else if (target.os == Target.OS.Windows && fd.isWinMain() && onlyOneMain(fd.loc))
{
includeWinLibs(false, "__acrtused");
if (libname)
obj_includelib(libname);
s.Sclass = SCglobal;
}
// Pull in RTL startup code
else if (target.os == Target.OS.Windows && fd.isDllMain() && onlyOneMain(fd.loc))
{
includeWinLibs(false, "__acrtused_dll");
if (libname)
obj_includelib(libname);
s.Sclass = SCglobal;
}
}
private bool onlyOneMain(Loc loc)
{
__gshared Loc lastLoc;
__gshared bool hasMain = false;
if (hasMain)
{
const(char)* otherMainNames = "";
if (target.os == Target.OS.Windows)
otherMainNames = ", `WinMain`, or `DllMain`";
error(loc, "only one `main`%s allowed. Previously found `main` at %s",
otherMainNames, lastLoc.toChars());
return false;
}
lastLoc = loc;
hasMain = true;
return true;
}
/* ================================================================== */
/*****************************
* Return back end type corresponding to D front end type.
*/
tym_t totym(Type tx)
{
tym_t t;
switch (tx.ty)
{
case Tvoid: t = TYvoid; break;
case Tint8: t = TYschar; break;
case Tuns8: t = TYuchar; break;
case Tint16: t = TYshort; break;
case Tuns16: t = TYushort; break;
case Tint32: t = TYint; break;
case Tuns32: t = TYuint; break;
case Tint64: t = TYllong; break;
case Tuns64: t = TYullong; break;
case Tfloat32: t = TYfloat; break;
case Tfloat64: t = TYdouble; break;
case Tfloat80: t = TYldouble; break;
case Timaginary32: t = TYifloat; break;
case Timaginary64: t = TYidouble; break;
case Timaginary80: t = TYildouble; break;
case Tcomplex32: t = TYcfloat; break;
case Tcomplex64: t = TYcdouble; break;
case Tcomplex80: t = TYcldouble; break;
case Tbool: t = TYbool; break;
case Tchar: t = TYchar; break;
case Twchar: t = TYwchar_t; break;
case Tdchar:
t = (driverParams.symdebug == 1 || target.os & Target.OS.Posix) ? TYdchar : TYulong;
break;
case Taarray: t = TYaarray; break;
case Tclass:
case Treference:
case Tpointer: t = TYnptr; break;
case Tdelegate: t = TYdelegate; break;
case Tarray: t = TYdarray; break;
case Tsarray: t = TYstruct; break;
case Tnoreturn: t = TYnoreturn; break;
case Tstruct:
t = TYstruct;
break;
case Tenum:
{
Type tb = tx.toBasetype();
const id = tx.toDsymbol(null).ident;
if (id == Id.__c_long)
t = tb.ty == Tint32 ? TYlong : TYllong;
else if (id == Id.__c_ulong)
t = tb.ty == Tuns32 ? TYulong : TYullong;
else if (id == Id.__c_long_double)
t = TYdouble;
else if (id == Id.__c_complex_float)
t = TYcfloat;
else if (id == Id.__c_complex_double)
t = TYcdouble;
else if (id == Id.__c_complex_real)
t = TYcldouble;
else
t = totym(tb);
break;
}
case Tident:
case Ttypeof:
case Tmixin:
//printf("ty = %d, '%s'\n", tx.ty, tx.toChars());
error(Loc.initial, "forward reference of `%s`", tx.toChars());
t = TYint;
break;
case Tnull:
t = TYnptr;
break;
case Tvector:
{
auto tv = cast(TypeVector)tx;
const tb = tv.elementType();
const s32 = tv.alignsize() == 32; // if 32 byte, 256 bit vector
switch (tb.ty)
{
case Tvoid:
case Tint8: t = s32 ? TYschar32 : TYschar16; break;
case Tuns8: t = s32 ? TYuchar32 : TYuchar16; break;
case Tint16: t = s32 ? TYshort16 : TYshort8; break;
case Tuns16: t = s32 ? TYushort16 : TYushort8; break;
case Tint32: t = s32 ? TYlong8 : TYlong4; break;
case Tuns32: t = s32 ? TYulong8 : TYulong4; break;
case Tint64: t = s32 ? TYllong4 : TYllong2; break;
case Tuns64: t = s32 ? TYullong4 : TYullong2; break;
case Tfloat32: t = s32 ? TYfloat8 : TYfloat4; break;
case Tfloat64: t = s32 ? TYdouble4 : TYdouble2; break;
default:
assert(0);
}
break;
}
case Tfunction:
{
auto tf = cast(TypeFunction)tx;
final switch (tf.linkage)
{
case LINK.windows:
if (target.is64bit)
goto case LINK.c;
t = (tf.parameterList.varargs == VarArg.variadic) ? TYnfunc : TYnsfunc;
break;
case LINK.c:
case LINK.cpp:
case LINK.objc:
t = TYnfunc;
if (target.os == Target.OS.Windows)
{
}
else if (!target.is64bit && retStyle(tf, false) == RET.stack)
t = TYhfunc;
break;
case LINK.d:
t = (tf.parameterList.varargs == VarArg.variadic) ? TYnfunc : TYjfunc;
break;
case LINK.default_:
case LINK.system:
printf("linkage = %d\n", tf.linkage);
assert(0);
}
if (tf.isnothrow)
t |= mTYnothrow;
return t;
}
default:
//printf("ty = %d, '%s'\n", tx.ty, tx.toChars());
assert(0);
}
t |= modToTym(tx.mod); // Add modifiers
return t;
}
/**************************************
*/
Symbol *toSymbol(Type t)
{
if (t.ty == Tclass)
{
return toSymbol((cast(TypeClass)t).sym);
}
assert(0);
}
/*******************************************
* Generate readonly symbol that consists of a bunch of zeros.
* Immutable Symbol instances can be mapped over it.
* Only one is generated per object file.
* Returns:
* bzero symbol
*/
Symbol* getBzeroSymbol()
{
Symbol* s = bzeroSymbol;
if (s)
return s;
s = symbol_calloc("__bzeroBytes");
s.Stype = type_static_array(128, type_fake(TYuchar));
s.Stype.Tmangle = mTYman_c;
s.Stype.Tcount++;
s.Sclass = SCglobal;
s.Sfl = FLdata;
s.Sflags |= SFLnodebug;
s.Salignment = 16;
auto dtb = DtBuilder(0);
dtb.nzeros(128);
s.Sdt = dtb.finish();
dt2common(&s.Sdt);
outdata(s);
bzeroSymbol = s;
return s;
}
/**************************************
* Generate elem that is a dynamic array slice of the module file name.
*/
private elem *toEfilename(Module m)
{
//printf("toEfilename(%s)\n", m.toChars());
const(char)* id = m.srcfile.toChars();
size_t len = strlen(id);
if (!m.sfilename)
{
// Put out as a static array
m.sfilename = toStringSymbol(id, len, 1);
}
// Turn static array into dynamic array
return el_pair(TYdarray, el_long(TYsize_t, len), el_ptr(m.sfilename));
}
// Used in e2ir.d
elem *toEfilenamePtr(Module m)
{
//printf("toEfilenamePtr(%s)\n", m.toChars());
const(char)* id = m.srcfile.toChars();
size_t len = strlen(id);
Symbol* s = toStringSymbol(id, len, 1);
return el_ptr(s);
}
|
D
|
// *********************************************************************
// main menu (startup)
// *********************************************************************
INSTANCE MENU_MAIN(C_MENU_DEF)
{
backpic = MENU_BACK_PIC;
musictheme = "SYS_Menu";
items[0] = "MENUITEM_MAIN_HEADLINE";
items[1] = "MENUITEM_MAIN_HEADLINE2";
items[2] = "MENUITEM_MAIN_NEWGAME";
items[3] = "MENUITEM_MAIN_SAVEGAME_LOAD";
items[4] = "MENUITEM_MAIN_SAVEGAME_SAVE";
items[5] = "MENUITEM_MAIN_RESUME";
items[6] = "MENUITEM_MAIN_OPTIONS";
items[7] = "MENUITEM_MAIN_INTRO";
items[8] = "MENUITEM_MAIN_CREDITS";
items[9] = "MENUITEM_MAIN_EXIT";
defaultOutGame = 2; // NEWGAME
defaultInGame = 4; // SAVEGAME
flags = flags | MENU_SHOW_INFO;
};
const int MENU_MAIN_DY = 550;
const int MENU_MAIN_Y = 2500;
//
// NEW GAME
//
instance MENUITEM_MAIN_NEWGAME(C_MENU_ITEM_DEF)
{
backpic = MENU_ITEM_BACK_PIC;
text[0] = "New Game";
text[1] = "Start a new adventure."; // Kommentar
// Positionen und Dimensionen
posx = 0; posy = MENU_MAIN_Y + MENU_MAIN_DY*0;
dimx = 8100; dimy = 750;
// Aktionen
onSelAction[0] = SEL_ACTION_CLOSE;
onSelAction_S[0]= "NEW_GAME";
// Weitere Eigenschaften
flags = flags | IT_TXT_CENTER;
};
//
// LOAD & SAVE GAME
//
INSTANCE MENUITEM_MAIN_SAVEGAME_LOAD(C_MENU_ITEM_DEF)
{
backpic = MENU_ITEM_BACK_PIC;
text[0] = "Load Game";
text[1] = "Load a saved game."; // Kommentar
// Positionen und Dimensionen
posx = 0; posy = MENU_MAIN_Y + MENU_MAIN_DY*1;
dimx = 8100; dimy = 750;
// Aktionen
onSelAction_S[0]= "MENU_SAVEGAME_LOAD";
onSelAction[0] = SEL_ACTION_STARTMENU;
// Weitere Eigenschaften
flags = flags | IT_TXT_CENTER;
};
instance MENUITEM_MAIN_SAVEGAME_SAVE(C_MENU_ITEM_DEF)
{
backpic = MENU_ITEM_BACK_PIC;
text[0] = "Save Game";
text[1] = "Save current game."; // Kommentar
// Positionen und Dimensionen
posx = 0; posy = MENU_MAIN_Y + MENU_MAIN_DY*2;
dimx = 8100; dimy = 750;
// Aktionen
onSelAction_S[0]= "MENU_SAVEGAME_SAVE";
onSelAction[0] = SEL_ACTION_STARTMENU;
// Weitere Eigenschaften
flags = flags | IT_TXT_CENTER | IT_ONLY_IN_GAME;
};
//
// RESUME
//
INSTANCE MENUITEM_MAIN_RESUME(C_MENU_ITEM_DEF)
{
backpic = MENU_ITEM_BACK_PIC;
text[0] = "Continue";
text[1] = "Continue current game."; // Kommentar
// Position und Dimension
posx = 0; posy = MENU_MAIN_Y + MENU_MAIN_DY*3;
dimx = 8192; dimy = 750;
// Aktionen
onSelAction[0] = SEL_ACTION_BACK;
// Weitere Eigenschaften
flags = flags | IT_TXT_CENTER | IT_ONLY_IN_GAME;
};
//
// OPTIONS, INTRO & CREDITS
//
instance MENUITEM_MAIN_OPTIONS(C_MENU_ITEM_DEF)
{
backpic = MENU_ITEM_BACK_PIC;
text[0] = "Settings";
text[1] = "Adjust game, graphics, sound and keyboard"; // Kommentar
// Positionen und Dimensionen
posx = 0; posy = MENU_MAIN_Y + MENU_MAIN_DY*4;
dimx = 8100; dimy = 750;
// Aktionen
onSelAction[0] = SEL_ACTION_STARTMENU;
onSelAction_S[0]= "MENU_OPTIONS";
// Weitere Eigenschaften
flags = flags | IT_TXT_CENTER;
};
instance MENUITEM_MAIN_INTRO(C_MENU_ITEM_DEF)
{
backpic = MENU_ITEM_BACK_PIC;
text[0] = "Play Intro";
text[1] = "Play intro sequence again.";
// Positionen und Dimensione
posx = 0; posy = MENU_MAIN_Y + MENU_MAIN_DY*5;
dimx = 8100; dimy = 750;
// Aktionen
onSelAction[0] = SEL_ACTION_UNDEF;
onEventAction[EVENT_EXECUTE] = ShowIntro;
// Weitere Eigenschaften
flags = flags | IT_TXT_CENTER;
};
INSTANCE MENUITEM_MAIN_CREDITS(C_MENU_ITEM_DEF)
{
backpic = MENU_ITEM_BACK_PIC;
text[0] = "Credits";
text[1] = "Credits"; // Kommentar
// Positionen und Dimensionen
posx = 0; posy = MENU_MAIN_Y + MENU_MAIN_DY*6;
dimx = 8100; dimy = 750;
// Aktionen
onSelAction[0] = SEL_ACTION_UNDEF;
onEventAction[EVENT_EXECUTE] = ShowCredits;
// Weitere Eigenschaften
flags = flags | IT_TXT_CENTER;
};
//
// EXIT
//
INSTANCE MENUITEM_MAIN_EXIT(C_MENU_ITEM_DEF)
{
backpic = MENU_ITEM_BACK_PIC;
text[0] = "Quit Gothic";
text[1] = "Leave the world of Gothic."; // Kommentar
// Positionen und Dimensionen
posx = 0; posy = MENU_MAIN_Y + MENU_MAIN_DY*7;
dimx = 8100; dimy = 750;
// Aktionen
onSelAction[0] = SEL_ACTION_STARTMENU;
onSelAction_S[0]= "MENU_LEAVE_GAME";
// Weitere Eigenschaften
flags = flags | IT_TXT_CENTER;
};
//
// Statische Items
//
INSTANCE MENUITEM_MAIN_HEADLINE2(C_MENU_ITEM_DEF)
{
backPic = "menu_gothic.tga";
// Positionen und Dimensionen
posx = 250; posy = 500;
dimx = 7900; dimy = 2300;
// Weitere Eigenschaften
alphaMode = "BLEND";
alpha = 255;
flags = flags | IT_TXT_CENTER;
flags = flags & ~IT_SELECTABLE;
};
INSTANCE MENUITEM_MAIN_HEADLINE(C_MENU_ITEM_DEF)
{
backPic = "menu_gothicshadow.tga";
// Positionen und Dimensionen
posx = 250; posy = 500;
dimx = 7900; dimy = 2300;
// Weitere Eigenschaften
alphaMode = "BLEND";
alpha = 220;
flags = flags | IT_TXT_CENTER;
flags = flags & ~IT_SELECTABLE;
};
func int ShowIntro()
{
PlayVideo("intro.bik");
return 1;
};
func int ShowCredits()
{
PlayVideo("credits.bik");
return 1;
};
|
D
|
module time.WallClock;
public import time.Time, time.Clock, sys.Common;
struct Куранты
{
static Время сейчас ();
static ИнтервалВремени зона ();
static ДатаВремя вДату ();
static ДатаВремя вДату (Время utc);
static Время изДаты (ref ДатаВремя дата);
static Время вМестное (Время utc);
static Время toUtc (Время wall);
}
|
D
|
<?xml version="1.0" encoding="UTF-8"?>
<di:SashWindowsMngr xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:di="http://www.eclipse.org/papyrus/0.7.0/sashdi">
<pageList>
<availablePage>
<emfPageIdentifier href="Verify3.notation#_akMKgD2qEeO0W5WLsM8PpQ"/>
</availablePage>
</pageList>
<sashModel currentSelection="//@sashModel/@windows.0/@children.0">
<windows>
<children xsi:type="di:TabFolder">
<children>
<emfPageIdentifier href="Verify3.notation#_akMKgD2qEeO0W5WLsM8PpQ"/>
</children>
</children>
</windows>
</sashModel>
</di:SashWindowsMngr>
|
D
|
module mud.memory.memstream;
private import mud.container.growing;
private import std.exception : assertThrown;
private import core.exception : AssertError;
/// Output memory stream. Convenient for accessing elements in a byte array
struct OMemStream
{
/// Check if the stream had ended
@property bool eof() @nogc @safe nothrow { return pos >= data.length; }
///
@safe unittest
{
ubyte[1] data = [13];
auto stream = OMemStream(data);
stream.read!ubyte;
assert(stream.eof);
}
/// Constructs new output memory stream from `data`
@safe @nogc this(ubyte[] data) nothrow
{
this.data = data;
}
///
@safe unittest
{
ubyte[4] data = [0, 0, 0, 0];
const stream = OMemStream(data);
}
/// Read `size` bytes from the stream
ubyte[] read(size_t size) @safe @nogc nothrow
in(!eof)
{
if(pos + size > data.length)
size = data.length - pos;
ubyte[] ret = data[pos .. pos+size];
pos += size;
return ret;
}
///
@trusted unittest
{
ubyte[4] data = [0, 1, 2, 3];
auto stream = OMemStream(data);
const res = stream.read(4);
assert(res == data);
assertThrown!AssertError(stream.read(1));
}
/// Read an element from stream. If there are no elements, returns default constructed `T`
T read(T)() @trusted @nogc nothrow
{
if(pos + T.sizeof > data.length)
return T();
T val = *cast(T*)(data.ptr + pos);
pos += T.sizeof;
return val;
}
///
@safe unittest
{
ubyte[1] data = [13];
auto stream = OMemStream(data);
assert(stream.read!ubyte == 13);
assert(stream.read!ubyte == ubyte.init);
}
private:
size_t pos;
ubyte[] data;
}
@safe unittest
{
ubyte[7] check = [10, 11, 0, 14, 0, 0, 0];
auto os = OMemStream(check);
immutable a = os.read!ubyte;
immutable b = os.read!short;
immutable c = os.read!int;
assert(a == 10);
assert(b == 11);
assert(c == 14);
assert(os.eof);
}
// Unittest for reading more data than there is
@safe unittest
{
ubyte[7] check = [10, 11, 0, 14, 0, 0, 0];
auto os = OMemStream(check);
const r = os.read(10);
assert(r.length == 7);
assert(os.eof);
}
/// Input memory stream. Convenient for storing elements in a byte array
/// default size is 100KB
struct IMemStream(size_t back_sz = 100 * 1024)
{
/// Returns a copy of underlying bytes
@property ubyte[] getBytes() @safe nothrow
{
ubyte[] ret = new ubyte[sz];
ret[0 .. sz] = bytes.get[0 .. sz];
return ret;
}
///
@safe unittest
{
immutable ubyte[1] check = [13];
IMemStream m;
m.put!ubyte(13);
assert(check == m.getBytes);
}
/// Returns underlying bytes. MAY LEAK REFERENCES
@property ubyte[] peekBytes() @safe @nogc nothrow { return bytes.get[0 .. sz]; }
///
@safe unittest
{
immutable ubyte[1] check = [13];
IMemStream m;
m.put!ubyte(13);
assert(check == m.peekBytes);
}
/// Put an element of type `T` into the stream
void put(T)(T val) @trusted nothrow
{
ubyte *back = cast(ubyte*)&val;
foreach(e; back[0 .. T.sizeof])
bytes.put(e);
sz += T.sizeof;
}
///
@safe unittest
{
IMemStream m;
m.put!ubyte(13);
m.put!int(1_333_333);
m.put!double(0.31);
}
/// Put a string into the stream
void put(T : string)(T data) @safe @nogc nothrow
{
foreach(c; data)
{
bytes.put(cast(ubyte)c);
sz++;
}
}
///
@safe unittest
{
string test = "Hello, world!";
IMemStream stream;
stream.put(test);
for(int i=0; i<test.length; i++)
assert(stream.getBytes[i] == test[i]);
}
/// Put a byte array into the stream
void put(T : ubyte[])(T data) @safe @nogc nothrow
{
foreach(e; data)
bytes.put(e);
sz += data.length;
}
///
@safe unittest
{
ubyte[4] data = [10, 11, 12, 13];
IMemStream stream;
stream.put(data);
for(int i=0; i<4; i++)
assert(stream.getBytes[i] == data[i]);
}
/// ditto
void put(T : const(ubyte[]))(T val) @safe @nogc nothrow
{
foreach(e; val)
bytes.put(e);
sz += val.length;
}
/// ditto
void put(T : byte[])(T val) @safe @nogc nothrow
{
foreach(e; val)
bytes.put(e);
sz += val.length;
}
///
void put(T : void[])(T val) @trusted @nogc nothrow
{
put(cast(ubyte[])val);
}
///
void put(T : const(void[]))(T val) @trusted @nogc nothrow
{
put(cast(const(ubyte[]))val);
}
private:
size_t sz = 0;
GrowingContainer!(ubyte, back_sz) bytes;
}
///
@safe unittest
{
IMemStream!() m;
m.put!ubyte(10);
m.put!short(11);
m.put!int(14);
auto res = m.getBytes;
assert(res.length == 7);
assert(res[0] == 10);
assert(res[1] == 11);
assert(res[2] == 0);
assert(res[3] == 14);
assert(res[4] == 0);
assert(res[5] == 0);
assert(res[6] == 0);
}
|
D
|
module android.java.android.icu.text.MessageFormat_d_interface;
import arsd.jni : IJavaObjectImplementation, JavaPackageId, JavaName, IJavaObject, ImportExportImpl, JavaInterfaceMembers;
static import arsd.jni;
import import1 = android.java.android.icu.util.ULocale_d_interface;
import import3 = android.java.java.text.Format_d_interface;
import import8 = android.java.java.text.AttributedCharacterIterator_d_interface;
import import0 = android.java.java.util.Locale_d_interface;
import import7 = android.java.java.text.FieldPosition_d_interface;
import import9 = android.java.java.text.ParsePosition_d_interface;
import import2 = android.java.android.icu.text.MessagePattern_ApostropheMode_d_interface;
import import10 = android.java.java.lang.Class_d_interface;
import import5 = android.java.java.util.Set_d_interface;
import import6 = android.java.java.lang.StringBuffer_d_interface;
import import4 = android.java.java.util.Map_d_interface;
final class MessageFormat : IJavaObject {
static immutable string[] _d_canCastTo = [
];
@Import this(string);
@Import this(string, import0.Locale);
@Import this(string, import1.ULocale);
@Import void setLocale(import0.Locale);
@Import void setLocale(import1.ULocale);
@Import import0.Locale getLocale();
@Import import1.ULocale getULocale();
@Import void applyPattern(string);
@Import void applyPattern(string, import2.MessagePattern_ApostropheMode);
@Import import2.MessagePattern_ApostropheMode getApostropheMode();
@Import string toPattern();
@Import void setFormatsByArgumentIndex(import3.Format[]);
@Import void setFormatsByArgumentName(import4.Map);
@Import void setFormats(import3.Format[]);
@Import void setFormatByArgumentIndex(int, import3.Format);
@Import void setFormatByArgumentName(string, import3.Format);
@Import void setFormat(int, import3.Format);
@Import import3.Format[] getFormatsByArgumentIndex();
@Import import3.Format[] getFormats();
@Import import5.Set getArgumentNames();
@Import import3.Format getFormatByArgumentName(string);
@Import import6.StringBuffer format(IJavaObject, import6.StringBuffer, import7.FieldPosition[]);
@Import import6.StringBuffer format(import4.Map, import6.StringBuffer, import7.FieldPosition);
@Import static string format(string, IJavaObject[]);
@Import static string format(string, import4.Map);
@Import bool usesNamedArguments();
@Import import6.StringBuffer format(IJavaObject, import6.StringBuffer, import7.FieldPosition);
@Import import8.AttributedCharacterIterator formatToCharacterIterator(IJavaObject);
@Import IJavaObject[] parse(string, import9.ParsePosition);
@Import import4.Map parseToMap(string, import9.ParsePosition);
@Import IJavaObject[] parse(string);
@Import import4.Map parseToMap(string);
@Import IJavaObject parseObject(string, import9.ParsePosition);
@Import IJavaObject clone();
@Import bool equals(IJavaObject);
@Import int hashCode();
@Import static string autoQuoteApostrophe(string);
@Import string format(IJavaObject);
@Import IJavaObject parseObject(string);
@Import import10.Class getClass();
@Import @JavaName("toString") string toString_();
override string toString() { return arsd.jni.javaObjectToString(this); }
@Import void notify();
@Import void notifyAll();
@Import void wait(long);
@Import void wait(long, int);
@Import void wait();
mixin IJavaObjectImplementation!(false);
public static immutable string _javaParameterString = "Landroid/icu/text/MessageFormat;";
}
|
D
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.0
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
module SWIGTYPE_p_vtkHyperTreeIterator;
static import vtkd_im;
class SWIGTYPE_p_vtkHyperTreeIterator {
private void* swigCPtr;
public this(void* cObject, bool futureUse) {
swigCPtr = cObject;
}
protected this() {
swigCPtr = null;
}
public static void* swigGetCPtr(SWIGTYPE_p_vtkHyperTreeIterator obj) {
return (obj is null) ? null : obj.swigCPtr;
}
mixin vtkd_im.SwigOperatorDefinitions;
}
|
D
|
module android.java.android.widget.CursorAdapter_d_interface;
import arsd.jni : IJavaObjectImplementation, JavaPackageId, JavaName, IJavaObject, ImportExportImpl, JavaInterfaceMembers;
static import arsd.jni;
import import5 = android.java.java.lang.CharSequence_d_interface;
import import1 = android.java.android.database.Cursor_d_interface;
import import2 = android.java.android.content.res.Resources_Theme_d_interface;
import import3 = android.java.android.view.View_d_interface;
import import7 = android.java.android.widget.FilterQueryProvider_d_interface;
import import8 = android.java.android.database.DataSetObserver_d_interface;
import import9 = android.java.java.lang.Class_d_interface;
import import4 = android.java.android.view.ViewGroup_d_interface;
import import6 = android.java.android.widget.Filter_d_interface;
import import0 = android.java.android.content.Context_d_interface;
final class CursorAdapter : IJavaObject {
static immutable string[] _d_canCastTo = [
"android/widget/Filterable",
"android/widget/ThemedSpinnerAdapter",
];
@Import this(import0.Context, import1.Cursor);
@Import this(import0.Context, import1.Cursor, bool);
@Import this(import0.Context, import1.Cursor, int);
@Import void setDropDownViewTheme(import2.Resources_Theme);
@Import import2.Resources_Theme getDropDownViewTheme();
@Import import1.Cursor getCursor();
@Import int getCount();
@Import IJavaObject getItem(int);
@Import long getItemId(int);
@Import bool hasStableIds();
@Import import3.View getView(int, import3.View, import4.ViewGroup);
@Import import3.View getDropDownView(int, import3.View, import4.ViewGroup);
@Import import3.View newView(import0.Context, import1.Cursor, import4.ViewGroup);
@Import import3.View newDropDownView(import0.Context, import1.Cursor, import4.ViewGroup);
@Import void bindView(import3.View, import0.Context, import1.Cursor);
@Import void changeCursor(import1.Cursor);
@Import import1.Cursor swapCursor(import1.Cursor);
@Import import5.CharSequence convertToString(import1.Cursor);
@Import import1.Cursor runQueryOnBackgroundThread(import5.CharSequence);
@Import import6.Filter getFilter();
@Import import7.FilterQueryProvider getFilterQueryProvider();
@Import void setFilterQueryProvider(import7.FilterQueryProvider);
@Import void registerDataSetObserver(import8.DataSetObserver);
@Import void unregisterDataSetObserver(import8.DataSetObserver);
@Import void notifyDataSetChanged();
@Import void notifyDataSetInvalidated();
@Import bool areAllItemsEnabled();
@Import bool isEnabled(int);
@Import int getItemViewType(int);
@Import int getViewTypeCount();
@Import bool isEmpty();
@Import import5.CharSequence[] getAutofillOptions();
@Import void setAutofillOptions(import5.CharSequence[]);
@Import import9.Class getClass();
@Import int hashCode();
@Import bool equals(IJavaObject);
@Import @JavaName("toString") string toString_();
override string toString() { return arsd.jni.javaObjectToString(this); }
@Import void notify();
@Import void notifyAll();
@Import void wait(long);
@Import void wait(long, int);
@Import void wait();
mixin IJavaObjectImplementation!(false);
public static immutable string _javaParameterString = "Landroid/widget/CursorAdapter;";
}
|
D
|
/Users/hasan/PycharmProjects/Rust/rust-cli/email-sending/target/debug/build/rand_chacha-8f12a30830111b58/build_script_build-8f12a30830111b58: /Users/hasan/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_chacha-0.1.1/build.rs
/Users/hasan/PycharmProjects/Rust/rust-cli/email-sending/target/debug/build/rand_chacha-8f12a30830111b58/build_script_build-8f12a30830111b58.d: /Users/hasan/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_chacha-0.1.1/build.rs
/Users/hasan/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_chacha-0.1.1/build.rs:
|
D
|
import core.thread;
import core.time;
version (linux)
{
version (X86_64)
{
alias x86_64_asm_linux_lock = void;
}
}
immutable string readFence = ``;
immutable string writeFence = ``;
extern(C) uint GetThreadId()
{
asm nothrow {
naked;
db 0x64, 0x48, 0x8b, 0x0c, 0x25, 0x00, 0x00, 0x00, 0x00;
// mov RCX, qword ptr FS:0x0; But dmds iasm cannot do that :(
// rcx = thread_id
shr RCX, 8;
mov RAX, RCX;
ret;
}
}
/// NOTE: I am aware how this function looks,
/// Given the tools I have (buggy iasm) this the best
string LockQueue(string lock)
{
assert(__ctfe);
return
`
static assert(is(typeof(` ~ lock ~ `) == shared uint), "can only lock on uint");
{
enum lbl = mixin("\"L" ~ __LINE__.stringof ~ "\"");
enum lockName = "` ~ lock ~ `";
auto lockPtr = &` ~lock ~ `;
static if (is(x86_64_asm_linux_lock))
{
{
asm nothrow
{
push RAX;
push RCX;
push RDX;
db 0x64, 0x48, 0x8b, 0x0c, 0x25, 0x00, 0x00, 0x00, 0x00;
// mov RCX, qword ptr FS:0x0; But dmds iasm cannot do that :(
// rcx = thread_id
shr RCX, 8;
// the first byte is always 0 due to alignment
}
mixin(lbl ~ ":" ~ "
asm nothrow {
xor RAX, RAX; // rax = 0
mov RDX, [lockPtr]; // load ptr
lock; cmpxchg dword ptr [RDX], ECX; // xchg()
// xchg the lock value
je " ~ lbl ~ ";
// this code is eqivalent to
// if (lock == 0) { lock = thread_id; }
pop RDX;
pop RCX;
pop RAX;
}");
}
}
else
{
import core.atomic;
import core.thread;
/+
auto t = Thread.getThis();
const uint id = cast(uint) t.id();
+/
const shared uint id = GetThreadId();
uint expected = 0;
while((*lockPtr) != id && cas((cast(shared)lockPtr), 0, id))
{
expected = 0;
` ~ __mmPause ~ `
}
}
}`;
}
string UnlockQueue(string lock)
{
return "(*(&" ~ lock ~ ")) = 0;";
}
struct CopyQueueEntry
{
void* dest;
const (void)* source;
ulong size;
ubyte[4] pad;
}
__gshared align(16) CopyQueueEntry[256] copyQueue;
__gshared align(16) size_t copyQueueCount;
__gshared align(16) size_t workDoneCount;
shared align(16) uint copyQueueLocked;
static immutable string __mmPause = "asm nothrow pure { rep; nop; }";
import core.stdc.stdio;
extern (C) void* copyLoop(void* arg)
{
import core.stdc.string;
import core.stdc.stdio;
// printf("starting copyLoop\n");
size_t nextCopyItem = 0;
for(;;)
{
assert(copyQueueCount < 192); // we are getting to close the limit
if (copyQueueCount > 32 && !copyQueueLocked)
{
mixin(LockQueue("copyQueueLocked"));
// not a foreach because the optimizer can't see the limit
// due to lowering :/
const ourCopyQueueCount = copyQueueCount;
//written that way for some smart autovectorizer :)
for(int i = 0; i < ourCopyQueueCount; i += 4)
{
auto e1 = copyQueue[nextCopyItem++];
auto e2 = copyQueue[nextCopyItem++];
auto e3 = copyQueue[nextCopyItem++];
auto e4 = copyQueue[nextCopyItem++];
memcpy(e1.dest, e1.source, e1.size);
memcpy(e2.dest, e2.source, e2.size);
memcpy(e3.dest, e3.source, e3.size);
memcpy(e4.dest, e4.source, e4.size);
workDoneCount += 4;
copyQueueCount -= 4;
}
goto LsmallCopy;
}
mixin(__mmPause);
mixin(readFence);
if (copyQueueCount && !copyQueueLocked)
{
mixin(LockQueue("copyQueueLocked"));
LsmallCopy:
for( ; copyQueueCount;)
{
auto e1 = copyQueue[nextCopyItem++];
memcpy(e1.dest, e1.source, e1.size);
workDoneCount++;
copyQueueCount--;
}
}
else if (!copyQueueLocked && !copyQueueCount)
{
// printf("No work to be done\n");
Thread.sleep(msecs(100));
}
LCopyfinished:
mixin(writeFence);
mixin(UnlockQueue("copyQueueLocked"));
// non critical
nextCopyItem = 0;
mixin(__mmPause);
}
}
void initWorkerThread()
{
copyQueueLocked = 0;
version (linux)
{
import core.sys.posix.pthread;
pthread_t copyThread;
pthread_create(©Thread, null, ©Loop, null);
}
else
{
import core.thread;
auto copyThread = new Thread(©Loop).start();
}
}
// enqueueMalloc()
// enqueueRealloc()
// enqueueMangle()
// TOOD --- PERFORMANCE ----
// Replace LockedQueue by SmarterScheme which uses two rings
/// Assumes that memory at source will valid forever!
static string enqueueCopyString(string dest, string source, string size, string waitHandle = null)
{
assert(__ctfe);
string result =
"
do {
auto entry = CopyQueueEntry(
" ~ dest ~ ",
" ~ source ~ ",
" ~ size ~ "
);
if ((!copyQueueLocked) && copyQueueCount < 192) {
" ~ LockQueue("copyQueueLocked") ~ "
// when we reach this point the lock has been aquired.
" ~ (waitHandle !is null ? waitHandle ~ " = copyQueueCount;" : "") ~ "
copyQueue[copyQueueCount++] = entry;
" ~ UnlockQueue("copyQueueLocked") ~ "
}
else {
" ~ __mmPause ~ "
continue; }
} while (0);
";
return result;
}
void main()
{
assert(!copyQueueLocked);
uint my_thread_id = GetThreadId();
printf("GetThreadId: %d\n", my_thread_id);
initWorkerThread();
printf("copyQueueLocked: %d\n", copyQueueLocked);
mixin(LockQueue("copyQueueLocked"));
// we've got the lock which means we're the owner
assert(cast(uint)copyQueueLocked == my_thread_id);
printf("copyQueueLocked: %d\n", cast(uint)copyQueueLocked);
mixin(UnlockQueue("copyQueueLocked"));
long source = 22;
long dest = 0;
size_t wait_handle;
mixin(enqueueCopyString("&dest", "&source", "ulong.sizeof", "wait_handle"));
while (workDoneCount <= wait_handle)
{
mixin(__mmPause);
}
assert(dest == source);
}
|
D
|
/*
* $Id: screen3d.d,v 1.1.1.1 2006/02/19 04:57:26 kenta Exp $
*
* Copyright 2005 Kenta Cho. Some rights reserved.
*/
module abagames.util.sdl.screen3d;
private import std.string;
private import std.conv;
private import SDL;
private import opengl;
private import abagames.util.vector;
private import abagames.util.sdl.screen;
private import abagames.util.sdl.sdlexception;
/**
* SDL screen handler(3D, OpenGL).
*/
public class Screen3D: Screen, SizableScreen {
private:
static float _brightness = 1;
float _farPlane = 1000;
float _nearPlane = 0.1;
int _width = 640;
int _height = 480;
int _startx = 0;
int _starty = 0;
bool _windowMode = false;
protected abstract void init();
protected abstract void close();
public void initSDL() {
// Initialize SDL.
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
throw new SDLInitFailedException(
"Unable to initialize SDL: " ~ to!string(SDL_GetError()));
}
// Create an OpenGL screen.
Uint32 videoFlags;
videoFlags = SDL_OPENGL;
if (_windowMode) {
videoFlags |= SDL_RESIZABLE;
} else {
videoFlags |= SDL_FULLSCREEN;
}
int physical_width = _width;
int physical_height = _height;
if (!windowMode) {
version (PANDORA) {
physical_width = 800;
physical_height = 480;
}
// center image on screen
_startx = (physical_width - _width) / 2;
_starty = (physical_height - _height) / 2;
}
if (SDL_SetVideoMode(physical_width, physical_height, 0, videoFlags) == null) {
throw new SDLInitFailedException
("Unable to create SDL screen: " ~ to!string(SDL_GetError()));
}
glViewport(_startx, _starty, _width, _height);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
resized(_width, _height);
SDL_ShowCursor(SDL_DISABLE);
init();
}
// Reset a viewport when the screen is resized.
public void screenResized() {
glViewport(_startx, _starty, _width, _height);
glMatrixMode(GL_PROJECTION);
setPerspective();
glMatrixMode(GL_MODELVIEW);
}
public void setPerspective() {
glLoadIdentity();
//gluPerspective(45.0f, cast(GLfloat) width / cast(GLfloat) height, nearPlane, farPlane);
glFrustum(-_nearPlane,
_nearPlane,
-_nearPlane * cast(GLfloat) _height / cast(GLfloat) _width,
_nearPlane * cast(GLfloat) _height / cast(GLfloat) _width,
0.1f, _farPlane);
}
public void resized(int w, int h) {
_width = w;
_height = h;
screenResized();
}
public void closeSDL() {
close();
SDL_ShowCursor(SDL_ENABLE);
}
public void flip() {
handleError();
SDL_GL_SwapBuffers();
}
public void clear() {
glClear(GL_COLOR_BUFFER_BIT);
}
public void handleError() {
GLenum error = glGetError();
if (error == GL_NO_ERROR)
return;
closeSDL();
throw new Exception("OpenGL error(" ~ to!string(error) ~ ")");
}
protected void setCaption(const char[] name) {
SDL_WM_SetCaption(std.string.toStringz(name), null);
}
public bool windowMode(bool v) {
return _windowMode = v;
}
public bool windowMode() {
return _windowMode;
}
public int width(int v) {
return _width = v;
}
public int width() {
return _width;
}
public int height(int v) {
return _height = v;
}
public int height() {
return _height;
}
public int startx() {
return _startx;
}
public int starty() {
return _starty;
}
public static void glVertex(Vector v) {
glVertex3f(v.x, v.y, 0);
}
public static void glVertex(Vector3 v) {
glVertex3f(v.x, v.y, v.z);
}
public static void glTranslate(Vector v) {
glTranslatef(v.x, v.y, 0);
}
public static void glTranslate(Vector3 v) {
glTranslatef(v.x, v.y, v.z);
}
public static void setColor(float r, float g, float b, float a = 1) {
glColor4f(r * _brightness, g * _brightness, b * _brightness, a);
}
public static void setClearColor(float r, float g, float b, float a = 1) {
glClearColor(r * _brightness, g * _brightness, b * _brightness, a);
}
public static float brightness(float v) {
return _brightness = v;
}
}
|
D
|
module grimoire.stdlib.math;
import std.random, std.math;
import std.algorithm.comparison: clamp;
import grimoire.compiler, grimoire.runtime;
package(grimoire.stdlib)
void grLoadStdLibMath(GrData data) {
data.addPrimitive(&_clamp, "clamp", ["v", "min", "max"], [grFloat, grFloat, grFloat], [grFloat]);
data.addPrimitive(&_random01, "random", [], [], [grFloat]);
data.addPrimitive(&_randomf, "random", ["v1", "v2"], [grFloat, grFloat], [grFloat]);
data.addPrimitive(&_randomi, "random", ["v1", "v2"], [grInt, grInt], [grInt]);
data.addPrimitive(&_cos, "cos", ["v"], [grFloat], [grFloat]);
data.addPrimitive(&_sin, "sin", ["v"], [grFloat], [grFloat]);
data.addPrimitive(&_sqrt, "sqrt", ["v"], [grFloat], [grFloat]);
data.addPrimitive(&_lerp, "lerp", ["a", "b", "t"], [grFloat, grFloat, grFloat], [grFloat]);
data.addPrimitive(&_rlerp, "rlerp", ["a", "b", "v"], [grFloat, grFloat, grFloat], [grFloat]);
}
private void _clamp(GrCall call) {
call.setFloat(clamp(call.getFloat("v"), call.getFloat("min"), call.getFloat("max")));
}
private void _random01(GrCall call) {
call.setFloat(uniform01());
}
private void _randomf(GrCall call) {
call.setFloat(uniform!"[]"(call.getFloat("v1"), call.getFloat("v2")));
}
private void _randomi(GrCall call) {
call.setInt(uniform!"[]"(call.getInt("v1"), call.getInt("v2")));
}
private void _cos(GrCall call) {
call.setFloat(cos(call.getFloat("v")));
}
private void _sin(GrCall call) {
call.setFloat(sin(call.getFloat("v")));
}
private void _sqrt(GrCall call) {
call.setFloat(sqrt(call.getFloat("v")));
}
private void _lerp(GrCall call) {
const float a = call.getFloat("a");
const float b = call.getFloat("b");
const float t = call.getFloat("t");
call.setFloat(t * b + (1f - t) * a);
}
private void _rlerp(GrCall call) {
const float a = call.getFloat("a");
const float b = call.getFloat("b");
const float v = call.getFloat("v");
if((b - a) == 0f) {
call.setFloat(0f);
return;
}
call.setFloat((v - a) / (b - a));
}
|
D
|
/home/alansky/Dev/Parity/substrate-node-template/target/debug/build/httparse-6828d44b08f07b99/build_script_build-6828d44b08f07b99: /home/alansky/.cargo/registry/src/github.com-1ecc6299db9ec823/httparse-1.3.4/build.rs
/home/alansky/Dev/Parity/substrate-node-template/target/debug/build/httparse-6828d44b08f07b99/build_script_build-6828d44b08f07b99.d: /home/alansky/.cargo/registry/src/github.com-1ecc6299db9ec823/httparse-1.3.4/build.rs
/home/alansky/.cargo/registry/src/github.com-1ecc6299db9ec823/httparse-1.3.4/build.rs:
|
D
|
module UnrealScript.TribesGame.TrDroppedPickup;
import ScriptClasses;
import UnrealScript.Helpers;
import UnrealScript.UTGame.UTDroppedPickup;
import UnrealScript.Engine.SoundCue;
import UnrealScript.Engine.Pawn;
import UnrealScript.Engine.Canvas;
import UnrealScript.TribesGame.TrCollisionProxy;
import UnrealScript.Engine.Actor;
import UnrealScript.TribesGame.TrPawn;
import UnrealScript.Engine.PlayerController;
extern(C++) interface TrDroppedPickup : UTDroppedPickup
{
public extern(D):
private static __gshared ScriptClass mStaticClass;
@property final static ScriptClass StaticClass() { mixin(MGSCC("Class TribesGame.TrDroppedPickup")); }
private static __gshared TrDroppedPickup mDefaultProperties;
@property final static TrDroppedPickup DefaultProperties() { mixin(MGDPC("TrDroppedPickup", "TrDroppedPickup TribesGame.Default__TrDroppedPickup")); }
static struct Functions
{
private static __gshared
{
ScriptFunction mDestroyed;
ScriptFunction mGiveTo;
ScriptFunction mPostBeginPlay;
ScriptFunction mDoBounce;
ScriptFunction mHitWall;
ScriptFunction mOnCollisionProxyTouched;
ScriptFunction mTick;
ScriptFunction mPostRenderFor;
}
public @property static final
{
ScriptFunction Destroyed() { mixin(MGF("mDestroyed", "Function TribesGame.TrDroppedPickup.Destroyed")); }
ScriptFunction GiveTo() { mixin(MGF("mGiveTo", "Function TribesGame.TrDroppedPickup.GiveTo")); }
ScriptFunction PostBeginPlay() { mixin(MGF("mPostBeginPlay", "Function TribesGame.TrDroppedPickup.PostBeginPlay")); }
ScriptFunction DoBounce() { mixin(MGF("mDoBounce", "Function TribesGame.TrDroppedPickup.DoBounce")); }
ScriptFunction HitWall() { mixin(MGF("mHitWall", "Function TribesGame.TrDroppedPickup.HitWall")); }
ScriptFunction OnCollisionProxyTouched() { mixin(MGF("mOnCollisionProxyTouched", "Function TribesGame.TrDroppedPickup.OnCollisionProxyTouched")); }
ScriptFunction Tick() { mixin(MGF("mTick", "Function TribesGame.TrDroppedPickup.Tick")); }
ScriptFunction PostRenderFor() { mixin(MGF("mPostRenderFor", "Function TribesGame.TrDroppedPickup.PostRenderFor")); }
}
}
static struct Pickup
{
private static __gshared ScriptState mStaticClass;
@property final static ScriptState StaticClass() { mixin(MGSCSA("State TribesGame.TrDroppedPickup.Pickup")); }
}
@property final
{
auto ref
{
TrCollisionProxy m_CollisionProxy() { mixin(MGPC("TrCollisionProxy", 552)); }
float m_fMarkerOpacity() { mixin(MGPC("float", 548)); }
float m_fCurrentMarkerTime() { mixin(MGPC("float", 544)); }
Rotator m_rMarkerRot() { mixin(MGPC("Rotator", 532)); }
float m_fMarkerBlinkSpeed() { mixin(MGPC("float", 528)); }
float m_fMarkerScale() { mixin(MGPC("float", 524)); }
float m_fMarkerZOffset() { mixin(MGPC("float", 520)); }
float m_PctAmmoToRefill() { mixin(MGPC("float", 516)); }
SoundCue m_AmmoPickupSound() { mixin(MGPC("SoundCue", 512)); }
}
bool m_bHasHitObjective() { mixin(MGBPC(556, 0x1)); }
bool m_bHasHitObjective(bool val) { mixin(MSBPC(556, 0x1)); }
}
final:
void Destroyed()
{
(cast(ScriptObject)this).ProcessEvent(Functions.Destroyed, cast(void*)0, cast(void*)0);
}
void GiveTo(Pawn P)
{
ubyte params[4];
params[] = 0;
*cast(Pawn*)params.ptr = P;
(cast(ScriptObject)this).ProcessEvent(Functions.GiveTo, params.ptr, cast(void*)0);
}
void PostBeginPlay()
{
(cast(ScriptObject)this).ProcessEvent(Functions.PostBeginPlay, cast(void*)0, cast(void*)0);
}
void DoBounce(Actor Other, Vector HitNormal)
{
ubyte params[16];
params[] = 0;
*cast(Actor*)params.ptr = Other;
*cast(Vector*)¶ms[4] = HitNormal;
(cast(ScriptObject)this).ProcessEvent(Functions.DoBounce, params.ptr, cast(void*)0);
}
void HitWall(Vector HitNormal, Actor Wall,
// ERROR: Unknown object class 'Class Core.ComponentProperty'!
void* WallComp)
{
ubyte params[20];
params[] = 0;
*cast(Vector*)params.ptr = HitNormal;
*cast(Actor*)¶ms[12] = Wall;
*cast(
// ERROR: Unknown object class 'Class Core.ComponentProperty'!
void**)¶ms[16] = WallComp;
(cast(ScriptObject)this).ProcessEvent(Functions.HitWall, params.ptr, cast(void*)0);
}
void OnCollisionProxyTouched(TrPawn TRP)
{
ubyte params[4];
params[] = 0;
*cast(TrPawn*)params.ptr = TRP;
(cast(ScriptObject)this).ProcessEvent(Functions.OnCollisionProxyTouched, params.ptr, cast(void*)0);
}
void Tick(float DeltaTime)
{
ubyte params[4];
params[] = 0;
*cast(float*)params.ptr = DeltaTime;
(cast(ScriptObject)this).ProcessEvent(Functions.Tick, params.ptr, cast(void*)0);
}
void PostRenderFor(PlayerController PC, Canvas pCanvas, Vector CameraPosition, Vector CameraDir)
{
ubyte params[32];
params[] = 0;
*cast(PlayerController*)params.ptr = PC;
*cast(Canvas*)¶ms[4] = pCanvas;
*cast(Vector*)¶ms[8] = CameraPosition;
*cast(Vector*)¶ms[20] = CameraDir;
(cast(ScriptObject)this).ProcessEvent(Functions.PostRenderFor, params.ptr, cast(void*)0);
}
}
|
D
|
module gargula.builtin.sprite;
import gargula.builtin.tween;
import gargula.node;
import gargula.resource.texture;
import gargula.wrapper.raylib;
enum SpriteOptions
{
/// Default options: dynamic rotation and pivot
none = 0,
/// Axis Aligned Sprites may not rotate
axisAligned = 1 << 0,
/// Pivot is fixed to Sprite's center
fixedPivot = 1 << 1,
/// Use rect.size as size directly instead of scale factor
rectSize = 1 << 2,
/// Animate frame changes on `update`, only useful on Textures with more than one region
animated = 1 << 3,
}
struct SpriteTemplate(TextureType, SpriteOptions options = SpriteOptions.none)
{
mixin Node;
// Workaround for error `struct SpriteTemplate has constructors, cannot use { initializers }, use SpriteTemplate( initializers ) instead` in LDC
// Who knows why =S
version (LDC) @disable this();
TextureType texture;
Rectangle rect = { 0, 1 };
alias rect this;
Color tintColor = WHITE;
@property Vector2 position() const
{
return rect.origin;
}
@property void position(const Vector2 value)
{
rect.origin = value;
}
static if (options & SpriteOptions.rectSize)
{
enum Vector2 scale = 1;
@property Vector2 size() const
{
return rect.size;
}
}
else
{
@property Vector2 scale() const
{
return rect.size;
}
@property void scale(const Vector2 value)
{
rect.size = value;
}
@property Vector2 size() const
{
return scale * sourceRect.size;
}
}
static if (options & SpriteOptions.fixedPivot)
{
enum Vector2 pivot = 0.5;
}
else
{
Vector2 pivot = 0.5;
}
static if (options & SpriteOptions.axisAligned)
{
enum float rotation = 0;
}
else
{
float rotation = 0;
}
Rectangle sourceRect = { 0, 0 };
int region = 0;
void setFullRegion()
{
this.region = -1;
sourceRect = texture.fullRegion;
}
void setRegion(int region)
{
this.region = region;
sourceRect = texture.region(region);
}
static if (options & SpriteOptions.animated)
{
Tween!"linear" animation = {
looping: true,
};
}
void lateInitialize()
{
if (region < 0)
{
setFullRegion();
}
else
{
setRegion(region);
}
}
Rectangle drawnRectangle() const
{
Vector2 destOrigin = pivot * this.size;
Rectangle drawnRect = { position - destOrigin, this.size };
return drawnRect;
}
void lateUpdate()
{
static if (options & SpriteOptions.animated)
{
int currentRegion = animation.value(0, cast(int) texture.regions.length);
if (currentRegion != region)
{
setRegion(currentRegion);
}
}
}
void draw()
{
Vector2 destOrigin = pivot * this.size;
Rectangle destRect = { position, this.size };
texture.draw(sourceRect, destRect, destOrigin, rotation, tintColor);
}
}
mixin template SpriteVariations(TextureType)
{
import gargula.builtin.sprite : SpriteOptions, SpriteTemplate;
alias Sprite = SpriteTemplate!(TextureType);
alias SpriteRect = SpriteTemplate!(TextureType, SpriteOptions.rectSize);
alias CenteredSprite = SpriteTemplate!(TextureType, SpriteOptions.fixedPivot);
alias CenteredSpriteRect = SpriteTemplate!(TextureType, SpriteOptions.fixedPivot | SpriteOptions.rectSize);
alias AASprite = SpriteTemplate!(TextureType, SpriteOptions.axisAligned);
alias AASpriteRect = SpriteTemplate!(TextureType, SpriteOptions.axisAligned | SpriteOptions.rectSize);
alias AACenteredSprite = SpriteTemplate!(TextureType, SpriteOptions.axisAligned | SpriteOptions.fixedPivot);
alias AACenteredSpriteRect = SpriteTemplate!(TextureType, SpriteOptions.axisAligned | SpriteOptions.fixedPivot | SpriteOptions.rectSize);
alias AnimatedSprite = SpriteTemplate!(TextureType, SpriteOptions.animated);
alias AnimatedSpriteRect = SpriteTemplate!(TextureType, SpriteOptions.animated | SpriteOptions.rectSize);
alias AnimatedCenteredSprite = SpriteTemplate!(TextureType, SpriteOptions.animated | SpriteOptions.fixedPivot);
alias AnimatedCenteredSpriteRect = SpriteTemplate!(TextureType, SpriteOptions.animated | SpriteOptions.fixedPivot | SpriteOptions.rectSize);
alias AnimatedAASprite = SpriteTemplate!(TextureType, SpriteOptions.animated | SpriteOptions.axisAligned);
alias AnimatedAASpriteRect = SpriteTemplate!(TextureType, SpriteOptions.axisAligned | SpriteOptions.rectSize);
alias AnimatedAACenteredSprite = SpriteTemplate!(TextureType, SpriteOptions.animated | SpriteOptions.axisAligned | SpriteOptions.fixedPivot);
alias AnimatedAACenteredSpriteRect = SpriteTemplate!(TextureType, SpriteOptions.animated | SpriteOptions.axisAligned | SpriteOptions.fixedPivot | SpriteOptions.rectSize);
}
mixin SpriteVariations!TextureAtlas;
|
D
|
/*
* This file is part of moss.
*
* Copyright © 2020 Serpent OS Developers
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
module moss.format.binary;
public import std.stdint : uint32_t;
public import moss.format.binary.contentPayload;
public import moss.format.binary.endianness;
public import moss.format.binary.header;
public import moss.format.binary.index;
public import moss.format.binary.indexPayload;
public import moss.format.binary.layout;
public import moss.format.binary.layoutPayload;
public import moss.format.binary.metaPayload;
public import moss.format.binary.payload;
public import moss.format.binary.reader;
public import moss.format.binary.record;
public import moss.format.binary.writer;
/**
* Current version of the package format that we target.
*/
const uint32_t MossFormatVersionNumber = 1;
|
D
|
/**
* D header file for GNU/Linux
*
* $(LINK2 http://sourceware.org/git/?p=glibc.git;a=blob;f=stdlib/errno.h, glibc stdlib/errno.h)
*/
module core.sys.linux.errno;
version (linux):
extern (C):
nothrow:
public import core.stdc.errno;
import core.sys.linux.config;
static if (__USE_GNU)
{
extern __gshared char* program_invocation_name, program_invocation_short_name;
alias error_t = int;
}
|
D
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Assistant of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QHELPCONTENTWIDGET_H
#define QHELPCONTENTWIDGET_H
public import qt.QtHelp.qhelp_global;
public import qt.QtCore.QQueue;
public import qt.QtCore.QString;
public import qt.QtWidgets.QTreeView;
QT_BEGIN_NAMESPACE
class QHelpEnginePrivate;
class QHelpDBReader;
class QHelpContentItemPrivate;
class QHelpContentModelPrivate;
class QHelpEngine;
class QHelpContentProvider;
class QHELP_EXPORT QHelpContentItem
{
public:
~QHelpContentItem();
QHelpContentItem *child(int row) const;
int childCount() const;
QString title() const;
QUrl url() const;
int row() const;
QHelpContentItem *parent() const;
int childPosition(QHelpContentItem *child) const;
private:
QHelpContentItem(ref const(QString) name, ref const(QString) link,
QHelpDBReader *reader, QHelpContentItem *parent = 0);
void appendChild(QHelpContentItem *child);
QHelpContentItemPrivate *d;
friend class QHelpContentProvider;
};
class QHELP_EXPORT QHelpContentModel : public QAbstractItemModel
{
mixin Q_OBJECT;
public:
~QHelpContentModel();
void createContents(ref const(QString) customFilterName);
QHelpContentItem *contentItemAt(ref const(QModelIndex) index) const;
QVariant data(ref const(QModelIndex) index, int role) const;
QModelIndex index(int row, int column,
ref const(QModelIndex) parent = QModelIndex()) const;
QModelIndex parent(ref const(QModelIndex) index) const;
int rowCount(ref const(QModelIndex) parent = QModelIndex()) const;
int columnCount(ref const(QModelIndex) parent = QModelIndex()) const;
bool isCreatingContents() const;
Q_SIGNALS:
void contentsCreationStarted();
void contentsCreated();
private Q_SLOTS:
void insertContents();
void invalidateContents(bool onShutDown = false);
private:
QHelpContentModel(QHelpEnginePrivate *helpEngine);
QHelpContentModelPrivate *d;
friend class QHelpEnginePrivate;
};
class QHELP_EXPORT QHelpContentWidget : public QTreeView
{
mixin Q_OBJECT;
public:
QModelIndex indexOf(ref const(QUrl) link);
Q_SIGNALS:
void linkActivated(ref const(QUrl) link);
private Q_SLOTS:
void showLink(ref const(QModelIndex) index);
private:
bool searchContentItem(QHelpContentModel *model,
ref const(QModelIndex) parent, ref const(QString) path);
QModelIndex m_syncIndex;
private:
QHelpContentWidget();
friend class QHelpEngine;
};
QT_END_NAMESPACE
#endif
|
D
|
# FIXED
driverlib/mpu.obj: C:/ti/TivaWare_C_Series-2.1.4.178/driverlib/mpu.c
driverlib/mpu.obj: C:/ti/ccsv7/tools/compiler/ti-cgt-arm_16.9.0.LTS/include/stdbool.h
driverlib/mpu.obj: C:/ti/ccsv7/tools/compiler/ti-cgt-arm_16.9.0.LTS/include/stdint.h
driverlib/mpu.obj: C:/ti/TivaWare_C_Series-2.1.4.178/inc/hw_ints.h
driverlib/mpu.obj: C:/ti/TivaWare_C_Series-2.1.4.178/inc/hw_nvic.h
driverlib/mpu.obj: C:/ti/TivaWare_C_Series-2.1.4.178/inc/hw_types.h
driverlib/mpu.obj: C:/ti/TivaWare_C_Series-2.1.4.178/driverlib/debug.h
driverlib/mpu.obj: C:/ti/TivaWare_C_Series-2.1.4.178/driverlib/interrupt.h
driverlib/mpu.obj: C:/ti/TivaWare_C_Series-2.1.4.178/driverlib/mpu.h
C:/ti/TivaWare_C_Series-2.1.4.178/driverlib/mpu.c:
C:/ti/ccsv7/tools/compiler/ti-cgt-arm_16.9.0.LTS/include/stdbool.h:
C:/ti/ccsv7/tools/compiler/ti-cgt-arm_16.9.0.LTS/include/stdint.h:
C:/ti/TivaWare_C_Series-2.1.4.178/inc/hw_ints.h:
C:/ti/TivaWare_C_Series-2.1.4.178/inc/hw_nvic.h:
C:/ti/TivaWare_C_Series-2.1.4.178/inc/hw_types.h:
C:/ti/TivaWare_C_Series-2.1.4.178/driverlib/debug.h:
C:/ti/TivaWare_C_Series-2.1.4.178/driverlib/interrupt.h:
C:/ti/TivaWare_C_Series-2.1.4.178/driverlib/mpu.h:
|
D
|
/**
* Compiler implementation of the
* $(LINK2 http://www.dlang.org, D programming language).
*
* Copyright: Copyright (C) 1999-2019 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 http://www.digitalmars.com, Walter Bright)
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/lexer.d, _lexer.d)
* Documentation: https://dlang.org/phobos/dmd_lexer.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/lexer.d
*/
module dmd.lexer;
import core.stdc.ctype;
import core.stdc.errno;
import core.stdc.stdarg;
import core.stdc.stdio;
import core.stdc.string;
import core.stdc.time;
import dmd.entity;
import dmd.errors;
import dmd.globals;
import dmd.id;
import dmd.identifier;
import dmd.root.ctfloat;
import dmd.root.outbuffer;
import dmd.root.port;
import dmd.root.rmem;
import dmd.tokens;
import dmd.utf;
private enum LS = 0x2028; // UTF line separator
private enum PS = 0x2029; // UTF paragraph separator
/********************************************
* Do our own char maps
*/
private static immutable cmtable = () {
ubyte[256] table;
foreach (const c; 0 .. table.length)
{
if ('0' <= c && c <= '7')
table[c] |= CMoctal;
if (c_isxdigit(c))
table[c] |= CMhex;
if (c_isalnum(c) || c == '_')
table[c] |= CMidchar;
switch (c)
{
case 'x': case 'X':
case 'b': case 'B':
table[c] |= CMzerosecond;
break;
case '0': .. case '9':
case 'e': case 'E':
case 'f': case 'F':
case 'l': case 'L':
case 'p': case 'P':
case 'u': case 'U':
case 'i':
case '.':
case '_':
table[c] |= CMzerosecond | CMdigitsecond;
break;
default:
break;
}
switch (c)
{
case '\\':
case '\n':
case '\r':
case 0:
case 0x1A:
case '\'':
break;
default:
if (!(c & 0x80))
table[c] |= CMsinglechar;
break;
}
}
return table;
}();
private
{
enum CMoctal = 0x1;
enum CMhex = 0x2;
enum CMidchar = 0x4;
enum CMzerosecond = 0x8;
enum CMdigitsecond = 0x10;
enum CMsinglechar = 0x20;
}
private bool isoctal(const char c)
{
return (cmtable[c] & CMoctal) != 0;
}
private bool ishex(const char c)
{
return (cmtable[c] & CMhex) != 0;
}
private bool isidchar(const char c)
{
return (cmtable[c] & CMidchar) != 0;
}
private bool isZeroSecond(const char c)
{
return (cmtable[c] & CMzerosecond) != 0;
}
private bool isDigitSecond(const char c)
{
return (cmtable[c] & CMdigitsecond) != 0;
}
private bool issinglechar(const char c)
{
return (cmtable[c] & CMsinglechar) != 0;
}
private bool c_isxdigit(const int c)
{
return (( c >= '0' && c <= '9') ||
( c >= 'a' && c <= 'f') ||
( c >= 'A' && c <= 'F'));
}
private bool c_isalnum(const int c)
{
return (( c >= '0' && c <= '9') ||
( c >= 'a' && c <= 'z') ||
( c >= 'A' && c <= 'Z'));
}
unittest
{
//printf("lexer.unittest\n");
/* Not much here, just trying things out.
*/
string text = "int"; // We rely on the implicit null-terminator
scope diagnosticReporter = new StderrDiagnosticReporter(global.params.useDeprecated);
scope Lexer lex1 = new Lexer(null, text.ptr, 0, text.length, 0, 0, diagnosticReporter);
TOK tok;
tok = lex1.nextToken();
//printf("tok == %s, %d, %d\n", Token::toChars(tok), tok, TOK.int32);
assert(tok == TOK.int32);
tok = lex1.nextToken();
assert(tok == TOK.endOfFile);
tok = lex1.nextToken();
assert(tok == TOK.endOfFile);
tok = lex1.nextToken();
assert(tok == TOK.endOfFile);
}
unittest
{
// We don't want to see Lexer error output during these tests.
uint errors = global.startGagging();
scope(exit) global.endGagging(errors);
// Test malformed input: even malformed input should end in a TOK.endOfFile.
static immutable char[][] testcases =
[ // Testcase must end with 0 or 0x1A.
[0], // not malformed, but pathological
['\'', 0],
['\'', 0x1A],
['{', '{', 'q', '{', 0],
[0xFF, 0],
[0xFF, 0x80, 0],
[0xFF, 0xFF, 0],
[0xFF, 0xFF, 0],
['x', '"', 0x1A],
];
foreach (testcase; testcases)
{
scope diagnosticReporter = new StderrDiagnosticReporter(global.params.useDeprecated);
scope Lexer lex2 = new Lexer(null, testcase.ptr, 0, testcase.length-1, 0, 0, diagnosticReporter);
TOK tok = lex2.nextToken();
size_t iterations = 1;
while ((tok != TOK.endOfFile) && (iterations++ < testcase.length))
{
tok = lex2.nextToken();
}
assert(tok == TOK.endOfFile);
tok = lex2.nextToken();
assert(tok == TOK.endOfFile);
}
}
/***********************************************************
*/
class Lexer
{
private __gshared OutBuffer stringbuffer;
Loc scanloc; // for error messages
Loc prevloc; // location of token before current
const(char)* p; // current character
Token token;
private
{
const(char)* base; // pointer to start of buffer
const(char)* end; // pointer to last element of buffer
const(char)* line; // start of current line
bool doDocComment; // collect doc comment information
bool anyToken; // seen at least one token
bool commentToken; // comments are TOK.comment's
int lastDocLine; // last line of previous doc comment
DiagnosticReporter diagnosticReporter;
Token* tokenFreelist;
}
/*********************
* Creates a Lexer for the source code base[begoffset..endoffset+1].
* The last character, base[endoffset], must be null (0) or EOF (0x1A).
*
* Params:
* filename = used for error messages
* base = source code, must be terminated by a null (0) or EOF (0x1A) character
* begoffset = starting offset into base[]
* endoffset = the last offset to read into base[]
* doDocComment = handle documentation comments
* commentToken = comments become TOK.comment's
* diagnosticReporter = the diagnostic reporter to use
*/
this(const(char)* filename, const(char)* base, size_t begoffset,
size_t endoffset, bool doDocComment, bool commentToken,
DiagnosticReporter diagnosticReporter)
in
{
assert(diagnosticReporter !is null);
}
body
{
this.diagnosticReporter = diagnosticReporter;
scanloc = Loc(filename, 1, 1);
//printf("Lexer::Lexer(%p,%d)\n",base,length);
//printf("lexer.filename = %s\n", filename);
token = Token.init;
this.base = base;
this.end = base + endoffset;
p = base + begoffset;
line = p;
this.doDocComment = doDocComment;
this.commentToken = commentToken;
this.lastDocLine = 0;
//initKeywords();
/* If first line starts with '#!', ignore the line
*/
if (p && p[0] == '#' && p[1] == '!')
{
p += 2;
while (1)
{
char c = *p++;
switch (c)
{
case 0:
case 0x1A:
p--;
goto case;
case '\n':
break;
default:
continue;
}
break;
}
endOfLine();
}
}
/// Returns: `true` if any errors occurred during lexing or parsing.
final bool errors()
{
return diagnosticReporter.errorCount > 0;
}
/// Returns: a newly allocated `Token`.
Token* allocateToken() pure nothrow @safe
{
if (tokenFreelist)
{
Token* t = tokenFreelist;
tokenFreelist = t.next;
t.next = null;
return t;
}
return new Token();
}
/// Frees the given token by returning it to the freelist.
private void releaseToken(Token* token) pure nothrow @nogc @safe
{
token.next = tokenFreelist;
tokenFreelist = token;
}
final TOK nextToken()
{
prevloc = token.loc;
if (token.next)
{
Token* t = token.next;
memcpy(&token, t, Token.sizeof);
releaseToken(t);
}
else
{
scan(&token);
}
//printf(token.toChars());
return token.value;
}
/***********************
* Look ahead at next token's value.
*/
final TOK peekNext()
{
return peek(&token).value;
}
/***********************
* Look 2 tokens ahead at value.
*/
final TOK peekNext2()
{
Token* t = peek(&token);
return peek(t).value;
}
/****************************
* Turn next token in buffer into a token.
*/
final void scan(Token* t)
{
const lastLine = scanloc.linnum;
Loc startLoc;
t.blockComment = null;
t.lineComment = null;
while (1)
{
t.ptr = p;
//printf("p = %p, *p = '%c'\n",p,*p);
t.loc = loc();
switch (*p)
{
case 0:
case 0x1A:
t.value = TOK.endOfFile; // end of file
// Intentionally not advancing `p`, such that subsequent calls keep returning TOK.endOfFile.
return;
case ' ':
case '\t':
case '\v':
case '\f':
p++;
continue; // skip white space
case '\r':
p++;
if (*p != '\n') // if CR stands by itself
endOfLine();
continue; // skip white space
case '\n':
p++;
endOfLine();
continue; // skip white space
case '0':
if (!isZeroSecond(p[1])) // if numeric literal does not continue
{
++p;
t.unsvalue = 0;
t.value = TOK.int32Literal;
return;
}
goto Lnumber;
case '1': .. case '9':
if (!isDigitSecond(p[1])) // if numeric literal does not continue
{
t.unsvalue = *p - '0';
++p;
t.value = TOK.int32Literal;
return;
}
Lnumber:
t.value = number(t);
return;
case '\'':
if (issinglechar(p[1]) && p[2] == '\'')
{
t.unsvalue = p[1]; // simple one character literal
t.value = TOK.charLiteral;
p += 3;
}
else
t.value = charConstant(t);
return;
case 'r':
if (p[1] != '"')
goto case_ident;
p++;
goto case '`';
case '`':
wysiwygStringConstant(t);
return;
case 'x':
if (p[1] != '"')
goto case_ident;
p++;
t.value = hexStringConstant(t);
deprecation("Built-in hex string literals are deprecated, use `std.conv.hexString` instead.");
return;
case 'q':
if (p[1] == '"')
{
p++;
delimitedStringConstant(t);
return;
}
else if (p[1] == '{')
{
p++;
tokenStringConstant(t);
return;
}
else
goto case_ident;
case '"':
escapeStringConstant(t);
return;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
/*case 'q': case 'r':*/
case 's':
case 't':
case 'u':
case 'v':
case 'w':
/*case 'x':*/
case 'y':
case 'z':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case_ident:
{
while (1)
{
const c = *++p;
if (isidchar(c))
continue;
else if (c & 0x80)
{
const s = p;
const u = decodeUTF();
if (isUniAlpha(u))
continue;
error("char 0x%04x not allowed in identifier", u);
p = s;
}
break;
}
Identifier id = Identifier.idPool(cast(char*)t.ptr, cast(uint)(p - t.ptr));
t.ident = id;
t.value = cast(TOK)id.getValue();
anyToken = 1;
if (*t.ptr == '_') // if special identifier token
{
__gshared bool initdone = false;
__gshared char[11 + 1] date;
__gshared char[8 + 1] time;
__gshared char[24 + 1] timestamp;
if (!initdone) // lazy evaluation
{
initdone = true;
time_t ct;
.time(&ct);
const p = ctime(&ct);
assert(p);
sprintf(&date[0], "%.6s %.4s", p + 4, p + 20);
sprintf(&time[0], "%.8s", p + 11);
sprintf(×tamp[0], "%.24s", p);
}
if (id == Id.DATE)
{
t.ustring = date.ptr;
goto Lstr;
}
else if (id == Id.TIME)
{
t.ustring = time.ptr;
goto Lstr;
}
else if (id == Id.VENDOR)
{
t.ustring = global.vendor;
goto Lstr;
}
else if (id == Id.TIMESTAMP)
{
t.ustring = timestamp.ptr;
Lstr:
t.value = TOK.string_;
t.postfix = 0;
t.len = cast(uint)strlen(t.ustring);
}
else if (id == Id.VERSIONX)
{
t.value = TOK.int64Literal;
t.unsvalue = global.versionNumber();
}
else if (id == Id.EOFX)
{
t.value = TOK.endOfFile;
// Advance scanner to end of file
while (!(*p == 0 || *p == 0x1A))
p++;
}
}
//printf("t.value = %d\n",t.value);
return;
}
case '/':
p++;
switch (*p)
{
case '=':
p++;
t.value = TOK.divAssign;
return;
case '*':
p++;
startLoc = loc();
while (1)
{
while (1)
{
const c = *p;
switch (c)
{
case '/':
break;
case '\n':
endOfLine();
p++;
continue;
case '\r':
p++;
if (*p != '\n')
endOfLine();
continue;
case 0:
case 0x1A:
error("unterminated /* */ comment");
p = end;
t.loc = loc();
t.value = TOK.endOfFile;
return;
default:
if (c & 0x80)
{
const u = decodeUTF();
if (u == PS || u == LS)
endOfLine();
}
p++;
continue;
}
break;
}
p++;
if (p[-2] == '*' && p - 3 != t.ptr)
break;
}
if (commentToken)
{
t.loc = startLoc;
t.value = TOK.comment;
return;
}
else if (doDocComment && t.ptr[2] == '*' && p - 4 != t.ptr)
{
// if /** but not /**/
getDocComment(t, lastLine == startLoc.linnum, startLoc.linnum - lastDocLine > 1);
lastDocLine = scanloc.linnum;
}
continue;
case '/': // do // style comments
startLoc = loc();
while (1)
{
const c = *++p;
switch (c)
{
case '\n':
break;
case '\r':
if (p[1] == '\n')
p++;
break;
case 0:
case 0x1A:
if (commentToken)
{
p = end;
t.loc = startLoc;
t.value = TOK.comment;
return;
}
if (doDocComment && t.ptr[2] == '/')
{
getDocComment(t, lastLine == startLoc.linnum, startLoc.linnum - lastDocLine > 1);
lastDocLine = scanloc.linnum;
}
p = end;
t.loc = loc();
t.value = TOK.endOfFile;
return;
default:
if (c & 0x80)
{
const u = decodeUTF();
if (u == PS || u == LS)
break;
}
continue;
}
break;
}
if (commentToken)
{
p++;
endOfLine();
t.loc = startLoc;
t.value = TOK.comment;
return;
}
if (doDocComment && t.ptr[2] == '/')
{
getDocComment(t, lastLine == startLoc.linnum, startLoc.linnum - lastDocLine > 1);
lastDocLine = scanloc.linnum;
}
p++;
endOfLine();
continue;
case '+':
{
int nest;
startLoc = loc();
p++;
nest = 1;
while (1)
{
char c = *p;
switch (c)
{
case '/':
p++;
if (*p == '+')
{
p++;
nest++;
}
continue;
case '+':
p++;
if (*p == '/')
{
p++;
if (--nest == 0)
break;
}
continue;
case '\r':
p++;
if (*p != '\n')
endOfLine();
continue;
case '\n':
endOfLine();
p++;
continue;
case 0:
case 0x1A:
error("unterminated /+ +/ comment");
p = end;
t.loc = loc();
t.value = TOK.endOfFile;
return;
default:
if (c & 0x80)
{
uint u = decodeUTF();
if (u == PS || u == LS)
endOfLine();
}
p++;
continue;
}
break;
}
if (commentToken)
{
t.loc = startLoc;
t.value = TOK.comment;
return;
}
if (doDocComment && t.ptr[2] == '+' && p - 4 != t.ptr)
{
// if /++ but not /++/
getDocComment(t, lastLine == startLoc.linnum, startLoc.linnum - lastDocLine > 1);
lastDocLine = scanloc.linnum;
}
continue;
}
default:
break;
}
t.value = TOK.div;
return;
case '.':
p++;
if (isdigit(*p))
{
/* Note that we don't allow ._1 and ._ as being
* valid floating point numbers.
*/
p--;
t.value = inreal(t);
}
else if (p[0] == '.')
{
if (p[1] == '.')
{
p += 2;
t.value = TOK.dotDotDot;
}
else
{
p++;
t.value = TOK.slice;
}
}
else
t.value = TOK.dot;
return;
case '&':
p++;
if (*p == '=')
{
p++;
t.value = TOK.andAssign;
}
else if (*p == '&')
{
p++;
t.value = TOK.andAnd;
}
else
t.value = TOK.and;
return;
case '|':
p++;
if (*p == '=')
{
p++;
t.value = TOK.orAssign;
}
else if (*p == '|')
{
p++;
t.value = TOK.orOr;
}
else
t.value = TOK.or;
return;
case '-':
p++;
if (*p == '=')
{
p++;
t.value = TOK.minAssign;
}
else if (*p == '-')
{
p++;
t.value = TOK.minusMinus;
}
else
t.value = TOK.min;
return;
case '+':
p++;
if (*p == '=')
{
p++;
t.value = TOK.addAssign;
}
else if (*p == '+')
{
p++;
t.value = TOK.plusPlus;
}
else
t.value = TOK.add;
return;
case '<':
p++;
if (*p == '=')
{
p++;
t.value = TOK.lessOrEqual; // <=
}
else if (*p == '<')
{
p++;
if (*p == '=')
{
p++;
t.value = TOK.leftShiftAssign; // <<=
}
else
t.value = TOK.leftShift; // <<
}
else
t.value = TOK.lessThan; // <
return;
case '>':
p++;
if (*p == '=')
{
p++;
t.value = TOK.greaterOrEqual; // >=
}
else if (*p == '>')
{
p++;
if (*p == '=')
{
p++;
t.value = TOK.rightShiftAssign; // >>=
}
else if (*p == '>')
{
p++;
if (*p == '=')
{
p++;
t.value = TOK.unsignedRightShiftAssign; // >>>=
}
else
t.value = TOK.unsignedRightShift; // >>>
}
else
t.value = TOK.rightShift; // >>
}
else
t.value = TOK.greaterThan; // >
return;
case '!':
p++;
if (*p == '=')
{
p++;
t.value = TOK.notEqual; // !=
}
else
t.value = TOK.not; // !
return;
case '=':
p++;
if (*p == '=')
{
p++;
t.value = TOK.equal; // ==
}
else if (*p == '>')
{
p++;
t.value = TOK.goesTo; // =>
}
else
t.value = TOK.assign; // =
return;
case '~':
p++;
if (*p == '=')
{
p++;
t.value = TOK.concatenateAssign; // ~=
}
else
t.value = TOK.tilde; // ~
return;
case '^':
p++;
if (*p == '^')
{
p++;
if (*p == '=')
{
p++;
t.value = TOK.powAssign; // ^^=
}
else
t.value = TOK.pow; // ^^
}
else if (*p == '=')
{
p++;
t.value = TOK.xorAssign; // ^=
}
else
t.value = TOK.xor; // ^
return;
case '(':
p++;
t.value = TOK.leftParentheses;
return;
case ')':
p++;
t.value = TOK.rightParentheses;
return;
case '[':
p++;
t.value = TOK.leftBracket;
return;
case ']':
p++;
t.value = TOK.rightBracket;
return;
case '{':
p++;
t.value = TOK.leftCurly;
return;
case '}':
p++;
t.value = TOK.rightCurly;
return;
case '?':
p++;
t.value = TOK.question;
return;
case ',':
p++;
t.value = TOK.comma;
return;
case ';':
p++;
t.value = TOK.semicolon;
return;
case ':':
p++;
t.value = TOK.colon;
return;
case '$':
p++;
t.value = TOK.dollar;
return;
case '@':
p++;
t.value = TOK.at;
return;
case '*':
p++;
if (*p == '=')
{
p++;
t.value = TOK.mulAssign;
}
else
t.value = TOK.mul;
return;
case '%':
p++;
if (*p == '=')
{
p++;
t.value = TOK.modAssign;
}
else
t.value = TOK.mod;
return;
case '#':
{
p++;
Token n;
scan(&n);
if (n.value == TOK.identifier)
{
if (n.ident == Id.line)
{
poundLine();
continue;
}
else
{
const locx = loc();
warning(locx, "C preprocessor directive `#%s` is not supported", n.ident.toChars());
}
}
else if (n.value == TOK.if_)
{
error("C preprocessor directive `#if` is not supported, use `version` or `static if`");
}
t.value = TOK.pound;
return;
}
default:
{
dchar c = *p;
if (c & 0x80)
{
c = decodeUTF();
// Check for start of unicode identifier
if (isUniAlpha(c))
goto case_ident;
if (c == PS || c == LS)
{
endOfLine();
p++;
continue;
}
}
if (c < 0x80 && isprint(c))
error("character '%c' is not a valid token", c);
else
error("character 0x%02x is not a valid token", c);
p++;
continue;
}
}
}
}
final Token* peek(Token* ct)
{
Token* t;
if (ct.next)
t = ct.next;
else
{
t = allocateToken();
scan(t);
ct.next = t;
}
return t;
}
/*********************************
* tk is on the opening (.
* Look ahead and return token that is past the closing ).
*/
final Token* peekPastParen(Token* tk)
{
//printf("peekPastParen()\n");
int parens = 1;
int curlynest = 0;
while (1)
{
tk = peek(tk);
//tk.print();
switch (tk.value)
{
case TOK.leftParentheses:
parens++;
continue;
case TOK.rightParentheses:
--parens;
if (parens)
continue;
tk = peek(tk);
break;
case TOK.leftCurly:
curlynest++;
continue;
case TOK.rightCurly:
if (--curlynest >= 0)
continue;
break;
case TOK.semicolon:
if (curlynest)
continue;
break;
case TOK.endOfFile:
break;
default:
continue;
}
return tk;
}
}
/*******************************************
* Parse escape sequence.
*/
private uint escapeSequence()
{
return Lexer.escapeSequence(token.loc, diagnosticReporter, p);
}
/**
Parse the given string literal escape sequence into a single character.
Params:
loc = the location of the current token
handler = the diagnostic reporter object
sequence = pointer to string with escape sequence to parse. this is a reference
variable that is also used to return the position after the sequence
Returns:
the escaped sequence as a single character
*/
private static dchar escapeSequence(const ref Loc loc, DiagnosticReporter handler, ref const(char)* sequence)
in
{
assert(handler !is null);
}
body
{
const(char)* p = sequence; // cache sequence reference on stack
scope(exit) sequence = p;
uint c = *p;
int ndigits;
switch (c)
{
case '\'':
case '"':
case '?':
case '\\':
Lconsume:
p++;
break;
case 'a':
c = 7;
goto Lconsume;
case 'b':
c = 8;
goto Lconsume;
case 'f':
c = 12;
goto Lconsume;
case 'n':
c = 10;
goto Lconsume;
case 'r':
c = 13;
goto Lconsume;
case 't':
c = 9;
goto Lconsume;
case 'v':
c = 11;
goto Lconsume;
case 'u':
ndigits = 4;
goto Lhex;
case 'U':
ndigits = 8;
goto Lhex;
case 'x':
ndigits = 2;
Lhex:
p++;
c = *p;
if (ishex(cast(char)c))
{
uint v = 0;
int n = 0;
while (1)
{
if (isdigit(cast(char)c))
c -= '0';
else if (islower(c))
c -= 'a' - 10;
else
c -= 'A' - 10;
v = v * 16 + c;
c = *++p;
if (++n == ndigits)
break;
if (!ishex(cast(char)c))
{
handler.error(loc, "escape hex sequence has %d hex digits instead of %d", n, ndigits);
break;
}
}
if (ndigits != 2 && !utf_isValidDchar(v))
{
handler.error(loc, "invalid UTF character \\U%08x", v);
v = '?'; // recover with valid UTF character
}
c = v;
}
else
{
handler.error(loc, "undefined escape hex sequence \\%c%c", sequence[0], c);
p++;
}
break;
case '&':
// named character entity
for (const idstart = ++p; 1; p++)
{
switch (*p)
{
case ';':
c = HtmlNamedEntity(idstart, p - idstart);
if (c == ~0)
{
handler.error(loc, "unnamed character entity &%.*s;", cast(int)(p - idstart), idstart);
c = '?';
}
p++;
break;
default:
if (isalpha(*p) || (p != idstart && isdigit(*p)))
continue;
handler.error(loc, "unterminated named entity &%.*s;", cast(int)(p - idstart + 1), idstart);
c = '?';
break;
}
break;
}
break;
case 0:
case 0x1A:
// end of file
c = '\\';
break;
default:
if (isoctal(cast(char)c))
{
uint v = 0;
int n = 0;
do
{
v = v * 8 + (c - '0');
c = *++p;
}
while (++n < 3 && isoctal(cast(char)c));
c = v;
if (c > 0xFF)
handler.error(loc, "escape octal sequence \\%03o is larger than \\377", c);
}
else
{
handler.error(loc, "undefined escape sequence \\%c", c);
p++;
}
break;
}
return c;
}
/**
Lex a wysiwyg string. `p` must be pointing to the first character before the
contents of the string literal. The character pointed to by `p` will be used as
the terminating character (i.e. backtick or double-quote).
Params:
result = pointer to the token that accepts the result
*/
private void wysiwygStringConstant(Token* result)
{
result.value = TOK.string_;
Loc start = loc();
auto terminator = p[0];
p++;
stringbuffer.reset();
while (1)
{
dchar c = p[0];
p++;
switch (c)
{
case '\n':
endOfLine();
break;
case '\r':
if (p[0] == '\n')
continue; // ignore
c = '\n'; // treat EndOfLine as \n character
endOfLine();
break;
case 0:
case 0x1A:
error("unterminated string constant starting at %s", start.toChars());
result.setString();
// rewind `p` so it points to the EOF character
p--;
return;
default:
if (c == terminator)
{
result.setString(stringbuffer);
stringPostfix(result);
return;
}
else if (c & 0x80)
{
p--;
const u = decodeUTF();
p++;
if (u == PS || u == LS)
endOfLine();
stringbuffer.writeUTF8(u);
continue;
}
break;
}
stringbuffer.writeByte(c);
}
}
/**************************************
* Lex hex strings:
* x"0A ae 34FE BD"
*/
private TOK hexStringConstant(Token* t)
{
Loc start = loc();
uint n = 0;
uint v = ~0; // dead assignment, needed to suppress warning
p++;
stringbuffer.reset();
while (1)
{
dchar c = *p++;
switch (c)
{
case ' ':
case '\t':
case '\v':
case '\f':
continue; // skip white space
case '\r':
if (*p == '\n')
continue; // ignore '\r' if followed by '\n'
// Treat isolated '\r' as if it were a '\n'
goto case '\n';
case '\n':
endOfLine();
continue;
case 0:
case 0x1A:
error("unterminated string constant starting at %s", start.toChars());
t.setString();
// decrement `p`, because it needs to point to the next token (the 0 or 0x1A character is the TOK.endOfFile token).
p--;
return TOK.hexadecimalString;
case '"':
if (n & 1)
{
error("odd number (%d) of hex characters in hex string", n);
stringbuffer.writeByte(v);
}
t.setString(stringbuffer);
stringPostfix(t);
return TOK.hexadecimalString;
default:
if (c >= '0' && c <= '9')
c -= '0';
else if (c >= 'a' && c <= 'f')
c -= 'a' - 10;
else if (c >= 'A' && c <= 'F')
c -= 'A' - 10;
else if (c & 0x80)
{
p--;
const u = decodeUTF();
p++;
if (u == PS || u == LS)
endOfLine();
else
error("non-hex character \\u%04x in hex string", u);
}
else
error("non-hex character '%c' in hex string", c);
if (n & 1)
{
v = (v << 4) | c;
stringbuffer.writeByte(v);
}
else
v = c;
n++;
break;
}
}
assert(0); // see bug 15731
}
/**
Lex a delimited string. Some examples of delimited strings are:
---
q"(foo(xxx))" // "foo(xxx)"
q"[foo$(LPAREN)]" // "foo$(LPAREN)"
q"/foo]/" // "foo]"
q"HERE
foo
HERE" // "foo\n"
---
It is assumed that `p` points to the opening double-quote '"'.
Params:
result = pointer to the token that accepts the result
*/
private void delimitedStringConstant(Token* result)
{
result.value = TOK.string_;
Loc start = loc();
dchar delimleft = 0;
dchar delimright = 0;
uint nest = 1;
uint nestcount = ~0; // dead assignment, needed to suppress warning
Identifier hereid = null;
uint blankrol = 0;
uint startline = 0;
p++;
stringbuffer.reset();
while (1)
{
dchar c = *p++;
//printf("c = '%c'\n", c);
switch (c)
{
case '\n':
Lnextline:
endOfLine();
startline = 1;
if (blankrol)
{
blankrol = 0;
continue;
}
if (hereid)
{
stringbuffer.writeUTF8(c);
continue;
}
break;
case '\r':
if (*p == '\n')
continue; // ignore
c = '\n'; // treat EndOfLine as \n character
goto Lnextline;
case 0:
case 0x1A:
error("unterminated delimited string constant starting at %s", start.toChars());
result.setString();
// decrement `p`, because it needs to point to the next token (the 0 or 0x1A character is the TOK.endOfFile token).
p--;
return;
default:
if (c & 0x80)
{
p--;
c = decodeUTF();
p++;
if (c == PS || c == LS)
goto Lnextline;
}
break;
}
if (delimleft == 0)
{
delimleft = c;
nest = 1;
nestcount = 1;
if (c == '(')
delimright = ')';
else if (c == '{')
delimright = '}';
else if (c == '[')
delimright = ']';
else if (c == '<')
delimright = '>';
else if (isalpha(c) || c == '_' || (c >= 0x80 && isUniAlpha(c)))
{
// Start of identifier; must be a heredoc
Token tok;
p--;
scan(&tok); // read in heredoc identifier
if (tok.value != TOK.identifier)
{
error("identifier expected for heredoc, not %s", tok.toChars());
delimright = c;
}
else
{
hereid = tok.ident;
//printf("hereid = '%s'\n", hereid.toChars());
blankrol = 1;
}
nest = 0;
}
else
{
delimright = c;
nest = 0;
if (isspace(c))
error("delimiter cannot be whitespace");
}
}
else
{
if (blankrol)
{
error("heredoc rest of line should be blank");
blankrol = 0;
continue;
}
if (nest == 1)
{
if (c == delimleft)
nestcount++;
else if (c == delimright)
{
nestcount--;
if (nestcount == 0)
goto Ldone;
}
}
else if (c == delimright)
goto Ldone;
if (startline && (isalpha(c) || c == '_' || (c >= 0x80 && isUniAlpha(c))) && hereid)
{
Token tok;
auto psave = p;
p--;
scan(&tok); // read in possible heredoc identifier
//printf("endid = '%s'\n", tok.ident.toChars());
if (tok.value == TOK.identifier && tok.ident.equals(hereid))
{
/* should check that rest of line is blank
*/
goto Ldone;
}
p = psave;
}
stringbuffer.writeUTF8(c);
startline = 0;
}
}
Ldone:
if (*p == '"')
p++;
else if (hereid)
error("delimited string must end in %s\"", hereid.toChars());
else
error("delimited string must end in %c\"", delimright);
result.setString(stringbuffer);
stringPostfix(result);
}
/**
Lex a token string. Some examples of token strings are:
---
q{ foo(xxx) } // " foo(xxx) "
q{foo$(LPAREN)} // "foo$(LPAREN)"
q{{foo}"}"} // "{foo}"}""
---
It is assumed that `p` points to the opening curly-brace '{'.
Params:
result = pointer to the token that accepts the result
*/
private void tokenStringConstant(Token* result)
{
result.value = TOK.string_;
uint nest = 1;
const start = loc();
const pstart = ++p;
while (1)
{
Token tok;
scan(&tok);
switch (tok.value)
{
case TOK.leftCurly:
nest++;
continue;
case TOK.rightCurly:
if (--nest == 0)
{
result.setString(pstart, p - 1 - pstart);
stringPostfix(result);
return;
}
continue;
case TOK.endOfFile:
error("unterminated token string constant starting at %s", start.toChars());
result.setString();
return;
default:
continue;
}
}
}
/**
Scan a double-quoted string while building the processed string value by
handling escape sequences. The result is returned in the given `t` token.
This function assumes that `p` currently points to the opening double-quote
of the string.
Params:
t = the token to set the resulting string to
*/
private void escapeStringConstant(Token* t)
{
t.value = TOK.string_;
const start = loc();
p++;
stringbuffer.reset();
while (1)
{
dchar c = *p++;
switch (c)
{
case '\\':
switch (*p)
{
case 'u':
case 'U':
case '&':
c = escapeSequence();
stringbuffer.writeUTF8(c);
continue;
default:
c = escapeSequence();
break;
}
break;
case '\n':
endOfLine();
break;
case '\r':
if (*p == '\n')
continue; // ignore
c = '\n'; // treat EndOfLine as \n character
endOfLine();
break;
case '"':
t.setString(stringbuffer);
stringPostfix(t);
return;
case 0:
case 0x1A:
// decrement `p`, because it needs to point to the next token (the 0 or 0x1A character is the TOK.endOfFile token).
p--;
error("unterminated string constant starting at %s", start.toChars());
t.setString();
return;
default:
if (c & 0x80)
{
p--;
c = decodeUTF();
if (c == LS || c == PS)
{
c = '\n';
endOfLine();
}
p++;
stringbuffer.writeUTF8(c);
continue;
}
break;
}
stringbuffer.writeByte(c);
}
}
/**************************************
*/
private TOK charConstant(Token* t)
{
TOK tk = TOK.charLiteral;
//printf("Lexer::charConstant\n");
p++;
dchar c = *p++;
switch (c)
{
case '\\':
switch (*p)
{
case 'u':
t.unsvalue = escapeSequence();
tk = TOK.wcharLiteral;
break;
case 'U':
case '&':
t.unsvalue = escapeSequence();
tk = TOK.dcharLiteral;
break;
default:
t.unsvalue = escapeSequence();
break;
}
break;
case '\n':
L1:
endOfLine();
goto case;
case '\r':
goto case '\'';
case 0:
case 0x1A:
// decrement `p`, because it needs to point to the next token (the 0 or 0x1A character is the TOK.endOfFile token).
p--;
goto case;
case '\'':
error("unterminated character constant");
t.unsvalue = '?';
return tk;
default:
if (c & 0x80)
{
p--;
c = decodeUTF();
p++;
if (c == LS || c == PS)
goto L1;
if (c < 0xD800 || (c >= 0xE000 && c < 0xFFFE))
tk = TOK.wcharLiteral;
else
tk = TOK.dcharLiteral;
}
t.unsvalue = c;
break;
}
if (*p != '\'')
{
error("unterminated character constant");
t.unsvalue = '?';
return tk;
}
p++;
return tk;
}
/***************************************
* Get postfix of string literal.
*/
private void stringPostfix(Token* t)
{
switch (*p)
{
case 'c':
case 'w':
case 'd':
t.postfix = *p;
p++;
break;
default:
t.postfix = 0;
break;
}
}
/**************************************
* Read in a number.
* If it's an integer, store it in tok.TKutok.Vlong.
* integers can be decimal, octal or hex
* Handle the suffixes U, UL, LU, L, etc.
* If it's double, store it in tok.TKutok.Vdouble.
* Returns:
* TKnum
* TKdouble,...
*/
private TOK number(Token* t)
{
int base = 10;
const start = p;
uinteger_t n = 0; // unsigned >=64 bit integer type
int d;
bool err = false;
bool overflow = false;
bool anyBinaryDigitsNoSingleUS = false;
bool anyHexDigitsNoSingleUS = false;
dchar c = *p;
if (c == '0')
{
++p;
c = *p;
switch (c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
base = 8;
break;
case 'x':
case 'X':
++p;
base = 16;
break;
case 'b':
case 'B':
++p;
base = 2;
break;
case '.':
if (p[1] == '.')
goto Ldone; // if ".."
if (isalpha(p[1]) || p[1] == '_' || p[1] & 0x80)
goto Ldone; // if ".identifier" or ".unicode"
goto Lreal; // '.' is part of current token
case 'i':
case 'f':
case 'F':
goto Lreal;
case '_':
++p;
base = 8;
break;
case 'L':
if (p[1] == 'i')
goto Lreal;
break;
default:
break;
}
}
while (1)
{
c = *p;
switch (c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
++p;
d = c - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
++p;
if (base != 16)
{
if (c == 'e' || c == 'E' || c == 'f' || c == 'F')
goto Lreal;
}
if (c >= 'a')
d = c + 10 - 'a';
else
d = c + 10 - 'A';
break;
case 'L':
if (p[1] == 'i')
goto Lreal;
goto Ldone;
case '.':
if (p[1] == '.')
goto Ldone; // if ".."
if (base == 10 && (isalpha(p[1]) || p[1] == '_' || p[1] & 0x80))
goto Ldone; // if ".identifier" or ".unicode"
goto Lreal; // otherwise as part of a floating point literal
case 'p':
case 'P':
case 'i':
Lreal:
p = start;
return inreal(t);
case '_':
++p;
continue;
default:
goto Ldone;
}
// got a digit here, set any necessary flags, check for errors
anyHexDigitsNoSingleUS = true;
anyBinaryDigitsNoSingleUS = true;
if (!err && d >= base)
{
error("%s digit expected, not `%c`", base == 2 ? "binary".ptr :
base == 8 ? "octal".ptr :
"decimal".ptr, c);
err = true;
}
// Avoid expensive overflow check if we aren't at risk of overflow
if (n <= 0x0FFF_FFFF_FFFF_FFFFUL)
n = n * base + d;
else
{
import core.checkedint : mulu, addu;
n = mulu(n, base, overflow);
n = addu(n, d, overflow);
}
}
Ldone:
if (overflow && !err)
{
error("integer overflow");
err = true;
}
// Deprecated in 2018-06.
// Change to error in 2019-06.
// @@@DEPRECATED_2019-06@@@
if ((base == 2 && !anyBinaryDigitsNoSingleUS) ||
(base == 16 && !anyHexDigitsNoSingleUS))
deprecation("`%.*s` isn't a valid integer literal, use `%.*s0` instead", cast(int)(p - start), start, 2, start);
enum FLAGS : int
{
none = 0,
decimal = 1, // decimal
unsigned = 2, // u or U suffix
long_ = 4, // L suffix
}
FLAGS flags = (base == 10) ? FLAGS.decimal : FLAGS.none;
// Parse trailing 'u', 'U', 'l' or 'L' in any combination
const psuffix = p;
while (1)
{
FLAGS f;
switch (*p)
{
case 'U':
case 'u':
f = FLAGS.unsigned;
goto L1;
case 'l':
f = FLAGS.long_;
error("lower case integer suffix 'l' is not allowed. Please use 'L' instead");
goto L1;
case 'L':
f = FLAGS.long_;
L1:
p++;
if ((flags & f) && !err)
{
error("unrecognized token");
err = true;
}
flags = cast(FLAGS)(flags | f);
continue;
default:
break;
}
break;
}
if (base == 8 && n >= 8)
{
if (err)
// can't translate invalid octal value, just show a generic message
error("octal literals larger than 7 are no longer supported");
else
error("octal literals `0%llo%.*s` are no longer supported, use `std.conv.octal!%llo%.*s` instead",
n, cast(int)(p - psuffix), psuffix, n, cast(int)(p - psuffix), psuffix);
}
TOK result;
switch (flags)
{
case FLAGS.none:
/* Octal or Hexadecimal constant.
* First that fits: int, uint, long, ulong
*/
if (n & 0x8000000000000000L)
result = TOK.uns64Literal;
else if (n & 0xFFFFFFFF00000000L)
result = TOK.int64Literal;
else if (n & 0x80000000)
result = TOK.uns32Literal;
else
result = TOK.int32Literal;
break;
case FLAGS.decimal:
/* First that fits: int, long, long long
*/
if (n & 0x8000000000000000L)
{
if (!err)
{
error("signed integer overflow");
err = true;
}
result = TOK.uns64Literal;
}
else if (n & 0xFFFFFFFF80000000L)
result = TOK.int64Literal;
else
result = TOK.int32Literal;
break;
case FLAGS.unsigned:
case FLAGS.decimal | FLAGS.unsigned:
/* First that fits: uint, ulong
*/
if (n & 0xFFFFFFFF00000000L)
result = TOK.uns64Literal;
else
result = TOK.uns32Literal;
break;
case FLAGS.decimal | FLAGS.long_:
if (n & 0x8000000000000000L)
{
if (!err)
{
error("signed integer overflow");
err = true;
}
result = TOK.uns64Literal;
}
else
result = TOK.int64Literal;
break;
case FLAGS.long_:
if (n & 0x8000000000000000L)
result = TOK.uns64Literal;
else
result = TOK.int64Literal;
break;
case FLAGS.unsigned | FLAGS.long_:
case FLAGS.decimal | FLAGS.unsigned | FLAGS.long_:
result = TOK.uns64Literal;
break;
default:
debug
{
printf("%x\n", flags);
}
assert(0);
}
t.unsvalue = n;
return result;
}
/**************************************
* Read in characters, converting them to real.
* Bugs:
* Exponent overflow not detected.
* Too much requested precision is not detected.
*/
private TOK inreal(Token* t)
{
//printf("Lexer::inreal()\n");
debug
{
assert(*p == '.' || isdigit(*p));
}
bool isWellformedString = true;
stringbuffer.reset();
auto pstart = p;
bool hex = false;
dchar c = *p++;
// Leading '0x'
if (c == '0')
{
c = *p++;
if (c == 'x' || c == 'X')
{
hex = true;
c = *p++;
}
}
// Digits to left of '.'
while (1)
{
if (c == '.')
{
c = *p++;
break;
}
if (isdigit(c) || (hex && isxdigit(c)) || c == '_')
{
c = *p++;
continue;
}
break;
}
// Digits to right of '.'
while (1)
{
if (isdigit(c) || (hex && isxdigit(c)) || c == '_')
{
c = *p++;
continue;
}
break;
}
if (c == 'e' || c == 'E' || (hex && (c == 'p' || c == 'P')))
{
c = *p++;
if (c == '-' || c == '+')
{
c = *p++;
}
bool anyexp = false;
while (1)
{
if (isdigit(c))
{
anyexp = true;
c = *p++;
continue;
}
if (c == '_')
{
c = *p++;
continue;
}
if (!anyexp)
{
error("missing exponent");
isWellformedString = false;
}
break;
}
}
else if (hex)
{
error("exponent required for hex float");
isWellformedString = false;
}
--p;
while (pstart < p)
{
if (*pstart != '_')
stringbuffer.writeByte(*pstart);
++pstart;
}
stringbuffer.writeByte(0);
auto sbufptr = cast(const(char)*)stringbuffer.data;
TOK result;
bool isOutOfRange = false;
t.floatvalue = (isWellformedString ? CTFloat.parse(sbufptr, &isOutOfRange) : CTFloat.zero);
switch (*p)
{
case 'F':
case 'f':
if (isWellformedString && !isOutOfRange)
isOutOfRange = Port.isFloat32LiteralOutOfRange(sbufptr);
result = TOK.float32Literal;
p++;
break;
default:
if (isWellformedString && !isOutOfRange)
isOutOfRange = Port.isFloat64LiteralOutOfRange(sbufptr);
result = TOK.float64Literal;
break;
case 'l':
error("use 'L' suffix instead of 'l'");
goto case 'L';
case 'L':
result = TOK.float80Literal;
p++;
break;
}
if (*p == 'i' || *p == 'I')
{
if (*p == 'I')
error("use 'i' suffix instead of 'I'");
p++;
switch (result)
{
case TOK.float32Literal:
result = TOK.imaginary32Literal;
break;
case TOK.float64Literal:
result = TOK.imaginary64Literal;
break;
case TOK.float80Literal:
result = TOK.imaginary80Literal;
break;
default:
break;
}
}
const isLong = (result == TOK.float80Literal || result == TOK.imaginary80Literal);
if (isOutOfRange && !isLong)
{
const char* suffix = (result == TOK.float32Literal || result == TOK.imaginary32Literal) ? "f" : "";
error(scanloc, "number `%s%s` is not representable", sbufptr, suffix);
}
debug
{
switch (result)
{
case TOK.float32Literal:
case TOK.float64Literal:
case TOK.float80Literal:
case TOK.imaginary32Literal:
case TOK.imaginary64Literal:
case TOK.imaginary80Literal:
break;
default:
assert(0);
}
}
return result;
}
final Loc loc()
{
scanloc.charnum = cast(uint)(1 + p - line);
return scanloc;
}
final void error(const(char)* format, ...)
{
va_list args;
va_start(args, format);
diagnosticReporter.error(token.loc, format, args);
va_end(args);
}
final void error(const ref Loc loc, const(char)* format, ...)
{
va_list args;
va_start(args, format);
diagnosticReporter.error(loc, format, args);
va_end(args);
}
final void errorSupplemental(const ref Loc loc, const(char)* format, ...)
{
va_list args;
va_start(args, format);
diagnosticReporter.errorSupplemental(loc, format, args);
va_end(args);
}
final void warning(const ref Loc loc, const(char)* format, ...)
{
va_list args;
va_start(args, format);
diagnosticReporter.warning(loc, format, args);
va_end(args);
}
final void warningSupplemental(const ref Loc loc, const(char)* format, ...)
{
va_list args;
va_start(args, format);
diagnosticReporter.warningSupplemental(loc, format, args);
va_end(args);
}
final void deprecation(const(char)* format, ...)
{
va_list args;
va_start(args, format);
diagnosticReporter.deprecation(token.loc, format, args);
va_end(args);
}
final void deprecation(const ref Loc loc, const(char)* format, ...)
{
va_list args;
va_start(args, format);
diagnosticReporter.deprecation(loc, format, args);
va_end(args);
}
final void deprecationSupplemental(const ref Loc loc, const(char)* format, ...)
{
va_list args;
va_start(args, format);
diagnosticReporter.deprecationSupplemental(loc, format, args);
va_end(args);
}
/*********************************************
* parse:
* #line linnum [filespec]
* also allow __LINE__ for linnum, and __FILE__ for filespec
*/
private void poundLine()
{
auto linnum = this.scanloc.linnum;
const(char)* filespec = null;
const loc = this.loc();
Token tok;
scan(&tok);
if (tok.value == TOK.int32Literal || tok.value == TOK.int64Literal)
{
const lin = cast(int)(tok.unsvalue - 1);
if (lin != tok.unsvalue - 1)
error("line number `%lld` out of range", cast(ulong)tok.unsvalue);
else
linnum = lin;
}
else if (tok.value == TOK.line)
{
}
else
goto Lerr;
while (1)
{
switch (*p)
{
case 0:
case 0x1A:
case '\n':
Lnewline:
this.scanloc.linnum = linnum;
if (filespec)
this.scanloc.filename = filespec;
return;
case '\r':
p++;
if (*p != '\n')
{
p--;
goto Lnewline;
}
continue;
case ' ':
case '\t':
case '\v':
case '\f':
p++;
continue; // skip white space
case '_':
if (memcmp(p, "__FILE__".ptr, 8) == 0)
{
p += 8;
filespec = mem.xstrdup(scanloc.filename);
continue;
}
goto Lerr;
case '"':
if (filespec)
goto Lerr;
stringbuffer.reset();
p++;
while (1)
{
uint c;
c = *p;
switch (c)
{
case '\n':
case '\r':
case 0:
case 0x1A:
goto Lerr;
case '"':
stringbuffer.writeByte(0);
filespec = mem.xstrdup(cast(const(char)*)stringbuffer.data);
p++;
break;
default:
if (c & 0x80)
{
uint u = decodeUTF();
if (u == PS || u == LS)
goto Lerr;
}
stringbuffer.writeByte(c);
p++;
continue;
}
break;
}
continue;
default:
if (*p & 0x80)
{
uint u = decodeUTF();
if (u == PS || u == LS)
goto Lnewline;
}
goto Lerr;
}
}
Lerr:
error(loc, "#line integer [\"filespec\"]\\n expected");
}
/********************************************
* Decode UTF character.
* Issue error messages for invalid sequences.
* Return decoded character, advance p to last character in UTF sequence.
*/
private uint decodeUTF()
{
const s = p;
assert(*s & 0x80);
// Check length of remaining string up to 4 UTF-8 characters
size_t len;
for (len = 1; len < 4 && s[len]; len++)
{
}
size_t idx = 0;
dchar u;
const msg = utf_decodeChar(s, len, idx, u);
p += idx - 1;
if (msg)
{
error("%s", msg);
}
return u;
}
/***************************************************
* Parse doc comment embedded between t.ptr and p.
* Remove trailing blanks and tabs from lines.
* Replace all newlines with \n.
* Remove leading comment character from each line.
* Decide if it's a lineComment or a blockComment.
* Append to previous one for this token.
*
* If newParagraph is true, an extra newline will be
* added between adjoining doc comments.
*/
private void getDocComment(Token* t, uint lineComment, bool newParagraph)
{
/* ct tells us which kind of comment it is: '/', '*', or '+'
*/
const ct = t.ptr[2];
/* Start of comment text skips over / * *, / + +, or / / /
*/
const(char)* q = t.ptr + 3; // start of comment text
const(char)* qend = p;
if (ct == '*' || ct == '+')
qend -= 2;
/* Scan over initial row of ****'s or ++++'s or ////'s
*/
for (; q < qend; q++)
{
if (*q != ct)
break;
}
/* Remove leading spaces until start of the comment
*/
int linestart = 0;
if (ct == '/')
{
while (q < qend && (*q == ' ' || *q == '\t'))
++q;
}
else if (q < qend)
{
if (*q == '\r')
{
++q;
if (q < qend && *q == '\n')
++q;
linestart = 1;
}
else if (*q == '\n')
{
++q;
linestart = 1;
}
}
/* Remove trailing row of ****'s or ++++'s
*/
if (ct != '/')
{
for (; q < qend; qend--)
{
if (qend[-1] != ct)
break;
}
}
/* Comment is now [q .. qend].
* Canonicalize it into buf[].
*/
OutBuffer buf;
void trimTrailingWhitespace()
{
const s = buf.peekSlice();
auto len = s.length;
while (len && (s[len - 1] == ' ' || s[len - 1] == '\t'))
--len;
buf.setsize(len);
}
for (; q < qend; q++)
{
char c = *q;
switch (c)
{
case '*':
case '+':
if (linestart && c == ct)
{
linestart = 0;
/* Trim preceding whitespace up to preceding \n
*/
trimTrailingWhitespace();
continue;
}
break;
case ' ':
case '\t':
break;
case '\r':
if (q[1] == '\n')
continue; // skip the \r
goto Lnewline;
default:
if (c == 226)
{
// If LS or PS
if (q[1] == 128 && (q[2] == 168 || q[2] == 169))
{
q += 2;
goto Lnewline;
}
}
linestart = 0;
break;
Lnewline:
c = '\n'; // replace all newlines with \n
goto case;
case '\n':
linestart = 1;
/* Trim trailing whitespace
*/
trimTrailingWhitespace();
break;
}
buf.writeByte(c);
}
/* Trim trailing whitespace (if the last line does not have newline)
*/
trimTrailingWhitespace();
// Always end with a newline
const s = buf.peekSlice();
if (s.length == 0 || s[$ - 1] != '\n')
buf.writeByte('\n');
// It's a line comment if the start of the doc comment comes
// after other non-whitespace on the same line.
auto dc = (lineComment && anyToken) ? &t.lineComment : &t.blockComment;
// Combine with previous doc comment, if any
if (*dc)
*dc = combineComments(*dc, buf.peekString(), newParagraph);
else
*dc = buf.extractString();
}
/********************************************
* Combine two document comments into one,
* separated by an extra newline if newParagraph is true.
*/
static const(char)* combineComments(const(char)* c1, const(char)* c2, bool newParagraph)
{
//printf("Lexer::combineComments('%s', '%s', '%i')\n", c1, c2, newParagraph);
auto c = c2;
const(int) newParagraphSize = newParagraph ? 1 : 0; // Size of the combining '\n'
if (c1)
{
c = c1;
if (c2)
{
size_t len1 = strlen(c1);
size_t len2 = strlen(c2);
int insertNewLine = 0;
if (len1 && c1[len1 - 1] != '\n')
{
++len1;
insertNewLine = 1;
}
auto p = cast(char*)mem.xmalloc(len1 + newParagraphSize + len2 + 1);
memcpy(p, c1, len1 - insertNewLine);
if (insertNewLine)
p[len1 - 1] = '\n';
if (newParagraph)
p[len1] = '\n';
memcpy(p + len1 + newParagraphSize, c2, len2);
p[len1 + newParagraphSize + len2] = 0;
c = p;
}
}
return c;
}
private:
void endOfLine()
{
scanloc.linnum++;
line = p;
}
}
unittest
{
static final class AssertDiagnosticReporter : DiagnosticReporter
{
override int errorCount() { assert(0); }
override int warningCount() { assert(0); }
override int deprecationCount() { assert(0); }
override void error(const ref Loc, const(char)*, va_list) { assert(0); }
override void errorSupplemental(const ref Loc, const(char)*, va_list) { assert(0); }
override void warning(const ref Loc, const(char)*, va_list) { assert(0); }
override void warningSupplemental(const ref Loc, const(char)*, va_list) { assert(0); }
override void deprecation(const ref Loc, const(char)*, va_list) { assert(0); }
override void deprecationSupplemental(const ref Loc, const(char)*, va_list) { assert(0); }
}
static void test(T)(string sequence, T expected)
{
scope assertOnError = new AssertDiagnosticReporter();
auto p = cast(const(char)*)sequence.ptr;
assert(expected == Lexer.escapeSequence(Loc.initial, assertOnError, p));
assert(p == sequence.ptr + sequence.length);
}
test(`'`, '\'');
test(`"`, '"');
test(`?`, '?');
test(`\`, '\\');
test(`0`, '\0');
test(`a`, '\a');
test(`b`, '\b');
test(`f`, '\f');
test(`n`, '\n');
test(`r`, '\r');
test(`t`, '\t');
test(`v`, '\v');
test(`x00`, 0x00);
test(`xff`, 0xff);
test(`xFF`, 0xff);
test(`xa7`, 0xa7);
test(`x3c`, 0x3c);
test(`xe2`, 0xe2);
test(`1`, '\1');
test(`42`, '\42');
test(`357`, '\357');
test(`u1234`, '\u1234');
test(`uf0e4`, '\uf0e4');
test(`U0001f603`, '\U0001f603');
test(`"`, '"');
test(`<`, '<');
test(`>`, '>');
}
unittest
{
static final class ExpectDiagnosticReporter : DiagnosticReporter
{
string expected;
bool gotError;
this(string expected) { this.expected = expected; }
override int errorCount() { assert(0); }
override int warningCount() { assert(0); }
override int deprecationCount() { assert(0); }
override void error(const ref Loc loc, const(char)* format, va_list args)
{
gotError = true;
char[100] buffer;
auto actual = buffer[0 .. vsprintf(buffer.ptr, format, args)];
assert(expected == actual);
}
override void errorSupplemental(const ref Loc, const(char)*, va_list) { assert(0); }
override void warning(const ref Loc, const(char)*, va_list) { assert(0); }
override void warningSupplemental(const ref Loc, const(char)*, va_list) { assert(0); }
override void deprecation(const ref Loc, const(char)*, va_list) { assert(0); }
override void deprecationSupplemental(const ref Loc, const(char)*, va_list) { assert(0); }
}
static void test(string sequence, string expectedError, dchar expectedReturnValue, uint expectedScanLength)
{
scope handler = new ExpectDiagnosticReporter(expectedError);
auto p = cast(const(char)*)sequence.ptr;
auto actualReturnValue = Lexer.escapeSequence(Loc.initial, handler, p);
assert(handler.gotError);
assert(expectedReturnValue == actualReturnValue);
auto actualScanLength = p - sequence.ptr;
assert(expectedScanLength == actualScanLength);
}
test("c", `undefined escape sequence \c`, 'c', 1);
test("!", `undefined escape sequence \!`, '!', 1);
test("x1", `escape hex sequence has 1 hex digits instead of 2`, '\x01', 2);
test("u1" , `escape hex sequence has 1 hex digits instead of 4`, 0x1, 2);
test("u12" , `escape hex sequence has 2 hex digits instead of 4`, 0x12, 3);
test("u123", `escape hex sequence has 3 hex digits instead of 4`, 0x123, 4);
test("U0" , `escape hex sequence has 1 hex digits instead of 8`, 0x0, 2);
test("U00" , `escape hex sequence has 2 hex digits instead of 8`, 0x00, 3);
test("U000" , `escape hex sequence has 3 hex digits instead of 8`, 0x000, 4);
test("U0000" , `escape hex sequence has 4 hex digits instead of 8`, 0x0000, 5);
test("U0001f" , `escape hex sequence has 5 hex digits instead of 8`, 0x0001f, 6);
test("U0001f6" , `escape hex sequence has 6 hex digits instead of 8`, 0x0001f6, 7);
test("U0001f60", `escape hex sequence has 7 hex digits instead of 8`, 0x0001f60, 8);
test("ud800" , `invalid UTF character \U0000d800`, '?', 5);
test("udfff" , `invalid UTF character \U0000dfff`, '?', 5);
test("U00110000", `invalid UTF character \U00110000`, '?', 9);
test("xg0" , `undefined escape hex sequence \xg`, 'g', 2);
test("ug000" , `undefined escape hex sequence \ug`, 'g', 2);
test("Ug0000000", `undefined escape hex sequence \Ug`, 'g', 2);
test("&BAD;", `unnamed character entity &BAD;` , '?', 5);
test(""", `unterminated named entity "`, '?', 5);
test("400", `escape octal sequence \400 is larger than \377`, 0x100, 3);
}
|
D
|
/home/naufil/Desktop/rust/28April/index4_2/target/debug/index4_2: /home/naufil/Desktop/rust/28April/index4_2/src/main.rs
|
D
|
// Written in the D programming language.
/**
Networking client functionality as provided by $(HTTP _curl.haxx.se/libcurl,
libcurl). The libcurl library must be installed on the system in order to use
this module.
$(SCRIPT inhibitQuickIndex = 1;)
$(DIVC quickindex,
$(BOOKTABLE ,
$(TR $(TH Category) $(TH Functions)
)
$(TR $(TDNW High level) $(TD $(MYREF download) $(MYREF upload) $(MYREF get)
$(MYREF post) $(MYREF put) $(MYREF del) $(MYREF options) $(MYREF trace)
$(MYREF connect) $(MYREF byLine) $(MYREF byChunk)
$(MYREF byLineAsync) $(MYREF byChunkAsync) )
)
$(TR $(TDNW Low level) $(TD $(MYREF HTTP) $(MYREF FTP) $(MYREF
SMTP) )
)
)
)
Note:
You may need to link to the $(B curl) library, e.g. by adding $(D "libs": ["curl"])
to your $(B dub.json) file if you are using $(LINK2 http://code.dlang.org, DUB).
Windows x86 note:
A DMD compatible libcurl static library can be downloaded from the dlang.org
$(LINK2 http://dlang.org/download.html, download page).
Compared to using libcurl directly this module allows simpler client code for
common uses, requires no unsafe operations, and integrates better with the rest
of the language. Futhermore it provides <a href="std_range.html">$(D range)</a>
access to protocols supported by libcurl both synchronously and asynchronously.
A high level and a low level API are available. The high level API is built
entirely on top of the low level one.
The high level API is for commonly used functionality such as HTTP/FTP get. The
$(LREF byLineAsync) and $(LREF byChunkAsync) provides asynchronous <a
href="std_range.html">$(D ranges)</a> that performs the request in another
thread while handling a line/chunk in the current thread.
The low level API allows for streaming and other advanced features.
$(BOOKTABLE Cheat Sheet,
$(TR $(TH Function Name) $(TH Description)
)
$(LEADINGROW High level)
$(TR $(TDNW $(LREF download)) $(TD $(D
download("ftp.digitalmars.com/sieve.ds", "/tmp/downloaded-ftp-file"))
downloads file from URL to file system.)
)
$(TR $(TDNW $(LREF upload)) $(TD $(D
upload("/tmp/downloaded-ftp-file", "ftp.digitalmars.com/sieve.ds");)
uploads file from file system to URL.)
)
$(TR $(TDNW $(LREF get)) $(TD $(D
get("dlang.org")) returns a char[] containing the dlang.org web page.)
)
$(TR $(TDNW $(LREF put)) $(TD $(D
put("dlang.org", "Hi")) returns a char[] containing
the dlang.org web page. after a HTTP PUT of "hi")
)
$(TR $(TDNW $(LREF post)) $(TD $(D
post("dlang.org", "Hi")) returns a char[] containing
the dlang.org web page. after a HTTP POST of "hi")
)
$(TR $(TDNW $(LREF byLine)) $(TD $(D
byLine("dlang.org")) returns a range of char[] containing the
dlang.org web page.)
)
$(TR $(TDNW $(LREF byChunk)) $(TD $(D
byChunk("dlang.org", 10)) returns a range of ubyte[10] containing the
dlang.org web page.)
)
$(TR $(TDNW $(LREF byLineAsync)) $(TD $(D
byLineAsync("dlang.org")) returns a range of char[] containing the dlang.org web
page asynchronously.)
)
$(TR $(TDNW $(LREF byChunkAsync)) $(TD $(D
byChunkAsync("dlang.org", 10)) returns a range of ubyte[10] containing the
dlang.org web page asynchronously.)
)
$(LEADINGROW Low level
)
$(TR $(TDNW $(LREF HTTP)) $(TD $(D HTTP) struct for advanced usage))
$(TR $(TDNW $(LREF FTP)) $(TD $(D FTP) struct for advanced usage))
$(TR $(TDNW $(LREF SMTP)) $(TD $(D SMTP) struct for advanced usage))
)
Example:
---
import std.net.curl, std.stdio;
// Return a char[] containing the content specified by a URL
auto content = get("dlang.org");
// Post data and return a char[] containing the content specified by a URL
auto content = post("mydomain.com/here.cgi", ["name1" : "value1", "name2" : "value2"]);
// Get content of file from ftp server
auto content = get("ftp.digitalmars.com/sieve.ds");
// Post and print out content line by line. The request is done in another thread.
foreach (line; byLineAsync("dlang.org", "Post data"))
writeln(line);
// Get using a line range and proxy settings
auto client = HTTP();
client.proxy = "1.2.3.4";
foreach (line; byLine("dlang.org", client))
writeln(line);
---
For more control than the high level functions provide, use the low level API:
Example:
---
import std.net.curl, std.stdio;
// GET with custom data receivers
auto http = HTTP("dlang.org");
http.onReceiveHeader =
(in char[] key, in char[] value) { writeln(key, ": ", value); };
http.onReceive = (ubyte[] data) { /+ drop +/ return data.length; };
http.perform();
---
First, an instance of the reference-counted HTTP struct is created. Then the
custom delegates are set. These will be called whenever the HTTP instance
receives a header and a data buffer, respectively. In this simple example, the
headers are written to stdout and the data is ignored. If the request should be
stopped before it has finished then return something less than data.length from
the onReceive callback. See $(LREF onReceiveHeader)/$(LREF onReceive) for more
information. Finally the HTTP request is effected by calling perform(), which is
synchronous.
Source: $(PHOBOSSRC std/net/_curl.d)
Copyright: Copyright Jonas Drewsen 2011-2012
License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: Jonas Drewsen. Some of the SMTP code contributed by Jimmy Cao.
Credits: The functionally is based on $(HTTP _curl.haxx.se/libcurl, libcurl).
LibCurl is licensed under an MIT/X derivative license.
*/
/*
Copyright Jonas Drewsen 2011 - 2012.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
module std.net.curl;
import core.thread;
import etc.c.curl;
import std.algorithm;
import std.array;
import std.concurrency;
import std.conv;
import std.datetime;
import std.encoding;
import std.exception;
import std.meta;
import std.regex;
import std.socket : InternetAddress;
import std.string;
import std.traits;
import std.typecons;
import std.internal.cstring;
public import etc.c.curl : CurlOption;
version(unittest)
{
// Run unit test with the PHOBOS_TEST_ALLOW_NET=1 set in order to
// allow net traffic
import std.stdio;
import std.range;
import std.process : environment;
import std.file : deleteme;
import std.path : buildPath;
import std.socket : Address, INADDR_LOOPBACK, Socket, TcpSocket;
private struct TestServer
{
string addr() { return _addr; }
void handle(void function(Socket s) dg)
{
tid.send(dg);
}
private:
string _addr;
Tid tid;
static void loop(shared TcpSocket listener)
{
try while (true)
{
void function(Socket) handler = void;
try
handler = receiveOnly!(typeof(handler));
catch (OwnerTerminated)
return;
handler((cast()listener).accept);
}
catch (Throwable e)
{
import core.stdc.stdlib : exit, EXIT_FAILURE;
stderr.writeln(e);
exit(EXIT_FAILURE); // Bugzilla 7018
}
}
}
private TestServer startServer()
{
auto sock = new TcpSocket;
sock.bind(new InternetAddress(INADDR_LOOPBACK, InternetAddress.PORT_ANY));
sock.listen(1);
auto addr = sock.localAddress.toString();
auto tid = spawn(&TestServer.loop, cast(shared)sock);
return TestServer(addr, tid);
}
private ref TestServer testServer()
{
__gshared TestServer server;
return initOnce!server(startServer());
}
private struct Request(T)
{
string hdrs;
immutable(T)[] bdy;
}
private Request!T recvReq(T=char)(Socket s)
{
ubyte[1024] tmp=void;
ubyte[] buf;
while (true)
{
auto nbytes = s.receive(tmp[]);
assert(nbytes >= 0);
immutable beg = buf.length > 3 ? buf.length - 3 : 0;
buf ~= tmp[0 .. nbytes];
auto bdy = buf[beg .. $].find(cast(ubyte[])"\r\n\r\n");
if (bdy.empty)
continue;
auto hdrs = cast(string)buf[0 .. $ - bdy.length];
bdy.popFrontN(4);
// no support for chunked transfer-encoding
if (auto m = hdrs.matchFirst(ctRegex!(`Content-Length: ([0-9]+)`, "i")))
{
import std.uni : asUpperCase;
if (hdrs.asUpperCase.canFind("EXPECT: 100-CONTINUE"))
s.send(httpContinue);
size_t remain = m.captures[1].to!size_t - bdy.length;
while (remain)
{
nbytes = s.receive(tmp[0 .. min(remain, $)]);
assert(nbytes >= 0);
buf ~= tmp[0 .. nbytes];
remain -= nbytes;
}
}
else
{
assert(bdy.empty);
}
bdy = buf[hdrs.length + 4 .. $];
return typeof(return)(hdrs, cast(immutable(T)[])bdy);
}
}
private string httpOK(string msg)
{
return "HTTP/1.1 200 OK\r\n"~
"Content-Type: text/plain\r\n"~
"Content-Length: "~msg.length.to!string~"\r\n"
"\r\n"~
msg;
}
private string httpOK()
{
return "HTTP/1.1 200 OK\r\n"~
"Content-Length: 0\r\n"~
"\r\n";
}
private string httpNotFound()
{
return "HTTP/1.1 404 Not Found\r\n"~
"Content-Length: 0\r\n"~
"\r\n";
}
private enum httpContinue = "HTTP/1.1 100 Continue\r\n\r\n";
}
version(StdDdoc) import std.stdio;
// Default data timeout for Protocols
private enum _defaultDataTimeout = dur!"minutes"(2);
/**
Macros:
CALLBACK_PARAMS = $(TABLE ,
$(DDOC_PARAM_ROW
$(DDOC_PARAM_ID $(DDOC_PARAM dlTotal))
$(DDOC_PARAM_DESC total bytes to download)
)
$(DDOC_PARAM_ROW
$(DDOC_PARAM_ID $(DDOC_PARAM dlNow))
$(DDOC_PARAM_DESC currently downloaded bytes)
)
$(DDOC_PARAM_ROW
$(DDOC_PARAM_ID $(DDOC_PARAM ulTotal))
$(DDOC_PARAM_DESC total bytes to upload)
)
$(DDOC_PARAM_ROW
$(DDOC_PARAM_ID $(DDOC_PARAM ulNow))
$(DDOC_PARAM_DESC currently uploaded bytes)
)
)
*/
/** Connection type used when the URL should be used to auto detect the protocol.
*
* This struct is used as placeholder for the connection parameter when calling
* the high level API and the connection type (HTTP/FTP) should be guessed by
* inspecting the URL parameter.
*
* The rules for guessing the protocol are:
* 1, if URL starts with ftp://, ftps:// or ftp. then FTP connection is assumed.
* 2, HTTP connection otherwise.
*
* Example:
* ---
* import std.net.curl;
* // Two requests below will do the same.
* string content;
*
* // Explicit connection provided
* content = get!HTTP("dlang.org");
*
* // Guess connection type by looking at the URL
* content = get!AutoProtocol("ftp://foo.com/file");
* // and since AutoProtocol is default this is the same as
* connect = get("ftp://foo.com/file");
* // and will end up detecting FTP from the url and be the same as
* connect = get!FTP("ftp://foo.com/file");
* ---
*/
struct AutoProtocol { }
// Returns true if the url points to an FTP resource
private bool isFTPUrl(const(char)[] url)
{
return startsWith(url.toLower(), "ftp://", "ftps://", "ftp.") != 0;
}
// Is true if the Conn type is a valid Curl Connection type.
private template isCurlConn(Conn)
{
enum auto isCurlConn = is(Conn : HTTP) ||
is(Conn : FTP) || is(Conn : AutoProtocol);
}
/** HTTP/FTP download to local file system.
*
* Params:
* url = resource to download
* saveToPath = path to store the downloaded content on local disk
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* Example:
* ----
* import std.net.curl;
* download("d-lang.appspot.com/testUrl2", "/tmp/downloaded-http-file");
* ----
*/
void download(Conn = AutoProtocol)(const(char)[] url, string saveToPath, Conn conn = Conn())
if (isCurlConn!Conn)
{
static if (is(Conn : HTTP) || is(Conn : FTP))
{
import std.stdio : File;
conn.url = url;
auto f = File(saveToPath, "wb");
conn.onReceive = (ubyte[] data) { f.rawWrite(data); return data.length; };
conn.perform();
}
else
{
if (isFTPUrl(url))
return download!FTP(url, saveToPath, FTP());
else
return download!HTTP(url, saveToPath, HTTP());
}
}
unittest
{
static import std.file;
foreach (host; [testServer.addr, "http://"~testServer.addr])
{
testServer.handle((s) {
assert(s.recvReq.hdrs.canFind("GET /"));
s.send(httpOK("Hello world"));
});
auto fn = std.file.deleteme;
scope (exit) std.file.remove(fn);
download(host, fn);
assert(std.file.readText(fn) == "Hello world");
}
}
/** Upload file from local files system using the HTTP or FTP protocol.
*
* Params:
* loadFromPath = path load data from local disk.
* url = resource to upload to
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* Example:
* ----
* import std.net.curl;
* upload("/tmp/downloaded-ftp-file", "ftp.digitalmars.com/sieve.ds");
* upload("/tmp/downloaded-http-file", "d-lang.appspot.com/testUrl2");
* ----
*/
void upload(Conn = AutoProtocol)(string loadFromPath, const(char)[] url, Conn conn = Conn())
if (isCurlConn!Conn)
{
static if (is(Conn : HTTP))
{
conn.url = url;
conn.method = HTTP.Method.put;
}
else static if (is(Conn : FTP))
{
conn.url = url;
conn.handle.set(CurlOption.upload, 1L);
}
else
{
if (isFTPUrl(url))
return upload!FTP(loadFromPath, url, FTP());
else
return upload!HTTP(loadFromPath, url, HTTP());
}
static if (is(Conn : HTTP) || is(Conn : FTP))
{
import std.stdio : File;
auto f = File(loadFromPath, "rb");
conn.onSend = buf => f.rawRead(buf).length;
auto sz = f.size;
if (sz != ulong.max)
conn.contentLength = sz;
conn.perform();
}
}
unittest
{
static import std.file;
foreach (host; [testServer.addr, "http://"~testServer.addr])
{
auto fn = std.file.deleteme;
scope (exit) std.file.remove(fn);
std.file.write(fn, "upload data\n");
testServer.handle((s) {
auto req = s.recvReq;
assert(req.hdrs.canFind("PUT /path"));
assert(req.bdy.canFind("upload data"));
s.send(httpOK());
});
upload(fn, host ~ "/path");
}
}
/** HTTP/FTP get content.
*
* Params:
* url = resource to get
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* The template parameter $(D T) specifies the type to return. Possible values
* are $(D char) and $(D ubyte) to return $(D char[]) or $(D ubyte[]). If asking
* for $(D char), content will be converted from the connection character set
* (specified in HTTP response headers or FTP connection properties, both ISO-8859-1
* by default) to UTF-8.
*
* Example:
* ----
* import std.net.curl;
* auto content = get("d-lang.appspot.com/testUrl2");
* ----
*
* Returns:
* A T[] range containing the content of the resource pointed to by the URL.
*
* Throws:
*
* $(D CurlException) on error.
*
* See_Also: $(LREF HTTP.Method)
*/
T[] get(Conn = AutoProtocol, T = char)(const(char)[] url, Conn conn = Conn())
if ( isCurlConn!Conn && (is(T == char) || is(T == ubyte)) )
{
static if (is(Conn : HTTP))
{
conn.method = HTTP.Method.get;
return _basicHTTP!(T)(url, "", conn);
}
else static if (is(Conn : FTP))
{
return _basicFTP!(T)(url, "", conn);
}
else
{
if (isFTPUrl(url))
return get!(FTP,T)(url, FTP());
else
return get!(HTTP,T)(url, HTTP());
}
}
unittest
{
foreach (host; [testServer.addr, "http://"~testServer.addr])
{
testServer.handle((s) {
assert(s.recvReq.hdrs.canFind("GET /path"));
s.send(httpOK("GETRESPONSE"));
});
auto res = get(host ~ "/path");
assert(res == "GETRESPONSE");
}
}
/** HTTP post content.
*
* Params:
* url = resource to post to
* postDict = data to send as the body of the request. An associative array
* of $(D string) is accepted and will be encoded using
* www-form-urlencoding
* postData = data to send as the body of the request. An array
* of an arbitrary type is accepted and will be cast to ubyte[]
* before sending it.
* conn = HTTP connection to use
* T = The template parameter $(D T) specifies the type to return. Possible values
* are $(D char) and $(D ubyte) to return $(D char[]) or $(D ubyte[]). If asking
* for $(D char), content will be converted from the connection character set
* (specified in HTTP response headers or FTP connection properties, both ISO-8859-1
* by default) to UTF-8.
*
* Examples:
* ----
* import std.net.curl;
*
* auto content1 = post("d-lang.appspot.com/testUrl2", ["name1" : "value1", "name2" : "value2"]);
* auto content2 = post("d-lang.appspot.com/testUrl2", [1,2,3,4]);
* ----
*
* Returns:
* A T[] range containing the content of the resource pointed to by the URL.
*
* See_Also: $(LREF HTTP.Method)
*/
T[] post(T = char, PostUnit)(const(char)[] url, const(PostUnit)[] postData, HTTP conn = HTTP())
if (is(T == char) || is(T == ubyte))
{
conn.method = HTTP.Method.post;
return _basicHTTP!(T)(url, postData, conn);
}
unittest
{
foreach (host; [testServer.addr, "http://"~testServer.addr])
{
testServer.handle((s) {
auto req = s.recvReq;
assert(req.hdrs.canFind("POST /path"));
assert(req.bdy.canFind("POSTBODY"));
s.send(httpOK("POSTRESPONSE"));
});
auto res = post(host ~ "/path", "POSTBODY");
assert(res == "POSTRESPONSE");
}
}
unittest
{
auto data = new ubyte[](256);
foreach (i, ref ub; data)
ub = cast(ubyte)i;
testServer.handle((s) {
auto req = s.recvReq!ubyte;
assert(req.bdy.canFind(cast(ubyte[])[0, 1, 2, 3, 4]));
assert(req.bdy.canFind(cast(ubyte[])[253, 254, 255]));
s.send(httpOK(cast(ubyte[])[17, 27, 35, 41]));
});
auto res = post!ubyte(testServer.addr, data);
assert(res == cast(ubyte[])[17, 27, 35, 41]);
}
/// ditto
T[] post(T = char)(const(char)[] url, string[string] postDict, HTTP conn = HTTP())
if (is(T == char) || is(T == ubyte))
{
import std.uri : urlEncode;
return post(url, urlEncode(postDict), conn);
}
unittest
{
foreach (host; [testServer.addr, "http://" ~ testServer.addr])
{
testServer.handle((s) {
auto req = s.recvReq!char;
s.send(httpOK(req.bdy));
});
auto res = post(host ~ "/path", ["name1" : "value1", "name2" : "value2"]);
assert(res == "name1=value1&name2=value2");
}
}
/** HTTP/FTP put content.
*
* Params:
* url = resource to put
* putData = data to send as the body of the request. An array
* of an arbitrary type is accepted and will be cast to ubyte[]
* before sending it.
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* The template parameter $(D T) specifies the type to return. Possible values
* are $(D char) and $(D ubyte) to return $(D char[]) or $(D ubyte[]). If asking
* for $(D char), content will be converted from the connection character set
* (specified in HTTP response headers or FTP connection properties, both ISO-8859-1
* by default) to UTF-8.
*
* Example:
* ----
* import std.net.curl;
* auto content = put("d-lang.appspot.com/testUrl2",
* "Putting this data");
* ----
*
* Returns:
* A T[] range containing the content of the resource pointed to by the URL.
*
* See_Also: $(LREF HTTP.Method)
*/
T[] put(Conn = AutoProtocol, T = char, PutUnit)(const(char)[] url, const(PutUnit)[] putData,
Conn conn = Conn())
if ( isCurlConn!Conn && (is(T == char) || is(T == ubyte)) )
{
static if (is(Conn : HTTP))
{
conn.method = HTTP.Method.put;
return _basicHTTP!(T)(url, putData, conn);
}
else static if (is(Conn : FTP))
{
return _basicFTP!(T)(url, putData, conn);
}
else
{
if (isFTPUrl(url))
return put!(FTP,T)(url, putData, FTP());
else
return put!(HTTP,T)(url, putData, HTTP());
}
}
unittest
{
foreach (host; [testServer.addr, "http://"~testServer.addr])
{
testServer.handle((s) {
auto req = s.recvReq;
assert(req.hdrs.canFind("PUT /path"));
assert(req.bdy.canFind("PUTBODY"));
s.send(httpOK("PUTRESPONSE"));
});
auto res = put(host ~ "/path", "PUTBODY");
assert(res == "PUTRESPONSE");
}
}
/** HTTP/FTP delete content.
*
* Params:
* url = resource to delete
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* Example:
* ----
* import std.net.curl;
* del("d-lang.appspot.com/testUrl2");
* ----
*
* See_Also: $(LREF HTTP.Method)
*/
void del(Conn = AutoProtocol)(const(char)[] url, Conn conn = Conn())
if (isCurlConn!Conn)
{
static if (is(Conn : HTTP))
{
conn.method = HTTP.Method.del;
_basicHTTP!char(url, cast(void[]) null, conn);
}
else static if (is(Conn : FTP))
{
auto trimmed = url.findSplitAfter("ftp://")[1];
auto t = trimmed.findSplitAfter("/");
enum minDomainNameLength = 3;
enforce!CurlException(t[0].length > minDomainNameLength,
text("Invalid FTP URL for delete ", url));
conn.url = t[0];
enforce!CurlException(!t[1].empty,
text("No filename specified to delete for URL ", url));
conn.addCommand("DELE " ~ t[1]);
conn.perform();
}
else
{
if (isFTPUrl(url))
return del!FTP(url, FTP());
else
return del!HTTP(url, HTTP());
}
}
unittest
{
foreach (host; [testServer.addr, "http://"~testServer.addr])
{
testServer.handle((s) {
auto req = s.recvReq;
assert(req.hdrs.canFind("DELETE /path"));
s.send(httpOK());
});
del(host ~ "/path");
}
}
/** HTTP options request.
*
* Params:
* url = resource make a option call to
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* The template parameter $(D T) specifies the type to return. Possible values
* are $(D char) and $(D ubyte) to return $(D char[]) or $(D ubyte[]).
*
* Example:
* ----
* import std.net.curl;
* auto http = HTTP();
* options("d-lang.appspot.com/testUrl2", http);
* writeln("Allow set to " ~ http.responseHeaders["Allow"]);
* ----
*
* Returns:
* A T[] range containing the options of the resource pointed to by the URL.
*
* See_Also: $(LREF HTTP.Method)
*/
T[] options(T = char)(const(char)[] url, HTTP conn = HTTP())
if (is(T == char) || is(T == ubyte))
{
conn.method = HTTP.Method.options;
return _basicHTTP!(T)(url, null, conn);
}
// Explicitly undocumented. It will be removed in February 2017. @@@DEPRECATED_2017-02@@@
deprecated("options does not send any data")
T[] options(T = char, OptionsUnit)(const(char)[] url,
const(OptionsUnit)[] optionsData = null,
HTTP conn = HTTP())
if (is(T == char) || is(T == ubyte))
{
return options!T(url, conn);
}
unittest
{
testServer.handle((s) {
auto req = s.recvReq;
assert(req.hdrs.canFind("OPTIONS /path"));
s.send(httpOK("OPTIONSRESPONSE"));
});
auto res = options(testServer.addr ~ "/path");
assert(res == "OPTIONSRESPONSE");
}
/** HTTP trace request.
*
* Params:
* url = resource make a trace call to
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* The template parameter $(D T) specifies the type to return. Possible values
* are $(D char) and $(D ubyte) to return $(D char[]) or $(D ubyte[]).
*
* Example:
* ----
* import std.net.curl;
* trace("d-lang.appspot.com/testUrl1");
* ----
*
* Returns:
* A T[] range containing the trace info of the resource pointed to by the URL.
*
* See_Also: $(LREF HTTP.Method)
*/
T[] trace(T = char)(const(char)[] url, HTTP conn = HTTP())
if (is(T == char) || is(T == ubyte))
{
conn.method = HTTP.Method.trace;
return _basicHTTP!(T)(url, cast(void[]) null, conn);
}
unittest
{
testServer.handle((s) {
auto req = s.recvReq;
assert(req.hdrs.canFind("TRACE /path"));
s.send(httpOK("TRACERESPONSE"));
});
auto res = trace(testServer.addr ~ "/path");
assert(res == "TRACERESPONSE");
}
/** HTTP connect request.
*
* Params:
* url = resource make a connect to
* conn = HTTP connection to use
*
* The template parameter $(D T) specifies the type to return. Possible values
* are $(D char) and $(D ubyte) to return $(D char[]) or $(D ubyte[]).
*
* Example:
* ----
* import std.net.curl;
* connect("d-lang.appspot.com/testUrl1");
* ----
*
* Returns:
* A T[] range containing the connect info of the resource pointed to by the URL.
*
* See_Also: $(LREF HTTP.Method)
*/
T[] connect(T = char)(const(char)[] url, HTTP conn = HTTP())
if (is(T == char) || is(T == ubyte))
{
conn.method = HTTP.Method.connect;
return _basicHTTP!(T)(url, cast(void[]) null, conn);
}
unittest
{
testServer.handle((s) {
auto req = s.recvReq;
assert(req.hdrs.canFind("CONNECT /path"));
s.send(httpOK("CONNECTRESPONSE"));
});
auto res = connect(testServer.addr ~ "/path");
assert(res == "CONNECTRESPONSE");
}
/** HTTP patch content.
*
* Params:
* url = resource to patch
* patchData = data to send as the body of the request. An array
* of an arbitrary type is accepted and will be cast to ubyte[]
* before sending it.
* conn = HTTP connection to use
*
* The template parameter $(D T) specifies the type to return. Possible values
* are $(D char) and $(D ubyte) to return $(D char[]) or $(D ubyte[]).
*
* Example:
* ----
* auto http = HTTP();
* http.addRequestHeader("Content-Type", "application/json");
* auto content = patch("d-lang.appspot.com/testUrl2", `{"title": "Patched Title"}`, http);
* ----
*
* Returns:
* A T[] range containing the content of the resource pointed to by the URL.
*
* See_Also: $(LREF HTTP.Method)
*/
T[] patch(T = char, PatchUnit)(const(char)[] url, const(PatchUnit)[] patchData,
HTTP conn = HTTP())
if (is(T == char) || is(T == ubyte))
{
conn.method = HTTP.Method.patch;
return _basicHTTP!(T)(url, patchData, conn);
}
unittest
{
testServer.handle((s) {
auto req = s.recvReq;
assert(req.hdrs.canFind("PATCH /path"));
assert(req.bdy.canFind("PATCHBODY"));
s.send(httpOK("PATCHRESPONSE"));
});
auto res = patch(testServer.addr ~ "/path", "PATCHBODY");
assert(res == "PATCHRESPONSE");
}
/*
* Helper function for the high level interface.
*
* It performs an HTTP request using the client which must have
* been setup correctly before calling this function.
*/
private auto _basicHTTP(T)(const(char)[] url, const(void)[] sendData, HTTP client)
{
immutable doSend = sendData !is null &&
(client.method == HTTP.Method.post ||
client.method == HTTP.Method.put ||
client.method == HTTP.Method.patch);
scope (exit)
{
client.onReceiveHeader = null;
client.onReceiveStatusLine = null;
client.onReceive = null;
if (doSend)
{
client.onSend = null;
client.handle.onSeek = null;
client.contentLength = 0;
}
}
client.url = url;
HTTP.StatusLine statusLine;
import std.array : appender;
auto content = appender!(ubyte[])();
string[string] headers;
client.onReceive = (ubyte[] data)
{
content ~= data;
return data.length;
};
if (doSend)
{
client.contentLength = sendData.length;
auto remainingData = sendData;
client.onSend = delegate size_t(void[] buf)
{
size_t minLen = min(buf.length, remainingData.length);
if (minLen == 0) return 0;
buf[0..minLen] = remainingData[0..minLen];
remainingData = remainingData[minLen..$];
return minLen;
};
client.handle.onSeek = delegate(long offset, CurlSeekPos mode)
{
switch (mode)
{
case CurlSeekPos.set:
remainingData = sendData[cast(size_t)offset..$];
return CurlSeek.ok;
default:
// As of curl 7.18.0, libcurl will not pass
// anything other than CurlSeekPos.set.
return CurlSeek.cantseek;
}
};
}
client.onReceiveHeader = (in char[] key,
in char[] value)
{
if (key == "content-length")
{
import std.conv : to;
content.reserve(value.to!size_t);
}
if (auto v = key in headers)
{
*v ~= ", ";
*v ~= value;
}
else
headers[key] = value.idup;
};
client.onReceiveStatusLine = (HTTP.StatusLine l) { statusLine = l; };
client.perform();
enforce!CurlException(statusLine.code / 100 == 2,
format("HTTP request returned status code %d (%s)",
statusLine.code, statusLine.reason));
// Default charset defined in HTTP RFC
auto charset = "ISO-8859-1";
if (auto v = "content-type" in headers)
{
auto m = match(cast(char[]) (*v), regex("charset=([^;,]*)"));
if (!m.empty && m.captures.length > 1)
{
charset = m.captures[1].idup;
}
}
return _decodeContent!T(content.data, charset);
}
unittest
{
testServer.handle((s) {
auto req = s.recvReq;
assert(req.hdrs.canFind("GET /path"));
s.send(httpNotFound());
});
auto e = collectException!CurlException(get(testServer.addr ~ "/path"));
assert(e.msg == "HTTP request returned status code 404 (Not Found)");
}
// Bugzilla 14760 - content length must be reset after post
unittest
{
testServer.handle((s) {
auto req = s.recvReq;
assert(req.hdrs.canFind("POST /"));
assert(req.bdy.canFind("POSTBODY"));
s.send(httpOK("POSTRESPONSE"));
req = s.recvReq;
assert(req.hdrs.canFind("TRACE /"));
assert(req.bdy.empty);
s.blocking = false;
ubyte[6] buf = void;
assert(s.receive(buf[]) < 0);
s.send(httpOK("TRACERESPONSE"));
});
auto http = HTTP();
auto res = post(testServer.addr, "POSTBODY", http);
assert(res == "POSTRESPONSE");
res = trace(testServer.addr, http);
assert(res == "TRACERESPONSE");
}
/*
* Helper function for the high level interface.
*
* It performs an FTP request using the client which must have
* been setup correctly before calling this function.
*/
private auto _basicFTP(T)(const(char)[] url, const(void)[] sendData, FTP client)
{
scope (exit)
{
client.onReceive = null;
if (!sendData.empty)
client.onSend = null;
}
ubyte[] content;
if (client.encoding.empty)
client.encoding = "ISO-8859-1";
client.url = url;
client.onReceive = (ubyte[] data)
{
content ~= data;
return data.length;
};
if (!sendData.empty)
{
client.handle.set(CurlOption.upload, 1L);
client.onSend = delegate size_t(void[] buf)
{
size_t minLen = min(buf.length, sendData.length);
if (minLen == 0) return 0;
buf[0..minLen] = sendData[0..minLen];
sendData = sendData[minLen..$];
return minLen;
};
}
client.perform();
return _decodeContent!T(content, client.encoding);
}
/* Used by _basicHTTP() and _basicFTP() to decode ubyte[] to
* correct string format
*/
private auto _decodeContent(T)(ubyte[] content, string encoding)
{
static if (is(T == ubyte))
{
return content;
}
else
{
// Optimally just return the utf8 encoded content
if (encoding == "UTF-8")
return cast(char[])(content);
// The content has to be re-encoded to utf8
auto scheme = EncodingScheme.create(encoding);
enforce!CurlException(scheme !is null,
format("Unknown encoding '%s'", encoding));
auto strInfo = decodeString(content, scheme);
enforce!CurlException(strInfo[0] != size_t.max,
format("Invalid encoding sequence for encoding '%s'",
encoding));
return strInfo[1];
}
}
alias KeepTerminator = Flag!"keepTerminator";
/+
struct ByLineBuffer(Char)
{
bool linePresent;
bool EOF;
Char[] buffer;
ubyte[] decodeRemainder;
bool append(const(ubyte)[] data)
{
byLineBuffer ~= data;
}
@property bool linePresent()
{
return byLinePresent;
}
Char[] get()
{
if (!linePresent)
{
// Decode ubyte[] into Char[] until a Terminator is found.
// If not Terminator is found and EOF is false then raise an
// exception.
}
return byLineBuffer;
}
}
++/
/** HTTP/FTP fetch content as a range of lines.
*
* A range of lines is returned when the request is complete. If the method or
* other request properties is to be customized then set the $(D conn) parameter
* with a HTTP/FTP instance that has these properties set.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* foreach (line; byLine("dlang.org"))
* writeln(line);
* ----
*
* Params:
* url = The url to receive content from
* keepTerminator = KeepTerminator.yes signals that the line terminator should be
* returned as part of the lines in the range.
* terminator = The character that terminates a line
* conn = The connection to use e.g. HTTP or FTP.
*
* Returns:
* A range of Char[] with the content of the resource pointer to by the URL
*/
auto byLine(Conn = AutoProtocol, Terminator = char, Char = char)
(const(char)[] url, KeepTerminator keepTerminator = KeepTerminator.no,
Terminator terminator = '\n', Conn conn = Conn())
if (isCurlConn!Conn && isSomeChar!Char && isSomeChar!Terminator)
{
static struct SyncLineInputRange
{
private Char[] lines;
private Char[] current;
private bool currentValid;
private bool keepTerminator;
private Terminator terminator;
this(Char[] lines, bool kt, Terminator terminator)
{
this.lines = lines;
this.keepTerminator = kt;
this.terminator = terminator;
currentValid = true;
popFront();
}
@property @safe bool empty()
{
return !currentValid;
}
@property @safe Char[] front()
{
enforce!CurlException(currentValid, "Cannot call front() on empty range");
return current;
}
void popFront()
{
enforce!CurlException(currentValid, "Cannot call popFront() on empty range");
if (lines.empty)
{
currentValid = false;
return;
}
if (keepTerminator)
{
auto r = findSplitAfter(lines, [ terminator ]);
if (r[0].empty)
{
current = r[1];
lines = r[0];
}
else
{
current = r[0];
lines = r[1];
}
}
else
{
auto r = findSplit(lines, [ terminator ]);
current = r[0];
lines = r[2];
}
}
}
auto result = _getForRange!Char(url, conn);
return SyncLineInputRange(result, keepTerminator == KeepTerminator.yes, terminator);
}
unittest
{
foreach (host; [testServer.addr, "http://"~testServer.addr])
{
testServer.handle((s) {
auto req = s.recvReq;
s.send(httpOK("Line1\nLine2\nLine3"));
});
assert(byLine(host).equal(["Line1", "Line2", "Line3"]));
}
}
/** HTTP/FTP fetch content as a range of chunks.
*
* A range of chunks is returned when the request is complete. If the method or
* other request properties is to be customized then set the $(D conn) parameter
* with a HTTP/FTP instance that has these properties set.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* foreach (chunk; byChunk("dlang.org", 100))
* writeln(chunk); // chunk is ubyte[100]
* ----
*
* Params:
* url = The url to receive content from
* chunkSize = The size of each chunk
* conn = The connection to use e.g. HTTP or FTP.
*
* Returns:
* A range of ubyte[chunkSize] with the content of the resource pointer to by the URL
*/
auto byChunk(Conn = AutoProtocol)
(const(char)[] url, size_t chunkSize = 1024, Conn conn = Conn())
if (isCurlConn!(Conn))
{
static struct SyncChunkInputRange
{
private size_t chunkSize;
private ubyte[] _bytes;
private size_t offset;
this(ubyte[] bytes, size_t chunkSize)
{
this._bytes = bytes;
this.chunkSize = chunkSize;
}
@property @safe auto empty()
{
return offset == _bytes.length;
}
@property ubyte[] front()
{
size_t nextOffset = offset + chunkSize;
if (nextOffset > _bytes.length) nextOffset = _bytes.length;
return _bytes[offset..nextOffset];
}
@safe void popFront()
{
offset += chunkSize;
if (offset > _bytes.length) offset = _bytes.length;
}
}
auto result = _getForRange!ubyte(url, conn);
return SyncChunkInputRange(result, chunkSize);
}
unittest
{
foreach (host; [testServer.addr, "http://"~testServer.addr])
{
testServer.handle((s) {
auto req = s.recvReq;
s.send(httpOK(cast(ubyte[])[0, 1, 2, 3, 4, 5]));
});
assert(byChunk(host, 2).equal([[0, 1], [2, 3], [4, 5]]));
}
}
private T[] _getForRange(T,Conn)(const(char)[] url, Conn conn)
{
static if (is(Conn : HTTP))
{
conn.method = conn.method == HTTP.Method.undefined ? HTTP.Method.get : conn.method;
return _basicHTTP!(T)(url, null, conn);
}
else static if (is(Conn : FTP))
{
return _basicFTP!(T)(url, null, conn);
}
else
{
if (isFTPUrl(url))
return get!(FTP,T)(url, FTP());
else
return get!(HTTP,T)(url, HTTP());
}
}
/*
Main thread part of the message passing protocol used for all async
curl protocols.
*/
private mixin template WorkerThreadProtocol(Unit, alias units)
{
@property bool empty()
{
tryEnsureUnits();
return state == State.done;
}
@property Unit[] front()
{
tryEnsureUnits();
assert(state == State.gotUnits,
format("Expected %s but got $s",
State.gotUnits, state));
return units;
}
void popFront()
{
tryEnsureUnits();
assert(state == State.gotUnits,
format("Expected %s but got $s",
State.gotUnits, state));
state = State.needUnits;
// Send to worker thread for buffer reuse
workerTid.send(cast(immutable(Unit)[]) units);
units = null;
}
/** Wait for duration or until data is available and return true if data is
available
*/
bool wait(Duration d)
{
if (state == State.gotUnits)
return true;
enum noDur = dur!"hnsecs"(0);
StopWatch sw;
sw.start();
while (state != State.gotUnits && d > noDur)
{
final switch (state)
{
case State.needUnits:
receiveTimeout(d,
(Tid origin, CurlMessage!(immutable(Unit)[]) _data)
{
if (origin != workerTid)
return false;
units = cast(Unit[]) _data.data;
state = State.gotUnits;
return true;
},
(Tid origin, CurlMessage!bool f)
{
if (origin != workerTid)
return false;
state = state.done;
return true;
}
);
break;
case State.gotUnits: return true;
case State.done:
return false;
}
d -= sw.peek();
sw.reset();
}
return state == State.gotUnits;
}
enum State
{
needUnits,
gotUnits,
done
}
State state;
void tryEnsureUnits()
{
while (true)
{
final switch (state)
{
case State.needUnits:
receive(
(Tid origin, CurlMessage!(immutable(Unit)[]) _data)
{
if (origin != workerTid)
return false;
units = cast(Unit[]) _data.data;
state = State.gotUnits;
return true;
},
(Tid origin, CurlMessage!bool f)
{
if (origin != workerTid)
return false;
state = state.done;
return true;
}
);
break;
case State.gotUnits: return;
case State.done:
return;
}
}
}
}
// @@@@BUG 15831@@@@
// this should be inside byLineAsync
// Range that reads one line at a time asynchronously.
private static struct AsyncLineInputRange(Char)
{
private Char[] line;
mixin WorkerThreadProtocol!(Char, line);
private Tid workerTid;
private State running;
private this(Tid tid, size_t transmitBuffers, size_t bufferSize)
{
workerTid = tid;
state = State.needUnits;
// Send buffers to other thread for it to use. Since no mechanism is in
// place for moving ownership a cast to shared is done here and casted
// back to non-shared in the receiving end.
foreach (i ; 0..transmitBuffers)
{
auto arr = new Char[](bufferSize);
workerTid.send(cast(immutable(Char[]))arr);
}
}
}
/** HTTP/FTP fetch content as a range of lines asynchronously.
*
* A range of lines is returned immediately and the request that fetches the
* lines is performed in another thread. If the method or other request
* properties is to be customized then set the $(D conn) parameter with a
* HTTP/FTP instance that has these properties set.
*
* If $(D postData) is non-_null the method will be set to $(D post) for HTTP
* requests.
*
* The background thread will buffer up to transmitBuffers number of lines
* before it stops receiving data from network. When the main thread reads the
* lines from the range it frees up buffers and allows for the background thread
* to receive more data from the network.
*
* If no data is available and the main thread accesses the range it will block
* until data becomes available. An exception to this is the $(D wait(Duration)) method on
* the $(LREF AsyncLineInputRange). This method will wait at maximum for the
* specified duration and return true if data is available.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* // Get some pages in the background
* auto range1 = byLineAsync("www.google.com");
* auto range2 = byLineAsync("www.wikipedia.org");
* foreach (line; byLineAsync("dlang.org"))
* writeln(line);
*
* // Lines already fetched in the background and ready
* foreach (line; range1) writeln(line);
* foreach (line; range2) writeln(line);
* ----
*
* ----
* import std.net.curl, std.stdio;
* // Get a line in a background thread and wait in
* // main thread for 2 seconds for it to arrive.
* auto range3 = byLineAsync("dlang.com");
* if (range.wait(dur!"seconds"(2)))
* writeln(range.front);
* else
* writeln("No line received after 2 seconds!");
* ----
*
* Params:
* url = The url to receive content from
* postData = Data to HTTP Post
* keepTerminator = KeepTerminator.yes signals that the line terminator should be
* returned as part of the lines in the range.
* terminator = The character that terminates a line
* transmitBuffers = The number of lines buffered asynchronously
* conn = The connection to use e.g. HTTP or FTP.
*
* Returns:
* A range of Char[] with the content of the resource pointer to by the
* URL.
*/
auto byLineAsync(Conn = AutoProtocol, Terminator = char, Char = char, PostUnit)
(const(char)[] url, const(PostUnit)[] postData,
KeepTerminator keepTerminator = KeepTerminator.no,
Terminator terminator = '\n',
size_t transmitBuffers = 10, Conn conn = Conn())
if (isCurlConn!Conn && isSomeChar!Char && isSomeChar!Terminator)
{
static if (is(Conn : AutoProtocol))
{
if (isFTPUrl(url))
return byLineAsync(url, postData, keepTerminator,
terminator, transmitBuffers, FTP());
else
return byLineAsync(url, postData, keepTerminator,
terminator, transmitBuffers, HTTP());
}
else
{
// 50 is just an arbitrary number for now
setMaxMailboxSize(thisTid, 50, OnCrowding.block);
auto tid = spawn(&_spawnAsync!(Conn, Char, Terminator));
tid.send(thisTid);
tid.send(terminator);
tid.send(keepTerminator == KeepTerminator.yes);
_asyncDuplicateConnection(url, conn, postData, tid);
return AsyncLineInputRange!Char(tid, transmitBuffers,
Conn.defaultAsyncStringBufferSize);
}
}
/// ditto
auto byLineAsync(Conn = AutoProtocol, Terminator = char, Char = char)
(const(char)[] url, KeepTerminator keepTerminator = KeepTerminator.no,
Terminator terminator = '\n',
size_t transmitBuffers = 10, Conn conn = Conn())
{
static if (is(Conn : AutoProtocol))
{
if (isFTPUrl(url))
return byLineAsync(url, cast(void[])null, keepTerminator,
terminator, transmitBuffers, FTP());
else
return byLineAsync(url, cast(void[])null, keepTerminator,
terminator, transmitBuffers, HTTP());
}
else
{
return byLineAsync(url, cast(void[])null, keepTerminator,
terminator, transmitBuffers, conn);
}
}
unittest
{
foreach (host; [testServer.addr, "http://"~testServer.addr])
{
testServer.handle((s) {
auto req = s.recvReq;
s.send(httpOK("Line1\nLine2\nLine3"));
});
assert(byLineAsync(host).equal(["Line1", "Line2", "Line3"]));
}
}
// @@@@BUG 15831@@@@
// this should be inside byLineAsync
// Range that reads one chunk at a time asynchronously.
private static struct AsyncChunkInputRange
{
private ubyte[] chunk;
mixin WorkerThreadProtocol!(ubyte, chunk);
private Tid workerTid;
private State running;
private this(Tid tid, size_t transmitBuffers, size_t chunkSize)
{
workerTid = tid;
state = State.needUnits;
// Send buffers to other thread for it to use. Since no mechanism is in
// place for moving ownership a cast to shared is done here and a cast
// back to non-shared in the receiving end.
foreach (i ; 0..transmitBuffers)
{
ubyte[] arr = new ubyte[](chunkSize);
workerTid.send(cast(immutable(ubyte[]))arr);
}
}
}
/** HTTP/FTP fetch content as a range of chunks asynchronously.
*
* A range of chunks is returned immediately and the request that fetches the
* chunks is performed in another thread. If the method or other request
* properties is to be customized then set the $(D conn) parameter with a
* HTTP/FTP instance that has these properties set.
*
* If $(D postData) is non-_null the method will be set to $(D post) for HTTP
* requests.
*
* The background thread will buffer up to transmitBuffers number of chunks
* before is stops receiving data from network. When the main thread reads the
* chunks from the range it frees up buffers and allows for the background
* thread to receive more data from the network.
*
* If no data is available and the main thread access the range it will block
* until data becomes available. An exception to this is the $(D wait(Duration))
* method on the $(LREF AsyncChunkInputRange). This method will wait at maximum for the specified
* duration and return true if data is available.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* // Get some pages in the background
* auto range1 = byChunkAsync("www.google.com", 100);
* auto range2 = byChunkAsync("www.wikipedia.org");
* foreach (chunk; byChunkAsync("dlang.org"))
* writeln(chunk); // chunk is ubyte[100]
*
* // Chunks already fetched in the background and ready
* foreach (chunk; range1) writeln(chunk);
* foreach (chunk; range2) writeln(chunk);
* ----
*
* ----
* import std.net.curl, std.stdio;
* // Get a line in a background thread and wait in
* // main thread for 2 seconds for it to arrive.
* auto range3 = byChunkAsync("dlang.com", 10);
* if (range.wait(dur!"seconds"(2)))
* writeln(range.front);
* else
* writeln("No chunk received after 2 seconds!");
* ----
*
* Params:
* url = The url to receive content from
* postData = Data to HTTP Post
* chunkSize = The size of the chunks
* transmitBuffers = The number of chunks buffered asynchronously
* conn = The connection to use e.g. HTTP or FTP.
*
* Returns:
* A range of ubyte[chunkSize] with the content of the resource pointer to by
* the URL.
*/
auto byChunkAsync(Conn = AutoProtocol, PostUnit)
(const(char)[] url, const(PostUnit)[] postData,
size_t chunkSize = 1024, size_t transmitBuffers = 10,
Conn conn = Conn())
if (isCurlConn!(Conn))
{
static if (is(Conn : AutoProtocol))
{
if (isFTPUrl(url))
return byChunkAsync(url, postData, chunkSize,
transmitBuffers, FTP());
else
return byChunkAsync(url, postData, chunkSize,
transmitBuffers, HTTP());
}
else
{
// 50 is just an arbitrary number for now
setMaxMailboxSize(thisTid, 50, OnCrowding.block);
auto tid = spawn(&_spawnAsync!(Conn, ubyte));
tid.send(thisTid);
_asyncDuplicateConnection(url, conn, postData, tid);
return AsyncChunkInputRange(tid, transmitBuffers, chunkSize);
}
}
/// ditto
auto byChunkAsync(Conn = AutoProtocol)
(const(char)[] url,
size_t chunkSize = 1024, size_t transmitBuffers = 10,
Conn conn = Conn())
if (isCurlConn!(Conn))
{
static if (is(Conn : AutoProtocol))
{
if (isFTPUrl(url))
return byChunkAsync(url, cast(void[])null, chunkSize,
transmitBuffers, FTP());
else
return byChunkAsync(url, cast(void[])null, chunkSize,
transmitBuffers, HTTP());
}
else
{
return byChunkAsync(url, cast(void[])null, chunkSize,
transmitBuffers, conn);
}
}
unittest
{
foreach (host; [testServer.addr, "http://"~testServer.addr])
{
testServer.handle((s) {
auto req = s.recvReq;
s.send(httpOK(cast(ubyte[])[0, 1, 2, 3, 4, 5]));
});
assert(byChunkAsync(host, 2).equal([[0, 1], [2, 3], [4, 5]]));
}
}
/* Used by byLineAsync/byChunkAsync to duplicate an existing connection
* that can be used exclusively in a spawned thread.
*/
private void _asyncDuplicateConnection(Conn, PostData)
(const(char)[] url, Conn conn, PostData postData, Tid tid)
{
// no move semantic available in std.concurrency ie. must use casting.
auto connDup = conn.dup();
connDup.url = url;
static if ( is(Conn : HTTP) )
{
connDup.p.headersOut = null;
connDup.method = conn.method == HTTP.Method.undefined ?
HTTP.Method.get : conn.method;
if (postData !is null)
{
if (connDup.method == HTTP.Method.put)
{
connDup.handle.set(CurlOption.infilesize_large,
postData.length);
}
else
{
// post
connDup.method = HTTP.Method.post;
connDup.handle.set(CurlOption.postfieldsize_large,
postData.length);
}
connDup.handle.set(CurlOption.copypostfields,
cast(void*) postData.ptr);
}
tid.send(cast(ulong)connDup.handle.handle);
tid.send(connDup.method);
}
else
{
enforce!CurlException(postData is null,
"Cannot put ftp data using byLineAsync()");
tid.send(cast(ulong)connDup.handle.handle);
tid.send(HTTP.Method.undefined);
}
connDup.p.curl.handle = null; // make sure handle is not freed
}
/*
Mixin template for all supported curl protocols. This is the commom
functionallity such as timeouts and network interface settings. This should
really be in the HTTP/FTP/SMTP structs but the documentation tool does not
support a mixin to put its doc strings where a mixin is done. Therefore docs
in this template is copied into each of HTTP/FTP/SMTP below.
*/
private mixin template Protocol()
{
/// Value to return from $(D onSend)/$(D onReceive) delegates in order to
/// pause a request
alias requestPause = CurlReadFunc.pause;
/// Value to return from onSend delegate in order to abort a request
alias requestAbort = CurlReadFunc.abort;
static uint defaultAsyncStringBufferSize = 100;
/**
The curl handle used by this connection.
*/
@property ref Curl handle() return
{
return p.curl;
}
/**
True if the instance is stopped. A stopped instance is not usable.
*/
@property bool isStopped()
{
return p.curl.stopped;
}
/// Stop and invalidate this instance.
void shutdown()
{
p.curl.shutdown();
}
/** Set verbose.
This will print request information to stderr.
*/
@property void verbose(bool on)
{
p.curl.set(CurlOption.verbose, on ? 1L : 0L);
}
// Connection settings
/// Set timeout for activity on connection.
@property void dataTimeout(Duration d)
{
p.curl.set(CurlOption.low_speed_limit, 1);
p.curl.set(CurlOption.low_speed_time, d.total!"seconds");
}
/** Set maximum time an operation is allowed to take.
This includes dns resolution, connecting, data transfer, etc.
*/
@property void operationTimeout(Duration d)
{
p.curl.set(CurlOption.timeout_ms, d.total!"msecs");
}
/// Set timeout for connecting.
@property void connectTimeout(Duration d)
{
p.curl.set(CurlOption.connecttimeout_ms, d.total!"msecs");
}
// Network settings
/** Proxy
* See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy)
*/
@property void proxy(const(char)[] host)
{
p.curl.set(CurlOption.proxy, host);
}
/** Proxy port
* See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXYPORT, _proxy_port)
*/
@property void proxyPort(ushort port)
{
p.curl.set(CurlOption.proxyport, cast(long) port);
}
/// Type of proxy
alias CurlProxy = etc.c.curl.CurlProxy;
/** Proxy type
* See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy_type)
*/
@property void proxyType(CurlProxy type)
{
p.curl.set(CurlOption.proxytype, cast(long) type);
}
/// DNS lookup timeout.
@property void dnsTimeout(Duration d)
{
p.curl.set(CurlOption.dns_cache_timeout, d.total!"msecs");
}
/**
* The network interface to use in form of the the IP of the interface.
*
* Example:
* ----
* theprotocol.netInterface = "192.168.1.32";
* theprotocol.netInterface = [ 192, 168, 1, 32 ];
* ----
*
* See: $(REF InternetAddress, std,socket)
*/
@property void netInterface(const(char)[] i)
{
p.curl.set(CurlOption.intrface, i);
}
/// ditto
@property void netInterface(const(ubyte)[4] i)
{
auto str = format("%d.%d.%d.%d", i[0], i[1], i[2], i[3]);
netInterface = str;
}
/// ditto
@property void netInterface(InternetAddress i)
{
netInterface = i.toAddrString();
}
/**
Set the local outgoing port to use.
Params:
port = the first outgoing port number to try and use
*/
@property void localPort(ushort port)
{
p.curl.set(CurlOption.localport, cast(long)port);
}
/**
Set the local outgoing port range to use.
This can be used together with the localPort property.
Params:
range = if the first port is occupied then try this many
port number forwards
*/
@property void localPortRange(ushort range)
{
p.curl.set(CurlOption.localportrange, cast(long)range);
}
/** Set the tcp no-delay socket option on or off.
See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTCPNODELAY, nodelay)
*/
@property void tcpNoDelay(bool on)
{
p.curl.set(CurlOption.tcp_nodelay, cast(long) (on ? 1 : 0) );
}
/** Sets whether SSL peer certificates should be verified.
See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTSSLVERIFYPEER, verifypeer)
*/
@property void verifyPeer(bool on)
{
p.curl.set(CurlOption.ssl_verifypeer, on ? 1 : 0);
}
/** Sets whether the host within an SSL certificate should be verified.
See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTSSLVERIFYHOST, verifypeer)
*/
@property void verifyHost(bool on)
{
p.curl.set(CurlOption.ssl_verifyhost, on ? 2 : 0);
}
// Authentication settings
/**
Set the user name, password and optionally domain for authentication
purposes.
Some protocols may need authentication in some cases. Use this
function to provide credentials.
Params:
username = the username
password = the password
domain = used for NTLM authentication only and is set to the NTLM domain
name
*/
void setAuthentication(const(char)[] username, const(char)[] password,
const(char)[] domain = "")
{
if (!domain.empty)
username = format("%s/%s", domain, username);
p.curl.set(CurlOption.userpwd, format("%s:%s", username, password));
}
unittest
{
testServer.handle((s) {
auto req = s.recvReq;
assert(req.hdrs.canFind("GET /"));
assert(req.hdrs.canFind("Basic dXNlcjpwYXNz"));
s.send(httpOK());
});
auto http = HTTP(testServer.addr);
http.onReceive = (ubyte[] data) { return data.length; };
http.setAuthentication("user", "pass");
http.perform();
}
/**
Set the user name and password for proxy authentication.
Params:
username = the username
password = the password
*/
void setProxyAuthentication(const(char)[] username, const(char)[] password)
{
p.curl.set(CurlOption.proxyuserpwd,
format("%s:%s",
username.replace(":", "%3A"),
password.replace(":", "%3A"))
);
}
/**
* The event handler that gets called when data is needed for sending. The
* length of the $(D void[]) specifies the maximum number of bytes that can
* be sent.
*
* Returns:
* The callback returns the number of elements in the buffer that have been
* filled and are ready to send.
* The special value $(D .abortRequest) can be returned in order to abort the
* current request.
* The special value $(D .pauseRequest) can be returned in order to pause the
* current request.
*
* Example:
* ----
* import std.net.curl;
* string msg = "Hello world";
* auto client = HTTP("dlang.org");
* client.onSend = delegate size_t(void[] data)
* {
* auto m = cast(void[])msg;
* size_t length = m.length > data.length ? data.length : m.length;
* if (length == 0) return 0;
* data[0..length] = m[0..length];
* msg = msg[length..$];
* return length;
* };
* client.perform();
* ----
*/
@property void onSend(size_t delegate(void[]) callback)
{
p.curl.clear(CurlOption.postfields); // cannot specify data when using callback
p.curl.onSend = callback;
}
/**
* The event handler that receives incoming data. Be sure to copy the
* incoming ubyte[] since it is not guaranteed to be valid after the
* callback returns.
*
* Returns:
* The callback returns the number of incoming bytes read. If the entire array is
* not read the request will abort.
* The special value .pauseRequest can be returned in order to pause the
* current request.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* auto client = HTTP("dlang.org");
* client.onReceive = (ubyte[] data)
* {
* writeln("Got data", to!(const(char)[])(data));
* return data.length;
* };
* client.perform();
* ----
*/
@property void onReceive(size_t delegate(ubyte[]) callback)
{
p.curl.onReceive = callback;
}
/**
* The event handler that gets called to inform of upload/download progress.
*
* Params:
* dlTotal = total bytes to download
* dlNow = currently downloaded bytes
* ulTotal = total bytes to upload
* ulNow = currently uploaded bytes
*
* Returns:
* Return 0 from the callback to signal success, return non-zero to abort
* transfer
*
* Example:
* ----
* import std.net.curl, std.stdio;
* auto client = HTTP("dlang.org");
* client.onProgress = delegate int(size_t dl, size_t dln, size_t ul, size_t ult)
* {
* writeln("Progress: downloaded ", dln, " of ", dl);
* writeln("Progress: uploaded ", uln, " of ", ul);
* };
* client.perform();
* ----
*/
@property void onProgress(int delegate(size_t dlTotal, size_t dlNow,
size_t ulTotal, size_t ulNow) callback)
{
p.curl.onProgress = callback;
}
}
/*
Decode $(D ubyte[]) array using the provided EncodingScheme up to maxChars
Returns: Tuple of ubytes read and the $(D Char[]) characters decoded.
Not all ubytes are guaranteed to be read in case of decoding error.
*/
private Tuple!(size_t,Char[])
decodeString(Char = char)(const(ubyte)[] data,
EncodingScheme scheme,
size_t maxChars = size_t.max)
{
Char[] res;
auto startLen = data.length;
size_t charsDecoded = 0;
while (data.length && charsDecoded < maxChars)
{
dchar dc = scheme.safeDecode(data);
if (dc == INVALID_SEQUENCE)
{
return typeof(return)(size_t.max, cast(Char[])null);
}
charsDecoded++;
res ~= dc;
}
return typeof(return)(startLen-data.length, res);
}
/*
Decode $(D ubyte[]) array using the provided $(D EncodingScheme) until a the
line terminator specified is found. The basesrc parameter is effectively
prepended to src as the first thing.
This function is used for decoding as much of the src buffer as
possible until either the terminator is found or decoding fails. If
it fails as the last data in the src it may mean that the src buffer
were missing some bytes in order to represent a correct code
point. Upon the next call to this function more bytes have been
received from net and the failing bytes should be given as the
basesrc parameter. It is done this way to minimize data copying.
Returns: true if a terminator was found
Not all ubytes are guaranteed to be read in case of decoding error.
any decoded chars will be inserted into dst.
*/
private bool decodeLineInto(Terminator, Char = char)(ref const(ubyte)[] basesrc,
ref const(ubyte)[] src,
ref Char[] dst,
EncodingScheme scheme,
Terminator terminator)
{
auto startLen = src.length;
size_t charsDecoded = 0;
// if there is anything in the basesrc then try to decode that
// first.
if (basesrc.length != 0)
{
// Try to ensure 4 entries in the basesrc by copying from src.
auto blen = basesrc.length;
size_t len = (basesrc.length + src.length) >= 4 ?
4 : basesrc.length + src.length;
basesrc.length = len;
dchar dc = scheme.safeDecode(basesrc);
if (dc == INVALID_SEQUENCE)
{
enforce!CurlException(len != 4, "Invalid code sequence");
return false;
}
dst ~= dc;
src = src[len-basesrc.length-blen .. $]; // remove used ubytes from src
basesrc.length = 0;
}
while (src.length)
{
auto lsrc = src;
dchar dc = scheme.safeDecode(src);
if (dc == INVALID_SEQUENCE)
{
if (src.empty)
{
// The invalid sequence was in the end of the src. Maybe there
// just need to be more bytes available so these last bytes are
// put back to src for later use.
src = lsrc;
return false;
}
dc = '?';
}
dst ~= dc;
if (dst.endsWith(terminator))
return true;
}
return false; // no terminator found
}
/**
* HTTP client functionality.
*
* Example:
* ---
* import std.net.curl, std.stdio;
*
* // Get with custom data receivers
* auto http = HTTP("dlang.org");
* http.onReceiveHeader =
* (in char[] key, in char[] value) { writeln(key ~ ": " ~ value); };
* http.onReceive = (ubyte[] data) { /+ drop +/ return data.length; };
* http.perform();
*
* // Put with data senders
* auto msg = "Hello world";
* http.contentLength = msg.length;
* http.onSend = (void[] data)
* {
* auto m = cast(void[])msg;
* size_t len = m.length > data.length ? data.length : m.length;
* if (len == 0) return len;
* data[0..len] = m[0..len];
* msg = msg[len..$];
* return len;
* };
* http.perform();
*
* // Track progress
* http.method = HTTP.Method.get;
* http.url = "http://upload.wikimedia.org/wikipedia/commons/"
* "5/53/Wikipedia-logo-en-big.png";
* http.onReceive = (ubyte[] data) { return data.length; };
* http.onProgress = (size_t dltotal, size_t dlnow,
* size_t ultotal, size_t ulnow)
* {
* writeln("Progress ", dltotal, ", ", dlnow, ", ", ultotal, ", ", ulnow);
* return 0;
* };
* http.perform();
* ---
*
* See_Also: $(HTTP www.ietf.org/rfc/rfc2616.txt, RFC2616)
*
*/
struct HTTP
{
mixin Protocol;
/// Authentication method equal to $(REF CurlAuth, etc,c,curl)
alias AuthMethod = CurlAuth;
static private uint defaultMaxRedirects = 10;
private struct Impl
{
~this()
{
if (headersOut !is null)
Curl.curl.slist_free_all(headersOut);
if (curl.handle !is null) // work around RefCounted/emplace bug
curl.shutdown();
}
Curl curl;
curl_slist* headersOut;
string[string] headersIn;
string charset;
/// The status line of the final sub-request in a request.
StatusLine status;
private void delegate(StatusLine) onReceiveStatusLine;
/// The HTTP method to use.
Method method = Method.undefined;
@property void onReceiveHeader(void delegate(in char[] key,
in char[] value) callback)
{
// Wrap incoming callback in order to separate http status line from
// http headers. On redirected requests there may be several such
// status lines. The last one is the one recorded.
auto dg = (in char[] header)
{
import std.utf : UTFException;
try
{
if (header.empty)
{
// header delimiter
return;
}
if (header.startsWith("HTTP/"))
{
string[string] empty;
headersIn = empty; // clear
auto m = match(header, regex(r"^HTTP/(\d+)\.(\d+) (\d+) (.*)$"));
if (m.empty)
{
// Invalid status line
}
else
{
status.majorVersion = to!ushort(m.captures[1]);
status.minorVersion = to!ushort(m.captures[2]);
status.code = to!ushort(m.captures[3]);
status.reason = m.captures[4].idup;
if (onReceiveStatusLine != null)
onReceiveStatusLine(status);
}
return;
}
// Normal http header
auto m = match(cast(char[]) header, regex("(.*?): (.*)$"));
auto fieldName = m.captures[1].toLower().idup;
if (fieldName == "content-type")
{
auto mct = match(cast(char[]) m.captures[2],
regex("charset=([^;]*)"));
if (!mct.empty && mct.captures.length > 1)
charset = mct.captures[1].idup;
}
if (!m.empty && callback !is null)
callback(fieldName, m.captures[2]);
headersIn[fieldName] = m.captures[2].idup;
}
catch (UTFException e)
{
//munch it - a header should be all ASCII, any "wrong UTF" is broken header
}
};
curl.onReceiveHeader = dg;
}
}
private RefCounted!Impl p;
/** Time condition enumeration as an alias of $(REF CurlTimeCond, etc,c,curl)
$(HTTP www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25, _RFC2616 Section 14.25)
*/
alias TimeCond = CurlTimeCond;
/**
Constructor taking the url as parameter.
*/
static HTTP opCall(const(char)[] url)
{
HTTP http;
http.initialize();
http.url = url;
return http;
}
///
static HTTP opCall()
{
HTTP http;
http.initialize();
return http;
}
///
HTTP dup()
{
HTTP copy;
copy.initialize();
copy.p.method = p.method;
curl_slist* cur = p.headersOut;
curl_slist* newlist = null;
while (cur)
{
newlist = Curl.curl.slist_append(newlist, cur.data);
cur = cur.next;
}
copy.p.headersOut = newlist;
copy.p.curl.set(CurlOption.httpheader, copy.p.headersOut);
copy.p.curl = p.curl.dup();
copy.dataTimeout = _defaultDataTimeout;
copy.onReceiveHeader = null;
return copy;
}
private void initialize()
{
p.curl.initialize();
maxRedirects = HTTP.defaultMaxRedirects;
p.charset = "ISO-8859-1"; // Default charset defined in HTTP RFC
p.method = Method.undefined;
setUserAgent(HTTP.defaultUserAgent);
dataTimeout = _defaultDataTimeout;
onReceiveHeader = null;
verifyPeer = true;
verifyHost = true;
}
/**
Perform a http request.
After the HTTP client has been setup and possibly assigned callbacks the
$(D perform()) method will start performing the request towards the
specified server.
Params:
throwOnError = whether to throw an exception or return a CurlCode on error
*/
CurlCode perform(ThrowOnError throwOnError = ThrowOnError.yes)
{
p.status.reset();
CurlOption opt;
final switch (p.method)
{
case Method.head:
p.curl.set(CurlOption.nobody, 1L);
opt = CurlOption.nobody;
break;
case Method.undefined:
case Method.get:
p.curl.set(CurlOption.httpget, 1L);
opt = CurlOption.httpget;
break;
case Method.post:
p.curl.set(CurlOption.post, 1L);
opt = CurlOption.post;
break;
case Method.put:
p.curl.set(CurlOption.upload, 1L);
opt = CurlOption.upload;
break;
case Method.del:
p.curl.set(CurlOption.customrequest, "DELETE");
opt = CurlOption.customrequest;
break;
case Method.options:
p.curl.set(CurlOption.customrequest, "OPTIONS");
opt = CurlOption.customrequest;
break;
case Method.trace:
p.curl.set(CurlOption.customrequest, "TRACE");
opt = CurlOption.customrequest;
break;
case Method.connect:
p.curl.set(CurlOption.customrequest, "CONNECT");
opt = CurlOption.customrequest;
break;
case Method.patch:
p.curl.set(CurlOption.customrequest, "PATCH");
opt = CurlOption.customrequest;
break;
}
scope (exit) p.curl.clear(opt);
return p.curl.perform(throwOnError);
}
/// The URL to specify the location of the resource.
@property void url(const(char)[] url)
{
if (!startsWith(url.toLower(), "http://", "https://"))
url = "http://" ~ url;
p.curl.set(CurlOption.url, url);
}
/// Set the CA certificate bundle file to use for SSL peer verification
@property void caInfo(const(char)[] caFile)
{
p.curl.set(CurlOption.cainfo, caFile);
}
// This is a workaround for mixed in content not having its
// docs mixed in.
version (StdDdoc)
{
/// Value to return from $(D onSend)/$(D onReceive) delegates in order to
/// pause a request
alias requestPause = CurlReadFunc.pause;
/// Value to return from onSend delegate in order to abort a request
alias requestAbort = CurlReadFunc.abort;
/**
True if the instance is stopped. A stopped instance is not usable.
*/
@property bool isStopped();
/// Stop and invalidate this instance.
void shutdown();
/** Set verbose.
This will print request information to stderr.
*/
@property void verbose(bool on);
// Connection settings
/// Set timeout for activity on connection.
@property void dataTimeout(Duration d);
/** Set maximum time an operation is allowed to take.
This includes dns resolution, connecting, data transfer, etc.
*/
@property void operationTimeout(Duration d);
/// Set timeout for connecting.
@property void connectTimeout(Duration d);
// Network settings
/** Proxy
* See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy)
*/
@property void proxy(const(char)[] host);
/** Proxy port
* See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXYPORT, _proxy_port)
*/
@property void proxyPort(ushort port);
/// Type of proxy
alias CurlProxy = etc.c.curl.CurlProxy;
/** Proxy type
* See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy_type)
*/
@property void proxyType(CurlProxy type);
/// DNS lookup timeout.
@property void dnsTimeout(Duration d);
/**
* The network interface to use in form of the the IP of the interface.
*
* Example:
* ----
* theprotocol.netInterface = "192.168.1.32";
* theprotocol.netInterface = [ 192, 168, 1, 32 ];
* ----
*
* See: $(REF InternetAddress, std,socket)
*/
@property void netInterface(const(char)[] i);
/// ditto
@property void netInterface(const(ubyte)[4] i);
/// ditto
@property void netInterface(InternetAddress i);
/**
Set the local outgoing port to use.
Params:
port = the first outgoing port number to try and use
*/
@property void localPort(ushort port);
/**
Set the local outgoing port range to use.
This can be used together with the localPort property.
Params:
range = if the first port is occupied then try this many
port number forwards
*/
@property void localPortRange(ushort range);
/** Set the tcp no-delay socket option on or off.
See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTCPNODELAY, nodelay)
*/
@property void tcpNoDelay(bool on);
// Authentication settings
/**
Set the user name, password and optionally domain for authentication
purposes.
Some protocols may need authentication in some cases. Use this
function to provide credentials.
Params:
username = the username
password = the password
domain = used for NTLM authentication only and is set to the NTLM domain
name
*/
void setAuthentication(const(char)[] username, const(char)[] password,
const(char)[] domain = "");
/**
Set the user name and password for proxy authentication.
Params:
username = the username
password = the password
*/
void setProxyAuthentication(const(char)[] username, const(char)[] password);
/**
* The event handler that gets called when data is needed for sending. The
* length of the $(D void[]) specifies the maximum number of bytes that can
* be sent.
*
* Returns:
* The callback returns the number of elements in the buffer that have been
* filled and are ready to send.
* The special value $(D .abortRequest) can be returned in order to abort the
* current request.
* The special value $(D .pauseRequest) can be returned in order to pause the
* current request.
*
* Example:
* ----
* import std.net.curl;
* string msg = "Hello world";
* auto client = HTTP("dlang.org");
* client.onSend = delegate size_t(void[] data)
* {
* auto m = cast(void[])msg;
* size_t length = m.length > data.length ? data.length : m.length;
* if (length == 0) return 0;
* data[0..length] = m[0..length];
* msg = msg[length..$];
* return length;
* };
* client.perform();
* ----
*/
@property void onSend(size_t delegate(void[]) callback);
/**
* The event handler that receives incoming data. Be sure to copy the
* incoming ubyte[] since it is not guaranteed to be valid after the
* callback returns.
*
* Returns:
* The callback returns the incoming bytes read. If not the entire array is
* the request will abort.
* The special value .pauseRequest can be returned in order to pause the
* current request.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* auto client = HTTP("dlang.org");
* client.onReceive = (ubyte[] data)
* {
* writeln("Got data", to!(const(char)[])(data));
* return data.length;
* };
* client.perform();
* ----
*/
@property void onReceive(size_t delegate(ubyte[]) callback);
/**
* Register an event handler that gets called to inform of
* upload/download progress.
*
* Callback_parameters:
* $(CALLBACK_PARAMS)
*
* Callback_returns: Return 0 to signal success, return non-zero to
* abort transfer.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* auto client = HTTP("dlang.org");
* client.onProgress = delegate int(size_t dl, size_t dln, size_t ul, size_t ult)
* {
* writeln("Progress: downloaded ", dln, " of ", dl);
* writeln("Progress: uploaded ", uln, " of ", ul);
* };
* client.perform();
* ----
*/
@property void onProgress(int delegate(size_t dlTotal, size_t dlNow,
size_t ulTotal, size_t ulNow) callback);
}
/** Clear all outgoing headers.
*/
void clearRequestHeaders()
{
if (p.headersOut !is null)
Curl.curl.slist_free_all(p.headersOut);
p.headersOut = null;
p.curl.clear(CurlOption.httpheader);
}
/** Add a header e.g. "X-CustomField: Something is fishy".
*
* There is no remove header functionality. Do a $(LREF clearRequestHeaders)
* and set the needed headers instead.
*
* Example:
* ---
* import std.net.curl;
* auto client = HTTP();
* client.addRequestHeader("X-Custom-ABC", "This is the custom value");
* auto content = get("dlang.org", client);
* ---
*/
void addRequestHeader(const(char)[] name, const(char)[] value)
{
if (icmp(name, "User-Agent") == 0)
return setUserAgent(value);
string nv = format("%s: %s", name, value);
p.headersOut = Curl.curl.slist_append(p.headersOut,
nv.tempCString().buffPtr);
p.curl.set(CurlOption.httpheader, p.headersOut);
}
/**
* The default "User-Agent" value send with a request.
* It has the form "Phobos-std.net.curl/$(I PHOBOS_VERSION) (libcurl/$(I CURL_VERSION))"
*/
static string defaultUserAgent() @property
{
import std.compiler : version_major, version_minor;
// http://curl.haxx.se/docs/versions.html
enum fmt = "Phobos-std.net.curl/%d.%03d (libcurl/%d.%d.%d)";
enum maxLen = fmt.length - "%d%03d%d%d%d".length + 10 + 10 + 3 + 3 + 3;
static char[maxLen] buf = void;
static string userAgent;
if (!userAgent.length)
{
auto curlVer = Curl.curl.version_info(CURLVERSION_NOW).version_num;
userAgent = cast(immutable)sformat(
buf, fmt, version_major, version_minor,
curlVer >> 16 & 0xFF, curlVer >> 8 & 0xFF, curlVer & 0xFF);
}
return userAgent;
}
/** Set the value of the user agent request header field.
*
* By default a request has it's "User-Agent" field set to $(LREF
* defaultUserAgent) even if $(D setUserAgent) was never called. Pass
* an empty string to suppress the "User-Agent" field altogether.
*/
void setUserAgent(const(char)[] userAgent)
{
p.curl.set(CurlOption.useragent, userAgent);
}
/** The headers read from a successful response.
*
*/
@property string[string] responseHeaders()
{
return p.headersIn;
}
/// HTTP method used.
@property void method(Method m)
{
p.method = m;
}
/// ditto
@property Method method()
{
return p.method;
}
/**
HTTP status line of last response. One call to perform may
result in several requests because of redirection.
*/
@property StatusLine statusLine()
{
return p.status;
}
/// Set the active cookie string e.g. "name1=value1;name2=value2"
void setCookie(const(char)[] cookie)
{
p.curl.set(CurlOption.cookie, cookie);
}
/// Set a file path to where a cookie jar should be read/stored.
void setCookieJar(const(char)[] path)
{
p.curl.set(CurlOption.cookiefile, path);
if (path.length)
p.curl.set(CurlOption.cookiejar, path);
}
/// Flush cookie jar to disk.
void flushCookieJar()
{
p.curl.set(CurlOption.cookielist, "FLUSH");
}
/// Clear session cookies.
void clearSessionCookies()
{
p.curl.set(CurlOption.cookielist, "SESS");
}
/// Clear all cookies.
void clearAllCookies()
{
p.curl.set(CurlOption.cookielist, "ALL");
}
/**
Set time condition on the request.
Params:
cond = $(D CurlTimeCond.{none,ifmodsince,ifunmodsince,lastmod})
timestamp = Timestamp for the condition
$(HTTP www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25, _RFC2616 Section 14.25)
*/
void setTimeCondition(HTTP.TimeCond cond, SysTime timestamp)
{
p.curl.set(CurlOption.timecondition, cond);
p.curl.set(CurlOption.timevalue, timestamp.toUnixTime());
}
/** Specifying data to post when not using the onSend callback.
*
* The data is NOT copied by the library. Content-Type will default to
* application/octet-stream. Data is not converted or encoded by this
* method.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* auto http = HTTP("http://www.mydomain.com");
* http.onReceive = (ubyte[] data) { writeln(to!(const(char)[])(data)); return data.length; };
* http.postData = [1,2,3,4,5];
* http.perform();
* ----
*/
@property void postData(const(void)[] data)
{
setPostData(data, "application/octet-stream");
}
/** Specifying data to post when not using the onSend callback.
*
* The data is NOT copied by the library. Content-Type will default to
* text/plain. Data is not converted or encoded by this method.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* auto http = HTTP("http://www.mydomain.com");
* http.onReceive = (ubyte[] data) { writeln(to!(const(char)[])(data)); return data.length; };
* http.postData = "The quick....";
* http.perform();
* ----
*/
@property void postData(const(char)[] data)
{
setPostData(data, "text/plain");
}
/**
* Specify data to post when not using the onSend callback, with
* user-specified Content-Type.
* Params:
* data = Data to post.
* contentType = MIME type of the data, for example, "text/plain" or
* "application/octet-stream". See also:
* $(LINK2 http://en.wikipedia.org/wiki/Internet_media_type,
* Internet media type) on Wikipedia.
* -----
* import std.net.curl;
* auto http = HTTP("http://onlineform.example.com");
* auto data = "app=login&username=bob&password=s00perS3kret";
* http.setPostData(data, "application/x-www-form-urlencoded");
* http.onReceive = (ubyte[] data) { return data.length; };
* http.perform();
* -----
*/
void setPostData(const(void)[] data, string contentType)
{
// cannot use callback when specifying data directly so it is disabled here.
p.curl.clear(CurlOption.readfunction);
addRequestHeader("Content-Type", contentType);
p.curl.set(CurlOption.postfields, cast(void*)data.ptr);
p.curl.set(CurlOption.postfieldsize, data.length);
if (method == Method.undefined)
method = Method.post;
}
unittest
{
testServer.handle((s) {
auto req = s.recvReq!ubyte;
assert(req.hdrs.canFind("POST /path"));
assert(req.bdy.canFind(cast(ubyte[])[0, 1, 2, 3, 4]));
assert(req.bdy.canFind(cast(ubyte[])[253, 254, 255]));
s.send(httpOK(cast(ubyte[])[17, 27, 35, 41]));
});
auto data = new ubyte[](256);
foreach (i, ref ub; data)
ub = cast(ubyte)i;
auto http = HTTP(testServer.addr~"/path");
http.postData = data;
ubyte[] res;
http.onReceive = (data) { res ~= data; return data.length; };
http.perform();
assert(res == cast(ubyte[])[17, 27, 35, 41]);
}
/**
* Set the event handler that receives incoming headers.
*
* The callback will receive a header field key, value as parameter. The
* $(D const(char)[]) arrays are not valid after the delegate has returned.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* auto http = HTTP("dlang.org");
* http.onReceive = (ubyte[] data) { writeln(to!(const(char)[])(data)); return data.length; };
* http.onReceiveHeader = (in char[] key, in char[] value) { writeln(key, " = ", value); };
* http.perform();
* ----
*/
@property void onReceiveHeader(void delegate(in char[] key,
in char[] value) callback)
{
p.onReceiveHeader = callback;
}
/**
Callback for each received StatusLine.
Notice that several callbacks can be done for each call to
$(D perform()) due to redirections.
See_Also: $(LREF StatusLine)
*/
@property void onReceiveStatusLine(void delegate(StatusLine) callback)
{
p.onReceiveStatusLine = callback;
}
/**
The content length in bytes when using request that has content
e.g. POST/PUT and not using chunked transfer. Is set as the
"Content-Length" header. Set to ulong.max to reset to chunked transfer.
*/
@property void contentLength(ulong len)
{
CurlOption lenOpt;
// Force post if necessary
if (p.method != Method.put && p.method != Method.post &&
p.method != Method.patch)
p.method = Method.post;
if (p.method == Method.post || p.method == Method.patch)
lenOpt = CurlOption.postfieldsize_large;
else
lenOpt = CurlOption.infilesize_large;
if (size_t.max != ulong.max && len == size_t.max)
len = ulong.max; // check size_t.max for backwards compat, turn into error
if (len == ulong.max)
{
// HTTP 1.1 supports requests with no length header set.
addRequestHeader("Transfer-Encoding", "chunked");
addRequestHeader("Expect", "100-continue");
}
else
{
p.curl.set(lenOpt, to!curl_off_t(len));
}
}
/**
Authentication method as specified in $(LREF AuthMethod).
*/
@property void authenticationMethod(AuthMethod authMethod)
{
p.curl.set(CurlOption.httpauth, cast(long) authMethod);
}
/**
Set max allowed redirections using the location header.
uint.max for infinite.
*/
@property void maxRedirects(uint maxRedirs)
{
if (maxRedirs == uint.max)
{
// Disable
p.curl.set(CurlOption.followlocation, 0);
}
else
{
p.curl.set(CurlOption.followlocation, 1);
p.curl.set(CurlOption.maxredirs, maxRedirs);
}
}
/** <a name="HTTP.Method"/>The standard HTTP methods :
* $(HTTP www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1, _RFC2616 Section 5.1.1)
*/
enum Method
{
undefined,
head, ///
get, ///
post, ///
put, ///
del, ///
options, ///
trace, ///
connect, ///
patch, ///
}
/**
HTTP status line ie. the first line returned in an HTTP response.
If authentication or redirections are done then the status will be for
the last response received.
*/
struct StatusLine
{
ushort majorVersion; /// Major HTTP version ie. 1 in HTTP/1.0.
ushort minorVersion; /// Minor HTTP version ie. 0 in HTTP/1.0.
ushort code; /// HTTP status line code e.g. 200.
string reason; /// HTTP status line reason string.
/// Reset this status line
@safe void reset()
{
majorVersion = 0;
minorVersion = 0;
code = 0;
reason = "";
}
///
string toString() const
{
return format("%s %s (%s.%s)",
code, reason, majorVersion, minorVersion);
}
}
} // HTTP
/**
FTP client functionality.
See_Also: $(HTTP tools.ietf.org/html/rfc959, RFC959)
*/
struct FTP
{
mixin Protocol;
private struct Impl
{
~this()
{
if (commands !is null)
Curl.curl.slist_free_all(commands);
if (curl.handle !is null) // work around RefCounted/emplace bug
curl.shutdown();
}
curl_slist* commands;
Curl curl;
string encoding;
}
private RefCounted!Impl p;
/**
FTP access to the specified url.
*/
static FTP opCall(const(char)[] url)
{
FTP ftp;
ftp.initialize();
ftp.url = url;
return ftp;
}
///
static FTP opCall()
{
FTP ftp;
ftp.initialize();
return ftp;
}
///
FTP dup()
{
FTP copy = FTP();
copy.initialize();
copy.p.encoding = p.encoding;
copy.p.curl = p.curl.dup();
curl_slist* cur = p.commands;
curl_slist* newlist = null;
while (cur)
{
newlist = Curl.curl.slist_append(newlist, cur.data);
cur = cur.next;
}
copy.p.commands = newlist;
copy.p.curl.set(CurlOption.postquote, copy.p.commands);
copy.dataTimeout = _defaultDataTimeout;
return copy;
}
private void initialize()
{
p.curl.initialize();
p.encoding = "ISO-8859-1";
dataTimeout = _defaultDataTimeout;
}
/**
Performs the ftp request as it has been configured.
After a FTP client has been setup and possibly assigned callbacks the $(D
perform()) method will start performing the actual communication with the
server.
Params:
throwOnError = whether to throw an exception or return a CurlCode on error
*/
CurlCode perform(ThrowOnError throwOnError = ThrowOnError.yes)
{
return p.curl.perform(throwOnError);
}
/// The URL to specify the location of the resource.
@property void url(const(char)[] url)
{
if (!startsWith(url.toLower(), "ftp://", "ftps://"))
url = "ftp://" ~ url;
p.curl.set(CurlOption.url, url);
}
// This is a workaround for mixed in content not having its
// docs mixed in.
version (StdDdoc)
{
/// Value to return from $(D onSend)/$(D onReceive) delegates in order to
/// pause a request
alias requestPause = CurlReadFunc.pause;
/// Value to return from onSend delegate in order to abort a request
alias requestAbort = CurlReadFunc.abort;
/**
True if the instance is stopped. A stopped instance is not usable.
*/
@property bool isStopped();
/// Stop and invalidate this instance.
void shutdown();
/** Set verbose.
This will print request information to stderr.
*/
@property void verbose(bool on);
// Connection settings
/// Set timeout for activity on connection.
@property void dataTimeout(Duration d);
/** Set maximum time an operation is allowed to take.
This includes dns resolution, connecting, data transfer, etc.
*/
@property void operationTimeout(Duration d);
/// Set timeout for connecting.
@property void connectTimeout(Duration d);
// Network settings
/** Proxy
* See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy)
*/
@property void proxy(const(char)[] host);
/** Proxy port
* See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXYPORT, _proxy_port)
*/
@property void proxyPort(ushort port);
/// Type of proxy
alias CurlProxy = etc.c.curl.CurlProxy;
/** Proxy type
* See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy_type)
*/
@property void proxyType(CurlProxy type);
/// DNS lookup timeout.
@property void dnsTimeout(Duration d);
/**
* The network interface to use in form of the the IP of the interface.
*
* Example:
* ----
* theprotocol.netInterface = "192.168.1.32";
* theprotocol.netInterface = [ 192, 168, 1, 32 ];
* ----
*
* See: $(REF InternetAddress, std,socket)
*/
@property void netInterface(const(char)[] i);
/// ditto
@property void netInterface(const(ubyte)[4] i);
/// ditto
@property void netInterface(InternetAddress i);
/**
Set the local outgoing port to use.
Params:
port = the first outgoing port number to try and use
*/
@property void localPort(ushort port);
/**
Set the local outgoing port range to use.
This can be used together with the localPort property.
Params:
range = if the first port is occupied then try this many
port number forwards
*/
@property void localPortRange(ushort range);
/** Set the tcp no-delay socket option on or off.
See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTCPNODELAY, nodelay)
*/
@property void tcpNoDelay(bool on);
// Authentication settings
/**
Set the user name, password and optionally domain for authentication
purposes.
Some protocols may need authentication in some cases. Use this
function to provide credentials.
Params:
username = the username
password = the password
domain = used for NTLM authentication only and is set to the NTLM domain
name
*/
void setAuthentication(const(char)[] username, const(char)[] password,
const(char)[] domain = "");
/**
Set the user name and password for proxy authentication.
Params:
username = the username
password = the password
*/
void setProxyAuthentication(const(char)[] username, const(char)[] password);
/**
* The event handler that gets called when data is needed for sending. The
* length of the $(D void[]) specifies the maximum number of bytes that can
* be sent.
*
* Returns:
* The callback returns the number of elements in the buffer that have been
* filled and are ready to send.
* The special value $(D .abortRequest) can be returned in order to abort the
* current request.
* The special value $(D .pauseRequest) can be returned in order to pause the
* current request.
*
*/
@property void onSend(size_t delegate(void[]) callback);
/**
* The event handler that receives incoming data. Be sure to copy the
* incoming ubyte[] since it is not guaranteed to be valid after the
* callback returns.
*
* Returns:
* The callback returns the incoming bytes read. If not the entire array is
* the request will abort.
* The special value .pauseRequest can be returned in order to pause the
* current request.
*
*/
@property void onReceive(size_t delegate(ubyte[]) callback);
/**
* The event handler that gets called to inform of upload/download progress.
*
* Callback_parameters:
* $(CALLBACK_PARAMS)
*
* Callback_returns:
* Return 0 from the callback to signal success, return non-zero to
* abort transfer.
*/
@property void onProgress(int delegate(size_t dlTotal, size_t dlNow,
size_t ulTotal, size_t ulNow) callback);
}
/** Clear all commands send to ftp server.
*/
void clearCommands()
{
if (p.commands !is null)
Curl.curl.slist_free_all(p.commands);
p.commands = null;
p.curl.clear(CurlOption.postquote);
}
/** Add a command to send to ftp server.
*
* There is no remove command functionality. Do a $(LREF clearCommands) and
* set the needed commands instead.
*
* Example:
* ---
* import std.net.curl;
* auto client = FTP();
* client.addCommand("RNFR my_file.txt");
* client.addCommand("RNTO my_renamed_file.txt");
* upload("my_file.txt", "ftp.digitalmars.com", client);
* ---
*/
void addCommand(const(char)[] command)
{
p.commands = Curl.curl.slist_append(p.commands,
command.tempCString().buffPtr);
p.curl.set(CurlOption.postquote, p.commands);
}
/// Connection encoding. Defaults to ISO-8859-1.
@property void encoding(string name)
{
p.encoding = name;
}
/// ditto
@property string encoding()
{
return p.encoding;
}
/**
The content length in bytes of the ftp data.
*/
@property void contentLength(ulong len)
{
p.curl.set(CurlOption.infilesize_large, to!curl_off_t(len));
}
}
/**
* Basic SMTP protocol support.
*
* Example:
* ---
* import std.net.curl;
*
* // Send an email with SMTPS
* auto smtp = SMTP("smtps://smtp.gmail.com");
* smtp.setAuthentication("from.addr@gmail.com", "password");
* smtp.mailTo = ["<to.addr@gmail.com>"];
* smtp.mailFrom = "<from.addr@gmail.com>";
* smtp.message = "Example Message";
* smtp.perform();
* ---
*
* See_Also: $(HTTP www.ietf.org/rfc/rfc2821.txt, RFC2821)
*/
struct SMTP
{
mixin Protocol;
private struct Impl
{
~this()
{
if (curl.handle !is null) // work around RefCounted/emplace bug
curl.shutdown();
}
Curl curl;
@property void message(string msg)
{
auto _message = msg;
/**
This delegate reads the message text and copies it.
*/
curl.onSend = delegate size_t(void[] data)
{
if (!msg.length) return 0;
auto m = cast(void[])msg;
size_t to_copy = min(data.length, _message.length);
data[0..to_copy] = (cast(void[])_message)[0..to_copy];
_message = _message[to_copy..$];
return to_copy;
};
}
}
private RefCounted!Impl p;
/**
Sets to the URL of the SMTP server.
*/
static SMTP opCall(const(char)[] url)
{
SMTP smtp;
smtp.initialize();
smtp.url = url;
return smtp;
}
///
static SMTP opCall()
{
SMTP smtp;
smtp.initialize();
return smtp;
}
/+ TODO: The other structs have this function.
SMTP dup()
{
SMTP copy = SMTP();
copy.initialize();
copy.p.encoding = p.encoding;
copy.p.curl = p.curl.dup();
curl_slist* cur = p.commands;
curl_slist* newlist = null;
while (cur)
{
newlist = Curl.curl.slist_append(newlist, cur.data);
cur = cur.next;
}
copy.p.commands = newlist;
copy.p.curl.set(CurlOption.postquote, copy.p.commands);
copy.dataTimeout = _defaultDataTimeout;
return copy;
}
+/
/**
Performs the request as configured.
Params:
throwOnError = whether to throw an exception or return a CurlCode on error
*/
CurlCode perform(ThrowOnError throwOnError = ThrowOnError.yes)
{
return p.curl.perform(throwOnError);
}
/// The URL to specify the location of the resource.
@property void url(const(char)[] url)
{
auto lowered = url.toLower();
if (lowered.startsWith("smtps://"))
{
p.curl.set(CurlOption.use_ssl, CurlUseSSL.all);
}
else
{
enforce!CurlException(lowered.startsWith("smtp://"),
"The url must be for the smtp protocol.");
}
p.curl.set(CurlOption.url, url);
}
private void initialize()
{
p.curl.initialize();
p.curl.set(CurlOption.upload, 1L);
dataTimeout = _defaultDataTimeout;
verifyPeer = true;
verifyHost = true;
}
// This is a workaround for mixed in content not having its
// docs mixed in.
version (StdDdoc)
{
/// Value to return from $(D onSend)/$(D onReceive) delegates in order to
/// pause a request
alias requestPause = CurlReadFunc.pause;
/// Value to return from onSend delegate in order to abort a request
alias requestAbort = CurlReadFunc.abort;
/**
True if the instance is stopped. A stopped instance is not usable.
*/
@property bool isStopped();
/// Stop and invalidate this instance.
void shutdown();
/** Set verbose.
This will print request information to stderr.
*/
@property void verbose(bool on);
// Connection settings
/// Set timeout for activity on connection.
@property void dataTimeout(Duration d);
/** Set maximum time an operation is allowed to take.
This includes dns resolution, connecting, data transfer, etc.
*/
@property void operationTimeout(Duration d);
/// Set timeout for connecting.
@property void connectTimeout(Duration d);
// Network settings
/** Proxy
* See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy)
*/
@property void proxy(const(char)[] host);
/** Proxy port
* See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXYPORT, _proxy_port)
*/
@property void proxyPort(ushort port);
/// Type of proxy
alias CurlProxy = etc.c.curl.CurlProxy;
/** Proxy type
* See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy_type)
*/
@property void proxyType(CurlProxy type);
/// DNS lookup timeout.
@property void dnsTimeout(Duration d);
/**
* The network interface to use in form of the the IP of the interface.
*
* Example:
* ----
* theprotocol.netInterface = "192.168.1.32";
* theprotocol.netInterface = [ 192, 168, 1, 32 ];
* ----
*
* See: $(REF InternetAddress, std,socket)
*/
@property void netInterface(const(char)[] i);
/// ditto
@property void netInterface(const(ubyte)[4] i);
/// ditto
@property void netInterface(InternetAddress i);
/**
Set the local outgoing port to use.
Params:
port = the first outgoing port number to try and use
*/
@property void localPort(ushort port);
/**
Set the local outgoing port range to use.
This can be used together with the localPort property.
Params:
range = if the first port is occupied then try this many
port number forwards
*/
@property void localPortRange(ushort range);
/** Set the tcp no-delay socket option on or off.
See: $(HTTP curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTCPNODELAY, nodelay)
*/
@property void tcpNoDelay(bool on);
// Authentication settings
/**
Set the user name, password and optionally domain for authentication
purposes.
Some protocols may need authentication in some cases. Use this
function to provide credentials.
Params:
username = the username
password = the password
domain = used for NTLM authentication only and is set to the NTLM domain
name
*/
void setAuthentication(const(char)[] username, const(char)[] password,
const(char)[] domain = "");
/**
Set the user name and password for proxy authentication.
Params:
username = the username
password = the password
*/
void setProxyAuthentication(const(char)[] username, const(char)[] password);
/**
* The event handler that gets called when data is needed for sending. The
* length of the $(D void[]) specifies the maximum number of bytes that can
* be sent.
*
* Returns:
* The callback returns the number of elements in the buffer that have been
* filled and are ready to send.
* The special value $(D .abortRequest) can be returned in order to abort the
* current request.
* The special value $(D .pauseRequest) can be returned in order to pause the
* current request.
*/
@property void onSend(size_t delegate(void[]) callback);
/**
* The event handler that receives incoming data. Be sure to copy the
* incoming ubyte[] since it is not guaranteed to be valid after the
* callback returns.
*
* Returns:
* The callback returns the incoming bytes read. If not the entire array is
* the request will abort.
* The special value .pauseRequest can be returned in order to pause the
* current request.
*/
@property void onReceive(size_t delegate(ubyte[]) callback);
/**
* The event handler that gets called to inform of upload/download progress.
*
* Callback_parameters:
* $(CALLBACK_PARAMS)
*
* Callback_returns:
* Return 0 from the callback to signal success, return non-zero to
* abort transfer.
*/
@property void onProgress(int delegate(size_t dlTotal, size_t dlNow,
size_t ulTotal, size_t ulNow) callback);
}
/**
Setter for the sender's email address.
*/
@property void mailFrom()(const(char)[] sender)
{
assert(!sender.empty, "Sender must not be empty");
p.curl.set(CurlOption.mail_from, sender);
}
/**
Setter for the recipient email addresses.
*/
void mailTo()(const(char)[][] recipients...)
{
assert(!recipients.empty, "Recipient must not be empty");
curl_slist* recipients_list = null;
foreach (recipient; recipients)
{
recipients_list =
Curl.curl.slist_append(recipients_list,
recipient.tempCString().buffPtr);
}
p.curl.set(CurlOption.mail_rcpt, recipients_list);
}
/**
Sets the message body text.
*/
@property void message(string msg)
{
p.message = msg;
}
}
/++
Exception thrown on errors in std.net.curl functions.
+/
class CurlException : Exception
{
/++
Params:
msg = The message for the exception.
file = The file where the exception occurred.
line = The line number where the exception occurred.
next = The previous exception in the chain of exceptions, if any.
+/
@safe pure nothrow
this(string msg,
string file = __FILE__,
size_t line = __LINE__,
Throwable next = null)
{
super(msg, file, line, next);
}
}
/++
Exception thrown on timeout errors in std.net.curl functions.
+/
class CurlTimeoutException : CurlException
{
/++
Params:
msg = The message for the exception.
file = The file where the exception occurred.
line = The line number where the exception occurred.
next = The previous exception in the chain of exceptions, if any.
+/
@safe pure nothrow
this(string msg,
string file = __FILE__,
size_t line = __LINE__,
Throwable next = null)
{
super(msg, file, line, next);
}
}
/// Equal to $(REF CURLcode, etc,c,curl)
alias CurlCode = CURLcode;
import std.typecons : Flag;
/// Flag to specify whether or not an exception is thrown on error.
alias ThrowOnError = Flag!"throwOnError";
private struct CurlAPI
{
static struct API
{
extern(C):
import core.stdc.config : c_long;
CURLcode function(c_long flags) global_init;
void function() global_cleanup;
curl_version_info_data * function(CURLversion) version_info;
CURL* function() easy_init;
CURLcode function(CURL *curl, CURLoption option,...) easy_setopt;
CURLcode function(CURL *curl) easy_perform;
CURL* function(CURL *curl) easy_duphandle;
char* function(CURLcode) easy_strerror;
CURLcode function(CURL *handle, int bitmask) easy_pause;
void function(CURL *curl) easy_cleanup;
curl_slist* function(curl_slist *, char *) slist_append;
void function(curl_slist *) slist_free_all;
}
__gshared API _api;
__gshared void* _handle;
static ref API instance() @property
{
import std.concurrency;
initOnce!_handle(loadAPI());
return _api;
}
static void* loadAPI()
{
version (Posix)
{
import core.sys.posix.dlfcn;
alias loadSym = dlsym;
}
else version (Windows)
{
import core.sys.windows.windows;
alias loadSym = GetProcAddress;
}
else
static assert(0, "unimplemented");
void* handle;
version (Posix)
handle = dlopen(null, RTLD_LAZY);
else version (Windows)
handle = GetModuleHandleA(null);
assert(handle !is null);
// try to load curl from the executable to allow static linking
if (loadSym(handle, "curl_global_init") is null)
{
version (Posix)
dlclose(handle);
version (OSX)
static immutable names = ["libcurl.4.dylib"];
else version (Posix)
{
static immutable names = ["libcurl.so", "libcurl.so.4",
"libcurl-gnutls.so.4", "libcurl-nss.so.4", "libcurl.so.3"];
}
else version (Windows)
static immutable names = ["libcurl.dll", "curl.dll"];
foreach (name; names)
{
version (Posix)
handle = dlopen(name.ptr, RTLD_LAZY);
else version (Windows)
handle = LoadLibraryA(name.ptr);
if (handle !is null) break;
}
enforce!CurlException(handle !is null, "Failed to load curl, tried %(%s, %).".format(names));
}
foreach (i, FP; typeof(API.tupleof))
{
enum name = __traits(identifier, _api.tupleof[i]);
auto p = enforce!CurlException(loadSym(handle, "curl_"~name),
"Couldn't load curl_"~name~" from libcurl.");
_api.tupleof[i] = cast(FP) p;
}
enforce!CurlException(!_api.global_init(CurlGlobal.all),
"Failed to initialize libcurl");
return handle;
}
shared static ~this()
{
if (_handle is null) return;
_api.global_cleanup();
version (Posix)
{
import core.sys.posix.dlfcn;
dlclose(_handle);
}
else version (Windows)
{
import core.sys.windows.windows;
FreeLibrary(_handle);
}
else
static assert(0, "unimplemented");
_api = API.init;
_handle = null;
}
}
/**
Wrapper to provide a better interface to libcurl than using the plain C API.
It is recommended to use the $(D HTTP)/$(D FTP) etc. structs instead unless
raw access to libcurl is needed.
Warning: This struct uses interior pointers for callbacks. Only allocate it
on the stack if you never move or copy it. This also means passing by reference
when passing Curl to other functions. Otherwise always allocate on
the heap.
*/
struct Curl
{
alias OutData = void[];
alias InData = ubyte[];
private bool _stopped;
private static auto ref curl() @property { return CurlAPI.instance; }
// A handle should not be used by two threads simultaneously
private CURL* handle;
// May also return $(D CURL_READFUNC_ABORT) or $(D CURL_READFUNC_PAUSE)
private size_t delegate(OutData) _onSend;
private size_t delegate(InData) _onReceive;
private void delegate(in char[]) _onReceiveHeader;
private CurlSeek delegate(long,CurlSeekPos) _onSeek;
private int delegate(curl_socket_t,CurlSockType) _onSocketOption;
private int delegate(size_t dltotal, size_t dlnow,
size_t ultotal, size_t ulnow) _onProgress;
alias requestPause = CurlReadFunc.pause;
alias requestAbort = CurlReadFunc.abort;
/**
Initialize the instance by creating a working curl handle.
*/
void initialize()
{
enforce!CurlException(!handle, "Curl instance already initialized");
handle = curl.easy_init();
enforce!CurlException(handle, "Curl instance couldn't be initialized");
_stopped = false;
set(CurlOption.nosignal, 1);
}
///
@property bool stopped() const
{
return _stopped;
}
/**
Duplicate this handle.
The new handle will have all options set as the one it was duplicated
from. An exception to this is that all options that cannot be shared
across threads are reset thereby making it safe to use the duplicate
in a new thread.
*/
Curl dup()
{
Curl copy;
copy.handle = curl.easy_duphandle(handle);
copy._stopped = false;
with (CurlOption) {
auto tt = AliasSeq!(file, writefunction, writeheader,
headerfunction, infile, readfunction, ioctldata, ioctlfunction,
seekdata, seekfunction, sockoptdata, sockoptfunction,
opensocketdata, opensocketfunction, progressdata,
progressfunction, debugdata, debugfunction, interleavedata,
interleavefunction, chunk_data, chunk_bgn_function,
chunk_end_function, fnmatch_data, fnmatch_function, cookiejar, postfields);
foreach (option; tt)
copy.clear(option);
}
// The options are only supported by libcurl when it has been built
// against certain versions of OpenSSL - if your libcurl uses an old
// OpenSSL, or uses an entirely different SSL engine, attempting to
// clear these normally will raise an exception
copy.clearIfSupported(CurlOption.ssl_ctx_function);
copy.clearIfSupported(CurlOption.ssh_keydata);
// Enable for curl version > 7.21.7
static if (LIBCURL_VERSION_MAJOR >= 7 &&
LIBCURL_VERSION_MINOR >= 21 &&
LIBCURL_VERSION_PATCH >= 7)
{
copy.clear(CurlOption.closesocketdata);
copy.clear(CurlOption.closesocketfunction);
}
copy.set(CurlOption.nosignal, 1);
// copy.clear(CurlOption.ssl_ctx_data); Let ssl function be shared
// copy.clear(CurlOption.ssh_keyfunction); Let key function be shared
/*
Allow sharing of conv functions
copy.clear(CurlOption.conv_to_network_function);
copy.clear(CurlOption.conv_from_network_function);
copy.clear(CurlOption.conv_from_utf8_function);
*/
return copy;
}
private void _check(CurlCode code)
{
enforce!CurlTimeoutException(code != CurlError.operation_timedout,
errorString(code));
enforce!CurlException(code == CurlError.ok,
errorString(code));
}
private string errorString(CurlCode code)
{
import core.stdc.string : strlen;
auto msgZ = curl.easy_strerror(code);
// doing the following (instead of just using std.conv.to!string) avoids 1 allocation
return format("%s on handle %s", msgZ[0 .. strlen(msgZ)], handle);
}
private void throwOnStopped(string message = null)
{
auto def = "Curl instance called after being cleaned up";
enforce!CurlException(!stopped,
message == null ? def : message);
}
/**
Stop and invalidate this curl instance.
Warning: Do not call this from inside a callback handler e.g. $(D onReceive).
*/
void shutdown()
{
throwOnStopped();
_stopped = true;
curl.easy_cleanup(this.handle);
this.handle = null;
}
/**
Pausing and continuing transfers.
*/
void pause(bool sendingPaused, bool receivingPaused)
{
throwOnStopped();
_check(curl.easy_pause(this.handle,
(sendingPaused ? CurlPause.send_cont : CurlPause.send) |
(receivingPaused ? CurlPause.recv_cont : CurlPause.recv)));
}
/**
Set a string curl option.
Params:
option = A $(REF CurlOption, etc,c,curl) as found in the curl documentation
value = The string
*/
void set(CurlOption option, const(char)[] value)
{
throwOnStopped();
_check(curl.easy_setopt(this.handle, option, value.tempCString().buffPtr));
}
/**
Set a long curl option.
Params:
option = A $(REF CurlOption, etc,c,curl) as found in the curl documentation
value = The long
*/
void set(CurlOption option, long value)
{
throwOnStopped();
_check(curl.easy_setopt(this.handle, option, value));
}
/**
Set a void* curl option.
Params:
option = A $(REF CurlOption, etc,c,curl) as found in the curl documentation
value = The pointer
*/
void set(CurlOption option, void* value)
{
throwOnStopped();
_check(curl.easy_setopt(this.handle, option, value));
}
/**
Clear a pointer option.
Params:
option = A $(REF CurlOption, etc,c,curl) as found in the curl documentation
*/
void clear(CurlOption option)
{
throwOnStopped();
_check(curl.easy_setopt(this.handle, option, null));
}
/**
Clear a pointer option. Does not raise an exception if the underlying
libcurl does not support the option. Use sparingly.
Params:
option = A $(REF CurlOption, etc,c,curl) as found in the curl documentation
*/
void clearIfSupported(CurlOption option)
{
throwOnStopped();
auto rval = curl.easy_setopt(this.handle, option, null);
if (rval != CurlError.unknown_option && rval != CurlError.not_built_in)
_check(rval);
}
/**
perform the curl request by doing the HTTP,FTP etc. as it has
been setup beforehand.
Params:
throwOnError = whether to throw an exception or return a CurlCode on error
*/
CurlCode perform(ThrowOnError throwOnError = ThrowOnError.yes)
{
throwOnStopped();
CurlCode code = curl.easy_perform(this.handle);
if (throwOnError)
_check(code);
return code;
}
/**
* The event handler that receives incoming data.
*
* Params:
* callback = the callback that receives the $(D ubyte[]) data.
* Be sure to copy the incoming data and not store
* a slice.
*
* Returns:
* The callback returns the incoming bytes read. If not the entire array is
* the request will abort.
* The special value HTTP.pauseRequest can be returned in order to pause the
* current request.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* Curl curl;
* curl.initialize();
* curl.set(CurlOption.url, "http://dlang.org");
* curl.onReceive = (ubyte[] data) { writeln("Got data", to!(const(char)[])(data)); return data.length;};
* curl.perform();
* ----
*/
@property void onReceive(size_t delegate(InData) callback)
{
_onReceive = (InData id)
{
throwOnStopped("Receive callback called on cleaned up Curl instance");
return callback(id);
};
set(CurlOption.file, cast(void*) &this);
set(CurlOption.writefunction, cast(void*) &Curl._receiveCallback);
}
/**
* The event handler that receives incoming headers for protocols
* that uses headers.
*
* Params:
* callback = the callback that receives the header string.
* Make sure the callback copies the incoming params if
* it needs to store it because they are references into
* the backend and may very likely change.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* Curl curl;
* curl.initialize();
* curl.set(CurlOption.url, "http://dlang.org");
* curl.onReceiveHeader = (in char[] header) { writeln(header); };
* curl.perform();
* ----
*/
@property void onReceiveHeader(void delegate(in char[]) callback)
{
_onReceiveHeader = (in char[] od)
{
throwOnStopped("Receive header callback called on "~
"cleaned up Curl instance");
callback(od);
};
set(CurlOption.writeheader, cast(void*) &this);
set(CurlOption.headerfunction,
cast(void*) &Curl._receiveHeaderCallback);
}
/**
* The event handler that gets called when data is needed for sending.
*
* Params:
* callback = the callback that has a $(D void[]) buffer to be filled
*
* Returns:
* The callback returns the number of elements in the buffer that have been
* filled and are ready to send.
* The special value $(D Curl.abortRequest) can be returned in
* order to abort the current request.
* The special value $(D Curl.pauseRequest) can be returned in order to
* pause the current request.
*
* Example:
* ----
* import std.net.curl;
* Curl curl;
* curl.initialize();
* curl.set(CurlOption.url, "http://dlang.org");
*
* string msg = "Hello world";
* curl.onSend = (void[] data)
* {
* auto m = cast(void[])msg;
* size_t length = m.length > data.length ? data.length : m.length;
* if (length == 0) return 0;
* data[0..length] = m[0..length];
* msg = msg[length..$];
* return length;
* };
* curl.perform();
* ----
*/
@property void onSend(size_t delegate(OutData) callback)
{
_onSend = (OutData od)
{
throwOnStopped("Send callback called on cleaned up Curl instance");
return callback(od);
};
set(CurlOption.infile, cast(void*) &this);
set(CurlOption.readfunction, cast(void*) &Curl._sendCallback);
}
/**
* The event handler that gets called when the curl backend needs to seek
* the data to be sent.
*
* Params:
* callback = the callback that receives a seek offset and a seek position
* $(REF CurlSeekPos, etc,c,curl)
*
* Returns:
* The callback returns the success state of the seeking
* $(REF CurlSeek, etc,c,curl)
*
* Example:
* ----
* import std.net.curl;
* Curl curl;
* curl.initialize();
* curl.set(CurlOption.url, "http://dlang.org");
* curl.onSeek = (long p, CurlSeekPos sp)
* {
* return CurlSeek.cantseek;
* };
* curl.perform();
* ----
*/
@property void onSeek(CurlSeek delegate(long, CurlSeekPos) callback)
{
_onSeek = (long ofs, CurlSeekPos sp)
{
throwOnStopped("Seek callback called on cleaned up Curl instance");
return callback(ofs, sp);
};
set(CurlOption.seekdata, cast(void*) &this);
set(CurlOption.seekfunction, cast(void*) &Curl._seekCallback);
}
/**
* The event handler that gets called when the net socket has been created
* but a $(D connect()) call has not yet been done. This makes it possible to set
* misc. socket options.
*
* Params:
* callback = the callback that receives the socket and socket type
* $(REF CurlSockType, etc,c,curl)
*
* Returns:
* Return 0 from the callback to signal success, return 1 to signal error
* and make curl close the socket
*
* Example:
* ----
* import std.net.curl;
* Curl curl;
* curl.initialize();
* curl.set(CurlOption.url, "http://dlang.org");
* curl.onSocketOption = delegate int(curl_socket_t s, CurlSockType t) { /+ do stuff +/ };
* curl.perform();
* ----
*/
@property void onSocketOption(int delegate(curl_socket_t,
CurlSockType) callback)
{
_onSocketOption = (curl_socket_t sock, CurlSockType st)
{
throwOnStopped("Socket option callback called on "~
"cleaned up Curl instance");
return callback(sock, st);
};
set(CurlOption.sockoptdata, cast(void*) &this);
set(CurlOption.sockoptfunction,
cast(void*) &Curl._socketOptionCallback);
}
/**
* The event handler that gets called to inform of upload/download progress.
*
* Params:
* callback = the callback that receives the (total bytes to download,
* currently downloaded bytes, total bytes to upload, currently uploaded
* bytes).
*
* Returns:
* Return 0 from the callback to signal success, return non-zero to abort
* transfer
*
* Example:
* ----
* import std.net.curl;
* Curl curl;
* curl.initialize();
* curl.set(CurlOption.url, "http://dlang.org");
* curl.onProgress = delegate int(size_t dltotal, size_t dlnow, size_t ultotal, size_t uln)
* {
* writeln("Progress: downloaded bytes ", dlnow, " of ", dltotal);
* writeln("Progress: uploaded bytes ", ulnow, " of ", ultotal);
* curl.perform();
* };
* ----
*/
@property void onProgress(int delegate(size_t dlTotal,
size_t dlNow,
size_t ulTotal,
size_t ulNow) callback)
{
_onProgress = (size_t dlt, size_t dln, size_t ult, size_t uln)
{
throwOnStopped("Progress callback called on cleaned "~
"up Curl instance");
return callback(dlt, dln, ult, uln);
};
set(CurlOption.noprogress, 0);
set(CurlOption.progressdata, cast(void*) &this);
set(CurlOption.progressfunction, cast(void*) &Curl._progressCallback);
}
// Internal C callbacks to register with libcurl
extern (C) private static
size_t _receiveCallback(const char* str,
size_t size, size_t nmemb, void* ptr)
{
auto b = cast(Curl*) ptr;
if (b._onReceive != null)
return b._onReceive(cast(InData)(str[0..size*nmemb]));
return size*nmemb;
}
extern (C) private static
size_t _receiveHeaderCallback(const char* str,
size_t size, size_t nmemb, void* ptr)
{
auto b = cast(Curl*) ptr;
auto s = str[0..size*nmemb].chomp();
if (b._onReceiveHeader != null)
b._onReceiveHeader(s);
return size*nmemb;
}
extern (C) private static
size_t _sendCallback(char *str, size_t size, size_t nmemb, void *ptr)
{
Curl* b = cast(Curl*) ptr;
auto a = cast(void[]) str[0..size*nmemb];
if (b._onSend == null)
return 0;
return b._onSend(a);
}
extern (C) private static
int _seekCallback(void *ptr, curl_off_t offset, int origin)
{
auto b = cast(Curl*) ptr;
if (b._onSeek == null)
return CurlSeek.cantseek;
// origin: CurlSeekPos.set/current/end
// return: CurlSeek.ok/fail/cantseek
return b._onSeek(cast(long) offset, cast(CurlSeekPos) origin);
}
extern (C) private static
int _socketOptionCallback(void *ptr,
curl_socket_t curlfd, curlsocktype purpose)
{
auto b = cast(Curl*) ptr;
if (b._onSocketOption == null)
return 0;
// return: 0 ok, 1 fail
return b._onSocketOption(curlfd, cast(CurlSockType) purpose);
}
extern (C) private static
int _progressCallback(void *ptr,
double dltotal, double dlnow,
double ultotal, double ulnow)
{
auto b = cast(Curl*) ptr;
if (b._onProgress == null)
return 0;
// return: 0 ok, 1 fail
return b._onProgress(cast(size_t)dltotal, cast(size_t)dlnow,
cast(size_t)ultotal, cast(size_t)ulnow);
}
}
// Internal messages send between threads.
// The data is wrapped in this struct in order to ensure that
// other std.concurrency.receive calls does not pick up our messages
// by accident.
private struct CurlMessage(T)
{
public T data;
}
private static CurlMessage!T curlMessage(T)(T data)
{
return CurlMessage!T(data);
}
// Pool of to be used for reusing buffers
private struct Pool(Data)
{
private struct Entry
{
Data data;
Entry* next;
}
private Entry* root;
private Entry* freeList;
@safe @property bool empty()
{
return root == null;
}
@safe nothrow void push(Data d)
{
if (freeList == null)
{
// Allocate new Entry since there is no one
// available in the freeList
freeList = new Entry;
}
freeList.data = d;
Entry* oldroot = root;
root = freeList;
freeList = freeList.next;
root.next = oldroot;
}
@safe Data pop()
{
enforce!Exception(root != null, "pop() called on empty pool");
auto d = root.data;
auto n = root.next;
root.next = freeList;
freeList = root;
root = n;
return d;
}
}
// Shared function for reading incoming chunks of data and
// sending the to a parent thread
private static size_t _receiveAsyncChunks(ubyte[] data, ref ubyte[] outdata,
Pool!(ubyte[]) freeBuffers,
ref ubyte[] buffer, Tid fromTid,
ref bool aborted)
{
immutable datalen = data.length;
// Copy data to fill active buffer
while (!data.empty)
{
// Make sure a buffer is present
while ( outdata.empty && freeBuffers.empty)
{
// Active buffer is invalid and there are no
// available buffers in the pool. Wait for buffers
// to return from main thread in order to reuse
// them.
receive((immutable(ubyte)[] buf)
{
buffer = cast(ubyte[])buf;
outdata = buffer[];
},
(bool flag) { aborted = true; }
);
if (aborted) return cast(size_t)0;
}
if (outdata.empty)
{
buffer = freeBuffers.pop();
outdata = buffer[];
}
// Copy data
auto copyBytes = outdata.length < data.length ?
outdata.length : data.length;
outdata[0..copyBytes] = data[0..copyBytes];
outdata = outdata[copyBytes..$];
data = data[copyBytes..$];
if (outdata.empty)
fromTid.send(thisTid, curlMessage(cast(immutable(ubyte)[])buffer));
}
return datalen;
}
// ditto
private static void _finalizeAsyncChunks(ubyte[] outdata, ref ubyte[] buffer,
Tid fromTid)
{
if (!outdata.empty)
{
// Resize the last buffer
buffer.length = buffer.length - outdata.length;
fromTid.send(thisTid, curlMessage(cast(immutable(ubyte)[])buffer));
}
}
// Shared function for reading incoming lines of data and sending the to a
// parent thread
private static size_t _receiveAsyncLines(Terminator, Unit)
(const(ubyte)[] data, ref EncodingScheme encodingScheme,
bool keepTerminator, Terminator terminator,
ref const(ubyte)[] leftOverBytes, ref bool bufferValid,
ref Pool!(Unit[]) freeBuffers, ref Unit[] buffer,
Tid fromTid, ref bool aborted)
{
immutable datalen = data.length;
// Terminator is specified and buffers should be resized as determined by
// the terminator
// Copy data to active buffer until terminator is found.
// Decode as many lines as possible
while (true)
{
// Make sure a buffer is present
while (!bufferValid && freeBuffers.empty)
{
// Active buffer is invalid and there are no available buffers in
// the pool. Wait for buffers to return from main thread in order to
// reuse them.
receive((immutable(Unit)[] buf)
{
buffer = cast(Unit[])buf;
buffer.length = 0;
buffer.assumeSafeAppend();
bufferValid = true;
},
(bool flag) { aborted = true; }
);
if (aborted) return cast(size_t)0;
}
if (!bufferValid)
{
buffer = freeBuffers.pop();
bufferValid = true;
}
// Try to read a line from left over bytes from last onReceive plus the
// newly received bytes.
try
{
if (decodeLineInto(leftOverBytes, data, buffer,
encodingScheme, terminator))
{
if (keepTerminator)
{
fromTid.send(thisTid,
curlMessage(cast(immutable(Unit)[])buffer));
}
else
{
static if (isArray!Terminator)
fromTid.send(thisTid,
curlMessage(cast(immutable(Unit)[])
buffer[0..$-terminator.length]));
else
fromTid.send(thisTid,
curlMessage(cast(immutable(Unit)[])
buffer[0..$-1]));
}
bufferValid = false;
}
else
{
// Could not decode an entire line. Save
// bytes left in data for next call to
// onReceive. Can be up to a max of 4 bytes.
enforce!CurlException(data.length <= 4,
format(
"Too many bytes left not decoded %s"~
" > 4. Maybe the charset specified in"~
" headers does not match "~
"the actual content downloaded?",
data.length));
leftOverBytes ~= data;
break;
}
}
catch (CurlException ex)
{
prioritySend(fromTid, cast(immutable(CurlException))ex);
return cast(size_t)0;
}
}
return datalen;
}
// ditto
private static
void _finalizeAsyncLines(Unit)(bool bufferValid, Unit[] buffer, Tid fromTid)
{
if (bufferValid && buffer.length != 0)
fromTid.send(thisTid, curlMessage(cast(immutable(Unit)[])buffer[0..$]));
}
// Spawn a thread for handling the reading of incoming data in the
// background while the delegate is executing. This will optimize
// throughput by allowing simultaneous input (this struct) and
// output (e.g. AsyncHTTPLineOutputRange).
private static void _spawnAsync(Conn, Unit, Terminator = void)()
{
Tid fromTid = receiveOnly!Tid();
// Get buffer to read into
Pool!(Unit[]) freeBuffers; // Free list of buffer objects
// Number of bytes filled into active buffer
Unit[] buffer;
bool aborted = false;
EncodingScheme encodingScheme;
static if ( !is(Terminator == void))
{
// Only lines reading will receive a terminator
auto terminator = receiveOnly!Terminator();
auto keepTerminator = receiveOnly!bool();
// max number of bytes to carry over from an onReceive
// callback. This is 4 because it is the max code units to
// decode a code point in the supported encodings.
auto leftOverBytes = new const(ubyte)[4];
leftOverBytes.length = 0;
auto bufferValid = false;
}
else
{
Unit[] outdata;
}
// no move semantic available in std.concurrency ie. must use casting.
auto connDup = cast(CURL*)receiveOnly!ulong();
auto client = Conn();
client.p.curl.handle = connDup;
// receive a method for both ftp and http but just use it for http
auto method = receiveOnly!(HTTP.Method)();
client.onReceive = (ubyte[] data)
{
// If no terminator is specified the chunk size is fixed.
static if ( is(Terminator == void) )
return _receiveAsyncChunks(data, outdata, freeBuffers, buffer,
fromTid, aborted);
else
return _receiveAsyncLines(data, encodingScheme,
keepTerminator, terminator, leftOverBytes,
bufferValid, freeBuffers, buffer,
fromTid, aborted);
};
static if ( is(Conn == HTTP) )
{
client.method = method;
// register dummy header handler
client.onReceiveHeader = (in char[] key, in char[] value)
{
if (key == "content-type")
encodingScheme = EncodingScheme.create(client.p.charset);
};
}
else
{
encodingScheme = EncodingScheme.create(client.encoding);
}
// Start the request
CurlCode code;
try
{
code = client.perform(ThrowOnError.no);
}
catch (Exception ex)
{
prioritySend(fromTid, cast(immutable(Exception)) ex);
fromTid.send(thisTid, curlMessage(true)); // signal done
return;
}
if (code != CurlError.ok)
{
if (aborted && (code == CurlError.aborted_by_callback ||
code == CurlError.write_error))
{
fromTid.send(thisTid, curlMessage(true)); // signal done
return;
}
prioritySend(fromTid, cast(immutable(CurlException))
new CurlException(client.p.curl.errorString(code)));
fromTid.send(thisTid, curlMessage(true)); // signal done
return;
}
// Send remaining data that is not a full chunk size
static if ( is(Terminator == void) )
_finalizeAsyncChunks(outdata, buffer, fromTid);
else
_finalizeAsyncLines(bufferValid, buffer, fromTid);
fromTid.send(thisTid, curlMessage(true)); // signal done
}
|
D
|
a wormlike and often brightly colored and hairy or spiny larva of a butterfly or moth
a large tracked vehicle that is propelled by two endless metal belts
|
D
|
/home/philip/LearnDemo/rust-lang-book/Chapter04/demo4_6/target/debug/deps/demo4_6-b635395ddef084f1.rmeta: src/main.rs
/home/philip/LearnDemo/rust-lang-book/Chapter04/demo4_6/target/debug/deps/demo4_6-b635395ddef084f1.d: src/main.rs
src/main.rs:
|
D
|
instance DIA_328_Miliz_EXIT(C_Info)
{
npc = Mil_328_Miliz;
nr = 999;
condition = DIA_328_Miliz_EXIT_Condition;
information = DIA_328_Miliz_EXIT_Info;
permanent = TRUE;
description = Dialog_Ende;
};
func int DIA_328_Miliz_EXIT_Condition()
{
return TRUE;
};
func void DIA_328_Miliz_EXIT_Info()
{
AI_StopProcessInfos(self);
};
instance DIA_328_Miliz_Hi(C_Info)
{
npc = Mil_328_Miliz;
nr = 1;
condition = DIA_328_Miliz_Hi_Condition;
information = DIA_328_Miliz_Hi_Info;
permanent = FALSE;
important = TRUE;
};
func int DIA_328_Miliz_Hi_Condition()
{
return TRUE;
};
func void DIA_328_Miliz_Hi_Info()
{
AI_Output(self,other,"DIA_328_Miliz_Hi_08_00"); //Hele, tady nemáš co dělat. Rozumíš?
AI_Output(other,self,"DIA_328_Miliz_Hi_15_01"); //Kdo jsi?
AI_Output(self,other,"DIA_328_Miliz_Hi_08_02"); //Po tom ti vůbec nic není! Šéfuju tomu tady, jasný?
AI_Output(other,self,"DIA_328_Miliz_Hi_15_03"); //Šéfuješ? Čemu? Těm bednám?
AI_Output(self,other,"DIA_328_Miliz_Hi_08_04"); //Hele, skladiště spadá pod můj dohled, jasný? Tak vypadni, nebo si poneseš zuby v klobouku.
AI_StopProcessInfos(self);
Npc_SetRefuseTalk(self,30);
};
instance DIA_328_Miliz_Kill(C_Info)
{
npc = Mil_328_Miliz;
nr = 2;
condition = DIA_328_Miliz_Kill_Condition;
information = DIA_328_Miliz_Kill_Info;
permanent = TRUE;
important = TRUE;
};
func int DIA_328_Miliz_Kill_Condition()
{
if(Npc_RefuseTalk(self) == FALSE)
{
return TRUE;
};
};
func void DIA_328_Miliz_Kill_Info()
{
AI_Output(self,other,"DIA_328_Miliz_Kill_08_00"); //Hej, ty jsi pořád ještě tady. Neříkal jsem ti, že máš vypadnout?
AI_Output(self,other,"DIA_328_Miliz_Kill_08_01"); //Teď ti ukážu, kdo je tady šéf!
AI_StopProcessInfos(self);
Npc_SetRefuseTalk(self,20);
B_Attack(self,other,AR_KILL,1);
};
|
D
|
// *************************************************************************
// Kapitel 1
// *************************************************************************
// *************************************************************************
// EXIT
// *************************************************************************
INSTANCE Info_Grd_6_EXIT(C_INFO)
{
// npc wird in B_AssignAmbientInfos_Grd_6 (s.u.) jeweils gesetzt
nr = 999;
condition = Info_Grd_6_EXIT_Condition;
information = Info_Grd_6_EXIT_Info;
permanent = 1;
description = DIALOG_ENDE;
};
FUNC INT Info_Grd_6_EXIT_Condition()
{
return 1;
};
FUNC VOID Info_Grd_6_EXIT_Info()
{
AI_StopProcessInfos (self);
};
// *************************************************************************
// Einer von Euch werden
// *************************************************************************
INSTANCE Info_Grd_6_EinerVonEuchWerden (C_INFO) // E1
{
nr = 1;
condition = Info_Grd_6_EinerVonEuchWerden_Condition;
information = Info_Grd_6_EinerVonEuchWerden_Info;
permanent = 1;
description = "Ich will Gardist werden.";
};
FUNC INT Info_Grd_6_EinerVonEuchWerden_Condition()
{
if (Gardist_Dabei == FALSE)
&& (Erzbaron_Dabei == FALSE)
&& (Schatten_Dabei == FALSE)
{
return TRUE;
};
};
FUNC VOID Info_Grd_6_EinerVonEuchWerden_Info()
{
AI_Output(hero,self,"Info_Grd_6_EinerVonEuchWerden_15_00"); //Könnt ihr noch einen guten Mann brauchen?
AI_Output(self,hero,"Info_Grd_6_EinerVonEuchWerden_06_01"); //Frischling, was? Wenn du ein Lager suchst, das dich aufnimmt, probier's doch bei den Sektenspinnern, die nehmen jeden.
AI_Output(self,hero,"Info_Grd_6_EinerVonEuchWerden_06_02"); //Bei uns wird nicht jeder genommen!
};
// *************************************************************************
// Wichtige Personen
// *************************************************************************
INSTANCE Info_Grd_6_WichtigePersonen(C_INFO)
{
nr = 1;
condition = Info_Grd_6_WichtigePersonen_Condition;
information = Info_Grd_6_WichtigePersonen_Info;
permanent = 1;
description = "Wer hat hier das Sagen?";
};
FUNC INT Info_Grd_6_WichtigePersonen_Condition()
{
return 1;
};
FUNC VOID Info_Grd_6_WichtigePersonen_Info()
{
AI_Output(hero,self,"Info_Grd_6_WichtigePersonen_15_00"); //Wer hat hier das Sagen?
AI_Output(self,hero,"Info_Grd_6_WichtigePersonen_06_01"); //Thorus kümmert sich drum das alles läuft.
};
// *************************************************************************
// Das Lager (Orts-Infos)
// *************************************************************************
INSTANCE Info_Grd_6_DasLager(C_INFO)
{
nr = 1;
condition = Info_Grd_6_DasLager_Condition;
information = Info_Grd_6_DasLager_Info;
permanent = 1;
description = "Ich bin neu hier. Was läuft denn so?";
};
FUNC INT Info_Grd_6_DasLager_Condition()
{
if (Schatten_Dabei == FALSE)
&& (Gardist_Dabei == FALSE)
&& (Erzbaron_Dabei == FALSE)
{
return 1;
};
};
FUNC VOID Info_Grd_6_DasLager_Info()
{
AI_Output(hero,self,"Info_Grd_6_DasLager_15_00"); //Ich bin neu hier.
AI_Output(self,hero,"Info_Grd_6_DasLager_06_01"); //Sehe ich.
AI_Output(hero,self,"Info_Grd_6_DasLager_15_02"); //Was läuft denn so?
AI_Output(self,hero,"Info_Grd_6_DasLager_06_03"); //Wer hier Ärger macht bekommt was aufs Maul.
Info_ClearChoices(Info_Grd_6_DasLager);
Info_AddChoice(Info_Grd_6_DasLager, "Verstehe.", Info_Grd_6_DasLager_Verstehe);
Info_AddChoice(Info_Grd_6_DasLager, "Was verstehst du unter Ärger?", Info_Grd_6_DasLager_WasIstAerger);
};
FUNC VOID Info_Grd_6_DasLager_Verstehe()
{
AI_Output(hero,self,"Info_Grd_6_DasLager_Verstehe_15_00"); //Verstehe.
Info_ClearChoices(Info_Grd_6_DasLager);
};
FUNC VOID Info_Grd_6_DasLager_WasIstAerger()
{
AI_Output(hero,self,"Info_Grd_6_DasLager_WasIstAerger_15_00"); //Was verstehst du unter Ärger?
AI_Output(self,hero,"Info_Grd_6_DasLager_WasIstAerger_06_01"); //Die meisten Buddler bezahlen uns, damit wir sie beschützen.
AI_Output(self,hero,"Info_Grd_6_DasLager_WasIstAerger_06_02"); //Wenn du dich mit einem von ihnen anlegst, lernst du uns kennen.
AI_Output(self,hero,"Info_Grd_6_DasLager_WasIstAerger_06_03"); //Erwische ich dich beim rumstöbern in fremden Hütten ...
AI_Output(hero,self,"Info_Grd_6_DasLager_WasIstAerger_15_04"); //Schon gut, ich hab's verstanden.
Info_ClearChoices(Info_Grd_6_DasLager);
};
// *************************************************************************
// Die Lage
// *************************************************************************
INSTANCE Info_Grd_6_DieLage(C_INFO) // E1
{
nr = 1;
condition = Info_Grd_6_DieLage_Condition;
information = Info_Grd_6_DieLage_Info;
permanent = 1;
description = "Wie sieht's aus?";
};
FUNC INT Info_Grd_6_DieLage_Condition()
{
return 1;
};
FUNC VOID Info_Grd_6_DieLage_Info()
{
AI_Output(hero,self,"Info_Grd_6_DieLage_15_00"); //Wie sieht's aus?
AI_Output(self,hero,"Info_Grd_6_DieLage_06_01"); //Willst du Ärger machen?
};
INSTANCE Info_Mod_GRD_6_Pickpocket (C_INFO)
{
nr = 6;
condition = Info_Mod_GRD_6_Pickpocket_Condition;
information = Info_Mod_GRD_6_Pickpocket_Info;
permanent = 1;
important = 0;
description = Pickpocket_120;
};
FUNC INT Info_Mod_GRD_6_Pickpocket_Condition()
{
C_Beklauen (90+r_max(30), ItMi_Gold, 300+r_max(100));
};
FUNC VOID Info_Mod_GRD_6_Pickpocket_Info()
{
Info_ClearChoices (Info_Mod_GRD_6_Pickpocket);
Info_AddChoice (Info_Mod_GRD_6_Pickpocket, DIALOG_BACK, Info_Mod_GRD_6_Pickpocket_BACK);
Info_AddChoice (Info_Mod_GRD_6_Pickpocket, DIALOG_PICKPOCKET, Info_Mod_GRD_6_Pickpocket_DoIt);
};
FUNC VOID Info_Mod_GRD_6_Pickpocket_BACK()
{
Info_ClearChoices (Info_Mod_GRD_6_Pickpocket);
};
FUNC VOID Info_Mod_GRD_6_Pickpocket_DoIt()
{
if (B_Beklauen() == TRUE)
{
Info_ClearChoices (Info_Mod_GRD_6_Pickpocket);
}
else
{
Info_ClearChoices (Info_Mod_GRD_6_Pickpocket);
Info_AddChoice (Info_Mod_GRD_6_Pickpocket, DIALOG_PP_BESCHIMPFEN, Info_Mod_GRD_6_Pickpocket_Beschimpfen);
Info_AddChoice (Info_Mod_GRD_6_Pickpocket, DIALOG_PP_BESTECHUNG, Info_Mod_GRD_6_Pickpocket_Bestechung);
Info_AddChoice (Info_Mod_GRD_6_Pickpocket, DIALOG_PP_HERAUSREDEN, Info_Mod_GRD_6_Pickpocket_Herausreden);
};
};
FUNC VOID Info_Mod_GRD_6_Pickpocket_Beschimpfen()
{
B_Say (hero, self, "$PICKPOCKET_BESCHIMPFEN");
B_Say (self, hero, "$DIRTYTHIEF");
Info_ClearChoices (Info_Mod_GRD_6_Pickpocket);
AI_StopProcessInfos (self);
B_Attack (self, hero, AR_Theft, 1);
};
FUNC VOID Info_Mod_GRD_6_Pickpocket_Bestechung()
{
B_Say (hero, self, "$PICKPOCKET_BESTECHUNG");
var int rnd; rnd = r_max(99);
if (rnd < 25)
|| ((rnd >= 25) && (rnd < 50) && (Npc_HasItems(hero, ItMi_Gold) < 50))
|| ((rnd >= 50) && (rnd < 75) && (Npc_HasItems(hero, ItMi_Gold) < 100))
|| ((rnd >= 75) && (rnd < 100) && (Npc_HasItems(hero, ItMi_Gold) < 200))
{
B_Say (self, hero, "$DIRTYTHIEF");
Info_ClearChoices (Info_Mod_GRD_6_Pickpocket);
AI_StopProcessInfos (self);
B_Attack (self, hero, AR_Theft, 1);
}
else
{
if (rnd >= 75)
{
B_GiveInvItems (hero, self, ItMi_Gold, 200);
}
else if (rnd >= 50)
{
B_GiveInvItems (hero, self, ItMi_Gold, 100);
}
else if (rnd >= 25)
{
B_GiveInvItems (hero, self, ItMi_Gold, 50);
};
B_Say (self, hero, "$PICKPOCKET_BESTECHUNG_01");
Info_ClearChoices (Info_Mod_GRD_6_Pickpocket);
AI_StopProcessInfos (self);
};
};
FUNC VOID Info_Mod_GRD_6_Pickpocket_Herausreden()
{
B_Say (hero, self, "$PICKPOCKET_HERAUSREDEN");
if (r_max(99) < Mod_Verhandlungsgeschick)
{
B_Say (self, hero, "$PICKPOCKET_HERAUSREDEN_01");
Info_ClearChoices (Info_Mod_GRD_6_Pickpocket);
}
else
{
B_Say (self, hero, "$PICKPOCKET_HERAUSREDEN_02");
};
};
// *************************************************************************
// -------------------------------------------------------------------------
FUNC VOID B_AssignAmbientInfos_GRD_6(var c_NPC slf)
{
Info_Grd_6_EXIT.npc = Hlp_GetInstanceID(slf);
Info_Grd_6_EinerVonEuchWerden.npc = Hlp_GetInstanceID(slf);
Info_Grd_6_WichtigePersonen.npc = Hlp_GetInstanceID(slf);
Info_Grd_6_DasLager.npc = Hlp_GetInstanceID(slf);
Info_Grd_6_DieLage.npc = Hlp_GetInstanceID(slf);
Info_Mod_GRD_6_Pickpocket.npc = Hlp_GetInstanceID(slf);
};
|
D
|
module mqttd.factory;
import mqttd.message;
import cerealed.decerealiser;
import std.stdio;
struct MqttFactory {
static this() {
with(MqttType) {
registerType!MqttConnect(CONNECT);
registerType!MqttConnack(CONNACK);
registerType!MqttPublish(PUBLISH);
registerType!MqttSubscribe(SUBSCRIBE);
registerType!MqttSuback(SUBACK);
registerType!MqttUnsubscribe(UNSUBSCRIBE);
registerType!MqttUnsuback(UNSUBACK);
registerType!MqttPingReq(PINGREQ);
registerType!MqttPingResp(PINGRESP);
registerType!MqttDisconnect(DISCONNECT);
}
}
static MqttMessage create(in ubyte[] bytes) {
auto cereal = Decerealiser(bytes);
auto fixedHeader = cereal.value!MqttFixedHeader;
if(!fixedHeader.check(bytes, cereal.bytes.length)) {
return null;
}
cereal.reset(); //so that the created MqttMessage can re-read the header
if(fixedHeader.type !in _msgCreators) {
stderr.writeln("Unknown MQTT message type: ", fixedHeader.type);
return null;
}
return _msgCreators[fixedHeader.type](fixedHeader, cereal);
}
private:
alias MessageCreator = MqttMessage function(MqttFixedHeader, Decerealiser);
static MessageCreator[MqttType] _msgCreators;
static void registerType(T)(MqttType type) {
_msgCreators[type] = (header, cereal) {
return cereal.value!T(header);
};
}
}
|
D
|
<?xml version="1.0" encoding="ASCII" standalone="no"?>
<di:SashWindowsMngr xmlns:di="http://www.eclipse.org/papyrus/0.7.0/sashdi" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmi:version="2.0">
<pageList>
<availablePage>
<emfPageIdentifier href="VAR_13_BeT-1851257868.notation#_copSALmGEeKQQp7P9cQvNQ"/>
</availablePage>
</pageList>
<sashModel currentSelection="//@sashModel/@windows.0/@children.0">
<windows>
<children xsi:type="di:TabFolder">
<children>
<emfPageIdentifier href="VAR_13_BeT-1851257868.notation#_copSALmGEeKQQp7P9cQvNQ"/>
</children>
</children>
</windows>
</sashModel>
</di:SashWindowsMngr>
|
D
|
/**
* Compiler implementation of the
* $(LINK2 http://www.dlang.org, D programming language).
*
* Copyright: Copyright (C) 1999-2018 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 http://www.digitalmars.com, Walter Bright)
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/init.d, _init.d)
* Documentation: https://dlang.org/phobos/dmd_init.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/init.d
*/
module dmd.init;
import core.stdc.stdio;
import core.checkedint;
import dmd.arraytypes;
import dmd.dsymbol;
import dmd.expression;
import dmd.globals;
import dmd.hdrgen;
import dmd.identifier;
import dmd.mtype;
import dmd.root.outbuffer;
import dmd.root.rootobject;
import dmd.tokens;
import dmd.visitor;
enum NeedInterpret : int
{
INITnointerpret,
INITinterpret,
}
alias INITnointerpret = NeedInterpret.INITnointerpret;
alias INITinterpret = NeedInterpret.INITinterpret;
/***********************************************************
*/
extern (C++) class Initializer : RootObject
{
Loc loc;
extern (D) this(const ref Loc loc)
{
this.loc = loc;
}
abstract Initializer syntaxCopy();
static Initializers* arraySyntaxCopy(Initializers* ai)
{
Initializers* a = null;
if (ai)
{
a = new Initializers();
a.setDim(ai.dim);
for (size_t i = 0; i < a.dim; i++)
(*a)[i] = (*ai)[i].syntaxCopy();
}
return a;
}
override final const(char)* toChars()
{
OutBuffer buf;
HdrGenState hgs;
.toCBuffer(this, &buf, &hgs);
return buf.extractString();
}
ErrorInitializer isErrorInitializer()
{
return null;
}
VoidInitializer isVoidInitializer()
{
return null;
}
StructInitializer isStructInitializer()
{
return null;
}
ArrayInitializer isArrayInitializer()
{
return null;
}
ExpInitializer isExpInitializer()
{
return null;
}
void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class VoidInitializer : Initializer
{
Type type; // type that this will initialize to
extern (D) this(const ref Loc loc)
{
super(loc);
}
override Initializer syntaxCopy()
{
return new VoidInitializer(loc);
}
override VoidInitializer isVoidInitializer()
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class ErrorInitializer : Initializer
{
extern (D) this()
{
super(Loc.initial);
}
override Initializer syntaxCopy()
{
return this;
}
override ErrorInitializer isErrorInitializer()
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class StructInitializer : Initializer
{
Identifiers field; // of Identifier *'s
Initializers value; // parallel array of Initializer *'s
extern (D) this(const ref Loc loc)
{
super(loc);
}
override Initializer syntaxCopy()
{
auto ai = new StructInitializer(loc);
assert(field.dim == value.dim);
ai.field.setDim(field.dim);
ai.value.setDim(value.dim);
for (size_t i = 0; i < field.dim; i++)
{
ai.field[i] = field[i];
ai.value[i] = value[i].syntaxCopy();
}
return ai;
}
void addInit(Identifier field, Initializer value)
{
//printf("StructInitializer::addInit(field = %p, value = %p)\n", field, value);
this.field.push(field);
this.value.push(value);
}
override StructInitializer isStructInitializer()
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class ArrayInitializer : Initializer
{
Expressions index; // indices
Initializers value; // of Initializer *'s
uint dim; // length of array being initialized
Type type; // type that array will be used to initialize
bool sem; // true if semantic() is run
extern (D) this(const ref Loc loc)
{
super(loc);
}
override Initializer syntaxCopy()
{
//printf("ArrayInitializer::syntaxCopy()\n");
auto ai = new ArrayInitializer(loc);
assert(index.dim == value.dim);
ai.index.setDim(index.dim);
ai.value.setDim(value.dim);
for (size_t i = 0; i < ai.value.dim; i++)
{
ai.index[i] = index[i] ? index[i].syntaxCopy() : null;
ai.value[i] = value[i].syntaxCopy();
}
return ai;
}
void addInit(Expression index, Initializer value)
{
this.index.push(index);
this.value.push(value);
dim = 0;
type = null;
}
bool isAssociativeArray()
{
for (size_t i = 0; i < value.dim; i++)
{
if (index[i])
return true;
}
return false;
}
override ArrayInitializer isArrayInitializer()
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class ExpInitializer : Initializer
{
Expression exp;
bool expandTuples;
extern (D) this(const ref Loc loc, Expression exp)
{
super(loc);
this.exp = exp;
}
override Initializer syntaxCopy()
{
return new ExpInitializer(loc, exp.syntaxCopy());
}
override ExpInitializer isExpInitializer()
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
version (all)
{
extern (C++) bool hasNonConstPointers(Expression e)
{
static bool checkArray(Expressions* elems)
{
foreach (e; *elems)
{
if (e && hasNonConstPointers(e))
return true;
}
return false;
}
if (e.type.ty == Terror)
return false;
if (e.op == TOK.null_)
return false;
if (e.op == TOK.structLiteral)
{
StructLiteralExp se = cast(StructLiteralExp)e;
return checkArray(se.elements);
}
if (e.op == TOK.arrayLiteral)
{
if (!e.type.nextOf().hasPointers())
return false;
ArrayLiteralExp ae = cast(ArrayLiteralExp)e;
return checkArray(ae.elements);
}
if (e.op == TOK.assocArrayLiteral)
{
AssocArrayLiteralExp ae = cast(AssocArrayLiteralExp)e;
if (ae.type.nextOf().hasPointers() && checkArray(ae.values))
return true;
if ((cast(TypeAArray)ae.type).index.hasPointers())
return checkArray(ae.keys);
return false;
}
if (e.op == TOK.address)
{
AddrExp ae = cast(AddrExp)e;
if (ae.e1.op == TOK.structLiteral)
{
StructLiteralExp se = cast(StructLiteralExp)ae.e1;
if (!(se.stageflags & stageSearchPointers))
{
int old = se.stageflags;
se.stageflags |= stageSearchPointers;
bool ret = checkArray(se.elements);
se.stageflags = old;
return ret;
}
else
{
return false;
}
}
return true;
}
if (e.type.ty == Tpointer && e.type.nextOf().ty != Tfunction)
{
if (e.op == TOK.symbolOffset) // address of a global is OK
return false;
if (e.op == TOK.int64) // cast(void *)int is OK
return false;
if (e.op == TOK.string_) // "abc".ptr is OK
return false;
return true;
}
return false;
}
}
|
D
|
module replace;
//import std.metastrings;
import std.conv;
/**
Performs compile time string replacements on $(D base)
Parameters:
T = replacement specs, alternating between string to be replaced and $(D toStringNow)-able object to replace with.
Example:
---
import std.metastrings;
import std.stdio;
void main()
{
string s = Replace!(q{$ret func(T)(T t){ return new $ret(t+$i); }},
"$ret", "C",
"$i", 5000);
writeln(s); // "C func(T)(T t){ return new C(t+5000); }"
}
---
If there is ambiguity between two substrings to replace, the longer one is preferred:
---
enum s = Replace!("boy eats boysenberry", "boy", "girl", "boysenberry", "plum");
writeln(s) // "girl eats plum"
---
*/
template Replace(string base, T...)
{
import std.algorithm;
static assert(T.length % 2 == 0);
template NextAt(string base, string longest_spec,
size_t _at0, size_t _ti0, T...)
{
static assert(T.length % 2 == 0);
static if(T.length == 0)
{
static if(_at0 == -1)
{
enum size_t at = base.length;
enum size_t ti = -1;
}
else
{
enum at = _at0;
enum ti = _ti0;
}
}
else
{
enum size_t _at1 = countUntil(base, T[$-2]);
static if(_at1 < _at0 ||
_at1 == _at0 && T[$-2].length > longest_spec.length)
{
alias NextAt!(base, T[$-2], _at1, T.length-2,T[0 .. $-2]) N2;
}
else
{
alias NextAt!(base,longest_spec,_at0,_ti0,T[0 .. $-2]) N2;
}
enum at = N2.at;
enum ti = N2.ti;
}
}
alias NextAt!(base,"",-1,-1,T) N;
static if(N.ti == -1)
enum Replace = base;
else
enum Replace = base[0 .. N.at] ~ to!string(T[N.ti+1]) ~
Replace!(base[N.at + T[N.ti].length .. $], T);
}
|
D
|
/*
Copyright © 2020-2023, Inochi2D Project
Distributed under the 2-Clause BSD License, see LICENSE file.
Authors: Luna Nielsen
*/
module creator.io.psd;
import creator;
import creator.ext;
import creator.core.tasks;
import creator.widgets.dialog;
import inochi2d.math;
import inochi2d;
import psd;
import i18n;
import std.format;
import creator.io;
import mir.serde;
private {
}
bool incImportShowPSDDialog() {
TFD_Filter[] filters = [{ ["*.psd"], "Photoshop Document (*.psd)" }];
string file = incShowImportDialog(filters, _("Import..."));
if (file) {
incImportPSD(file, IncPSDImportSettings(false));
return true;
}
return false;
}
class IncPSDLayer {
string name;
bool hidden;
bool isLayerGroup;
BlendMode blendMode;
@serdeIgnore
Layer psdLayerRef;
@serdeIgnore
int index;
@serdeIgnore
IncPSDLayer parent;
IncPSDLayer[] children;
this(Layer layer, bool isGroup, IncPSDLayer parent = null, int index = 0) {
this.parent = parent;
this.psdLayerRef = layer;
this.name = psdLayerRef.name;
this.isLayerGroup = isGroup;
this.index = index;
switch(layer.blendModeKey) {
case BlendingMode.Normal: blendMode = BlendMode.Normal; break;
case BlendingMode.Multiply: blendMode = BlendMode.Multiply; break;
case BlendingMode.Screen: blendMode = BlendMode.Screen; break;
case BlendingMode.Overlay: blendMode = BlendMode.Overlay; break;
case BlendingMode.Darken: blendMode = BlendMode.Darken; break;
case BlendingMode.Lighten: blendMode = BlendMode.Lighten; break;
case BlendingMode.ColorDodge: blendMode = BlendMode.ColorDodge; break;
case BlendingMode.LinearDodge: blendMode = BlendMode.LinearDodge; break;
case BlendingMode.ColorBurn: blendMode = BlendMode.ColorBurn; break;
case BlendingMode.HardLight: blendMode = BlendMode.HardLight; break;
case BlendingMode.SoftLight: blendMode = BlendMode.SoftLight; break;
case BlendingMode.Difference: blendMode = BlendMode.Difference; break;
case BlendingMode.Exclusion: blendMode = BlendMode.Exclusion; break;
case BlendingMode.Subtract: blendMode = BlendMode.Subtract; break;
default: blendMode = BlendMode.Normal; break;
}
}
/**
Gets the layer path
*/
string getLayerPath() {
return parent !is null ? parent.getLayerPath() ~ "/" ~ name : "/" ~ name;
}
/**
Gets the amount of layers
*/
int count() {
int c = 1;
foreach(child; children) {
c += child.count;
}
return c;
}
}
IncPSDLayer[] incPSDBuildLayerLayout(PSD document) {
IncPSDLayer[] outLayers;
IncPSDLayer[] groupStack;
int index = 0;
foreach_reverse(layer; document.layers) {
index--;
if (layer.name == "</Layer set>" || layer.name == "</Layer group>") {
if (groupStack.length == 1) {
outLayers ~= groupStack[$-1];
groupStack.length--;
continue;
} else if (groupStack.length > 1) {
groupStack[$-2].children ~= groupStack[$-1];
groupStack.length--;
continue;
}
// uh, this should not happen?
throw new Exception("Unexpected closing layer group");
}
IncPSDLayer curLayer = new IncPSDLayer(
layer,
!layer.type == LayerType.Any,
groupStack.length > 0 ? groupStack[$-1] : null,
index
);
// Add output layers in
if (curLayer.isLayerGroup) groupStack ~= curLayer;
else if (groupStack.length > 0) {
groupStack[$-1].children ~= curLayer;
} else {
outLayers ~= curLayer;
}
}
return outLayers;
}
struct IncPSDImportSettings {
bool keepStructure = false;
}
/**
Imports a PSD file.
*/
void incImportPSD(string file, IncPSDImportSettings settings = IncPSDImportSettings.init) {
incNewProject();
// TODO: Split this up to a seperate file and make it cleaner
try {
import psd : PSD, Layer, LayerType, LayerFlags, parseDocument, BlendingMode;
PSD doc = parseDocument(file);
IncPSDLayer[] layers = incPSDBuildLayerLayout(doc);
vec2i docCenter = vec2i(doc.width/2, doc.height/2);
Puppet puppet = new ExPuppet();
void recurseAdd(Node n, IncPSDLayer layer) {
Node child;
if (layer.isLayerGroup) {
if (layer.psdLayerRef.blendModeKey == BlendingMode.PassThrough || layer.psdLayerRef.blendModeKey == BlendingMode.Normal) {
if (settings.keepStructure) child = new Node(cast(Node)null);
} else {
child = new Composite(null);
(cast(Composite)child).blendingMode = layer.blendMode;
}
} else {
layer.psdLayerRef.extractLayerImage();
inTexPremultiply(layer.psdLayerRef.data);
auto tex = new Texture(layer.psdLayerRef.data, layer.psdLayerRef.width, layer.psdLayerRef.height);
ExPart part = incCreateExPart(tex, null, layer.name);
part.layerPath = layer.getLayerPath();
auto layerSize = cast(int[2])layer.psdLayerRef.size();
vec2i layerPosition = vec2i(
layer.psdLayerRef.left,
layer.psdLayerRef.top
);
// TODO: more intelligent placement
part.localTransform.translation = vec3(
(layerPosition.x+(layerSize[0]/2))-docCenter.x,
(layerPosition.y+(layerSize[1]/2))-docCenter.y,
0
);
part.enabled = (layer.psdLayerRef.flags & LayerFlags.Visible) == 0;
part.opacity = (cast(float)layer.psdLayerRef.opacity)/255;
part.blendingMode = layer.blendMode;
child = part;
}
if (child) {
child.name = layer.name;
child.zSort = -(cast(float)layer.index);
child.reparent(n, 0);
}
// Add children
foreach(sublayer; layer.children) {
if (settings.keepStructure) {
// Normal adding
recurseAdd(child, sublayer);
} else {
if (auto composite = cast(Composite)child) {
// Composite child iteration
recurseAdd(composite, sublayer);
} else {
// Non-composite child iteration
recurseAdd(n, sublayer);
}
}
}
}
foreach(layer; layers) {
recurseAdd(puppet.root, layer);
}
puppet.populateTextureSlots();
incActiveProject().puppet = puppet;
incFocusCamera(incActivePuppet().root);
incSetStatus(_("%s was imported...".format(file)));
} catch (Exception ex) {
incSetStatus(_("Import failed..."));
incDialog(__("Error"), _("An error occured during PSD import:\n%s").format(ex.msg));
}
incFreeMemory();
}
|
D
|
# FIXED
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/Common/Minimal/EventGroupsDemo.c
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/FreeRTOS.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/stddef.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/stdint.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/sys/stdint.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/sys/cdefs.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/sys/_types.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/machine/_types.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/machine/_stdint.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/sys/_stdint.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/FreeRTOSConfig.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/driverlib.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/adc14.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/ccs_base/arm/include/msp.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/ccs_base/arm/include/msp432p401r.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/ccs_base/arm/include/msp_compatibility.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/ccs_base/arm/include/msp432p401r_classic.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/ccs_base/arm/include/CMSIS/core_cm4.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/ccs_base/arm/include/CMSIS/cmsis_compiler.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/ccs_base/arm/include/CMSIS/cmsis_ccs.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/ccs_base/arm/include/system_msp432p401r.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/stdbool.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/aes256.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/comp_e.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/cpu.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/crc32.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/cs.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/dma.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/eusci.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/flash.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/fpu.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/gpio.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/i2c.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/interrupt.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/mpu.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/pcm.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/pmap.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/pss.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/ref_a.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/reset.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/rom.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/rom_map.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/rtc_c.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/spi.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/sysctl.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/systick.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/timer32.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/timer_a.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/uart.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/wdt_a.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/projdefs.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/portable.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/deprecated_definitions.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/portable/CCS/ARM_CM4F/portmacro.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/mpu_wrappers.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/task.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/list.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/event_groups.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/timers.h
Full_Demo/Standard_Demo_Tasks/EventGroupsDemo.obj: C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/Common/include/EventGroupsDemo.h
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/Common/Minimal/EventGroupsDemo.c:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/FreeRTOS.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/stddef.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/stdint.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/sys/stdint.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/sys/cdefs.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/sys/_types.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/machine/_types.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/machine/_stdint.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/sys/_stdint.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/FreeRTOSConfig.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/driverlib.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/adc14.h:
C:/ti/ccsv8/ccs_base/arm/include/msp.h:
C:/ti/ccsv8/ccs_base/arm/include/msp432p401r.h:
C:/ti/ccsv8/ccs_base/arm/include/msp_compatibility.h:
C:/ti/ccsv8/ccs_base/arm/include/msp432p401r_classic.h:
C:/ti/ccsv8/ccs_base/arm/include/CMSIS/core_cm4.h:
C:/ti/ccsv8/ccs_base/arm/include/CMSIS/cmsis_compiler.h:
C:/ti/ccsv8/ccs_base/arm/include/CMSIS/cmsis_ccs.h:
C:/ti/ccsv8/ccs_base/arm/include/system_msp432p401r.h:
C:/ti/ccsv8/tools/compiler/ti-cgt-arm_18.1.2.LTS/include/stdbool.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/aes256.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/comp_e.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/cpu.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/crc32.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/cs.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/dma.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/eusci.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/flash.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/fpu.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/gpio.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/i2c.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/interrupt.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/mpu.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/pcm.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/pmap.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/pss.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/ref_a.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/reset.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/rom.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/rom_map.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/rtc_c.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/spi.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/sysctl.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/systick.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/timer32.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/timer_a.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/uart.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/wdt_a.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/projdefs.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/portable.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/deprecated_definitions.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/portable/CCS/ARM_CM4F/portmacro.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/mpu_wrappers.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/task.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/list.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/event_groups.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Source/include/timers.h:
C:/Users/student/Desktop/FreeRTOSv10.1.1/FreeRTOS/Demo/Common/include/EventGroupsDemo.h:
|
D
|
/*******************************************************************************
Base class for Asynchronously/Selector managed DLS bulk get requests
(GetAll, GetRange, GetAllKeys)
The bulk DLS commands all return compressed batches of values. This base
class implements the functionality to receive these batches and to extract
the records contained with them.
All bulk requests also have the facility for being suspended / resumed by
the user of the DlsClient.
Copyright:
Copyright (c) 2011-2017 dunnhumby Germany GmbH. All rights reserved.
License:
Boost Software License Version 1.0. See LICENSE.txt for details.
*******************************************************************************/
module dlsproto.client.legacy.internal.request.model.IBulkGetRequest;
/*******************************************************************************
Imports
*******************************************************************************/
import ocean.meta.types.Qualifiers;
import swarm.Const : NodeItem;
import swarm.common.request.helper.LoopCeder;
import swarm.client.request.model.IStreamInfo;
import swarm.client.request.helper.RequestSuspender;
import dlsproto.client.legacy.internal.request.model.IChannelRequest;
import ocean.io.select.client.FiberSelectEvent;
import ocean.io.compress.lzo.LzoChunkCompressor;
/*******************************************************************************
IBulkGetRequest abstract base class
*******************************************************************************/
abstract private class IBulkGetRequest : IChannelRequest, IStreamInfo
{
/***************************************************************************
Total bytes handled by this request.
***************************************************************************/
private size_t bytes_handled_;
/***************************************************************************
Constructor.
Note: the same FiberSelectEvent is used for both user-requested
suspension of the bulk request, and for ceding of the request to allow
other select clients to be handled. This is perfectly fine, as the fiber
is strictly sequential.
Params:
reader = fiber select reader instance to use for read requests
writer = fiber select writer instance to use for write requests
resources = shared resources which might be required by the request
***************************************************************************/
public this ( FiberSelectReader reader, FiberSelectWriter writer,
IDlsRequestResources resources )
{
super(reader, writer, resources);
}
/***************************************************************************
Returns:
the number of bytes sent/received by the stream (we currently assume
that a stream request is either sending or receiving)
***************************************************************************/
override public size_t bytes_handled ( )
{
return this.bytes_handled_;
}
/***************************************************************************
Returns:
the nodeitem this producer is associated with
***************************************************************************/
override public NodeItem nodeitem ( )
{
return NodeItem(this.resources.conn_pool_info.address,
this.resources.conn_pool_info.port);
}
/***************************************************************************
Handles a request once the request data has been sent and a valid status
has been received from the node.
Note: the reader cedes after processing every batch, in order to avoid
the odd situation where multiple bulk requests are running at the same
time, and, due to the order in which epoll handles the file decriptors,
one of the requests may receive far more processing time than the
others.
***************************************************************************/
final override protected void handle__ ( )
{
this.resources.request_suspender.start();
// Pass suspendable interface to user.
if ( this.params.suspend_register !is null )
{
this.params.suspend_register(this.params.context,
this.resources.request_suspender);
}
// Pass stream info interface to user.
if ( this.params.stream_info_register !is null )
{
this.params.stream_info_register(this.params.context, this);
}
bool received_batch;
do
{
received_batch = this.readBatch();
auto suspended = this.resources.request_suspender.handleSuspension();
if ( !suspended && received_batch )
{
this.resources.loop_ceder.handleCeding();
}
}
while ( received_batch ); // end upon receiving ""
}
/***************************************************************************
Reads the next batch of records from the node, and calls the
processBatch() method if the received batch is of non-0 length. (A batch
of 0 length indicates end of stream.)
Returns:
true if a batch was received, false if "" was received (indicating
end of stream)
***************************************************************************/
private bool readBatch ( )
{
this.reader.readArray(*this.resources.batch_buffer);
if ( this.resources.batch_buffer.length )
{
this.bytes_handled_ += this.resources.batch_buffer.length;
this.processBatch(*this.resources.batch_buffer);
return true;
}
return false;
}
/***************************************************************************
Processes a received batch of records.
Params:
batch = batch received (still compressed)
***************************************************************************/
abstract protected void processBatch ( cstring batch );
}
/*******************************************************************************
Base class for bulk requests which handle paired values.
*******************************************************************************/
abstract public class IBulkGetPairsRequest : IBulkGetRequest
{
/***************************************************************************
Constructor.
Params:
reader = fiber select reader instance to use for read requests
writer = fiber select writer instance to use for write requests
resources = shared resources which might be required by the request
***************************************************************************/
public this ( FiberSelectReader reader, FiberSelectWriter writer,
IDlsRequestResources resources )
{
super(reader, writer, resources);
}
/***************************************************************************
Processes a received batch of records.
Params:
batch = batch received (still compressed)
***************************************************************************/
final override protected void processBatch ( cstring batch )
{
void receivePair ( cstring value1, cstring value2 )
{
this.processPair(value1, value2);
this.resources.request_suspender.handleSuspension();
}
this.resources.record_batch.decompress(cast(ubyte[])batch);
foreach ( key, value; this.resources.record_batch )
{
receivePair(key, value);
}
}
/***************************************************************************
Processes a received pair (typically a key/value pair).
Params:
value1 = 1st value extracted from batch
value2 = 2nd value extracted from batch
***************************************************************************/
abstract protected void processPair ( cstring value1, cstring value2 );
}
/*******************************************************************************
Base class for bulk requests which handle single values.
*******************************************************************************/
abstract public class IBulkGetValuesRequest : IBulkGetRequest
{
/***************************************************************************
Constructor.
Params:
reader = fiber select reader instance to use for read requests
writer = fiber select writer instance to use for write requests
resources = shared resources which might be required by the request
***************************************************************************/
public this ( FiberSelectReader reader, FiberSelectWriter writer,
IDlsRequestResources resources )
{
super(reader, writer, resources);
}
/***************************************************************************
Processes a received batch of records.
Params:
batch = batch received (still compressed)
***************************************************************************/
final override protected void processBatch ( cstring batch )
{
void receiveValue ( cstring value )
{
this.processValue(value);
this.resources.request_suspender.handleSuspension();
}
this.resources.record_batch.decompress(cast(ubyte[])batch);
foreach ( value; this.resources.record_batch )
{
receiveValue(value);
}
}
/***************************************************************************
Processes a received value.
Params:
value = value extracted from batch
***************************************************************************/
abstract protected void processValue ( cstring value );
}
|
D
|
import std.algorithm.comparison;
import std.stdio: write, writeln, writef, writefln , fscanf, readln,readf;
import std.exception : assertThrown;
import std.array;
import std.string;
import std.path;
import std.uni;
import std.format;
import std.file;
void man(string[] aux,float quantidade){
if(equal(aux[1],"mkdir")){
"./manual/".chdir;
cat(aux);
"../".chdir;
}
}
void mkdir(string[] aux,float quantidade){
import std.file: mkdir,rmdir;
for(int i = 1;i < quantidade;i++){
if(aux[i].exists == true){
write("Diretorio ja existe,deseja substituir?(s ou n)\n");
string decisao = readln();
if(equal(decisao,"s\x0a") == true || equal(decisao,"S\x0a") == true){
write("substituição funciona");
aux[i].rmdirRecurse;
aux[i].mkdirRecurse;
}else if((equal(decisao,"n\x0a") == true || equal(decisao,"N\x0a") == true)){
write("Diretorio foi mantido\n");
}
else{
write("Comando inválido\n");
}
}else{
write("criar");
aux[i].mkdirRecurse;
}
}
}
void rmdir(string[] aux,float quantidade){
for(int i = 1;i < quantidade;i++){
aux[i].rmdirRecurse;
}
}
void mkfile(string[] aux,float quantidade){
for(int i = 1;i < quantidade - 1;i++){
if(aux[i].exists == true){
write("Arquivo ja existe,deseja substituir?(s ou n)\n");
string decisao = readln();
if(equal(decisao,"s\x0a") == true || equal(decisao,"S\x0a") == true){
remove(aux[i]);
append(aux[i],aux[i+1]); //Caminho, dados do arquivo
}
else if(equal(decisao,"n\x0a") == true || equal(decisao,"N\x0a") == true){
append(aux[i],aux[i+1]); //Caminho, dados do arquivo
}else{
write("Comando inválido\n");
}
}else{
append(aux[i],aux[i+1]);
write("Arquivo foi criado\n");
}
}
}
void rmfile(string[] aux,float quantidade){
for(int i = 1;i < quantidade;i++)
remove(aux[i]);
}
void cat(string[] aux){
write(readText(aux[1]),"\n");
}
void cpy(string[] aux,float quantidade){
// string caminho = getcwd();
// aux[2].chdir;
// string caminho_arquivo = join([aux[2],aux[1]]);
// write(caminho_arquivo);
for(int i = 1; i < quantidade - 1;i++){
//copiar arquivos
if(aux[i].isFile == true){
if(aux[i+1].exists == true){
write("Arquivo ja existe,deseja substituir?(s ou n)\n");
string decisao = readln();
if(equal(decisao,"s\x0a") == true || equal(decisao,"S\x0a") == true){
write("substituiu");
remove(aux[i+1]);
copy(aux[i],aux[i+1]); //nome arquivo, destino
}
else if(decisao == "n\x0a")
write("Arquivo foi mantido");
}else{
append(aux[i+1],null);
copy(aux[i],aux[i+1]);
}
}
//copia diretórios = encontrar função
else if(aux[i].isDir == true){
}
}
}
void main(){
string parametros;
// int quantidade_argumentos(string parametros){
// int quantidade = 0;
// for(int i = 0;i < count(parametros);i++){
// if(parametros[i] == ' ')
// quantidade += 1;
// }
// write(quantidade);
// return quantidade;
// }
while(1){
write(">");
parametros = readln();
string[] aux = parametros.split;
float quantidade = count(aux);
if(equal(aux[0],"mkdir") == true){
mkdir(aux,quantidade);
}
else if(equal(aux[0],"rmdir") == true){
rmdir(aux,quantidade);
}
else if(equal(aux[0],"mkfile") == true){
mkfile(aux,quantidade);
}
else if(equal(aux[0],"rmfile") == true){
rmfile(aux,quantidade);
}
else if(equal(aux[0],"copy") == true){
cpy(aux,quantidade);
}
else if(equal(aux[0],"cat") == true){
cat(aux);
}
else if(equal(aux[0],"clear") == true){
write("\033[H\033[2J");
}
else if(equal(aux[0],"cd") == true){
aux[1].chdir;
}
// else if(equal(aux[0],"move"){
// }
// else if(equal(aux[0],"ls") == 0){
// }
else if(equal(aux[0],"exit") == true){
return;
}
else if(equal(aux[0],"man")== true){
man(aux,quantidade);
}
else{
write("Comando não encontrado\n");
}
}
}
|
D
|
import core.stdc.stdio: printf;
int main() {
int i = 0;
for (int z = 1; ; ++z)
for (int x = 1; x <= z; ++x)
for (int y = x; y <= z; ++y)
if (x*x + y*y == z*z) {
printf("(%i, %i, %i)\n", x, y, z);
if (++i == 1000)
goto done;
}
done:
return 0;
}
|
D
|
import std.stdio;
import std.string : format;
export int sayHello1 (string str)
{
writeln ("Hello %s from library 1.".format (str));
return 4;
}
version (Windows)
{
import core.sys.windows.dll;
mixin SimpleDllMain;
}
|
D
|
import vibe.d; //https://vibed.org/docs
import std.stdio;
import std.json;
import deimos.sodium;
import core.stdc.stdlib;
import core.thread;
import std.digest.sha;
import std.string;
import tinyredis; //https://adilbaig.github.io/Tiny-Redis/
__gshared Redis conn = void;
__gshared ulong block = 0;
__gshared bool started = false;
__gshared bool running = true;
class WebService
{
private SessionVar!(string, "username")
username_;
void index(HTTPServerResponse res) {
auto contents = q{<html> <head> <title>http fake mining server</title> </head> <body> </body> </html>};
res.writeBody(contents,"text/html; charset=UTF-8");
}
// curl 127.0.0.1:2826/blocks
@path("/blocks")
void getBlocks(HTTPServerRequest req, HTTPServerResponse res) {
auto contents = q{};
res.writeBody(contents, "text/html; charset=UTF-8");
writeln("GET at /blocks ", block );
// GET all blocks
auto keys_resp = conn.send("KEYS *");
string keys_str = keys_resp.toString;
string keys = strip(keys_str, "[", "]");
auto a = split(keys, ',');
writeln("[");
for (int n = 0; n < a.length; ++n) {
auto k = strip (a[n], " ", "'");
string rq = format!"%s %s"("GET ", k);
auto blk = conn.send(rq);
auto s = blk.toString;
writeln(s);
if (n < a.length-1 ) writeln(",");
}
writeln("]");
}
//curl -X POST -H "Content-Type: application/json" http://127.0.0.1:2826/transaction --data-raw '{"outputs":[{"key":"0xee0edfbe581fa81481e858f75fda3414cd3a655ff17ec987af775e666412bf1f","amount":4000000},{"key":"0xf4012c71c9be512613c4820a3f6b1e55f8515a441913cf9cb06ccc3076ccbebd","amount":96000000}],"inputs":[{"hash":"0xc2c5be0cb790c8d85b9096c409dd439aebaa9af6df2e476d23f8d6f624e87f95","sig":"0x0ec47ca9f8d0101a8c3cabf6ba1fa73aa123294dcf0f5578addc5f01463f7dfc1bd3719636a77f3e4f95b07f1b77a2a58df046c6aa66e4bec91d908a66c3f608","index":0},{"hash":"0xc2c5be0cb790c8d85b9096c409dd439aebaa9af6df2e476d23f8d6f624e87f95","sig":"0x096a7ff44ee2a1d88674b2ba5583a00fd47ccb80ebc2761b40361e4319bc7da9080304ea87d46c5401d6b92f4304fb176f1f5e0dce9872024297659be7a83774","index":1}]}'
@path("/transaction")
void postTransaction(HTTPServerRequest req, HTTPServerResponse res) {
auto contents = q{};
res.writeBody(contents,"text/html; charset=UTF-8");
auto s = req.bodyReader.readAllUTF8();
//writeln("POST at /transaction ", s);
JSONValue j = parseJSON(s);
auto o = j["outputs"].get!(JSONValue[]);
for (int n = 0; n < o.length; ++n) {
auto key = o[n]["key"].str;
auto amo = o[n]["amount"].get!int;
writeln("key = " , key );
writeln("amount = " , amo );
}
auto i = j["inputs"].get!(JSONValue[]);
for (int n = 0; n < i.length; ++n) {
auto hsh = i[n]["hash"].str;
auto ind = i[n]["index"].get!int;
writeln("hash = " , hsh );
writeln("index = " , ind );
}
if (!started) {
started = true;
auto composed = new Thread(&threadMining).start();
writeln("started = " , started );
}
}
}
void threadMining()
{
string prev = to!string("0x0000000000000000000000000000000000000000000000000000000000000000");
while (running)
{
if (started) {
Thread.sleep( dur!("msecs")( 1000 ) );
//writeln("more one block ", block);
ubyte[crypto_box_SECRETKEYBYTES] key;
ubyte[crypto_box_PUBLICKEYBYTES] pkey;
ubyte[crypto_box_MACBYTES] mac;
randombytes_buf(key.ptr, key.length);
randombytes_buf(mac.ptr, mac.length);
string trans = "{}";
string jblock = format!"\'{\n \"previous\" : %s,\n \"nonce\" : 0x%s,\n \"height\" : %d,\n \"transaction\" : %s \n}\'"(prev, toHexString(mac), block, trans);
//[ { "previous": "0x0000000000000000000000000000000000000000000000000000000000000000", "nonce": 524632, "height": 0 } ]
writeln(jblock);
string dat = format!"%s %s%d %s"("SET", "block",block, jblock);
conn.send(dat);
ubyte [] MESSAGE;
MESSAGE.length = jblock.length;
MESSAGE = cast( ubyte[]) jblock;
ubyte[32] hash256 = sha256Of(MESSAGE);
string curr = format!"%s%s"("0x",toHexString(hash256));
prev = curr;
block++;
/*
//encrypt i.e. transaction
ubyte [] ciphertext;
ciphertext. length = MESSAGE.length + crypto_box_MACBYTES;
crypto_box_easy (ciphertext.ptr, MESSAGE.ptr, MESSAGE.length, mac.ptr, key.ptr, key.ptr);
//writeln("ciphertext :" , ciphertext);
// decrypt i.e transaction
ubyte [] msg;
msg.length = jblock.length;
//crypto_box_open_easy(decrypted, ciphertext, nonce, alice_publickey, bob_secretkey));
crypto_box_open_easy (msg.ptr, ciphertext.ptr, ciphertext.length, mac.ptr, key.ptr, key.ptr);
string omsg = cast(string)msg;
//writeln("message :" , omsg);
*/
}
else {
Thread.sleep(dur!("msecs")(1000));
}
}
}
extern(C) void signal(int sig, void function(int));
extern(C) void exit(int exit_val);
extern(C) void handle(int sig) {
writeln("Control-C was pressed..aborting program....goodbye...");
exit(EXIT_SUCCESS);
}
void main() {
if (sodium_init() < 0) {
writeln("sodium init error");
exit(EXIT_FAILURE);
}
enum SIGINT = 2;
signal(SIGINT,&handle);
conn = new Redis("localhost", 6379);
conn.send("FLUSHALL");
auto router = new URLRouter;
router.registerWebInterface(new WebService);
auto settings = new HTTPServerSettings;
settings.sessionStore = new MemorySessionStore;
settings.port = 2826;
listenHTTP(settings, router);
runApplication();
scope (exit){
writeln("Cleanup");
running = false;
}
}
|
D
|
# FIXED
Drivers/NV/crc.obj: C:/ti/simplelink_cc13x2_26x2_sdk_3_40_00_02/source/ti/common/nv/crc.c
Drivers/NV/crc.obj: C:/ti/simplelink_cc13x2_26x2_sdk_3_40_00_02/source/ti/common/nv/crc.h
Drivers/NV/crc.obj: C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/stdlib.h
Drivers/NV/crc.obj: C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/_ti_config.h
Drivers/NV/crc.obj: C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/linkage.h
Drivers/NV/crc.obj: C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/sys/cdefs.h
Drivers/NV/crc.obj: C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/stdint.h
Drivers/NV/crc.obj: C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/_stdint40.h
Drivers/NV/crc.obj: C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/sys/stdint.h
Drivers/NV/crc.obj: C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/sys/_types.h
Drivers/NV/crc.obj: C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/machine/_types.h
Drivers/NV/crc.obj: C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/machine/_stdint.h
Drivers/NV/crc.obj: C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/sys/_stdint.h
Drivers/NV/crc.obj: C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/stdlib.h
C:/ti/simplelink_cc13x2_26x2_sdk_3_40_00_02/source/ti/common/nv/crc.c:
C:/ti/simplelink_cc13x2_26x2_sdk_3_40_00_02/source/ti/common/nv/crc.h:
C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/stdlib.h:
C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/_ti_config.h:
C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/linkage.h:
C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/sys/cdefs.h:
C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/stdint.h:
C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/_stdint40.h:
C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/sys/stdint.h:
C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/sys/_types.h:
C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/machine/_types.h:
C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/machine/_stdint.h:
C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/sys/_stdint.h:
C:/ti/ccs920/ccs/tools/compiler/ti-cgt-arm_18.12.3.LTS/include/stdlib.h:
|
D
|
// Written in the D programming language.
/**
This is a submodule of $(MREF std, algorithm).
It contains generic algorithms that implement set operations.
$(BOOKTABLE Cheat Sheet,
$(TR $(TH Function Name) $(TH Description))
$(T2 cartesianProduct,
Computes Cartesian product of two ranges.)
$(T2 largestPartialIntersection,
Copies out the values that occur most frequently in a range of ranges.)
$(T2 largestPartialIntersectionWeighted,
Copies out the values that occur most frequently (multiplied by
per-value weights) in a range of ranges.)
$(T2 nWayUnion,
Computes the union of a set of sets implemented as a range of sorted
ranges.)
$(T2 setDifference,
Lazily computes the set difference of two or more sorted ranges.)
$(T2 setIntersection,
Lazily computes the intersection of two or more sorted ranges.)
$(T2 setSymmetricDifference,
Lazily computes the symmetric set difference of two or more sorted
ranges.)
)
Copyright: Andrei Alexandrescu 2008-.
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP erdani.com, Andrei Alexandrescu)
Source: $(PHOBOSSRC std/algorithm/_setops.d)
Macros:
T2=$(TR $(TDNW $(LREF $1)) $(TD $+))
*/
module std.algorithm.setops;
import std.range.primitives;
// FIXME
import std.functional; // : unaryFun, binaryFun;
import std.traits;
// FIXME
import std.meta; // : AliasSeq, staticMap, allSatisfy, anySatisfy;
import std.algorithm.sorting; // : Merge;
import std.typecons : No;
// cartesianProduct
/**
Lazily computes the Cartesian product of two or more ranges. The product is a
_range of tuples of elements from each respective range.
The conditions for the two-range case are as follows:
If both ranges are finite, then one must be (at least) a forward range and the
other an input range.
If one _range is infinite and the other finite, then the finite _range must
be a forward _range, and the infinite range can be an input _range.
If both ranges are infinite, then both must be forward ranges.
When there are more than two ranges, the above conditions apply to each
adjacent pair of ranges.
Params:
range1 = The first range
range2 = The second range
ranges = Two or more non-infinite forward ranges
otherRanges = Zero or more non-infinite forward ranges
Returns:
A forward range of $(REF Tuple, std,typecons) representing elements of the
cartesian product of the given ranges.
*/
auto cartesianProduct(R1, R2)(R1 range1, R2 range2)
if (!allSatisfy!(isForwardRange, R1, R2) ||
anySatisfy!(isInfinite, R1, R2))
{
import std.algorithm.iteration : map, joiner;
static if (isInfinite!R1 && isInfinite!R2)
{
static if (isForwardRange!R1 && isForwardRange!R2)
{
import std.range : zip, repeat, take, chain, sequence;
// This algorithm traverses the cartesian product by alternately
// covering the right and bottom edges of an increasing square area
// over the infinite table of combinations. This schedule allows us
// to require only forward ranges.
return zip(sequence!"n"(cast(size_t)0), range1.save, range2.save,
repeat(range1), repeat(range2))
.map!(function(a) => chain(
zip(repeat(a[1]), take(a[4].save, a[0])),
zip(take(a[3].save, a[0]+1), repeat(a[2]))
))()
.joiner();
}
else static assert(0, "cartesianProduct of infinite ranges requires "~
"forward ranges");
}
else static if (isInputRange!R1 && isForwardRange!R2 && !isInfinite!R2)
{
import std.range : zip, repeat;
return joiner(map!((ElementType!R1 a) => zip(repeat(a), range2.save))
(range1));
}
else static if (isInputRange!R2 && isForwardRange!R1 && !isInfinite!R1)
{
import std.range : zip, repeat;
return joiner(map!((ElementType!R2 a) => zip(range1.save, repeat(a)))
(range2));
}
else static assert(0, "cartesianProduct involving finite ranges must "~
"have at least one finite forward range");
}
///
@safe unittest
{
import std.algorithm.searching : canFind;
import std.range;
import std.typecons : tuple;
auto N = sequence!"n"(0); // the range of natural numbers
auto N2 = cartesianProduct(N, N); // the range of all pairs of natural numbers
// Various arbitrary number pairs can be found in the range in finite time.
assert(canFind(N2, tuple(0, 0)));
assert(canFind(N2, tuple(123, 321)));
assert(canFind(N2, tuple(11, 35)));
assert(canFind(N2, tuple(279, 172)));
}
///
@safe unittest
{
import std.algorithm.searching : canFind;
import std.typecons : tuple;
auto B = [ 1, 2, 3 ];
auto C = [ 4, 5, 6 ];
auto BC = cartesianProduct(B, C);
foreach (n; [[1, 4], [2, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6],
[2, 6], [3, 6]])
{
assert(canFind(BC, tuple(n[0], n[1])));
}
}
@safe unittest
{
// Test cartesian product of two infinite ranges
import std.algorithm.searching : canFind;
import std.range;
import std.typecons : tuple;
auto Even = sequence!"2*n"(0);
auto Odd = sequence!"2*n+1"(0);
auto EvenOdd = cartesianProduct(Even, Odd);
foreach (pair; [[0, 1], [2, 1], [0, 3], [2, 3], [4, 1], [4, 3], [0, 5],
[2, 5], [4, 5], [6, 1], [6, 3], [6, 5]])
{
assert(canFind(EvenOdd, tuple(pair[0], pair[1])));
}
// This should terminate in finite time
assert(canFind(EvenOdd, tuple(124, 73)));
assert(canFind(EvenOdd, tuple(0, 97)));
assert(canFind(EvenOdd, tuple(42, 1)));
}
@safe unittest
{
// Test cartesian product of an infinite input range and a finite forward
// range.
import std.algorithm.searching : canFind;
import std.range;
import std.typecons : tuple;
auto N = sequence!"n"(0);
auto M = [100, 200, 300];
auto NM = cartesianProduct(N,M);
foreach (pair; [[0, 100], [0, 200], [0, 300], [1, 100], [1, 200], [1, 300],
[2, 100], [2, 200], [2, 300], [3, 100], [3, 200],
[3, 300]])
{
assert(canFind(NM, tuple(pair[0], pair[1])));
}
// We can't solve the halting problem, so we can only check a finite
// initial segment here.
assert(!canFind(NM.take(100), tuple(100, 0)));
assert(!canFind(NM.take(100), tuple(1, 1)));
assert(!canFind(NM.take(100), tuple(100, 200)));
auto MN = cartesianProduct(M,N);
foreach (pair; [[100, 0], [200, 0], [300, 0], [100, 1], [200, 1], [300, 1],
[100, 2], [200, 2], [300, 2], [100, 3], [200, 3],
[300, 3]])
{
assert(canFind(MN, tuple(pair[0], pair[1])));
}
// We can't solve the halting problem, so we can only check a finite
// initial segment here.
assert(!canFind(MN.take(100), tuple(0, 100)));
assert(!canFind(MN.take(100), tuple(0, 1)));
assert(!canFind(MN.take(100), tuple(100, 200)));
}
@safe unittest
{
import std.algorithm.searching : canFind;
import std.typecons : tuple;
// Test cartesian product of two finite ranges.
auto X = [1, 2, 3];
auto Y = [4, 5, 6];
auto XY = cartesianProduct(X, Y);
auto Expected = [[1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4],
[3, 5], [3, 6]];
// Verify Expected ⊆ XY
foreach (pair; Expected)
{
assert(canFind(XY, tuple(pair[0], pair[1])));
}
// Verify XY ⊆ Expected
foreach (pair; XY)
{
assert(canFind(Expected, [pair[0], pair[1]]));
}
// And therefore, by set comprehension, XY == Expected
}
@safe unittest
{
import std.algorithm.searching : canFind;
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.typecons : tuple;
import std.range;
auto N = sequence!"n"(0);
// To force the template to fall to the second case, we wrap N in a struct
// that doesn't allow bidirectional access.
struct FwdRangeWrapper(R)
{
R impl;
// Input range API
@property auto front() { return impl.front; }
void popFront() { impl.popFront(); }
static if (isInfinite!R)
enum empty = false;
else
@property bool empty() { return impl.empty; }
// Forward range API
@property auto save() { return typeof(this)(impl.save); }
}
auto fwdWrap(R)(R range) { return FwdRangeWrapper!R(range); }
// General test: two infinite bidirectional ranges
auto N2 = cartesianProduct(N, N);
assert(canFind(N2, tuple(0, 0)));
assert(canFind(N2, tuple(123, 321)));
assert(canFind(N2, tuple(11, 35)));
assert(canFind(N2, tuple(279, 172)));
// Test first case: forward range with bidirectional range
auto fwdN = fwdWrap(N);
auto N2_a = cartesianProduct(fwdN, N);
assert(canFind(N2_a, tuple(0, 0)));
assert(canFind(N2_a, tuple(123, 321)));
assert(canFind(N2_a, tuple(11, 35)));
assert(canFind(N2_a, tuple(279, 172)));
// Test second case: bidirectional range with forward range
auto N2_b = cartesianProduct(N, fwdN);
assert(canFind(N2_b, tuple(0, 0)));
assert(canFind(N2_b, tuple(123, 321)));
assert(canFind(N2_b, tuple(11, 35)));
assert(canFind(N2_b, tuple(279, 172)));
// Test third case: finite forward range with (infinite) input range
static struct InpRangeWrapper(R)
{
R impl;
// Input range API
@property auto front() { return impl.front; }
void popFront() { impl.popFront(); }
static if (isInfinite!R)
enum empty = false;
else
@property bool empty() { return impl.empty; }
}
auto inpWrap(R)(R r) { return InpRangeWrapper!R(r); }
auto inpN = inpWrap(N);
auto B = [ 1, 2, 3 ];
auto fwdB = fwdWrap(B);
auto BN = cartesianProduct(fwdB, inpN);
assert(equal(map!"[a[0],a[1]]"(BN.take(10)), [[1, 0], [2, 0], [3, 0],
[1, 1], [2, 1], [3, 1], [1, 2], [2, 2], [3, 2], [1, 3]]));
// Test fourth case: (infinite) input range with finite forward range
auto NB = cartesianProduct(inpN, fwdB);
assert(equal(map!"[a[0],a[1]]"(NB.take(10)), [[0, 1], [0, 2], [0, 3],
[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1]]));
// General finite range case
auto C = [ 4, 5, 6 ];
auto BC = cartesianProduct(B, C);
foreach (n; [[1, 4], [2, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6],
[2, 6], [3, 6]])
{
assert(canFind(BC, tuple(n[0], n[1])));
}
}
// Issue 13091
pure nothrow @safe @nogc unittest
{
int[1] a = [1];
foreach (t; cartesianProduct(a[], a[])) {}
}
/// ditto
auto cartesianProduct(RR...)(RR ranges)
if (ranges.length >= 2 &&
allSatisfy!(isForwardRange, RR) &&
!anySatisfy!(isInfinite, RR))
{
// This overload uses a much less template-heavy implementation when
// all ranges are finite forward ranges, which is the most common use
// case, so that we don't run out of resources too quickly.
//
// For infinite ranges or non-forward ranges, we fall back to the old
// implementation which expands an exponential number of templates.
import std.typecons : tuple;
static struct Result
{
RR ranges;
RR current;
bool empty = true;
this(RR _ranges)
{
ranges = _ranges;
empty = false;
foreach (i, r; ranges)
{
current[i] = r.save;
if (current[i].empty)
empty = true;
}
}
@property auto front()
{
import std.algorithm.internal : algoFormat;
import std.range : iota;
return mixin(algoFormat("tuple(%(current[%d].front%|,%))",
iota(0, current.length)));
}
void popFront()
{
foreach_reverse (i, ref r; current)
{
r.popFront();
if (!r.empty) break;
static if (i==0)
empty = true;
else
r = ranges[i].save; // rollover
}
}
@property Result save()
{
Result copy = this;
foreach (i, r; ranges)
{
copy.ranges[i] = r.save;
copy.current[i] = current[i].save;
}
return copy;
}
}
static assert(isForwardRange!Result);
return Result(ranges);
}
@safe unittest
{
// Issue 10693: cartesian product of empty ranges should be empty.
int[] a, b, c, d, e;
auto cprod = cartesianProduct(a,b,c,d,e);
assert(cprod.empty);
foreach (_; cprod) {} // should not crash
// Test case where only one of the ranges is empty: the result should still
// be empty.
int[] p=[1], q=[];
auto cprod2 = cartesianProduct(p,p,p,q,p);
assert(cprod2.empty);
foreach (_; cprod2) {} // should not crash
}
@safe unittest
{
// .init value of cartesianProduct should be empty
auto cprod = cartesianProduct([0,0], [1,1], [2,2]);
assert(!cprod.empty);
assert(cprod.init.empty);
}
@safe unittest
{
// Issue 13393
assert(!cartesianProduct([0],[0],[0]).save.empty);
}
/// ditto
auto cartesianProduct(R1, R2, RR...)(R1 range1, R2 range2, RR otherRanges)
if (!allSatisfy!(isForwardRange, R1, R2, RR) ||
anySatisfy!(isInfinite, R1, R2, RR))
{
/* We implement the n-ary cartesian product by recursively invoking the
* binary cartesian product. To make the resulting range nicer, we denest
* one level of tuples so that a ternary cartesian product, for example,
* returns 3-element tuples instead of nested 2-element tuples.
*/
import std.algorithm.internal : algoFormat;
import std.algorithm.iteration : map;
import std.range : iota;
enum string denest = algoFormat("tuple(a[0], %(a[1][%d]%|,%))",
iota(0, otherRanges.length+1));
return map!denest(
cartesianProduct(range1, cartesianProduct(range2, otherRanges))
);
}
@safe unittest
{
import std.algorithm.searching : canFind;
import std.range;
import std.typecons : tuple, Tuple;
auto N = sequence!"n"(0);
auto N3 = cartesianProduct(N, N, N);
// Check that tuples are properly denested
assert(is(ElementType!(typeof(N3)) == Tuple!(size_t,size_t,size_t)));
assert(canFind(N3, tuple(0, 27, 7)));
assert(canFind(N3, tuple(50, 23, 71)));
assert(canFind(N3, tuple(9, 3, 0)));
}
@safe unittest
{
import std.algorithm.searching : canFind;
import std.range;
import std.typecons : tuple, Tuple;
auto N = sequence!"n"(0);
auto N4 = cartesianProduct(N, N, N, N);
// Check that tuples are properly denested
assert(is(ElementType!(typeof(N4)) == Tuple!(size_t,size_t,size_t,size_t)));
assert(canFind(N4, tuple(1, 2, 3, 4)));
assert(canFind(N4, tuple(4, 3, 2, 1)));
assert(canFind(N4, tuple(10, 31, 7, 12)));
}
// Issue 9878
///
@safe unittest
{
import std.algorithm.comparison : equal;
import std.typecons : tuple;
auto A = [ 1, 2, 3 ];
auto B = [ 'a', 'b', 'c' ];
auto C = [ "x", "y", "z" ];
auto ABC = cartesianProduct(A, B, C);
assert(ABC.equal([
tuple(1, 'a', "x"), tuple(1, 'a', "y"), tuple(1, 'a', "z"),
tuple(1, 'b', "x"), tuple(1, 'b', "y"), tuple(1, 'b', "z"),
tuple(1, 'c', "x"), tuple(1, 'c', "y"), tuple(1, 'c', "z"),
tuple(2, 'a', "x"), tuple(2, 'a', "y"), tuple(2, 'a', "z"),
tuple(2, 'b', "x"), tuple(2, 'b', "y"), tuple(2, 'b', "z"),
tuple(2, 'c', "x"), tuple(2, 'c', "y"), tuple(2, 'c', "z"),
tuple(3, 'a', "x"), tuple(3, 'a', "y"), tuple(3, 'a', "z"),
tuple(3, 'b', "x"), tuple(3, 'b', "y"), tuple(3, 'b', "z"),
tuple(3, 'c', "x"), tuple(3, 'c', "y"), tuple(3, 'c', "z")
]));
}
pure @safe nothrow @nogc unittest
{
import std.range.primitives : isForwardRange;
int[2] A = [1,2];
auto C = cartesianProduct(A[], A[], A[]);
assert(isForwardRange!(typeof(C)));
C.popFront();
auto front1 = C.front;
auto D = C.save;
C.popFront();
assert(D.front == front1);
}
// Issue 13935
unittest
{
import std.algorithm.iteration : map;
auto seq = [1, 2].map!(x => x);
foreach (pair; cartesianProduct(seq, seq)) {}
}
// largestPartialIntersection
/**
Given a range of sorted forward ranges $(D ror), copies to $(D tgt)
the elements that are common to most ranges, along with their number
of occurrences. All ranges in $(D ror) are assumed to be sorted by $(D
less). Only the most frequent $(D tgt.length) elements are returned.
Params:
less = The predicate the ranges are sorted by.
ror = A range of forward ranges sorted by `less`.
tgt = The target range to copy common elements to.
sorted = Whether the elements copied should be in sorted order.
The function $(D largestPartialIntersection) is useful for
e.g. searching an $(LUCKY inverted index) for the documents most
likely to contain some terms of interest. The complexity of the search
is $(BIGOH n * log(tgt.length)), where $(D n) is the sum of lengths of
all input ranges. This approach is faster than keeping an associative
array of the occurrences and then selecting its top items, and also
requires less memory ($(D largestPartialIntersection) builds its
result directly in $(D tgt) and requires no extra memory).
Warning: Because $(D largestPartialIntersection) does not allocate
extra memory, it will leave $(D ror) modified. Namely, $(D
largestPartialIntersection) assumes ownership of $(D ror) and
discretionarily swaps and advances elements of it. If you want $(D
ror) to preserve its contents after the call, you may want to pass a
duplicate to $(D largestPartialIntersection) (and perhaps cache the
duplicate in between calls).
*/
void largestPartialIntersection
(alias less = "a < b", RangeOfRanges, Range)
(RangeOfRanges ror, Range tgt, SortOutput sorted = No.sortOutput)
{
struct UnitWeights
{
static int opIndex(ElementType!(ElementType!RangeOfRanges)) { return 1; }
}
return largestPartialIntersectionWeighted!less(ror, tgt, UnitWeights(),
sorted);
}
///
unittest
{
import std.typecons : tuple, Tuple;
// Figure which number can be found in most arrays of the set of
// arrays below.
double[][] a =
[
[ 1, 4, 7, 8 ],
[ 1, 7 ],
[ 1, 7, 8],
[ 4 ],
[ 7 ],
];
auto b = new Tuple!(double, uint)[1];
// it will modify the input range, hence we need to create a duplicate
largestPartialIntersection(a.dup, b);
// First member is the item, second is the occurrence count
assert(b[0] == tuple(7.0, 4u));
// 7.0 occurs in 4 out of 5 inputs, more than any other number
// If more of the top-frequent numbers are needed, just create a larger
// tgt range
auto c = new Tuple!(double, uint)[2];
largestPartialIntersection(a, c);
assert(c[0] == tuple(1.0, 3u));
// 1.0 occurs in 3 inputs
}
import std.algorithm.sorting : SortOutput; // FIXME
// largestPartialIntersectionWeighted
/**
Similar to $(D largestPartialIntersection), but associates a weight
with each distinct element in the intersection.
Params:
less = The predicate the ranges are sorted by.
ror = A range of forward ranges sorted by `less`.
tgt = The target range to copy common elements to.
weights = An associative array mapping elements to weights.
sorted = Whether the elements copied should be in sorted order.
*/
void largestPartialIntersectionWeighted
(alias less = "a < b", RangeOfRanges, Range, WeightsAA)
(RangeOfRanges ror, Range tgt, WeightsAA weights, SortOutput sorted = No.sortOutput)
{
import std.algorithm.iteration : group;
import std.algorithm.sorting : topNCopy;
if (tgt.empty) return;
alias InfoType = ElementType!Range;
bool heapComp(InfoType a, InfoType b)
{
return weights[a[0]] * a[1] > weights[b[0]] * b[1];
}
topNCopy!heapComp(group(nWayUnion!less(ror)), tgt, sorted);
}
///
unittest
{
import std.typecons : tuple, Tuple;
// Figure which number can be found in most arrays of the set of
// arrays below, with specific per-element weights
double[][] a =
[
[ 1, 4, 7, 8 ],
[ 1, 7 ],
[ 1, 7, 8],
[ 4 ],
[ 7 ],
];
auto b = new Tuple!(double, uint)[1];
double[double] weights = [ 1:1.2, 4:2.3, 7:1.1, 8:1.1 ];
largestPartialIntersectionWeighted(a, b, weights);
// First member is the item, second is the occurrence count
assert(b[0] == tuple(4.0, 2u));
// 4.0 occurs 2 times -> 4.6 (2 * 2.3)
// 7.0 occurs 3 times -> 4.4 (3 * 1.1)
}
unittest
{
import std.conv : text;
import std.typecons : tuple, Tuple, Yes;
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
double[][] a =
[
[ 1, 4, 7, 8 ],
[ 1, 7 ],
[ 1, 7, 8],
[ 4 ],
[ 7 ],
];
auto b = new Tuple!(double, uint)[2];
largestPartialIntersection(a, b, Yes.sortOutput);
//sort(b);
//writeln(b);
assert(b == [ tuple(7.0, 4u), tuple(1.0, 3u) ][], text(b));
assert(a[0].empty);
}
unittest
{
import std.conv : text;
import std.typecons : tuple, Tuple, Yes;
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
string[][] a =
[
[ "1", "4", "7", "8" ],
[ "1", "7" ],
[ "1", "7", "8"],
[ "4" ],
[ "7" ],
];
auto b = new Tuple!(string, uint)[2];
largestPartialIntersection(a, b, Yes.sortOutput);
//writeln(b);
assert(b == [ tuple("7", 4u), tuple("1", 3u) ][], text(b));
}
unittest
{
import std.typecons : tuple, Tuple;
//scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done.");
// Figure which number can be found in most arrays of the set of
// arrays below, with specific per-element weights
double[][] a =
[
[ 1, 4, 7, 8 ],
[ 1, 7 ],
[ 1, 7, 8],
[ 4 ],
[ 7 ],
];
auto b = new Tuple!(double, uint)[1];
double[double] weights = [ 1:1.2, 4:2.3, 7:1.1, 8:1.1 ];
largestPartialIntersectionWeighted(a, b, weights);
// First member is the item, second is the occurrence count
//writeln(b[0]);
assert(b[0] == tuple(4.0, 2u));
}
unittest
{
import std.container : Array;
import std.typecons : Tuple;
alias T = Tuple!(uint, uint);
const Array!T arrayOne = Array!T( [ T(1,2), T(3,4) ] );
const Array!T arrayTwo = Array!T([ T(1,2), T(3,4) ] );
assert(arrayOne == arrayTwo);
}
// NWayUnion
/**
Computes the union of multiple sets. The input sets are passed as a
range of ranges and each is assumed to be sorted by $(D
less). Computation is done lazily, one union element at a time. The
complexity of one $(D popFront) operation is $(BIGOH
log(ror.length)). However, the length of $(D ror) decreases as ranges
in it are exhausted, so the complexity of a full pass through $(D
NWayUnion) is dependent on the distribution of the lengths of ranges
contained within $(D ror). If all ranges have the same length $(D n)
(worst case scenario), the complexity of a full pass through $(D
NWayUnion) is $(BIGOH n * ror.length * log(ror.length)), i.e., $(D
log(ror.length)) times worse than just spanning all ranges in
turn. The output comes sorted (unstably) by $(D less).
Params:
less = Predicate the given ranges are sorted by.
ror = A range of ranges sorted by `less` to compute the union for.
Returns:
A range of the union of the ranges in `ror`.
Warning: Because $(D NWayUnion) does not allocate extra memory, it
will leave $(D ror) modified. Namely, $(D NWayUnion) assumes ownership
of $(D ror) and discretionarily swaps and advances elements of it. If
you want $(D ror) to preserve its contents after the call, you may
want to pass a duplicate to $(D NWayUnion) (and perhaps cache the
duplicate in between calls).
*/
struct NWayUnion(alias less, RangeOfRanges)
{
import std.container : BinaryHeap;
private alias ElementType = .ElementType!(.ElementType!RangeOfRanges);
private alias comp = binaryFun!less;
private RangeOfRanges _ror;
///
static bool compFront(.ElementType!RangeOfRanges a,
.ElementType!RangeOfRanges b)
{
// revert comparison order so we get the smallest elements first
return comp(b.front, a.front);
}
private BinaryHeap!(RangeOfRanges, compFront) _heap;
///
this(RangeOfRanges ror)
{
import std.algorithm.mutation : remove, SwapStrategy;
// Preemptively get rid of all empty ranges in the input
// No need for stability either
_ror = remove!("a.empty", SwapStrategy.unstable)(ror);
//Build the heap across the range
_heap.acquire(_ror);
}
///
@property bool empty() { return _ror.empty; }
///
@property auto ref front()
{
return _heap.front.front;
}
///
void popFront()
{
_heap.removeFront();
// let's look at the guy just popped
_ror.back.popFront();
if (_ror.back.empty)
{
_ror.popBack();
// nothing else to do: the empty range is not in the
// heap and not in _ror
return;
}
// Put the popped range back in the heap
_heap.conditionalInsert(_ror.back) || assert(false);
}
}
/// Ditto
NWayUnion!(less, RangeOfRanges) nWayUnion
(alias less = "a < b", RangeOfRanges)
(RangeOfRanges ror)
{
return typeof(return)(ror);
}
///
unittest
{
import std.algorithm.comparison : equal;
double[][] a =
[
[ 1, 4, 7, 8 ],
[ 1, 7 ],
[ 1, 7, 8],
[ 4 ],
[ 7 ],
];
auto witness = [
1, 1, 1, 4, 4, 7, 7, 7, 7, 8, 8
];
assert(equal(nWayUnion(a), witness));
}
/**
Lazily computes the difference of $(D r1) and $(D r2). The two ranges
are assumed to be sorted by $(D less). The element types of the two
ranges must have a common type.
Params:
less = Predicate the given ranges are sorted by.
r1 = The first range.
r2 = The range to subtract from `r1`.
Returns:
A range of the difference of `r1` and `r2`.
See_also: $(LREF setSymmetricDifference)
*/
struct SetDifference(alias less = "a < b", R1, R2)
if (isInputRange!(R1) && isInputRange!(R2))
{
private:
R1 r1;
R2 r2;
alias comp = binaryFun!(less);
void adjustPosition()
{
while (!r1.empty)
{
if (r2.empty || comp(r1.front, r2.front)) break;
if (comp(r2.front, r1.front))
{
r2.popFront();
}
else
{
// both are equal
r1.popFront();
r2.popFront();
}
}
}
public:
///
this(R1 r1, R2 r2)
{
this.r1 = r1;
this.r2 = r2;
// position to the first element
adjustPosition();
}
///
void popFront()
{
r1.popFront();
adjustPosition();
}
///
@property auto ref front()
{
assert(!empty);
return r1.front;
}
static if (isForwardRange!R1 && isForwardRange!R2)
{
///
@property typeof(this) save()
{
auto ret = this;
ret.r1 = r1.save;
ret.r2 = r2.save;
return ret;
}
}
///
@property bool empty() { return r1.empty; }
}
/// Ditto
SetDifference!(less, R1, R2) setDifference(alias less = "a < b", R1, R2)
(R1 r1, R2 r2)
{
return typeof(return)(r1, r2);
}
///
@safe unittest
{
import std.algorithm.comparison : equal;
import std.range.primitives : isForwardRange;
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
assert(equal(setDifference(a, b), [5, 9][]));
static assert(isForwardRange!(typeof(setDifference(a, b))));
}
@safe unittest // Issue 10460
{
import std.algorithm.comparison : equal;
int[] a = [1, 2, 3, 4, 5];
int[] b = [2, 4];
foreach (ref e; setDifference(a, b))
e = 0;
assert(equal(a, [0, 2, 0, 4, 0]));
}
/**
Lazily computes the intersection of two or more input ranges $(D
ranges). The ranges are assumed to be sorted by $(D less). The element
types of the ranges must have a common type.
Params:
less = Predicate the given ranges are sorted by.
ranges = The ranges to compute the intersection for.
Returns:
A range containing the intersection of the given ranges.
*/
struct SetIntersection(alias less = "a < b", Rs...)
if (Rs.length >= 2 && allSatisfy!(isInputRange, Rs) &&
!is(CommonType!(staticMap!(ElementType, Rs)) == void))
{
private:
Rs _input;
alias comp = binaryFun!less;
alias ElementType = CommonType!(staticMap!(.ElementType, Rs));
// Positions to the first elements that are all equal
void adjustPosition()
{
if (empty) return;
size_t done = Rs.length;
static if (Rs.length > 1) while (true)
{
foreach (i, ref r; _input)
{
alias next = _input[(i + 1) % Rs.length];
if (comp(next.front, r.front))
{
do
{
next.popFront();
if (next.empty) return;
} while (comp(next.front, r.front));
done = Rs.length;
}
if (--done == 0) return;
}
}
}
public:
///
this(Rs input)
{
this._input = input;
// position to the first element
adjustPosition();
}
///
@property bool empty()
{
foreach (ref r; _input)
{
if (r.empty) return true;
}
return false;
}
///
void popFront()
{
assert(!empty);
static if (Rs.length > 1) foreach (i, ref r; _input)
{
alias next = _input[(i + 1) % Rs.length];
assert(!comp(r.front, next.front));
}
foreach (ref r; _input)
{
r.popFront();
}
adjustPosition();
}
///
@property ElementType front()
{
assert(!empty);
return _input[0].front;
}
static if (allSatisfy!(isForwardRange, Rs))
{
///
@property SetIntersection save()
{
auto ret = this;
foreach (i, ref r; _input)
{
ret._input[i] = r.save;
}
return ret;
}
}
}
/// Ditto
SetIntersection!(less, Rs) setIntersection(alias less = "a < b", Rs...)(Rs ranges)
if (Rs.length >= 2 && allSatisfy!(isInputRange, Rs) &&
!is(CommonType!(staticMap!(ElementType, Rs)) == void))
{
return typeof(return)(ranges);
}
///
@safe unittest
{
import std.algorithm.comparison : equal;
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
int[] c = [ 0, 1, 4, 5, 7, 8 ];
assert(equal(setIntersection(a, a), a));
assert(equal(setIntersection(a, b), [1, 2, 4, 7]));
assert(equal(setIntersection(a, b, c), [1, 4, 7]));
}
@safe unittest
{
import std.algorithm.comparison : equal;
import std.algorithm.iteration : filter;
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
int[] c = [ 0, 1, 4, 5, 7, 8 ];
int[] d = [ 1, 3, 4 ];
int[] e = [ 4, 5 ];
assert(equal(setIntersection(a, a), a));
assert(equal(setIntersection(a, a, a), a));
assert(equal(setIntersection(a, b), [1, 2, 4, 7]));
assert(equal(setIntersection(a, b, c), [1, 4, 7]));
assert(equal(setIntersection(a, b, c, d), [1, 4]));
assert(equal(setIntersection(a, b, c, d, e), [4]));
auto inpA = a.filter!(_ => true), inpB = b.filter!(_ => true);
auto inpC = c.filter!(_ => true), inpD = d.filter!(_ => true);
assert(equal(setIntersection(inpA, inpB, inpC, inpD), [1, 4]));
assert(equal(setIntersection(a, b, b, a), [1, 2, 4, 7]));
assert(equal(setIntersection(a, c, b), [1, 4, 7]));
assert(equal(setIntersection(b, a, c), [1, 4, 7]));
assert(equal(setIntersection(b, c, a), [1, 4, 7]));
assert(equal(setIntersection(c, a, b), [1, 4, 7]));
assert(equal(setIntersection(c, b, a), [1, 4, 7]));
}
/**
Lazily computes the symmetric difference of $(D r1) and $(D r2),
i.e. the elements that are present in exactly one of $(D r1) and $(D
r2). The two ranges are assumed to be sorted by $(D less), and the
output is also sorted by $(D less). The element types of the two
ranges must have a common type.
If both arguments are ranges of L-values of the same type then
$(D SetSymmetricDifference) will also be a range of L-values of
that type.
Params:
less = Predicate the given ranges are sorted by.
r1 = The first range.
r2 = The second range.
Returns:
A range of the symmetric difference between `r1` and `r2`.
See_also: $(LREF setDifference)
*/
struct SetSymmetricDifference(alias less = "a < b", R1, R2)
if (isInputRange!(R1) && isInputRange!(R2))
{
private:
R1 r1;
R2 r2;
//bool usingR2;
alias comp = binaryFun!(less);
void adjustPosition()
{
while (!r1.empty && !r2.empty)
{
if (comp(r1.front, r2.front) || comp(r2.front, r1.front))
{
break;
}
// equal, pop both
r1.popFront();
r2.popFront();
}
}
public:
///
this(R1 r1, R2 r2)
{
this.r1 = r1;
this.r2 = r2;
// position to the first element
adjustPosition();
}
///
void popFront()
{
assert(!empty);
if (r1.empty) r2.popFront();
else if (r2.empty) r1.popFront();
else
{
// neither is empty
if (comp(r1.front, r2.front))
{
r1.popFront();
}
else
{
assert(comp(r2.front, r1.front));
r2.popFront();
}
}
adjustPosition();
}
///
@property auto ref front()
{
assert(!empty);
immutable chooseR1 = r2.empty || !r1.empty && comp(r1.front, r2.front);
assert(chooseR1 || r1.empty || comp(r2.front, r1.front));
return chooseR1 ? r1.front : r2.front;
}
static if (isForwardRange!R1 && isForwardRange!R2)
{
///
@property typeof(this) save()
{
auto ret = this;
ret.r1 = r1.save;
ret.r2 = r2.save;
return ret;
}
}
///
ref auto opSlice() { return this; }
///
@property bool empty() { return r1.empty && r2.empty; }
}
/// Ditto
SetSymmetricDifference!(less, R1, R2)
setSymmetricDifference(alias less = "a < b", R1, R2)
(R1 r1, R2 r2)
{
return typeof(return)(r1, r2);
}
///
@safe unittest
{
import std.algorithm.comparison : equal;
import std.range.primitives : isForwardRange;
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
assert(equal(setSymmetricDifference(a, b), [0, 5, 8, 9][]));
static assert(isForwardRange!(typeof(setSymmetricDifference(a, b))));
}
@safe unittest // Issue 10460
{
int[] a = [1, 2];
double[] b = [2.0, 3.0];
int[] c = [2, 3];
alias R1 = typeof(setSymmetricDifference(a, b));
static assert(is(ElementType!R1 == double));
static assert(!hasLvalueElements!R1);
alias R2 = typeof(setSymmetricDifference(a, c));
static assert(is(ElementType!R2 == int));
static assert(hasLvalueElements!R2);
}
// Explicitly undocumented. It will be removed in December 2016. @@@DEPRECATED_2016-12@@@
deprecated("Please use std.algorithm.sorting.merge to join ranges")
alias setUnion = merge;
// Explicitly undocumented. It will be removed in December 2016. @@@DEPRECATED_2016-12@@@
deprecated("Please use std.algorithm.sorting.merge to join ranges")
alias SetUnion = Merge;
/++
TODO: once SetUnion got deprecated we can provide the usual definition
(= merge + filter after uniqs)
See: https://github.com/dlang/phobos/pull/4249
/**
Lazily computes the union of two or more ranges $(D rs). The ranges
are assumed to be sorted by $(D less). Elements in the output are
unique. The element types of all ranges must have a common type.
Params:
less = Predicate the given ranges are sorted by.
rs = The ranges to compute the union for.
Returns:
A range containing the unique union of the given ranges.
See_Also:
$(REF merge, std,algorithm,sorting)
*/
auto setUnion(alias less = "a < b", Rs...)
(Rs rs)
{
import std.algorithm.iteration : uniq;
import std.algorithm.sorting : merge;
return merge!(less, Rs)(rs).uniq;
}
///
@safe pure nothrow unittest
///
{
import std.algorithm.comparison : equal;
int[] a = [1, 3, 5];
int[] b = [2, 3, 4];
assert(a.setUnion(b).equal([1, 2, 3, 4, 5]));
}
@safe pure nothrow unittest
{
import std.algorithm.comparison : equal;
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
double[] c = [ 10.5 ];
assert(equal(setUnion(a, b), [0, 1, 2, 4, 5, 7, 8, 9][]));
assert(equal(setUnion(a, c, b),
[0, 1, 2, 4, 5, 7, 8, 9, 10.5][]));
}
@safe unittest
{
// save
import std.range : dropOne;
int[] a = [0, 1, 2];
int[] b = [0, 3];
auto arr = a.setUnion(b);
assert(arr.front == 0);
assert(arr.save.dropOne.front == 1);
assert(arr.front == 0);
}
@nogc @safe pure nothrow unittest
{
import std.algorithm.comparison : equal;
static immutable a = [1, 3, 5];
static immutable b = [2, 4];
static immutable r = [1, 2, 3, 4, 5];
assert(a.setUnion(b).equal(r));
}
@safe pure nothrow unittest
{
import std.algorithm.comparison : equal;
import std.internal.test.dummyrange;
import std.range : iota;
auto dummyResult1 = [1, 1.5, 2, 3, 4, 5, 5.5, 6, 7, 8, 9, 10];
auto dummyResult2 = iota(1, 11);
foreach (DummyType; AllDummyRanges)
{
DummyType d;
assert(d.setUnion([1, 1.5, 5.5]).equal(dummyResult1));
assert(d.setUnion(d).equal(dummyResult2));
}
}
++/
|
D
|
module imports.a4481;
template reduce(alias pred)
{
auto reduce(R)(R range)
{
return pred(range[0]);
}
}
|
D
|
module android.java.android.view.textclassifier.TextClassificationSessionFactory;
public import android.java.android.view.textclassifier.TextClassificationSessionFactory_d_interface;
import arsd.jni : ImportExportImpl;
mixin ImportExportImpl!TextClassificationSessionFactory;
import import0 = android.java.android.view.textclassifier.TextClassifier;
import import2 = android.java.java.lang.Class;
|
D
|
/*
Copyright (c) 2011-2019 Timur Gafarov
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
module dlib.functional.hof;
T delegate(S) compose(T, U, S)(T function(U) f, U function(S) g)
{
return (S s) => f(g(s));
}
/+++
Y combinator
Description:
We're all familiar with the idea of a function as something that takes some
input value and returns some output value. Say, the function for squaring numbers:
f(x) = x*x;
The fixed points of a function are any input values for which f(x) is equal to x.
So, the fixed points of f(x) = x*x are 0 and 1.
Now, we have things called higher-order functions. These are functions that take another
function as input, or return a function as output, or both.
The fixed point of a higher-order function f is another function p such that f(p) = p.
It may be more helpful to think in terms of functions actually being executed.
The previous statement is equivalent to the statement that f(p)(x) = p(x) for all values of x.
Y (the Y combinator) is a special function that returns the fixed points of higher-order
functions, that is to say:
f(Y(f)) = Y(f)
Y combinator is commonly use to allow anonymous recursion without assuming your host
language supports it.
+++/
auto Y(R, P...) (R delegate(P) delegate(R delegate(P)) lambda)
{
struct RFunc {R delegate(P) delegate(RFunc) f;}
auto r = RFunc( (RFunc w) => lambda((P x) => w.f(w)(x)) );
return r.f(r);
}
unittest
{
import std.algorithm;
import std.range;
auto factorial = Y((int delegate(int) self) =>
(int n) => 0 == n ? 1 : n * self(n - 1));
auto ackermann = Y((ulong delegate(ulong, ulong) self) =>
(ulong m, ulong n) => (!m && n)?
(n+1) : (m && !n)? self(m-1, 1) : self(m-1, self(m, n-1)));
auto qsort = Y((int[] delegate(int[]) self) =>
(int[] arr) => arr.length?
self(arr.filter!(a => a < arr[0]).array)
~ arr[0]
~ self(arr.filter!(a => a > arr[0]).array) : []);
assert(factorial(6) == 720);
assert(ackermann(3, 5) == 253);
assert(qsort([8, 5, 10, 2, 16, 9, 1, 100, 3])
== [1, 2, 3, 5, 8, 9, 10, 16, 100]);
}
|
D
|
//-------------------------------------------------------------------
//
// Main resistence forces calculation
// (c) maisvendoo, 2015/01/25
//
//-------------------------------------------------------------------
module MainResForces;
import MathFuncs;
import physics;
enum int AXIS = 4;
//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
double get_main_res(double v, double m)
{
double res_force = 0;
double v_kmh = abs(v)*kmh;
double q0 = m/AXIS/TONN;
double w = 0;
if (q0 <= 6)
{
w = 1.0 + 0.044*v_kmh + 0.00024*v_kmh*v_kmh;
}
else
{
w = 0.7 + (3 + 0.1*v_kmh + 0.0025*v_kmh*v_kmh)/q0;
}
res_force = (m/TONN)*w*g;
return res_force;
}
|
D
|
//Автор Кристофер Миллер. Переработано для Динрус Виталием Кулич.
//Библиотека визуальных конпонентов VIZ (первоначально DFL).
module viz.button;
private import viz.common, viz.control, viz.app;
private extern(Windows) проц _initButton();
extern(D):
abstract class ОсноваКнопки: СуперКлассУпрЭлта // docmain
{
проц разместиТекст(ПРасположение calign) ;
ПРасположение разместиТекст();
protected override проц создайПараметры(inout ПарамыСозд cp);
protected override проц предшОкПроц(inout Сообщение сооб);
protected override проц поОбратномуСообщению(inout Сообщение m);
protected override проц окПроц(inout Сообщение сооб);
this();
protected:
final проц дефолт_ли(бул подтвержд);
final бул дефолт_ли();
protected override бул обработайМнемонику(дим кодСим);
Размер дефРазм() ;
}
class Кнопка: ОсноваКнопки, ИУпрЭлтКнопка // docmain
{
this();
ПРезДиалога резДиалога();
проц резДиалога(ПРезДиалога dr) ;
проц сообщиДеф(бул подтвержд);
проц выполниКлик();
protected override проц приКлике(АргиСоб ea);
protected override проц окПроц(inout Сообщение m);
override проц текст(Ткст txt) ;
alias УпрЭлт.текст текст; // Overload.
final Рисунок рисунок();
final проц рисунок(Рисунок img);
protected override проц поСозданиюУказателя(АргиСоб ea);
protected override проц поУдалениюУказателя(АргиСоб ea);
}
class Флажок: ОсноваКнопки // docmain
{
final проц наружность(ПНаружность ap);
final ПНаружность наружность() ;
final проц автоУстанов(бул подтвержд) ;
final бул автоУстанов() ;
this();
final проц установлен(бул подтвержд);
final бул установлен();
final проц состояние(ПСостУст st);
final ПСостУст состояние();
protected override проц поСозданиюУказателя(АргиСоб ea);
}
class РадиоКнопка: ОсноваКнопки // docmain
{
final проц наружность(ПНаружность ap);
final ПНаружность наружность() ;
final проц автоУстанов(бул подтвержд);
final бул автоУстанов();
this();
protected override проц приКлике(АргиСоб ea);
final проц установлен(бул подтвержд) ;
final бул установлен() ;
final проц состояние(ПСостУст st) ;
final ПСостУст состояние();
проц выполниКлик();
protected override проц поСозданиюУказателя(АргиСоб ea);
}
|
D
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.