code
stringlengths
2.5k
150k
kind
stringclasses
1 value
phaser Class: Phaser.Touch Class: Phaser.Touch =================== Constructor ----------- ### new Touch(game) Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch. You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 16](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L16)) Public Properties ----------------- ### callbackContext : Object The context under which callbacks are called. Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L42)) ### enabled : boolean Touch events will only be processed if enabled. Default Value * true Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L28)) ### event :TouchEvent The browser touch DOM event. Will be set to null if no touch event has ever been received. Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 84](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L84)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L21)) ### preventDefault : boolean If true the TouchEvent will have prevent.default called on it. Default Value * true Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L78)) ### touchCancelCallback : Function A callback that can be fired on a touchCancel event. Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 72](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L72)) ### touchEndCallback : Function A callback that can be fired on a touchEnd event. Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L57)) ### touchEnterCallback : Function A callback that can be fired on a touchEnter event. Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 62](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L62)) ### touchLeaveCallback : Function A callback that can be fired on a touchLeave event. Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 67](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L67)) ### <internal> touchLockCallbacks :array An array of callbacks that will be fired every time a native touch start or touch end event is received from the browser. This is used internally to handle audio and video unlocking on mobile devices. To add a callback to this array please use `Touch.addTouchLockCallback`. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L37)) ### touchMoveCallback : Function A callback that can be fired on a touchMove event. Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L52)) ### touchStartCallback : Function A callback that can be fired on a touchStart event. Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 47](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L47)) Public Methods -------------- ### addTouchLockCallback(callback, context, onEnd) Adds a callback that is fired when a browser touchstart or touchend event is received. This is used internally to handle audio and video unlocking on mobile devices. If the callback returns 'true' then the callback is automatically deleted once invoked. The callback is added to the Phaser.Touch.touchLockCallbacks array and should be removed with Phaser.Touch.removeTouchLockCallback. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The callback that will be called when a touchstart event is received. | | `context` | object | | | The context in which the callback will be called. | | `onEnd` | boolean | <optional> | false | Will the callback fire on a touchstart (default) or touchend event? | Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 200](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L200)) ### consumeTouchMove() Consumes all touchmove events on the document (only enable this if you know you need it!). Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 186](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L186)) ### onTouchCancel(event) Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome). Occurs for example on iOS when you put down 4 fingers and the app selector UI appears. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | TouchEvent | The native event from the browser. This gets stored in Touch.event. | Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 293](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L293)) ### onTouchEnd(event) The handler for the touchend events. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | TouchEvent | The native event from the browser. This gets stored in Touch.event. | Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 402](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L402)) ### onTouchEnter(event) For touch enter and leave its a list of the touch points that have entered or left the target. Doesn't appear to be supported by most browsers on a canvas element yet. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | TouchEvent | The native event from the browser. This gets stored in Touch.event. | Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 327](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L327)) ### onTouchLeave(event) For touch enter and leave its a list of the touch points that have entered or left the target. Doesn't appear to be supported by most browsers on a canvas element yet. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | TouchEvent | The native event from the browser. This gets stored in Touch.event. | Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 354](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L354)) ### onTouchMove(event) The handler for the touchmove events. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | TouchEvent | The native event from the browser. This gets stored in Touch.event. | Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 376](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L376)) ### onTouchStart(event) The internal method that handles the touchstart event from the browser. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | TouchEvent | The native event from the browser. This gets stored in Touch.event. | Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 247](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L247)) ### removeTouchLockCallback(callback, context) → {boolean} Removes the callback at the defined index from the Phaser.Touch.touchLockCallbacks array ##### Parameters | Name | Type | Description | | --- | --- | --- | | `callback` | function | The callback to be removed. | | `context` | object | The context in which the callback exists. | ##### Returns boolean - True if the callback was deleted, otherwise false. Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 222](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L222)) ### start() Starts the event listeners running. Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L132)) ### stop() Stop the event listeners. Source code: [input/Touch.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js) ([Line 443](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Touch.js#L443)) phaser Class: Phaser.TilemapLayer Class: Phaser.TilemapLayer ========================== Constructor ----------- ### new TilemapLayer(game, tilemap, index, width, height) A TilemapLayer is a Phaser.Image/Sprite that renders a specific TileLayer of a Tilemap. Since a TilemapLayer is a Sprite it can be moved around the display, added to other groups or display objects, etc. By default TilemapLayers have fixedToCamera set to `true`. Changing this will break Camera follow and scrolling behavior. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | Game reference to the currently running game. | | `tilemap` | [Phaser.Tilemap](phaser.tilemap) | The tilemap to which this layer belongs. | | `index` | integer | The index of the TileLayer to render within the Tilemap. | | `width` | integer | Width of the renderable area of the layer (in pixels). | | `height` | integer | Height of the renderable area of the layer (in pixels). | Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L23)) Extends ------- * [Phaser.Sprite](phaser.sprite) Public Properties ----------------- ### alive : boolean A useful flag to control if the Game Object is alive or dead. This is set automatically by the Health components `damage` method should the object run out of health. Or you can toggle it via your game code. This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. Inherited From * [Phaser.Component.LifeSpan#alive](phaser.component.lifespan#alive) Default Value * true Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L50)) ### anchor :Point The anchor sets the origin point of the texture. The default is 0,0 this means the texture's origin is the top left Setting than anchor to 0.5,0.5 means the textures origin is centered Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner Inherited From * [PIXI.Sprite#anchor](pixi.sprite#anchor) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L17)) ### angle : number The angle property is the rotation of the Game Object in *degrees* from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. If you wish to work in radians instead of degrees you can use the property `rotation` instead. Working in radians is slightly faster as it doesn't have to perform any calculations. Inherited From * [Phaser.Component.Angle#angle](phaser.component.angle#angle) Source code: [gameobjects/components/Angle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js#L29)) ### animations : [Phaser.AnimationManager](phaser.animationmanager) If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. Through it you can create, play, pause and stop animations. Inherited From * [Phaser.Component.Core#animations](phaser.component.core#animations) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L193)) See * [Phaser.AnimationManager](phaser.animationmanager) ### autoCull : boolean A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.AutoCull#autoCull](phaser.component.autocull#autoCull) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L28)) ### blendMode : number The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. Inherited From * [PIXI.Sprite#blendMode](pixi.sprite#blendMode) Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L82)) ### body : [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated properties and methods via it. By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, so the physics body is centered on the Game Object. If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. ##### Type * [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null Inherited From * [Phaser.Component.PhysicsBody#body](phaser.component.physicsbody#body) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L91)) ### bottom : number The sum of the y and height properties. This is the same as `y + height - offsetY`. Inherited From * [Phaser.Component.Bounds#bottom](phaser.component.bounds#bottom) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L168)) ### cameraOffset : [Phaser.Point](phaser.point) The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. Inherited From * [Phaser.Component.FixedToCamera#cameraOffset](phaser.component.fixedtocamera#cameraOffset) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L86)) ### <internal> canvas :HTMLCanvasElement The canvas to which this TilemapLayer draws. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 59](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L59)) ### centerX : number The center x coordinate of the Game Object. This is the same as `(x - offsetX) + (width / 2)`. Inherited From * [Phaser.Component.Bounds#centerX](phaser.component.bounds#centerX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L58)) ### centerY : number The center y coordinate of the Game Object. This is the same as `(y - offsetY) + (height / 2)`. Inherited From * [Phaser.Component.Bounds#centerY](phaser.component.bounds#centerY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L80)) ### checkWorldBounds : boolean If this is set to `true` the Game Object checks if it is within the World bounds each frame. When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. It also optionally kills the Game Object if `outOfBoundsKill` is `true`. When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.InWorld#checkWorldBounds](phaser.component.inworld#checkWorldBounds) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L98)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### <internal> components : Object The components this Game Object has installed. Inherited From * [Phaser.Component.Core#components](phaser.component.core#components) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L167)) ### cropRect : [Phaser.Rectangle](phaser.rectangle) The Rectangle used to crop the texture this Game Object uses. Set this property via `crop`. If you modify this property directly you must call `updateCrop` in order to have the change take effect. Inherited From * [Phaser.Component.Crop#cropRect](phaser.component.crop#cropRect) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L24)) ### damage Damages the Game Object. This removes the given amount of health from the `health` property. If health is taken below or is equal to zero then the `kill` method is called. Inherited From * [Phaser.Component.Health#damage](phaser.component.health#damage) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L46)) ### data : Object An empty Object that belongs to this Game Object. This value isn't ever used internally by Phaser, but may be used by your own code, or by Phaser Plugins, to store data that needs to be associated with the Game Object, without polluting the Game Object directly. Inherited From * [Phaser.Component.Core#data](phaser.component.core#data) Default Value * {} Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L160)) ### debug : boolean Enable an additional "debug rendering" pass to display collision information. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L110)) ### debugSettings Settings used for debugging and diagnostics. ##### Properties: | Name | Type | Argument | Description | | --- | --- | --- | --- | | `missingImageFill` | string | <nullable> | A tile is rendered as a rectangle using the following fill if a valid tileset/image cannot be found. A value of `null` prevents additional rendering for tiles without a valid tileset image. *This takes effect even when debug rendering for the layer is not enabled.* | | `debuggedTileOverfill` | string | <nullable> | If a Tile has `Tile#debug` true then, after normal tile image rendering, a rectangle with the following fill is drawn above/over it. *This takes effect even when debug rendering for the layer is not enabled.* | | `forceFullRedraw` | boolean | | When debug rendering (`debug` is true), and this option is enabled, the a full redraw is forced and rendering optimization is suppressed. | | `debugAlpha` | number | | When debug rendering (`debug` is true), the tileset is initially rendered with this alpha level. This can make the tile edges clearer. | | `facingEdgeStroke` | string | <nullable> | When debug rendering (`debug` is true), this color/stroke is used to draw "face" edges. A value of `null` disables coloring facing edges. | | `collidingTileOverfill` | string | <nullable> | When debug rendering (`debug` is true), this fill is used for tiles that are collidable. A value of `null` disables applying the additional overfill. | Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 133](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L133)) ### [readonly] deltaX : number Returns the delta x value. The difference between world.x now and in the previous frame. The value will be positive if the Game Object has moved to the right or negative if to the left. Inherited From * [Phaser.Component.Delta#deltaX](phaser.component.delta#deltaX) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L24)) ### [readonly] deltaY : number Returns the delta y value. The difference between world.y now and in the previous frame. The value will be positive if the Game Object has moved down or negative if up. Inherited From * [Phaser.Component.Delta#deltaY](phaser.component.delta#deltaY) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L42)) ### [readonly] deltaZ : number Returns the delta z value. The difference between rotation now and in the previous frame. The delta value. Inherited From * [Phaser.Component.Delta#deltaZ](phaser.component.delta#deltaZ) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L58)) ### [readonly] destroyPhase : boolean As a Game Object runs through its destroy method this flag is set to true, and can be checked in any sub-systems or plugins it is being destroyed from. Inherited From * [Phaser.Component.Destroy#destroyPhase](phaser.component.destroy#destroyPhase) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L22)) ### <internal> dirty : boolean If true tiles will be force rendered, even if such is not believed to be required. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L167)) ### events : [Phaser.Events](phaser.events) All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this Game Object, or any of its components. Inherited From * [Phaser.Component.Core#events](phaser.component.core#events) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L185)) See * [Phaser.Events](phaser.events) ### exists : boolean Controls if the core game loop and physics update this game object or not. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L115)) ### fixedToCamera : boolean A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering. The values are adjusted at the rendering stage, overriding the Game Objects actual world position. The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times regardless where in the world the camera is. The offsets are stored in the `cameraOffset` property. Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. Inherited From * [Phaser.Component.FixedToCamera#fixedToCamera](phaser.component.fixedtocamera#fixedToCamera) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L56)) ### frame : integer Gets or sets the current frame index of the texture being used to render this Game Object. To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, for example: `player.frame = 4`. If the frame index given doesn't exist it will revert to the first frame found in the texture. If you are using a texture atlas then you should use the `frameName` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frame](phaser.component.loadtexture#frame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 254](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L254)) ### frameName : string Gets or sets the current frame name of the texture being used to render this Game Object. To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, for example: `player.frameName = "idle"`. If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. If you are using a sprite sheet then you should use the `frame` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frameName](phaser.component.loadtexture#frameName) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 279](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L279)) ### [readonly] fresh : boolean A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. This property is mostly used internally by the physics systems, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#fresh](phaser.component.core#fresh) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L248)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Component.Core#game](phaser.component.core#game) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L142)) ### heal Heal the Game Object. This adds the given amount of health to the `health` property. Inherited From * [Phaser.Component.Health#heal](phaser.component.health#heal) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 90](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L90)) ### health : number The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. It can be used in combination with the `damage` method or modified directly. Inherited From * [Phaser.Component.Health#health](phaser.component.health#health) Default Value * 1 Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L26)) ### height : number The height of the sprite, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.Sprite#height](pixi.sprite#height) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L144)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### [readonly] inCamera : boolean Checks if the Game Objects bounds intersect with the Game Camera bounds. Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. Inherited From * [Phaser.Component.AutoCull#inCamera](phaser.component.autocull#inCamera) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L37)) ### <internal, readonly> index : number The index of this layer within the Tilemap. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L44)) ### input : [Phaser.InputHandler](phaser.inputhandler) | null The Input Handler for this Game Object. By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. After you have done this, this property will be a reference to the Phaser InputHandler. ##### Type * [Phaser.InputHandler](phaser.inputhandler) | null Inherited From * [Phaser.Component.InputEnabled#input](phaser.component.inputenabled#input) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L24)) ### inputEnabled : boolean By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created for this Game Object and it will then start to process click / touch events and more. You can then access the Input Handler via `this.input`. Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. If you set this property to false it will stop the Input Handler from processing any more input events. If you want to *temporarily* disable input for a Game Object, then it's better to set `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. You can then toggle this back on as needed. Inherited From * [Phaser.Component.InputEnabled#inputEnabled](phaser.component.inputenabled#inputEnabled) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L42)) ### [readonly] inWorld : boolean Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. Inherited From * [Phaser.Component.InWorld#inWorld](phaser.component.inworld#inWorld) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L129)) ### key : string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) The key of the image or texture used by this Game Object during rendering. If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. ##### Type * string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) Inherited From * [Phaser.Component.Core#key](phaser.component.core#key) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L203)) ### <internal, readonly> layer : Object The layer object within the Tilemap that this layer represents. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L52)) ### left : number The left coordinate of the Game Object. This is the same as `x - offsetX`. Inherited From * [Phaser.Component.Bounds#left](phaser.component.bounds#left) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L102)) ### lifespan : number The lifespan allows you to give a Game Object a lifespan in milliseconds. Once the Game Object is 'born' you can set this to a positive value. It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. When it reaches zero it will call the `kill` method. Very handy for particles, bullets, collectibles, or any other short-lived entity. Inherited From * [Phaser.Component.LifeSpan#lifespan](phaser.component.lifespan#lifespan) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L65)) ### <internal, readonly> map : [Phaser.Tilemap](phaser.tilemap) The Tilemap to which this layer is bound. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L36)) ### maxHealth : number The Game Objects maximum health value. This works in combination with the `heal` method to ensure the health value never exceeds the maximum. Inherited From * [Phaser.Component.Health#maxHealth](phaser.component.health#maxHealth) Default Value * 100 Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L35)) ### name : string A user defined name given to this Game Object. This value isn't ever used internally by Phaser, it is meant as a game level property. Inherited From * [Phaser.Component.Core#name](phaser.component.core#name) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L150)) ### [readonly] offsetX : number The amount the Game Object is visually offset from its x coordinate. This is the same as `width * anchor.x`. It will only be > 0 if anchor.x is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetX](phaser.component.bounds#offsetX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L24)) ### [readonly] offsetY : number The amount the Game Object is visually offset from its y coordinate. This is the same as `height * anchor.y`. It will only be > 0 if anchor.y is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetY](phaser.component.bounds#offsetY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L42)) ### outOfBoundsKill : boolean If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. Inherited From * [Phaser.Component.InWorld#outOfBoundsKill](phaser.component.inworld#outOfBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L106)) ### outOfCameraBoundsKill : boolean If this and the `autoCull` property are both set to `true`, then the `kill` method is called as soon as the Game Object leaves the camera bounds. Inherited From * [Phaser.Component.InWorld#outOfCameraBoundsKill](phaser.component.inworld#outOfCameraBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L115)) ### pendingDestroy : boolean A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. You can set it directly to allow you to flag an object to be destroyed on its next update. This is extremely useful if you wish to destroy an object from within one of its own callbacks such as with Buttons or other Input events. Inherited From * [Phaser.Component.Core#pendingDestroy](phaser.component.core#pendingDestroy) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L259)) ### [readonly] physicsType : number The const physics body type of this object. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 83](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L83)) ### [readonly] previousPosition : [Phaser.Point](phaser.point) The position the Game Object was located in the previous frame. Inherited From * [Phaser.Component.Core#previousPosition](phaser.component.core#previousPosition) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L225)) ### [readonly] previousRotation : number The rotation the Game Object was in set to in the previous frame. Value is in radians. Inherited From * [Phaser.Component.Core#previousRotation](phaser.component.core#previousRotation) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L232)) ### rayStepRate : integer When ray-casting against tiles this is the number of steps it will jump. For larger tile sizes you can increase this to improve performance. Default Value * 4 Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 174](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L174)) ### [readonly] renderOrderID : number The render order ID is used internally by the renderer and Input Manager and should not be modified. This property is mostly used internally by the renderers, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#renderOrderID](phaser.component.core#renderOrderID) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L240)) ### renderSettings Settings that control standard (non-diagnostic) rendering. ##### Properties: | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `enableScrollDelta` | boolean | <optional> | true | Delta scroll rendering only draws tiles/edges as they come into view. This can greatly improve scrolling rendering performance, especially when there are many small tiles. It should only be disabled in rare cases. | | `copyCanvas` | DOMCanvasElement | <optional> <nullable> | (auto) | [Internal] If set, force using a separate (shared) copy canvas. Using a canvas bitblt/copy when the source and destinations region overlap produces unexpected behavior in some browsers, notably Safari. | Default Value * {"enableScrollDelta":false,"overdrawRatio":0.2,"copyCanvas":null} Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L98)) ### right : number The right coordinate of the Game Object. This is the same as `x + width - offsetX`. Inherited From * [Phaser.Component.Bounds#right](phaser.component.bounds#right) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L124)) ### scaleMax : [Phaser.Point](phaser.point) The maximum scale this Game Object will scale up to. It allows you to prevent a parent from scaling this Game Object higher than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMax](phaser.component.scaleminmax#scaleMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L46)) ### scaleMin : [Phaser.Point](phaser.point) The minimum scale this Game Object will scale down to. It allows you to prevent a parent from scaling this Game Object lower than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMin](phaser.component.scaleminmax#scaleMin) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L36)) ### scrollFactorX : number Speed at which this layer scrolls horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do). Default Value * 1 Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 152](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L152)) ### scrollFactorY : number Speed at which this layer scrolls vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do) Default Value * 1 Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L160)) ### setHealth Sets the health property of the Game Object to the given amount. Will never exceed the `maxHealth` value. Inherited From * [Phaser.Component.Health#setHealth](phaser.component.health#setHealth) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L70)) ### shader : [PIXI.AbstractFilter](pixi.abstractfilter) The shader that will be used to render this Sprite. Set to null to remove a current shader. Inherited From * [PIXI.Sprite#shader](pixi.sprite#shader) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L93)) ### smoothed : boolean Enable or disable texture smoothing for this Game Object. It only takes effect if the Game Object is using an image based texture. Smoothing is enabled by default. Inherited From * [Phaser.Component.Smoothed#smoothed](phaser.component.smoothed#smoothed) Source code: [gameobjects/components/Smoothed.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js#L25)) ### texture : [PIXI.Texture](pixi.texture) The texture that the sprite is using Inherited From * [PIXI.Sprite#texture](pixi.sprite#texture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L28)) ### tint : number The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. Inherited From * [PIXI.Sprite#tint](pixi.sprite#tint) Default Value * 0xFFFFFF Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L54)) ### tintedTexture :Canvas A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) Inherited From * [PIXI.Sprite#tintedTexture](pixi.sprite#tintedTexture) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L73)) ### top : number The y coordinate of the Game Object. This is the same as `y - offsetY`. Inherited From * [Phaser.Component.Bounds#top](phaser.component.bounds#top) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L146)) ### transformCallback : Function The callback that will apply any scale limiting to the worldTransform. Inherited From * [Phaser.Component.ScaleMinMax#transformCallback](phaser.component.scaleminmax#transformCallback) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L20)) ### transformCallbackContext : Object The context under which `transformCallback` is called. Inherited From * [Phaser.Component.ScaleMinMax#transformCallbackContext](phaser.component.scaleminmax#transformCallbackContext) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L26)) ### <internal, readonly> type : number The const type of this object. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Default Value * Phaser.TILEMAPLAYER Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 77](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L77)) ### width : number The width of the sprite, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.Sprite#width](pixi.sprite#width) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L125)) ### world : [Phaser.Point](phaser.point) The world coordinates of this Game Object in pixels. Depending on where in the display list this Game Object is placed this value can differ from `position`, which contains the x/y coordinates relative to the Game Objects parent. Inherited From * [Phaser.Component.Core#world](phaser.component.core#world) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L211)) ### x : number The position of the Game Object on the x axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#x](phaser.component.physicsbody#x) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L98)) ### y : number The position of the Game Object on the y axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#y](phaser.component.physicsbody#y) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L124)) ### [readonly] z : number The z depth of this Game Object within its parent Group. No two objects in a Group can have the same z value. This value is adjusted automatically whenever the Group hierarchy changes. If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. Inherited From * [Phaser.Component.Core#z](phaser.component.core#z) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L177)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### alignIn(container, position, offsetX, offsetY) → {Object} Aligns this Game Object within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the container, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignIn](phaser.component.bounds#alignIn) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 223](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L223)) ### alignTo(parent, position, offsetX, offsetY) → {Object} Aligns this Game Object to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the parent, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignTo](phaser.component.bounds#alignTo) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L321)) ### bringToTop() → {PIXI.DisplayObject} Brings this Game Object to the top of its parents display list. Visually this means it will render over the top of any old child in the same Group. If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#bringToTop](phaser.component.bringtotop#bringToTop) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L24)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### crop(rect, copy) Crop allows you to crop the texture being used to display this Game Object. Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, or by modifying `cropRect` property directly and then calling `updateCrop`. The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, in which case the values are duplicated to a local object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `rect` | [Phaser.Rectangle](phaser.rectangle) | | | The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. | | `copy` | boolean | <optional> | false | If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. | Inherited From * [Phaser.Component.Crop#crop](phaser.component.crop#crop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L49)) ### destroy() Destroys this TilemapLayer. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 351](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L351)) ### <internal> ensureSharedCopyCanvas() Create if needed (and return) a shared copy canvas that is shared across all TilemapLayers. Code that uses the canvas is responsible to ensure the dimensions and save/restore state as appropriate. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 253](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L253)) ### getBounds(matrix) → {Rectangle} Returns the bounds of the Sprite as a rectangle. The bounds calculation takes the worldTransform into account. It is important to note that the transform is not updated when you call this method. So if this Sprite is the child of a Display Object which has had its transform updated since the last render pass, those changes will not yet have been applied to this Sprites worldTransform. If you need to ensure that all parent transforms are factored into this getBounds operation then you should call `updateTransform` on the root most object in this Sprites display list first. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | Matrix | the transformation matrix of the sprite | ##### Returns Rectangle - the framing rectangle Inherited From * [PIXI.Sprite#getBounds](pixi.sprite#getBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 199](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L199)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.Sprite#getLocalBounds](pixi.sprite#getLocalBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L315)) ### getRayCastTiles(line, stepRate, collides, interestingFace) → {Array.<[Phaser.Tile](phaser.tile)>} Gets all tiles that intersect with the given line. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `line` | [Phaser.Line](phaser.line) | | | The line used to determine which tiles to return. | | `stepRate` | integer | <optional> | (rayStepRate) | How many steps through the ray will we check? Defaults to `rayStepRate`. | | `collides` | boolean | <optional> | false | If true, *only* return tiles that collide on one or more faces. | | `interestingFace` | boolean | <optional> | false | If true, *only* return tiles that have interesting faces. | ##### Returns Array.<[Phaser.Tile](phaser.tile)> - An array of Phaser.Tiles. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 551](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L551)) ### getTiles(x, y, width, height, collides, interestingFace) → {array.<[Phaser.Tile](phaser.tile)>} Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | X position of the top left corner (in pixels). | | `y` | number | | | Y position of the top left corner (in pixels). | | `width` | number | | | Width of the area to get (in pixels). | | `height` | number | | | Height of the area to get (in pixels). | | `collides` | boolean | <optional> | false | If true, *only* return tiles that collide on one or more faces. | | `interestingFace` | boolean | <optional> | false | If true, *only* return tiles that have interesting faces. | ##### Returns array.<[Phaser.Tile](phaser.tile)> - An array of Tiles. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 598](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L598)) ### getTileX(x) → {integer} Convert a pixel value to a tile coordinate. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | X position of the point in target tile (in pixels). | ##### Returns integer - The X map location of the tile. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 502](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L502)) ### getTileXY(x, y, point) → {[Phaser.Point](phaser.point) | object} Convert a pixel coordinate to a tile coordinate. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | X position of the point in target tile (in pixels). | | `y` | number | Y position of the point in target tile (in pixels). | | `point` | [Phaser.Point](phaser.point) | object | The Point/object to update. | ##### Returns [Phaser.Point](phaser.point) | object - A Point/object with its `x` and `y` properties set. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 532](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L532)) ### getTileY(y) → {integer} Convert a pixel value to a tile coordinate. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `y` | number | Y position of the point in target tile (in pixels). | ##### Returns integer - The Y map location of the tile. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 517](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L517)) ### kill() → {PIXI.DisplayObject} Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. Note that killing a Game Object is a way for you to quickly recycle it in an object pool, it doesn't destroy the object or free it up from memory. If you don't need this Game Object any more you should call `destroy` instead. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#kill](phaser.component.lifespan#kill) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L113)) ### loadTexture(key, frame, stopAnimation) Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. You should only use `loadTexture` if you want to replace the base texture entirely. Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. Doing this then sets the key to be the `frame` argument (the frame is set to zero). This allows you to create sprites using `load.image` during development, and then change them to use a Texture Atlas later in development by simply searching your code for 'PENDING\_ATLAS' and swapping it to be the key of the atlas data. Note: You cannot use a RenderTexture as a texture for a TileSprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `stopAnimation` | boolean | <optional> | true | If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. | Inherited From * [Phaser.Component.LoadTexture#loadTexture](phaser.component.loadtexture#loadTexture) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L51)) ### moveDown() → {PIXI.DisplayObject} Moves this Game Object down one place in its parents display list. This call has no effect if the Game Object is already at the bottom of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveDown](phaser.component.bringtotop#moveDown) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L87)) ### moveUp() → {PIXI.DisplayObject} Moves this Game Object up one place in its parents display list. This call has no effect if the Game Object is already at the top of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveUp](phaser.component.bringtotop#moveUp) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L66)) ### overlap(displayObject) → {boolean} Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. It should be fine for low-volume testing where physics isn't required. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.TileSprite](phaser.tilesprite) | [Phaser.Button](phaser.button) | PIXI.DisplayObject | The display object to check against. | ##### Returns boolean - True if the bounds of this Game Object intersects at any point with the bounds of the given display object. Inherited From * [Phaser.Component.Overlap#overlap](phaser.component.overlap#overlap) Source code: [gameobjects/components/Overlap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js#L29)) ### play(name, frameRate, loop, killOnComplete) → {[Phaser.Animation](phaser.animation)} Plays an Animation. The animation should have previously been created via `animations.add`. If the animation is already playing calling this again won't do anything. If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. | | `frameRate` | number | <optional> | null | The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. | | `loop` | boolean | <optional> | false | Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. | | `killOnComplete` | boolean | <optional> | false | If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. | ##### Returns [Phaser.Animation](phaser.animation) - A reference to playing Animation. Inherited From * [Phaser.Component.Animation#play](phaser.component.animation#play) Source code: [gameobjects/components/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js#L31)) ### <internal> postUpdate() Automatically called by World.postUpdate. Handles cache updates. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 284](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L284)) ### preUpdate() Automatically called by World.preUpdate. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 273](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L273)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### <internal> render() Renders the tiles to the layer canvas and pushes to the display. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 1045](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L1045)) ### reset(x, y, health) → {PIXI.DisplayObject} Resets the Game Object. This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, `visible` and `renderable` to true. If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. If this Game Object has a Physics Body it will reset the Body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate (in world space) to position the Game Object at. | | `y` | number | | | The y coordinate (in world space) to position the Game Object at. | | `health` | number | <optional> | 1 | The health to give the Game Object if it has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.Reset#reset](phaser.component.reset#reset) Source code: [gameobjects/components/Reset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js#L30)) ### resetFrame() Resets the texture frame dimensions that the Game Object uses for rendering. Inherited From * [Phaser.Component.LoadTexture#resetFrame](phaser.component.loadtexture#resetFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L232)) ### resetTilesetCache() The TilemapLayer caches tileset look-ups. Call this method of clear the cache if tilesets have been added or updated after the layer has been rendered. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 693](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L693)) ### resize(width, height) Resizes the internal canvas and texture frame used by this TilemapLayer. This is an expensive call, so don't bind it to a window resize event! But instead call it at carefully selected times. Be aware that no validation of the new sizes takes place and the current map scroll coordinates are not modified either. You will have to handle both of these things from your game code if required. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | number | The new width of the TilemapLayer | | `height` | number | The new height of the TilemapLayer | Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 364](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L364)) ### resizeFrame(parent, width, height) Resizes the Frame dimensions that the Game Object uses for rendering. You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData it can be useful to adjust the dimensions directly in this way. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `parent` | object | The parent texture object that caused the resize, i.e. a Phaser.Video object. | | `width` | integer | The new width of the texture. | | `height` | integer | The new height of the texture. | Inherited From * [Phaser.Component.LoadTexture#resizeFrame](phaser.component.loadtexture#resizeFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L220)) ### resizeWorld() Sets the world size to match the size of this layer. Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 402](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L402)) ### revive(health) → {PIXI.DisplayObject} Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `health` | number | <optional> | 100 | The health to give the Game Object. Only set if the GameObject has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#revive](phaser.component.lifespan#revive) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L78)) ### sendToBack() → {PIXI.DisplayObject} Sends this Game Object to the bottom of its parents display list. Visually this means it will render below all other children in the same Group. If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#sendToBack](phaser.component.bringtotop#sendToBack) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L45)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setFrame(frame) Sets the texture frame the Game Object uses for rendering. This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | [Phaser.Frame](phaser.frame) | The Frame to be used by the texture. | Inherited From * [Phaser.Component.LoadTexture#setFrame](phaser.component.loadtexture#setFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L155)) ### setScale(xScale, yScale) This method will set the scale of the tilemap as well as update the underlying block data of this layer. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `xScale` | number | <optional> | 1 | The scale factor along the X-plane | | `yScale` | number | <optional> | | The scale factor along the Y-plane | Source code: [tilemap/TilemapLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js) ([Line 712](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapLayer.js#L712)) ### setScaleMinMax(minX, minY, maxX, maxY) Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. By setting these values you can carefully control how Game Objects deal with responsive scaling. If only one parameter is given then that value will be used for both scaleMin and scaleMax: `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, or pass `null` for the `maxX` and `maxY` parameters. Call `setScaleMinMax(null)` to clear all previously set values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `minX` | number | null | The minimum horizontal scale value this Game Object can scale down to. | | `minY` | number | null | The minimum vertical scale value this Game Object can scale down to. | | `maxX` | number | null | The maximum horizontal scale value this Game Object can scale up to. | | `maxY` | number | null | The maximum vertical scale value this Game Object can scale up to. | Inherited From * [Phaser.Component.ScaleMinMax#setScaleMinMax](phaser.component.scaleminmax#setScaleMinMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L110)) ### setTexture(texture, destroy) Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous texture this Sprite was using. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | | | The PIXI texture that is displayed by the sprite | | `destroy` | Boolean | <optional> | false | Call Texture.destroy on the current texture before replacing it with the new one? | Inherited From * [PIXI.Sprite#setTexture](pixi.sprite#setTexture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L163)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### update() Override this method in your own custom objects to handle any update requirements. It is called immediately after `preUpdate` and before `postUpdate`. Remember if this Game Object has any children you should call update on those too. Inherited From * [Phaser.Component.Core#update](phaser.component.core#update) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 328](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L328)) ### updateCrop() If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, or the rectangle it references, then you need to update the crop frame by calling this method. Inherited From * [Phaser.Component.Crop#updateCrop](phaser.component.crop#updateCrop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L86))
programming_docs
phaser Class: Phaser.Physics.P2.ContactMaterial Class: Phaser.Physics.P2.ContactMaterial ======================================== Constructor ----------- ### new ContactMaterial(materialA, materialB, options) Defines a physics material ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `materialA` | [Phaser.Physics.P2.Material](phaser.physics.p2.material) | | First material participating in the contact material. | | `materialB` | [Phaser.Physics.P2.Material](phaser.physics.p2.material) | | Second material participating in the contact material. | | `options` | object | <optional> | Additional configuration options. | Source code: [physics/p2/ContactMaterial.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/ContactMaterial.js) ([Line 16](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/ContactMaterial.js#L16)) phaser Class: PIXI.Texture Class: PIXI.Texture =================== Constructor ----------- ### new Texture(baseTexture, frame, crop, trim) A texture stores the information that represents an image or part of an image. It cannot be added to the display list directly. Instead use it as the texture for a PIXI.Sprite. If no frame is provided then the whole image is used. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `baseTexture` | [PIXI.BaseTexture](pixi.basetexture) | | The base texture source to create the texture from | | `frame` | Rectangle | | The rectangle frame of the texture to show | | `crop` | Rectangle | <optional> | The area of original texture | | `trim` | Rectangle | <optional> | Trimmed texture rectangle | Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 14](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L14)) Public Properties ----------------- ### baseTexture : [PIXI.BaseTexture](pixi.basetexture) The base texture that this texture uses. Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 47](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L47)) ### crop :Rectangle This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 128](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L128)) ### frame :Rectangle The frame specifies the region of the base texture that this texture uses Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L55)) ### height : number The height of the Texture in pixels. Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 120](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L120)) ### isTiling : boolean Is this a tiling texture? As used by the likes of a TilingSprite. Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 79](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L79)) ### noFrame : boolean Does this Texture have any frame data assigned to it? Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L28)) ### requiresReTint : boolean This will let a renderer know that a tinted parent has updated its texture. Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 95](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L95)) ### requiresUpdate : boolean This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L87)) ### trim :Rectangle The texture trim data. Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L63)) ### valid : boolean This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 71](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L71)) ### width : number The width of the Texture in pixels. Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L112)) Public Methods -------------- ### <static> fromCanvas(canvas, scaleMode) → {[PIXI.Texture](pixi.texture)} Helper function that creates a new a Texture based on the given canvas element. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `canvas` | Canvas | The canvas element source of the texture | | `scaleMode` | Number | See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values | ##### Returns [PIXI.Texture](pixi.texture) - Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 249](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L249)) ### destroy(destroyBase) Destroys this texture ##### Parameters | Name | Type | Description | | --- | --- | --- | | `destroyBase` | Boolean | Whether to destroy the base texture as well | Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L165)) ### setFrame(frame) Specifies the region of the baseTexture that this texture will use. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | Rectangle | The frame of the texture to set it to | Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 178](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L178)) phaser Class: PIXI.WebGLRenderer Class: PIXI.WebGLRenderer ========================= Constructor ----------- ### new WebGLRenderer(game) The WebGLRenderer draws the stage and all its content onto a webGL enabled canvas. This renderer should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. So no need for Sprite Batches or Sprite Clouds. Don't forget to add the view to your DOM or you will not see anything :) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | PhaserGame | A reference to the Phaser Game instance | Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 8](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L8)) Public Properties ----------------- ### autoResize : boolean Whether the render view should be resized automatically Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 53](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L53)) ### blendModeManager : [PIXI.WebGLBlendModeManager](pixi.webglblendmodemanager) Manages the blendModes Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L167)) ### clearBeforeRender : boolean This sets if the WebGLRenderer will clear the context texture or not before the new render pass. If true: If the Stage is NOT transparent, Pixi will clear to alpha (0, 0, 0, 0). If the Stage is transparent, Pixi will clear to the target Stage's background color. Disable this by setting this to false. For example: if your game has a canvas filling background image, you often don't need this set. Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L69)) ### filterManager : [PIXI.WebGLFilterManager](pixi.webglfiltermanager) Manages the filters Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L153)) ### game :PhaserGame Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L20)) ### height : number The height of the canvas view Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 89](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L89)) ### maskManager : [PIXI.WebGLMaskManager](http://phaser.io/docs/2.6.2/PIXI.WebGLMaskManager.html) Manages the masks using the stencil buffer Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L146)) ### offset :Point Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L124)) ### preserveDrawingBuffer : boolean The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L61)) ### projection :Point Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 118](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L118)) ### renderSession : Object Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 174](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L174)) ### resolution : number The resolution of the renderer Default Value * 1 Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L36)) ### shaderManager : [PIXI.WebGLShaderManager](http://phaser.io/docs/2.6.2/PIXI.WebGLShaderManager.html) Deals with managing the shader programs and their attribs Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L132)) ### spriteBatch : [PIXI.WebGLSpriteBatch](http://phaser.io/docs/2.6.2/PIXI.WebGLSpriteBatch.html) Manages the rendering of sprites Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L139)) ### stencilManager : [PIXI.WebGLStencilManager](http://phaser.io/docs/2.6.2/PIXI.WebGLStencilManager.html) Manages the stencil buffer Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L160)) ### transparent : boolean Whether the render view is transparent Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L45)) ### type : number Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L30)) ### view :HTMLCanvasElement The canvas element that everything is drawn to Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 97](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L97)) ### width : number The width of the canvas view Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 81](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L81)) Public Methods -------------- ### destroy() Removes everything from the renderer (event listeners, spritebatch, etc...) Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 398](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L398)) ### initContext() Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 204](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L204)) ### mapBlendModes() Maps Pixi blend modes to WebGL blend modes. Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 430](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L430)) ### render(stage) Renders the stage to its webGL view ##### Parameters | Name | Type | Description | | --- | --- | --- | | `stage` | Stage | the Stage element to be rendered | Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 243](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L243)) ### renderDisplayObject(displayObject, projection, buffer) Renders a Display Object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `displayObject` | [DisplayObject](global#DisplayObject) | The DisplayObject to render | | `projection` | Point | The projection | | `buffer` | Array | a standard WebGL buffer | Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 278](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L278)) ### resize(width, height) Resizes the webGL view to the specified width and height. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | Number | the new width of the webGL view | | `height` | Number | the new height of the webGL view | Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L315)) ### updateTexture(texture) → {Boolean} Updates and Creates a WebGL texture for the renderers context. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | the texture to update | ##### Returns Boolean - True if the texture was successfully bound, otherwise false. Source code: [pixi/renderers/webgl/WebGLRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js) ([Line 341](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/webgl/WebGLRenderer.js#L341)) phaser Class: PIXI.Graphics Class: PIXI.Graphics ==================== Constructor ----------- ### new Graphics() The Graphics class contains methods used to draw primitive shapes such as lines, circles and rectangles to the display, and color and fill them. Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 5](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L5)) Extends ------- * [PIXI.DisplayObjectContainer](pixi.displayobjectcontainer) Public Properties ----------------- ### blendMode : number The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode. Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L61)) ### boundsPadding : number The bounds' padding used for bounds calculation. Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 96](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L96)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### fillAlpha : number The alpha value used when filling the Graphics object. Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 18](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L18)) ### height : number The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#height](pixi.displayobjectcontainer#height) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L600)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### isMask : boolean Whether this shape is being used as a mask. Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 88](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L88)) ### lineColor : string The color of any lines drawn. Default Value * 0 Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 34](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L34)) ### lineWidth : number The width (thickness) of any lines drawn. Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L26)) ### tint : number The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to reset the tint. Default Value * 0xFFFFFF Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L52)) ### width : number The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#width](pixi.displayobjectcontainer#width) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L571)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### arc(cx, cy, radius, startAngle, endAngle, anticlockwise, segments) → {[PIXI.Graphics](pixi.graphics)} The arc method creates an arc/curve (used to create circles, or parts of circles). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `cx` | Number | The x-coordinate of the center of the circle | | `cy` | Number | The y-coordinate of the center of the circle | | `radius` | Number | The radius of the circle | | `startAngle` | Number | The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle) | | `endAngle` | Number | The ending angle, in radians | | `anticlockwise` | Boolean | Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. | | `segments` | Number | Optional. The number of segments to use when calculating the arc. The default is 40. If you need more fidelity use a higher number. | ##### Returns [PIXI.Graphics](pixi.graphics) - Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 405](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L405)) ### beginFill(color, alpha) → {[PIXI.Graphics](pixi.graphics)} Specifies a simple one-color fill that subsequent calls to other Graphics methods (such as lineTo() or drawCircle()) use when drawing. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | Number | the color of the fill | | `alpha` | Number | the alpha of the fill | ##### Returns [PIXI.Graphics](pixi.graphics) - Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 491](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L491)) ### bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) → {[PIXI.Graphics](pixi.graphics)} Calculate the points for a bezier curve and then draws it. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `cpX` | Number | Control point x | | `cpY` | Number | Control point y | | `cpX2` | Number | Second Control point x | | `cpY2` | Number | Second Control point y | | `toX` | Number | Destination point x | | `toY` | Number | Destination point y | ##### Returns [PIXI.Graphics](pixi.graphics) - Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 276](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L276)) ### clear() → {[PIXI.Graphics](pixi.graphics)} Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. ##### Returns [PIXI.Graphics](pixi.graphics) - Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 633](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L633)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### destroyCachedSprite() Destroys a previous cached sprite. Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 1173](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L1173)) ### drawCircle(x, y, diameter) → {[PIXI.Graphics](pixi.graphics)} Draws a circle. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | Number | The X coordinate of the center of the circle | | `y` | Number | The Y coordinate of the center of the circle | | `diameter` | Number | The diameter of the circle | ##### Returns [PIXI.Graphics](pixi.graphics) - Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 565](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L565)) ### drawEllipse(x, y, width, height) → {[PIXI.Graphics](pixi.graphics)} Draws an ellipse. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | Number | The X coordinate of the center of the ellipse | | `y` | Number | The Y coordinate of the center of the ellipse | | `width` | Number | The half width of the ellipse | | `height` | Number | The half height of the ellipse | ##### Returns [PIXI.Graphics](pixi.graphics) - Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 581](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L581)) ### drawPolygon(path) → {[PIXI.Graphics](pixi.graphics)} Draws a polygon using the given path. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `path` | Array | PhaserPolygon | The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object. | ##### Returns [PIXI.Graphics](pixi.graphics) - Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 598](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L598)) ### drawRect(x, y, width, height) → {[PIXI.Graphics](pixi.graphics)} ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | Number | The X coord of the top-left of the rectangle | | `y` | Number | The Y coord of the top-left of the rectangle | | `width` | Number | The width of the rectangle | | `height` | Number | The height of the rectangle | ##### Returns [PIXI.Graphics](pixi.graphics) - Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 534](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L534)) ### drawRoundedRect(x, y, width, height, radius) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | Number | The X coord of the top-left of the rectangle | | `y` | Number | The Y coord of the top-left of the rectangle | | `width` | Number | The width of the rectangle | | `height` | Number | The height of the rectangle | | `radius` | Number | Radius of the rectangle corners. In WebGL this must be a value between 0 and 9. | Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 550](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L550)) ### drawShape(shape) → {[PIXI.GraphicsData](pixi.graphicsdata)} Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `shape` | Circle | Rectangle | Ellipse | Line | Polygon | The Shape object to draw. | ##### Returns [PIXI.GraphicsData](pixi.graphicsdata) - The generated GraphicsData object. Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 1184](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L1184)) ### endFill() → {[PIXI.Graphics](pixi.graphics)} Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. ##### Returns [PIXI.Graphics](pixi.graphics) - Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 519](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L519)) ### generateTexture(resolution, scaleMode, padding) → {[PIXI.Texture](pixi.texture)} Useful function that returns a texture of the graphics object that can then be used to create sprites This can be quite useful if your geometry is complicated and needs to be reused multiple times. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `resolution` | Number | <optional> | 1 | The resolution of the texture being generated | | `scaleMode` | Number | <optional> | 0 | Should be one of the PIXI.scaleMode consts | | `padding` | Number | <optional> | 0 | Add optional extra padding to the generated texture (default 0) | ##### Returns [PIXI.Texture](pixi.texture) - a texture of the graphics object Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 654](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L654)) ### getBounds() → {Rectangle} Retrieves the bounds of the graphic shape as a rectangle object ##### Returns Rectangle - the rectangular bounding area Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 848](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L848)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the graphic shape as a rectangle. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 936](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L936)) ### lineStyle(lineWidth, color, alpha) → {[PIXI.Graphics](pixi.graphics)} Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `lineWidth` | Number | width of the line to draw, will update the objects stored style | | `color` | Number | color of the line to draw, will update the objects stored style | | `alpha` | Number | alpha of the line to draw, will update the objects stored style | ##### Returns [PIXI.Graphics](pixi.graphics) - Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L149)) ### lineTo(x, y) → {[PIXI.Graphics](pixi.graphics)} Draws a line using the current line style from the current drawing position to (x, y); The current drawing position is then set to (x, y). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | Number | the X coordinate to draw to | | `y` | Number | the Y coordinate to draw to | ##### Returns [PIXI.Graphics](pixi.graphics) - Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 198](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L198)) ### moveTo(x, y) → {[PIXI.Graphics](pixi.graphics)} Moves the current drawing position to x, y. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | Number | the X coordinate to move to | | `y` | Number | the Y coordinate to move to | ##### Returns [PIXI.Graphics](pixi.graphics) - Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 183](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L183)) ### quadraticCurveTo(cpX, cpY, toX, toY) → {[PIXI.Graphics](pixi.graphics)} Calculate the points for a quadratic bezier curve and then draws it. Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c ##### Parameters | Name | Type | Description | | --- | --- | --- | | `cpX` | Number | Control point x | | `cpY` | Number | Control point y | | `toX` | Number | Destination point x | | `toY` | Number | Destination point y | ##### Returns [PIXI.Graphics](pixi.graphics) - Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L221)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### updateLocalBounds() Update the bounds of the object Source code: [pixi/primitives/Graphics.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js) ([Line 997](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/Graphics.js#L997))
programming_docs
phaser Class: Phaser.Polygon Class: Phaser.Polygon ===================== Constructor ----------- ### new Polygon(points) Creates a new Polygon. The points can be set from a variety of formats: * An array of Point objects: `[new Phaser.Point(x1, y1), ...]` * An array of objects with public x/y properties: `[obj1, obj2, ...]` * An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` * As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` * As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` * As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` ##### Parameters | Name | Type | Description | | --- | --- | --- | | `points` | Array.<[Phaser.Point](phaser.point)> | Array.<number> | [Phaser.Point](phaser.point) | number | The points to set. | Source code: [geom/Polygon.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js#L24)) Public Properties ----------------- ### area : number The area of this Polygon. Source code: [geom/Polygon.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js#L29)) ### closed : boolean Is the Polygon closed or not? Source code: [geom/Polygon.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js#L45)) ### flattened : boolean Has this Polygon been flattened by a call to `Polygon.flatten` ? Source code: [geom/Polygon.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js#L50)) ### points : Array.<[Phaser.Point](phaser.point)> This method is *deprecated* and should not be used. It may be removed in the future. Sets and modifies the points of this polygon. See [setTo](phaser.polygon#setTo) for the different kinds of arrays formats that can be assigned. The array of vertex points. ##### Type * Array.<[Phaser.Point](phaser.point)> Deprecated: * Use `setTo`. Source code: [geom/Polygon.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js) ([Line 294](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js#L294)) ### type : number The base object type. Source code: [geom/Polygon.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js#L55)) Public Methods -------------- ### clone(output) → {[Phaser.Polygon](phaser.polygon)} Creates a copy of the given Polygon. This is a deep clone, the resulting copy contains new Phaser.Point objects ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `output` | [Phaser.Polygon](phaser.polygon) | <optional> | (new Polygon) | The polygon to update. If not specified a new polygon will be created. | ##### Returns [Phaser.Polygon](phaser.polygon) - The cloned (`output`) polygon object. Source code: [geom/Polygon.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js) ([Line 109](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js#L109)) ### contains(x, y) → {boolean} Checks whether the x and y coordinates are contained within this polygon. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The X value of the coordinate to test. | | `y` | number | The Y value of the coordinate to test. | ##### Returns boolean - True if the coordinates are within this polygon, otherwise false. Source code: [geom/Polygon.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js) ([Line 134](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js#L134)) ### flatten() → {[Phaser.Polygon](phaser.polygon)} Flattens this Polygon so the points are a sequence of numbers. Any Point objects found are removed and replaced with two numbers. Also sets the Polygon.flattened property to `true`. ##### Returns [Phaser.Polygon](phaser.polygon) - This Polygon object Source code: [geom/Polygon.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js#L91)) ### setTo(points) → {[Phaser.Polygon](phaser.polygon)} Sets this Polygon to the given points. The points can be set from a variety of formats: * An array of Point objects: `[new Phaser.Point(x1, y1), ...]` * An array of objects with public x/y properties: `[obj1, obj2, ...]` * An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` * An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` * As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` * As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` * As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` `setTo` may also be called without any arguments to remove all points. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `points` | Array.<[Phaser.Point](phaser.point)> | Array.<number> | [Phaser.Point](phaser.point) | number | The points to set. | ##### Returns [Phaser.Polygon](phaser.polygon) - This Polygon object Source code: [geom/Polygon.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js) ([Line 186](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js#L186)) ### toNumberArray(output) → {array} Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ] ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `output` | array | <optional> | The array to append the points to. If not specified a new array will be created. | ##### Returns array - The flattened array. Source code: [geom/Polygon.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Polygon.js#L61)) phaser Class: Phaser.Time Class: Phaser.Time ================== Constructor ----------- ### new Time(game) This is the core internal game clock. It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens, and also handles the standard Timer pool. To create a general timed event, use the master [Phaser.Timer](phaser.timer) accessible through events. There are different *types* of time in Phaser: * ***Game time*** always runs at the speed of time in real life. Unlike wall-clock time, *game time stops when Phaser is paused*. Game time is used for [timer events](phaser.timer). * ***Physics time*** represents the amount of time given to physics calculations. *When [slowMotion](phaser.time#slowMotion) is in effect physics time runs slower than game time.* Like game time, physics time stops when Phaser is paused. Physics time is used for physics calculations and [tweens](phaser.tween). * [***Wall-clock time***](https://en.wikipedia.org/wiki/Wall-clock_time) represents the duration between two events in real life time. This time is independent of Phaser and always progresses, regardless of if Phaser is paused. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L38)) Public Properties ----------------- ### advancedTiming : boolean If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L165)) ### desiredFps : integer The desired frame rate of the game. This is used is used to calculate the physic / logic multiplier and how to apply catch-up logic updates. The desired frame rate of the game. Defaults to 60. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 596](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L596)) ### <internal> desiredFpsMult : integer The desiredFps multiplier as used by Game.update. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 126](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L126)) ### <internal> elapsed : number Elapsed time since the last time update, in milliseconds, based on `now`. This value *may* include time that the game is paused/inactive. *Note:* This is updated only once per game loop - even if multiple logic update steps are done. Use physicsTime as a basis of game/logic calculations instead. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L86)) See * Phaser.Time.time ### <internal> elapsedMS : integer The time in ms since the last time update, in milliseconds, based on `time`. This value is corrected for game pauses and will be "about zero" after a game is resumed. *Note:* This is updated once per game loop - even if multiple logic update steps are done. Use physicsTime as a basis of game/logic calculations instead. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 99](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L99)) ### events : [Phaser.Timer](phaser.timer) A [Phaser.Timer](phaser.timer) object bound to the master clock (this Time object) which events can be added to. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 245](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L245)) ### [readonly] fps : number Advanced timing result: Frames per second. Only calculated if [advancedTiming](phaser.time#advancedTiming) is enabled. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 183](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L183)) ### fpsMax : number Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps). Only calculated if [advancedTiming](phaser.time#advancedTiming) is enabled. This value can be manually reset. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 201](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L201)) ### fpsMin : number Advanced timing result: The lowest rate the fps has dropped to. Only calculated if [advancedTiming](phaser.time#advancedTiming) is enabled. This value can be manually reset. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 192](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L192)) ### [readonly] frames : integer Advanced timing result: The number of render frames record in the last second. Only calculated if [advancedTiming](phaser.time#advancedTiming) is enabled. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 174](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L174)) ### <internal> game : [Phaser.Game](phaser.game) Local reference to game. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L44)) ### msMax : number Advanced timing result: The maximum amount of time the game has taken between consecutive frames. Only calculated if [advancedTiming](phaser.time#advancedTiming) is enabled. This value can be manually reset. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L220)) ### msMin : number Advanced timing result: The minimum amount of time the game has taken between consecutive frames. Only calculated if [advancedTiming](phaser.time#advancedTiming) is enabled. This value can be manually reset. Default Value * 1000 Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L211)) ### <internal> now : number An increasing value representing cumulative milliseconds since an undisclosed epoch. While this value is in milliseconds and can be used to compute time deltas, it must must *not* be used with `Date.now()` as it may not use the same epoch / starting reference. The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now; the value can only be relied upon within a particular game instance. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 72](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L72)) ### pauseDuration : number Records how long the game was last paused, in milliseconds. (This is not updated until the game is resumed.) Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 227](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L227)) ### physicsElapsed : number The physics update delta, in fractional seconds. This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`) to ensure consistent game timing. Game/logic timing can drift from real-world time if the system is unable to consistently maintain the desired FPS. With fixed-step updates this is normally equivalent to `1.0 / desiredFps`. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L112)) ### physicsElapsedMS : number The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L119)) ### <internal> prevTime : number The `now` when the previous update occurred. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L58)) ### slowMotion : number Scaling factor to make the game move smoothly in slow motion * 1.0 = normal speed * 2.0 = half speed Default Value * 1 Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 158](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L158)) ### suggestedFps : number The suggested frame rate for your game, based on an averaged real frame rate. This value is only populated if `Time.advancedTiming` is enabled. *Note:* This is not available until after a few frames have passed; until then it's set to the same value as desiredFps. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L149)) ### <internal> time : integer The `Date.now()` value when the time was last updated. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L51)) ### <internal> timeExpected : number The time when the next call is expected when using setTimer to control the update loop Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 239](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L239)) ### <internal> timeToCall : number The value that setTimeout needs to work out when to next update Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 233](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L233)) Public Methods -------------- ### add(timer) → {[Phaser.Timer](phaser.timer)} Adds an existing Phaser.Timer object to the Timer pool. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `timer` | [Phaser.Timer](phaser.timer) | An existing Phaser.Timer object. | ##### Returns [Phaser.Timer](phaser.timer) - The given Phaser.Timer object. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 308](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L308)) ### <internal> boot() Called automatically by Phaser.Game after boot. Should not be called directly. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 293](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L293)) ### create(autoDestroy) → {[Phaser.Timer](phaser.timer)} Creates a new stand-alone Phaser.Timer object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `autoDestroy` | boolean | <optional> | true | A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events). | ##### Returns [Phaser.Timer](phaser.timer) - The Timer object that was created. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 323](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L323)) ### elapsedSecondsSince(since) → {number} How long has passed since the given time (in seconds). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `since` | number | The time you want to measure (in seconds). | ##### Returns number - Duration between given time and now (in seconds). Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L571)) ### elapsedSince(since) → {number} How long has passed since the given time. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `since` | number | The time you want to measure against. | ##### Returns number - The difference between the given time and now. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 560](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L560)) ### refresh() Refreshes the Time.time and Time.elapsedMS properties from the system clock. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 360](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L360)) ### removeAll() Remove all Timer objects, regardless of their state and clears all Timers from the [events](phaser.time#events) timer. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 342](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L342)) ### reset() Resets the private \_started value to now and removes all currently running Timers. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 582](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L582)) ### totalElapsedSeconds() → {number} The number of seconds that have elapsed since the game was started. ##### Returns number - The number of seconds that have elapsed since the game was started. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 550](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L550)) ### <internal> update(time) Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `time` | number | The current relative timestamp; see [now](phaser.time#now). | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Time.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js) ([Line 378](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Time.js#L378))
programming_docs
phaser Class: Phaser.TilemapParser Class: Phaser.TilemapParser =========================== Constructor ----------- ### new TilemapParser() Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap. Source code: [tilemap/TilemapParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapParser.js) ([Line 13](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapParser.js#L13)) Public Properties ----------------- ### [static] INSERT\_NULL : boolean When scanning the Tiled map data the TilemapParser can either insert a null value (true) or a Phaser.Tile instance with an index of -1 (false, the default). Depending on your game type depends how this should be configured. If you've a large sparsely populated map and the tile data doesn't need to change then setting this value to `true` will help with memory consumption. However if your map is small, or you need to update the tiles (perhaps the map dynamically changes during the game) then leave the default value set. Source code: [tilemap/TilemapParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapParser.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapParser.js#L26)) Public Methods -------------- ### <static> getEmptyData() → {object} Returns an empty map data object. ##### Returns object - Generated map data. Source code: [tilemap/TilemapParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapParser.js) ([Line 135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapParser.js#L135)) ### <static> parse(game, key, tileWidth, tileHeight, width, height) → {object} Parse tilemap data from the cache and creates data for a Tilemap object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | Game reference to the currently running game. | | `key` | string | | | The key of the tilemap in the Cache. | | `tileWidth` | number | <optional> | 32 | The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. | | `tileHeight` | number | <optional> | 32 | The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. | | `width` | number | <optional> | 10 | The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. | | `height` | number | <optional> | 10 | The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. | ##### Returns object - The parsed map object. Source code: [tilemap/TilemapParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapParser.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapParser.js#L28)) ### <static> parseCSV(key, data, tileWidth, tileHeight) → {object} Parses a CSV file into valid map data. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The name you want to give the map data. | | `data` | string | | | The CSV file data. | | `tileWidth` | number | <optional> | 32 | The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. | | `tileHeight` | number | <optional> | 32 | The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. | ##### Returns object - Generated map data. Source code: [tilemap/TilemapParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapParser.js) ([Line 77](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapParser.js#L77)) ### <static> parseJSON(json) → {object} Parses a Tiled JSON file into valid map data. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `json` | object | The JSON map data. | ##### Returns object - Generated and parsed map data. Source code: [tilemap/TilemapParser.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapParser.js) ([Line 180](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tilemap/TilemapParser.js#L180)) phaser Class: Phaser.Timer Class: Phaser.Timer =================== Constructor ----------- ### new Timer(game, autoDestroy) A Timer is a way to create and manage [timer events](phaser.timerevent) that wait for a specific duration and then run a callback. Many different timer events, with individual delays, can be added to the same Timer. All Timer delays are in milliseconds (there are 1000 ms in 1 second); so a delay value of 250 represents a quarter of a second. Timers are based on real life time, adjusted for game pause durations. That is, *timer events are based on elapsed [game time](phaser.time)* and do *not* take physics time or slow motion into account. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | A reference to the currently running game. | | `autoDestroy` | boolean | <optional> | true | If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). | Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L21)) Public Properties ----------------- ### [static] HALF : integer Number of milliseconds in half a second. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 175](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L175)) ### [static] MINUTE : integer Number of milliseconds in a minute. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L161)) ### [static] QUARTER : integer Number of milliseconds in a quarter of a second. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 182](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L182)) ### [static] SECOND : integer Number of milliseconds in a second. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L168)) ### autoDestroy : boolean If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L45)) ### [readonly] duration : number The duration in ms remaining until the next event will occur. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 677](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L677)) ### <internal> elapsed : number Elapsed time since the last frame (in ms). Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L58)) ### events : Array.<[Phaser.TimerEvent](phaser.timerevent)> An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it. ##### Type * Array.<[Phaser.TimerEvent](phaser.timerevent)> Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L63)) ### [readonly] expired : boolean An expired Timer is one in which all of its events have been dispatched and none are pending. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L52)) ### <internal> game : [Phaser.Game](phaser.game) Local reference to game. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L29)) ### [readonly] length : number The number of pending events in the queue. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 699](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L699)) ### [readonly] ms : number The duration in milliseconds that this Timer has been running for. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 712](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L712)) ### [readonly] next : number The time at which the next event will occur. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 664](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L664)) ### <internal, readonly> nextTick : number The time the next tick will occur. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 79](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L79)) ### onComplete : [Phaser.Signal](phaser.signal) This signal will be dispatched when this Timer has completed which means that there are no more events in the queue. The signal is supplied with one argument, `timer`, which is this Timer object. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 72](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L72)) ### [readonly] paused : boolean The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L91)) ### [readonly] running : boolean True if the Timer is actively running. Do not modify this boolean - use [pause](phaser.timer#pause) (and [resume](phaser.timer#resume)) to pause the timer. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L39)) ### [readonly] seconds : number The duration in seconds that this Timer has been running for. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 734](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L734)) ### timeCap : number If the difference in time between two frame updates exceeds this value, the event times are reset to avoid catch-up situations. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 84](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L84)) Public Methods -------------- ### add(delay, callback, callbackContext, arguments) → {[Phaser.TimerEvent](phaser.timerevent)} Adds a new Event to this Timer. The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. Make sure to call [start](phaser.timer#start) after adding all of the Events you require for this Timer. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `delay` | integer | | The number of milliseconds, in [game time](phaser.time), before the timer event occurs. | | `callback` | function | | The callback that will be called when the timer event occurs. | | `callbackContext` | object | | The context in which the callback will be called. | | `arguments` | \* | <repeatable> | Additional arguments that will be supplied to the callback. | ##### Returns [Phaser.TimerEvent](phaser.timerevent) - The Phaser.TimerEvent object that was created. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 228](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L228)) ### <internal> adjustEvents() Adjusts the time of all pending events and the nextTick by the given baseTime. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 552](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L552)) ### <internal> clearPendingEvents() Clears any events from the Timer which have pendingDelete set to true and then resets the private \_len and \_i values. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 392](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L392)) ### destroy() Destroys this Timer. Any pending Events are not dispatched. The onComplete callbacks won't be called. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 646](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L646)) ### loop(delay, callback, callbackContext, arguments) → {[Phaser.TimerEvent](phaser.timerevent)} Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped. The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. Make sure to call [start](phaser.timer#start) after adding all of the Events you require for this Timer. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `delay` | integer | | The number of milliseconds, in [game time](phaser.time), before the timer event occurs. | | `callback` | function | | The callback that will be called when the timer event occurs. | | `callbackContext` | object | | The context in which the callback will be called. | | `arguments` | \* | <repeatable> | Additional arguments that will be supplied to the callback. | ##### Returns [Phaser.TimerEvent](phaser.timerevent) - The Phaser.TimerEvent object that was created. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 272](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L272)) ### <internal> order() Orders the events on this Timer so they are in tick order. This is called automatically when new events are created. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 354](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L354)) ### pause() Pauses the Timer and all events in the queue. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 510](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L510)) ### remove(event) Removes a pending TimerEvent from the queue. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | [Phaser.TimerEvent](phaser.timerevent) | The event to remove from the queue. | Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 334](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L334)) ### removeAll() Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running. The onComplete callbacks won't be called. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 631](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L631)) ### repeat(delay, repeatCount, callback, callbackContext, arguments) → {[Phaser.TimerEvent](phaser.timerevent)} Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations. The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. Make sure to call [start](phaser.timer#start) after adding all of the Events you require for this Timer. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `delay` | integer | | The number of milliseconds, in [game time](phaser.time), before the timer event occurs. | | `repeatCount` | number | | The number of times the event will repeat once is has finished playback. A repeatCount of 1 means it will repeat itself once, playing the event twice in total. | | `callback` | function | | The callback that will be called when the timer event occurs. | | `callbackContext` | object | | The context in which the callback will be called. | | `arguments` | \* | <repeatable> | Additional arguments that will be supplied to the callback. | ##### Returns [Phaser.TimerEvent](phaser.timerevent) - The Phaser.TimerEvent object that was created. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 249](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L249)) ### resume() Resumes the Timer and updates all pending events. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 590](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L590)) ### start(delay) Starts this Timer running. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `delay` | integer | <optional> | 0 | The number of milliseconds, in [game time](phaser.time), that should elapse before the Timer will start. | Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 293](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L293)) ### stop(clearEvents) Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `clearEvents` | boolean | <optional> | true | If true all the events in Timer will be cleared, otherwise they will remain. | Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 316](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L316)) ### <internal> update(time) → {boolean} The main Timer update event, called automatically by Phaser.Time.update. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `time` | number | The time from the core game clock. | ##### Returns boolean - True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [time/Timer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js) ([Line 415](https://github.com/photonstorm/phaser/tree/v2.6.2/src/time/Timer.js#L415))
programming_docs
phaser Class: Phaser.Physics.P2.LockConstraint Class: Phaser.Physics.P2.LockConstraint ======================================= Constructor ----------- ### new LockConstraint(world, bodyA, bodyB, offset, angle, maxForce) Locks the relative position between two bodies. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `world` | [Phaser.Physics.P2](phaser.physics.p2) | | | A reference to the P2 World. | | `bodyA` | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | First connected body. | | `bodyB` | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | Second connected body. | | `offset` | Array | <optional> | | The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `angle` | number | <optional> | 0 | The angle of bodyB in bodyA's frame. | | `maxForce` | number | <optional> | | The maximum force that should be applied to constrain the bodies. | Source code: [physics/p2/LockConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/LockConstraint.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/LockConstraint.js#L19)) Public Properties ----------------- ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [physics/p2/LockConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/LockConstraint.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/LockConstraint.js#L28)) ### world : [Phaser.Physics.P2](phaser.physics.p2) Local reference to P2 World. Source code: [physics/p2/LockConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/LockConstraint.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/LockConstraint.js#L33)) phaser Class: Phaser.AudioSprite Class: Phaser.AudioSprite ========================= Constructor ----------- ### new AudioSprite(game, key) Audio Sprites are a combination of audio files and a JSON configuration. The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | Reference to the current game instance. | | `key` | string | Asset key for the sound. | Source code: [sound/AudioSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js#L17)) Public Properties ----------------- ### autoplay : boolean Is a sound set to autoplay or not? Source code: [sound/AudioSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js) ([Line 48](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js#L48)) ### autoplayKey : string If a sound is set to auto play, this holds the marker key of it. Source code: [sound/AudioSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js) ([Line 41](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js#L41)) ### config : Object JSON audio atlas object. Source code: [sound/AudioSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js#L35)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Source code: [sound/AudioSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js) ([Line 23](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js#L23)) ### key : string Asset key for the Audio Sprite. Source code: [sound/AudioSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js#L29)) ### sounds : Object An object containing the Phaser.Sound objects for the Audio Sprite. Source code: [sound/AudioSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js#L54)) Public Methods -------------- ### get(marker) → {[Phaser.Sound](phaser.sound)} Get a sound with the given name. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `marker` | string | The name of sound to get. | ##### Returns [Phaser.Sound](phaser.sound) - The sound instance. Source code: [sound/AudioSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js#L115)) ### play(marker, volume) → {[Phaser.Sound](phaser.sound)} Play a sound with the given name. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `marker` | string | <optional> | | The name of sound to play | | `volume` | number | <optional> | 1 | Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). | ##### Returns [Phaser.Sound](phaser.sound) - This sound instance. Source code: [sound/AudioSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js) ([Line 77](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js#L77)) ### stop(marker) Stop a sound with the given name. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `marker` | string | <optional> | '' | The name of sound to stop. If none is given it will stop all sounds in the audio sprite. | Source code: [sound/AudioSprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/sound/AudioSprite.js#L93)) phaser Class: Phaser.Pointer Class: Phaser.Pointer ===================== Constructor ----------- ### new Pointer(game, id, pointerMode) A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen. ##### Parameters | Name | Type | Default | Description | | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | A reference to the currently running game. | | `id` | number | | The ID of the Pointer object within the game. Each game can have up to 10 active pointers. | | `pointerMode` | [Phaser.PointerMode](phaser.pointermode) | (CURSOR | CONTACT) | The operational mode of this pointer, eg. CURSOR or TOUCH. | Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 16](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L16)) Public Properties ----------------- ### [static] BACK\_BUTTON : number The X1 button. This is typically the mouse Back button, but is often reconfigured. On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 397](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L397)) ### [static] ERASER\_BUTTON : number The Eraser pen button on PointerEvent supported devices only. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 412](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L412)) ### [static] FORWARD\_BUTTON : number The X2 button. This is typically the mouse Forward button, but is often reconfigured. On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 405](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L405)) ### [static] LEFT\_BUTTON : number The Left Mouse button, or in PointerEvent devices a Touch contact or Pen contact. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 375](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L375)) ### [static] MIDDLE\_BUTTON : number The Middle Mouse button. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 389](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L389)) ### [static] NO\_BUTTON : number No buttons at all. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 368](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L368)) ### [static] RIGHT\_BUTTON : number The Right Mouse button, or in PointerEvent devices a Pen contact with a barrel button. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 382](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L382)) ### active : boolean An active pointer is one that is currently pressed down on the display. A Mouse is always active. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 316](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L316)) ### backButton : [Phaser.DeviceButton](phaser.devicebutton) If this Pointer is a Mouse or Pen / Stylus then you can access its X1 (back) button directly through this property. The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained button control. Please see the DeviceButton docs for details on browser button limitations. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 120](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L120)) ### button :any The button property of the most recent DOM event when this Pointer is started. You should not rely on this value for accurate button detection, instead use the Pointer properties `leftButton`, `rightButton`, `middleButton` and so on. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L70)) ### circle : [Phaser.Circle](phaser.circle) A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection. The Circle size is 44px (Apples recommended "finger tip" size). Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 344](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L344)) ### clientX : number The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 181](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L181)) ### clientY : number The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 186](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L186)) ### dirty : boolean A dirty pointer needs to re-poll any interactive objects it may have been over, regardless if it has moved or not. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 322](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L322)) ### [readonly] duration : number How long the Pointer has been depressed on the touchscreen or *any* of the mouse buttons have been held down. If not currently down it returns -1. If you need to test a specific mouse or pen button then access the buttons directly, i.e. `Pointer.rightButton.duration`. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 1192](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L1192)) ### eraserButton : [Phaser.DeviceButton](phaser.devicebutton) If this Pointer is a Pen / Stylus then you can access its eraser button directly through this property. The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained button control. Please see the DeviceButton docs for details on browser button limitations. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L146)) ### exists : boolean A Pointer object that exists is allowed to be checked for physics collisions and overlaps. Default Value * true Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L38)) ### forwardButton : [Phaser.DeviceButton](phaser.devicebutton) If this Pointer is a Mouse or Pen / Stylus then you can access its X2 (forward) button directly through this property. The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained button control. Please see the DeviceButton docs for details on browser button limitations. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 133](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L133)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L21)) ### id : number The ID of the Pointer object within the game. Each game can have up to 10 active pointers. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L26)) ### identifier : number The identifier property of the Pointer as set by the DOM event when this Pointer is started. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L44)) ### interactiveCandidates :array This array is erased and re-populated every time this Pointer is updated. It contains references to all of the Game Objects that were considered as being valid for processing by this Pointer, this frame. To be valid they must have suitable a `priorityID`, be Input enabled, visible and actually have the Pointer over them. You can check the contents of this array in events such as `onInputDown`, but beware it is reset every frame. Default Value * [] Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 310](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L310)) ### isDown : boolean If the Pointer is touching the touchscreen, or *any* mouse or pen button is held down, isDown is set to true. If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isDown. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 255](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L255)) ### isMouse : boolean If the Pointer is a mouse or pen / stylus this is true, otherwise false. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 247](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L247)) ### isUp : boolean If the Pointer is not touching the touchscreen, or *all* mouse or pen buttons are up, isUp is set to true. If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isUp. Default Value * true Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 263](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L263)) ### leftButton : [Phaser.DeviceButton](phaser.devicebutton) If this Pointer is a Mouse or Pen / Stylus then you can access its left button directly through this property. The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained button control. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 81](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L81)) ### middleButton : [Phaser.DeviceButton](phaser.devicebutton) If this Pointer is a Mouse or Pen / Stylus then you can access its middle button directly through this property. The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained button control. Please see the DeviceButton docs for details on browser button limitations. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 94](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L94)) ### movementX : number The horizontal processed relative movement of the Pointer in pixels since last event. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 224](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L224)) ### movementY : number The vertical processed relative movement of the Pointer in pixels since last event. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 230](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L230)) ### msSinceLastClick : number The number of milliseconds since the last click or touch event. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 293](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L293)) ### pageX : number The horizontal coordinate of the Pointer relative to whole document. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L191)) ### pageY : number The vertical coordinate of the Pointer relative to whole document. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 196](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L196)) ### pointerId : number The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L50)) ### pointerMode : [Phaser.PointerMode](phaser.pointermode) The operational mode of this pointer. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L55)) ### position : [Phaser.Point](phaser.point) A Phaser.Point object containing the current x/y values of the pointer on the display. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 327](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L327)) ### positionDown : [Phaser.Point](phaser.point) A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 332](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L332)) ### positionUp : [Phaser.Point](phaser.point) A Phaser.Point object containing the x/y values of the pointer when it was last released. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 337](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L337)) ### previousTapTime : number A timestamp representing when the Pointer was last tapped or clicked. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 281](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L281)) ### rawMovementX : number The horizontal raw relative movement of the Pointer in pixels since last event. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 212](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L212)) ### rawMovementY : number The vertical raw relative movement of the Pointer in pixels since last event. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L218)) ### rightButton : [Phaser.DeviceButton](phaser.devicebutton) If this Pointer is a Mouse or Pen / Stylus then you can access its right button directly through this property. The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained button control. Please see the DeviceButton docs for details on browser button limitations. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L107)) ### screenX : number The horizontal coordinate of the Pointer relative to the screen. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 201](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L201)) ### screenY : number The vertical coordinate of the Pointer relative to the screen. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 206](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L206)) ### target :any The target property of the Pointer as set by the DOM event when this Pointer is started. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L61)) ### targetObject :any The Game Object this Pointer is currently over / touching / dragging. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 299](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L299)) ### timeDown : number A timestamp representing when the Pointer first touched the touchscreen. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 269](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L269)) ### timeUp : number A timestamp representing when the Pointer left the touchscreen. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 275](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L275)) ### totalTouches : number The total number of times this Pointer has been touched to the touchscreen. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 287](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L287)) ### [readonly] type : number The const type of this object. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 32](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L32)) ### withinGame : boolean true if the Pointer is over the game canvas, otherwise false. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 176](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L176)) ### [readonly] worldX : number Gets the X value of this Pointer in world coordinates based on the world camera. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 1216](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L1216)) ### [readonly] worldY : number Gets the Y value of this Pointer in world coordinates based on the world camera. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 1232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L1232)) ### x : number The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 236](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L236)) ### y : number The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 242](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L242)) Public Methods -------------- ### <internal> addClickTrampoline(name, callback, callbackContext, callbackArgs) Add a click trampoline to this pointer. A click trampoline is a callback that is run on the DOM 'click' event; this is primarily needed with certain browsers (ie. IE11) which restrict some actions like requestFullscreen to the DOM 'click' event and rejects it for 'pointer*' and 'mouse*' events. This is used internally by the ScaleManager; click trampoline usage is uncommon. Click trampolines can only be added to pointers that are currently down. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The name of the trampoline; must be unique among active trampolines in this pointer. | | `callback` | function | Callback to run/trampoline. | | `callbackContext` | object | Context of the callback. | | `callbackArgs` | Array.<object> | null | Additional callback args, if any. Supplied as an array. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 1073](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L1073)) ### justPressed(duration) → {boolean} The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate. Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `duration` | number | <optional> | The time to check against. If none given it will use InputManager.justPressedRate. | ##### Returns boolean - true if the Pointer was pressed down within the duration given. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 1041](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L1041)) ### justReleased(duration) → {boolean} The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate. Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `duration` | number | <optional> | The time to check against. If none given it will use InputManager.justReleasedRate. | ##### Returns boolean - true if the Pointer was released within the duration given. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 1057](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L1057)) ### leave(event) Called when the Pointer leaves the target area. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | MouseEvent | PointerEvent | TouchEvent | The event passed up from the input handler. | Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 945](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L945)) ### move(event, fromClick) Called when the Pointer is moved. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `event` | MouseEvent | PointerEvent | TouchEvent | | | The event passed up from the input handler. | | `fromClick` | boolean | <optional> | false | Was this called from the click event? | Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 709](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L709)) ### <internal> processInteractiveObjects(fromClick) → {boolean} Process all interactive objects to find out which ones were updated in the recent Pointer move. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `fromClick` | boolean | <optional> | false | Was this called from the click event? | ##### Returns boolean - True if this method processes an object (i.e. a Sprite becomes the Pointers currentTarget), otherwise false. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 806](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L806)) ### reset() Resets the Pointer properties. Called by InputManager.reset when you perform a State change. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 1147](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L1147)) ### <internal> resetButtons() Resets the states of all the button booleans. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 416](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L416)) ### resetMovement() Resets the movementX and movementY properties. Use in your update handler after retrieving the values. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 1177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L1177)) ### start(event) Called when the Pointer is pressed onto the touchscreen. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | any | The DOM event from the browser. | Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 587](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L587)) ### stop(event) Called when the Pointer leaves the touchscreen. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | MouseEvent | PointerEvent | TouchEvent | The event passed up from the input handler. | Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 958](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L958)) ### swapTarget(newTarget, silent) This will change the `Pointer.targetObject` object to be the one provided. This allows you to have fine-grained control over which object the Pointer is targeting. Note that even if you set a new Target here, it is still able to be replaced by any other valid target during the next Pointer update. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `newTarget` | [Phaser.InputHandler](phaser.inputhandler) | | | The new target for this Pointer. Note this is an `InputHandler`, so don't pass a Sprite, instead pass `sprite.input` to it. | | `silent` | boolean | <optional> | false | If true the new target AND the old one will NOT dispatch their `onInputOver` or `onInputOut` events. | Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 886](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L886)) ### update() Called by the Input Manager. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 657](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L657)) ### <internal> updateButtons(event) Called when the event.buttons property changes from zero. Contains a button bitmask. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | MouseEvent | The DOM event. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Pointer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js) ([Line 527](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Pointer.js#L527))
programming_docs
phaser Class: Phaser.AnimationManager Class: Phaser.AnimationManager ============================== Constructor ----------- ### new AnimationManager(sprite) The Animation Manager is used to add, play and update Phaser Animations. Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | A reference to the Game Object that owns this AnimationManager. | Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 15](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L15)) Public Properties ----------------- ### currentAnim : [Phaser.Animation](phaser.animation) The currently displayed animation, if any. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 40](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L40)) ### currentFrame : [Phaser.Frame](phaser.frame) The currently displayed Frame of animation, if any. This property is only set once an Animation starts playing. Until that point it remains set as `null`. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 34](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L34)) ### frame : number Gets or sets the current frame index and updates the Texture Cache for display. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 500](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L500)) ### [readonly] frameData : [Phaser.FrameData](phaser.framedata) The current animations FrameData. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 436](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L436)) ### frameName : string Gets or sets the current frame name and updates the Texture Cache for display. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 531](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L531)) ### [readonly] frameTotal : number The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L449)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L25)) ### isLoaded : boolean Set to true once animation data has been loaded. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L52)) ### name : string Gets the current animation name, if set. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 483](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L483)) ### paused : boolean Gets and sets the paused state of the current animation. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 463](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L463)) ### sprite : [Phaser.Sprite](phaser.sprite) A reference to the parent Sprite that owns this AnimationManager. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L20)) ### updateIfVisible : boolean Should the animation data continue to update even if the Sprite.visible is set to false. Default Value * true Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L46)) Public Methods -------------- ### add(name, frames, frameRate, loop, useNumericIndex) → {[Phaser.Animation](phaser.animation)} Adds a new animation under the given key. Optionally set the frames, frame rate and loop. Animations added in this way are played back with the play function. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk". | | `frames` | Array | <optional> | null | An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. | | `frameRate` | number | <optional> | 60 | The speed at which the animation should play. The speed is given in frames per second. | | `loop` | boolean | <optional> | false | Whether or not the animation is looped or just plays once. | | `useNumericIndex` | boolean | <optional> | true | Are the given frames using numeric indexes (default) or strings? | ##### Returns [Phaser.Animation](phaser.animation) - The Animation object that was created. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 170](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L170)) ### destroy() Destroys all references this AnimationManager contains. Iterates through the list of animations stored in this manager and calls destroy on each of them. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 404](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L404)) ### getAnimation(name) → {[Phaser.Animation](phaser.animation)} Returns an animation that was previously added by name. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The name of the animation to be returned, e.g. "fire". | ##### Returns [Phaser.Animation](phaser.animation) - The Animation instance, if found, otherwise null. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 371](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L371)) ### next(quantity) Advances by the given number of frames in the current animation, taking the loop value into consideration. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `quantity` | number | <optional> | 1 | The number of frames to advance. | Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 339](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L339)) ### play(name, frameRate, loop, killOnComplete) → {[Phaser.Animation](phaser.animation)} Play an animation based on the given key. The animation should previously have been added via `animations.add` If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The name of the animation to be played, e.g. "fire", "walk", "jump". | | `frameRate` | number | <optional> | null | The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. | | `loop` | boolean | <optional> | false | Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. | | `killOnComplete` | boolean | <optional> | false | If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. | ##### Returns [Phaser.Animation](phaser.animation) - A reference to playing Animation instance. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 253](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L253)) ### previous(quantity) Moves backwards the given number of frames in the current animation, taking the loop value into consideration. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `quantity` | number | <optional> | 1 | The number of frames to move back. | Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 355](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L355)) ### refreshFrame() Refreshes the current frame data back to the parent Sprite and also resets the texture data. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 392](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L392)) ### stop(name, resetFrame) Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped. The currentAnim property of the AnimationManager is automatically set to the animation given. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | <optional> | null | The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped. | | `resetFrame` | boolean | <optional> | false | When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false) | Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 296](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L296)) ### <internal> update() → {boolean} The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events. ##### Returns boolean - True if a new animation frame has been set, otherwise false. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L315)) ### validateFrames(frames, useNumericIndex) → {boolean} Check whether the frames in the given array are valid and exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `frames` | Array | | | An array of frames to be validated. | | `useNumericIndex` | boolean | <optional> | true | Validate the frames based on their numeric index (true) or string index (false) | ##### Returns boolean - True if all given Frames are valid, otherwise false. Source code: [animation/AnimationManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js) ([Line 219](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/AnimationManager.js#L219)) phaser Class: Phaser.Particles.Arcade.Emitter Class: Phaser.Particles.Arcade.Emitter ====================================== Constructor ----------- ### new Emitter(game, x, y, maxParticles) Emitter is a lightweight particle emitter that uses Arcade Physics. It can be used for one-time explosions or for continuous effects like rain and fire. All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | Current game instance. | | `x` | number | <optional> | 0 | The x coordinate within the Emitter that the particles are emitted from. | | `y` | number | <optional> | 0 | The y coordinate within the Emitter that the particles are emitted from. | | `maxParticles` | number | <optional> | 50 | The total number of particles in this emitter. | Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L20)) Extends ------- * [Phaser.Group](phaser.group) Public Properties ----------------- ### alive : boolean The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. Inherited From * [Phaser.Group#alive](phaser.group#alive) Default Value * true Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L93)) ### alpha : number The alpha value of the group container. Inherited From * [Phaser.Group#alpha](phaser.group#alpha) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 3003](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L3003)) ### alphaData :array An array of the calculated alpha easing data applied to particles with alphaRates > 0. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 109](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L109)) ### angle : number The angle of rotation of the group container, in degrees. This adjusts the group itself by modifying its local rotation transform. This has no impact on the rotation/angle properties of the children, but it will update their worldTransform and on-screen orientation and position. Inherited From * [Phaser.Group#angle](phaser.group#angle) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2682](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2682)) ### angularDrag : number The angular drag component of particles launched from the emitter if they are rotating. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L132)) ### area : [Phaser.Rectangle](phaser.rectangle) The area of the emitter. Particles can be randomly generated from anywhere within this rectangle. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L51)) ### autoAlpha : boolean When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L193)) ### autoScale : boolean When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 188](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L188)) ### blendMode : number The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL) Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L167)) ### [readonly] bottom : number Gets the bottom position of the Emitter. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 990](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L990)) ### bounce : [Phaser.Point](phaser.point) How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L149)) ### cameraOffset : [Phaser.Point](phaser.point) If this object is [fixedToCamera](phaser.group#fixedToCamera) then this stores the x/y position offset relative to the top-left of the camera view. If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. Inherited From * [Phaser.Group#cameraOffset](phaser.group#cameraOffset) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 272](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L272)) ### centerX : number The center x coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#centerX](phaser.group#centerX) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2705](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2705)) ### centerY : number The center y coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#centerY](phaser.group#centerY) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2733](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2733)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### classType : Object The type of objects that will be created when using [create](phaser.group#create) or [createMultiple](phaser.group#createMultiple). Any object may be used but it should extend either Sprite or Image and accept the same constructor arguments: when a new object is created it is passed the following parameters to its constructor: `(game, x, y, key, frame)`. Inherited From * [Phaser.Group#classType](phaser.group#classType) Default Value * [Phaser.Sprite](phaser.sprite) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L130)) ### cursor : [DisplayObject](global#DisplayObject) The current display object that the group cursor is pointing to, if any. (Can be set manually.) The cursor is a way to iterate through the children in a Group using [next](phaser.group#next) and [previous](phaser.group#previous). Inherited From * [Phaser.Group#cursor](phaser.group#cursor) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L138)) ### [readonly] cursorIndex : integer The current index of the Group cursor. Advance it with Group.next. Inherited From * [Phaser.Group#cursorIndex](phaser.group#cursorIndex) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 255](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L255)) ### emitX : number The point the particles are emitted from. Emitter.x and Emitter.y control the containers location, which updates all current particles Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 175](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L175)) ### emitY : number The point the particles are emitted from. Emitter.x and Emitter.y control the containers location, which updates all current particles Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 183](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L183)) ### enableBody : boolean If true all Sprites created by, or added to this group, will have a physics body enabled on them. If there are children already in the Group at the time you set this property, they are not changed. The default body type is controlled with [physicsBodyType](phaser.group#physicsBodyType). Inherited From * [Phaser.Group#enableBody](phaser.group#enableBody) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 208](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L208)) ### enableBodyDebug : boolean If true when a physics body is created (via [enableBody](phaser.group#enableBody)) it will create a physics debug object as well. This only works for P2 bodies. Inherited From * [Phaser.Group#enableBodyDebug](phaser.group#enableBodyDebug) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L217)) ### exists : boolean If exists is true the group is updated, otherwise it is skipped. Inherited From * [Phaser.Group#exists](phaser.group#exists) Default Value * true Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L100)) ### fixedToCamera : boolean A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. Note that the cameraOffset values are in addition to any parent in the display list. So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x Inherited From * [Phaser.Group#fixedToCamera](phaser.group#fixedToCamera) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 265](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L265)) ### frequency : number How often a particle is emitted in ms (if emitter is started with Explode === false). Default Value * 100 Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L138)) ### <internal> game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Group#game](phaser.group#game) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L38)) ### gravity : number Sets the `body.gravity.y` of each particle sprite to this value on launch. Default Value * 100 Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L115)) ### hash :array The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. Only children of this Group can be added to and removed from the hash. This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own sorting and filtering of Group children without touching their z-index (and therefore display draw order) Inherited From * [Phaser.Group#hash](phaser.group#hash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 285](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L285)) ### height : number Gets or sets the height of the Emitter. This is the region in which a particle can be emitted. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 903](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L903)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### ignoreDestroy : boolean A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. Inherited From * [Phaser.Group#ignoreDestroy](phaser.group#ignoreDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L107)) ### inputEnableChildren : boolean A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` on any children *added* to, or *created by*, this Group. If there are children already in the Group at the time you set this property, they are not changed. Inherited From * [Phaser.Group#inputEnableChildren](phaser.group#inputEnableChildren) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L149)) ### [readonly] left : number Gets the left position of the Emitter. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 951](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L951)) ### [readonly] length : integer Total number of children in this group, regardless of exists/alive status. Inherited From * [Phaser.Group#length](phaser.group#length) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2665](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2665)) ### lifespan : number How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever. Default Value * 2000 Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L144)) ### maxParticleAlpha : number The maximum possible alpha value of a particle. Default Value * 1 Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L104)) ### maxParticles : number The total number of particles in this emitter. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L26)) ### maxParticleScale : number The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX. Default Value * 1 Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 75](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L75)) ### maxParticleSpeed : [Phaser.Point](phaser.point) The maximum possible velocity of a particle. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L63)) ### maxRotation : number The maximum possible angular velocity of a particle. Default Value * 360 Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 92](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L92)) ### minParticleAlpha : number The minimum possible alpha value of a particle. Default Value * 1 Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L98)) ### minParticleScale : number The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX. Default Value * 1 Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L69)) ### minParticleSpeed : [Phaser.Point](phaser.point) The minimum possible velocity of a particle. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L57)) ### minRotation : number The minimum possible angular velocity of a particle. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L86)) ### name : string A handy string name for this emitter. Can be set to anything. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L33)) ### on : boolean Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L155)) ### onChildInputDown : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputDown](phaser.group#onChildInputDown) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L161)) ### onChildInputOut : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputOut](phaser.group#onChildInputOut) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 198](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L198)) ### onChildInputOver : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputOver](phaser.group#onChildInputOver) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 186](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L186)) ### onChildInputUp : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer is still over the Sprite or not. Inherited From * [Phaser.Group#onChildInputUp](phaser.group#onChildInputUp) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 174](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L174)) ### onDestroy : [Phaser.Signal](phaser.signal) This signal is dispatched when the group is destroyed. Inherited From * [Phaser.Group#onDestroy](phaser.group#onDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 249](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L249)) ### particleAnchor : [Phaser.Point](phaser.point) When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation) Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L161)) ### particleBringToTop : boolean If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 199](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L199)) ### particleClass :any For emitting your own particle class types. They must extend Phaser.Particle. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 121](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L121)) ### particleDrag : [Phaser.Point](phaser.point) The X and Y drag component of particles launched from the emitter. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 126](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L126)) ### particleSendToBack : boolean If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 205](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L205)) ### pendingDestroy : boolean A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method called on the next logic update. You can set it directly to flag the Group to be destroyed on its next update. This is extremely useful if you wish to destroy a Group from within one of its own callbacks or a callback of one of its children. Inherited From * [Phaser.Group#pendingDestroy](phaser.group#pendingDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L119)) ### physicsBodyType : integer If [enableBody](phaser.group#enableBody) is true this is the type of physics body that is created on new Sprites. The valid values are [Phaser.Physics.ARCADE](phaser.physics#.ARCADE), [Phaser.Physics.P2JS](phaser.physics#.P2JS), [Phaser.Physics.NINJA](phaser.physics#.NINJA), etc. Inherited From * [Phaser.Group#physicsBodyType](phaser.group#physicsBodyType) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L225)) ### physicsSortDirection : integer If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. It should be set to one of the Phaser.Physics.Arcade sort direction constants: Phaser.Physics.Arcade.SORT\_NONE Phaser.Physics.Arcade.LEFT\_RIGHT Phaser.Physics.Arcade.RIGHT\_LEFT Phaser.Physics.Arcade.TOP\_BOTTOM Phaser.Physics.Arcade.BOTTOM\_TOP If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. Inherited From * [Phaser.Group#physicsSortDirection](phaser.group#physicsSortDirection) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 243](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L243)) ### [readonly] physicsType : number The const physics body type of this object. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L45)) ### [readonly] right : number Gets the right position of the Emitter. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 964](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L964)) ### rotation : number The angle of rotation of the group container, in radians. This will adjust the group container itself by modifying its rotation. This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. Inherited From * [Phaser.Group#rotation](phaser.group#rotation) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2987](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2987)) ### scaleData :array An array of the calculated scale easing data applied to particles with scaleRates > 0. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L80)) ### [readonly] top : number Gets the top position of the Emitter. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 977](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L977)) ### [readonly] total : integer Total number of existing children in the group. Inherited From * [Phaser.Group#total](phaser.group#total) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2648](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2648)) ### <internal> type : number Internal Phaser Type value. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 39](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L39)) ### visible : boolean The visible state of the group. Non-visible Groups and all of their children are not rendered. Inherited From * [Phaser.Group#visible](phaser.group#visible) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2996](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2996)) ### width : number Gets or sets the width of the Emitter. This is the region in which a particle can be emitted. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 887](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L887)) ### x : number Gets or sets the x position of the Emitter. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 919](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L919)) ### y : number Gets or sets the y position of the Emitter. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 935](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L935)) ### [readonly] z : integer The z-depth value of this object within its parent container/Group - the World is a Group as well. This value must be unique for each child in a Group. Inherited From * [Phaser.Group#z](phaser.group#z) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L57)) Public Methods -------------- ### add(child, silent, index) → {[DisplayObject](global#DisplayObject)} Adds an existing object as the top child in this group. The child is automatically added to the top of the group, and is displayed above every previous child. Or if the *optional* index is specified, the child is added at the location specified by the index value, this allows you to control child ordering. If the child was already in this Group, it is simply returned, and nothing else happens to it. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. Use [addAt](phaser.group#addAt) to control where a child is added. Use [create](phaser.group#create) to create and add a new child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | | The display object to add as a child. | | `silent` | boolean | <optional> | false | If true the child will not dispatch the `onAddedToGroup` event. | | `index` | integer | <optional> | | The index within the group to insert the child to. Where 0 is the bottom of the Group. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added to the group. Inherited From * [Phaser.Group#add](phaser.group#add) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 341](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L341)) ### addAll(property, amount, checkAlive, checkVisible) Adds the amount to the given property on all children in this group. `Group.addAll('x', 10)` will add 10 to the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to increment, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#addAll](phaser.group#addAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1386](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1386)) ### addAt(child, index, silent) → {[DisplayObject](global#DisplayObject)} Adds an existing object to this group. The child is added to the group at the location specified by the index value, this allows you to control child ordering. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | | The display object to add as a child. | | `index` | integer | <optional> | 0 | The index within the group to insert the child to. | | `silent` | boolean | <optional> | false | If true the child will not dispatch the `onAddedToGroup` event. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added to the group. Inherited From * [Phaser.Group#addAt](phaser.group#addAt) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 418](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L418)) ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### addMultiple(children, silent) → {Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group)} Adds an array of existing Display Objects to this Group. The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. As well as an array you can also pass another Group as the first argument. In this case all of the children from that Group will be removed from it and added into this Group. If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `children` | Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group) | | | An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. | | `silent` | boolean | <optional> | false | If true the children will not dispatch the `onAddedToGroup` event. | ##### Returns Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group) - The array of children or Group of children that were added to this Group. Inherited From * [Phaser.Group#addMultiple](phaser.group#addMultiple) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 489](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L489)) ### addToHash(child) → {boolean} Adds a child of this Group into the hash array. This call will return false if the child is not a child of this Group, or is already in the hash. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. | ##### Returns boolean - True if the child was successfully added to the hash, otherwise false. Inherited From * [Phaser.Group#addToHash](phaser.group#addToHash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 439](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L439)) ### align(width, height, cellWidth, cellHeight, position, offset) → {boolean} This method iterates through all children in the Group (regardless if they are visible or exist) and then changes their position so they are arranged in a Grid formation. Children must have the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have this. The grid dimensions are determined by the first four arguments. The `width` and `height` arguments relate to the width and height of the grid respectively. For example if the Group had 100 children in it: `Group.align(10, 10, 32, 32)` This will align all of the children into a grid formation of 10x10, using 32 pixels per grid cell. If you want a wider grid, you could do: `Group.align(25, 4, 32, 32)` This will align the children into a grid of 25x4, again using 32 pixels per grid cell. You can choose to set *either* the `width` or `height` value to -1. Doing so tells the method to keep on aligning children until there are no children left. For example if this Group had 48 children in it, the following: `Group.align(-1, 8, 32, 32)` ... will align the children so that there are 8 children vertically (the second argument), and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) You can also do: `Group.align(10, -1, 32, 32)` In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit all of the children in. The `position` property allows you to control where in each grid cell the child is positioned. This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. The final argument; `offset` lets you start the alignment from a specific child index. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `width` | integer | | | The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. | | `height` | integer | | | The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. | | `cellWidth` | integer | | | The width of each grid cell, in pixels. | | `cellHeight` | integer | | | The height of each grid cell, in pixels. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offset` | integer | <optional> | 0 | Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. | ##### Returns boolean - True if the Group children were aligned, otherwise false. Inherited From * [Phaser.Group#align](phaser.group#align) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 682](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L682)) ### alignIn(container, position, offsetX, offsetY) → {[Phaser.Group](phaser.group)} Aligns this Group within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Groups within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Group to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. Groups are placed in such a way that their *bounds* align with the container, taking into consideration rotation and scale of its children. This allows you to neatly align Groups, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Group. For example: `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns [Phaser.Group](phaser.group) - This Group. Inherited From * [Phaser.Group#alignIn](phaser.group#alignIn) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2873](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2873)) ### alignTo(parent, position, offsetX, offsetY) → {[Phaser.Group](phaser.group)} Aligns this Group to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Groups within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Group to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. Groups are placed in such a way that their *bounds* align with the parent, taking into consideration rotation and scale of the children. This allows you to neatly align Groups, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Group. For example: `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns [Phaser.Group](phaser.group) - This Group. Inherited From * [Phaser.Group#alignTo](phaser.group#alignTo) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2915](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2915)) ### <internal> ascendingSortHandler(a, b) An internal helper function for the sort process. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | object | The first object being sorted. | | `b` | object | The second object being sorted. | Inherited From * [Phaser.Group#ascendingSortHandler](phaser.group#ascendingSortHandler) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1919](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1919)) ### at(object) → {[Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter)} Change the emitters center to match the center of any object with a `center` property, such as a Sprite. If the object doesn't have a center property it will be set to object.x + object.width / 2 ##### Parameters | Name | Type | Description | | --- | --- | --- | | `object` | object | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.TileSprite](phaser.tilesprite) | [Phaser.Text](phaser.text) | PIXI.DisplayObject | The object that you wish to match the center with. | ##### Returns [Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter) - This Emitter instance. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 862](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L862)) ### bringToTop(child) → {any} Brings the given child to the top of this group so it renders above all other children. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to bring to the top of this group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#bringToTop](phaser.group#bringToTop) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 907](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L907)) ### callAll(method, context, args) Calls a function, specified by name, on all on children. The function is called for all children regardless if they are dead or alive (see callAllExists for different options). After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `method` | string | | | Name of the function on the child to call. Deep property lookup is supported. | | `context` | string | <optional> | null | A string containing the context under which the method will be executed. Set to null to default to the child. | | `args` | any | <repeatable> | | Additional parameters that will be passed to the method. | Inherited From * [Phaser.Group#callAll](phaser.group#callAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1538](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1538)) ### callAllExists(callback, existsValue, parameter) Calls a function, specified by name, on all children in the group who exist (or do not exist). After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `callback` | string | | Name of the function on the children to call. | | `existsValue` | boolean | | Only children with exists=existsValue will be called. | | `parameter` | any | <repeatable> | Additional parameters that will be passed to the callback. | Inherited From * [Phaser.Group#callAllExists](phaser.group#callAllExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1454](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1454)) ### <internal> callbackFromArray(child, callback, length) Returns a reference to a function that exists on a child of the group based on the given callback array. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | object | The object to inspect. | | `callback` | array | The array of function names. | | `length` | integer | The size of the array (pre-calculated in callAll). | Inherited From * [Phaser.Group#callbackFromArray](phaser.group#callbackFromArray) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1488](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1488)) ### checkAll(key, value, checkAlive, checkVisible, force) Quickly check that the same property across all children of this group is equal to the given value. This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be checked. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be checked. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be checked. This includes any Groups that are children. | | `force` | boolean | <optional> | false | If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned. | Inherited From * [Phaser.Group#checkAll](phaser.group#checkAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1353](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1353)) ### checkProperty(child, key, value, force) → {boolean} Checks a property for the given value on the child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to check the property value on. | | `key` | array | | | An array of strings that make up the property that will be set. | | `value` | any | | | The value that will be checked. | | `force` | boolean | <optional> | false | If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned. | ##### Returns boolean - True if the property was was equal to value, false if not. Inherited From * [Phaser.Group#checkProperty](phaser.group#checkProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1217)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### countDead() → {integer} Get the number of dead children in this group. ##### Returns integer - The number of children flagged as dead. Inherited From * [Phaser.Group#countDead](phaser.group#countDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2338)) ### countLiving() → {integer} Get the number of living children in this group. ##### Returns integer - The number of children flagged as alive. Inherited From * [Phaser.Group#countLiving](phaser.group#countLiving) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2326](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2326)) ### create(x, y, key, frame, exists, index) → {[DisplayObject](global#DisplayObject)} Creates a new Phaser.Sprite object and adds it to the top of this group. Use [classType](phaser.group#classType) to change the type of object created. The child is automatically added to the top of the group, and is displayed above every previous child. Or if the *optional* index is specified, the child is added at the location specified by the index value, this allows you to control child ordering. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. | | `y` | number | | | The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `exists` | boolean | <optional> | true | The default exists state of the Sprite. | | `index` | integer | <optional> | | The index within the group to insert the child to. Where 0 is the bottom of the Group. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was created: will be a [Phaser.Sprite](phaser.sprite) unless #classType has been changed. Inherited From * [Phaser.Group#create](phaser.group#create) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 544](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L544)) ### createMultiple(quantity, key, frame, exists) → {array} Creates multiple Phaser.Sprite objects and adds them to the top of this Group. This method is useful if you need to quickly generate a pool of sprites, such as bullets. Use [classType](phaser.group#classType) to change the type of object created. You can provide an array as the `key` and / or `frame` arguments. When you do this it will create `quantity` Sprites for every key (and frame) in the arrays. For example: `createMultiple(25, ['ball', 'carrot'])` In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be created in total, 25 of each. You can also have the `frame` as an array: `createMultiple(5, 'bricks', [0, 1, 2, 3])` In the above there is one key (bricks), which is a sprite sheet. The frames array tells this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with frame 1, and so on. If you set both the key and frame arguments to be arrays then understand it will create a total quantity of sprites equal to the size of both arrays times each other. I.e.: `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. In total it will have created 120 sprites. By default the Sprites will have their `exists` property set to `false`, and they will be positioned at 0x0, relative to the `Group.x / y` values. If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `quantity` | integer | | | The number of Sprites to create. | | `key` | string | array | | | The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. | | `frame` | integer | string | array | <optional> | 0 | If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. | | `exists` | boolean | <optional> | false | The default exists state of the Sprite. | ##### Returns array - An array containing all of the Sprites that were created. Inherited From * [Phaser.Group#createMultiple](phaser.group#createMultiple) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 581](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L581)) ### customSort(sortHandler, context) Sort the children in the group according to custom sort function. The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `sortHandler` | function | | The custom sort function. | | `context` | object | <optional> | The context in which the sortHandler is called. | Inherited From * [Phaser.Group#customSort](phaser.group#customSort) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1895](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1895)) ### <internal> descendingSortHandler(a, b) An internal helper function for the sort process. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | object | The first object being sorted. | | `b` | object | The second object being sorted. | Inherited From * [Phaser.Group#descendingSortHandler](phaser.group#descendingSortHandler) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1951](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1951)) ### destroy() Destroys this Emitter, all associated child Particles and then removes itself from the Particle Manager. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 681](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L681)) ### divideAll(property, amount, checkAlive, checkVisible) Divides the given property by the amount on all children in this group. `Group.divideAll('x', 2)` will half the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to divide, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#divideAll](phaser.group#divideAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1437)) ### emitParticle(x, y, key, frame) → {boolean} This function is used internally to emit the next particle in the queue. However it can also be called externally to emit a particle. When called externally you can use the arguments to override any defaults the Emitter has set. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | <optional> | The x coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitX` or if the Emitter has a width > 1 a random value between `Emitter.left` and `Emitter.right`. | | `y` | number | <optional> | The y coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitY` or if the Emitter has a height > 1 a random value between `Emitter.top` and `Emitter.bottom`. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns boolean - True if a particle was emitted, otherwise false. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 553](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L553)) ### explode(lifespan, quantity) → {[Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter)} Call this function to emit the given quantity of particles at all once (an explosion) ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `lifespan` | number | <optional> | 0 | How long each particle lives once emitted in ms. 0 = forever. | | `quantity` | number | <optional> | 0 | How many particles to launch. | ##### Returns [Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter) - This Emitter instance. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 438](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L438)) ### filter(predicate, checkExists) → {[Phaser.ArraySet](phaser.arrayset)} Find children matching a certain predicate. For example: ``` var healthyList = Group.filter(function(child, index, children) { return child.health > 10 ? true : false; }, true); healthyList.callAll('attack'); ``` Note: Currently this will skip any children which are Groups themselves. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `predicate` | function | | | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third | | `checkExists` | boolean | <optional> | false | If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. | ##### Returns [Phaser.ArraySet](phaser.arrayset) - Returns an array list containing all the children that the predicate returned true for Inherited From * [Phaser.Group#filter](phaser.group#filter) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1677](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1677)) ### flow(lifespan, frequency, quantity, total, immediate) → {[Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter)} Call this function to start emitting a flow of particles at the given frequency. It will carry on going until the total given is reached. Each time the flow is run the quantity number of particles will be emitted together. If you set the total to be 20 and quantity to be 5 then flow will emit 4 times in total (4 x 5 = 20 total) If you set the total to be -1 then no quantity cap is used and it will keep emitting. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `lifespan` | number | <optional> | 0 | How long each particle lives once emitted in ms. 0 = forever. | | `frequency` | number | <optional> | 250 | Frequency is how often to emit the particles, given in ms. | | `quantity` | number | <optional> | 1 | How many particles to launch each time the frequency is met. Can never be > Emitter.maxParticles. | | `total` | number | <optional> | -1 | How many particles to launch in total. If -1 it will carry on indefinitely. | | `immediate` | boolean | <optional> | true | Should the flow start immediately (true) or wait until the first frequency event? (false) | ##### Returns [Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter) - This Emitter instance. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 456](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L456)) ### forEach(callback, callbackContext, checkExists, args) Call a function on each child in this group. Additional arguments for the callback can be specified after the `checkExists` parameter. For example, ``` Group.forEach(awardBonusGold, this, true, 100, 500) ``` would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. Note: This check will skip any children which are Groups themselves. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `checkExists` | boolean | <optional> | false | If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEach](phaser.group#forEach) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1717](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1717)) ### forEachAlive(callback, callbackContext, args) Call a function on each alive child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachAlive](phaser.group#forEachAlive) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1799](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1799)) ### forEachDead(callback, callbackContext, args) Call a function on each dead child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachDead](phaser.group#forEachDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1827](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1827)) ### forEachExists(callback, callbackContext, args) Call a function on each existing child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachExists](phaser.group#forEachExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1771](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1771)) ### getAll(property, value, startIndex, endIndex) → {any} Returns all children in this Group. You can optionally specify a matching criteria using the `property` and `value` arguments. For example: `getAll('exists', true)` would return only children that have their exists property set. Optionally you can specify a start and end index. For example if this Group had 100 children, and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only the first 50 children in the Group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `property` | string | <optional> | | An optional property to test against the value argument. | | `value` | any | <optional> | | If property is set then Child.property must strictly equal this value to be included in the results. | | `startIndex` | integer | <optional> | 0 | The first child index to start the search from. | | `endIndex` | integer | <optional> | | The last child index to search up until. | ##### Returns any - A random existing child of this Group. Inherited From * [Phaser.Group#getAll](phaser.group#getAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2392](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2392)) ### getAt(index) → {[DisplayObject](global#DisplayObject) | integer} Returns the child found at the given index within this group. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | integer | The index to return the child from. | ##### Returns [DisplayObject](global#DisplayObject) | integer - The child that was found at the given index, or -1 for an invalid index. Inherited From * [Phaser.Group#getAt](phaser.group#getAt) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 524](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L524)) ### getBottom() → {any} Returns the child at the bottom of this group. The bottom child the child being displayed (rendered) below every other child. ##### Returns any - The child at the bottom of the Group. Inherited From * [Phaser.Group#getBottom](phaser.group#getBottom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2221)) ### getBounds(targetCoordinateSpace) → {Rectangle} Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `targetCoordinateSpace` | PIXIDisplayObject | PIXIMatrix | <optional> | Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. | ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getBounds](pixi.displayobjectcontainer#getBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 280](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L280)) ### getByName(name) → {any} Searches the Group for the first instance of a child with the `name` property matching the given argument. Should more than one child have the same name only the first instance is returned. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The name to search for. | ##### Returns any - The first child with a matching name, or null if none were found. Inherited From * [Phaser.Group#getByName](phaser.group#getByName) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1042](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1042)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getClosestTo(object, callback, callbackContext) → {any} Get the closest child to given Object, with optional callback to filter children. This can be a Sprite, Group, Image or any object with public x and y properties. 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. You can use the optional `callback` argument to apply your own filter to the distance checks. If the child is closer then the previous child, it will be sent to `callback` as the first argument, with the distance as the second. The callback should return `true` if it passes your filtering criteria, otherwise it should return `false`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `object` | any | | The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. | | `callback` | function | <optional> | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. | | `callbackContext` | object | <optional> | The context in which the function should be called (usually 'this'). | ##### Returns any - The child closest to given object, or `null` if no child was found. Inherited From * [Phaser.Group#getClosestTo](phaser.group#getClosestTo) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2238](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2238)) ### getFirstAlive(createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first child that is alive (`child.alive === true`). This is handy for choosing a squad leader, etc. You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `createIfNull` | boolean | <optional> | false | If `true` and no alive children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The alive dead child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstAlive](phaser.group#getFirstAlive) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2105](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2105)) ### getFirstDead(createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first child that is dead (`child.alive === false`). This is handy for checking if everything has been wiped out and adding to the pool as needed. You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `createIfNull` | boolean | <optional> | false | If `true` and no dead children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The first dead child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstDead](phaser.group#getFirstDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2135)) ### getFirstExists(exists, createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first display object that exists, or doesn't exist. You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `exists` | boolean | <optional> | true | If true, find the first existing child; otherwise find the first non-existing child. | | `createIfNull` | boolean | <optional> | false | If `true` and no alive children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The first child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstExists](phaser.group#getFirstExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2071](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2071)) ### getFurthestFrom(object, callback, callbackContext) → {any} Get the child furthest away from the given Object, with optional callback to filter children. This can be a Sprite, Group, Image or any object with public x and y properties. 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. You can use the optional `callback` argument to apply your own filter to the distance checks. If the child is closer then the previous child, it will be sent to `callback` as the first argument, with the distance as the second. The callback should return `true` if it passes your filtering criteria, otherwise it should return `false`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `object` | any | | The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. | | `callback` | function | <optional> | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. | | `callbackContext` | object | <optional> | The context in which the function should be called (usually 'this'). | ##### Returns any - The child furthest from the given object, or `null` if no child was found. Inherited From * [Phaser.Group#getFurthestFrom](phaser.group#getFurthestFrom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2282](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2282)) ### getIndex(child) → {integer} Get the index position of the given child in this group, which should match the child's `z` property. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to get the index for. | ##### Returns integer - The index of the child or -1 if it's not a member of this group. Inherited From * [Phaser.Group#getIndex](phaser.group#getIndex) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1029](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1029)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getLocalBounds](pixi.displayobjectcontainer#getLocalBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L437)) ### getRandom(startIndex, length) → {any} Returns a random child from the group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | <optional> | 0 | Offset from the front of the group (lowest child). | | `length` | integer | <optional> | (to top) | Restriction on the number of values you want to randomly select from. | ##### Returns any - A random child of this Group. Inherited From * [Phaser.Group#getRandom](phaser.group#getRandom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2350](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2350)) ### getRandomExists(startIndex, endIndex) → {any} Returns a random child from the Group that has `exists` set to `true`. Optionally you can specify a start and end index. For example if this Group had 100 children, and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only the first 50 children in the Group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | <optional> | 0 | The first child index to start the search from. | | `endIndex` | integer | <optional> | | The last child index to search up to. | ##### Returns any - A random child of this Group that exists. Inherited From * [Phaser.Group#getRandomExists](phaser.group#getRandomExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2372](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2372)) ### getTop() → {any} Return the child at the top of this group. The top child is the child displayed (rendered) above every other child. ##### Returns any - The child at the top of the Group. Inherited From * [Phaser.Group#getTop](phaser.group#getTop) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2204](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2204)) ### hasProperty(child, key) → {boolean} Checks if the child has the given property. Will scan up to 4 levels deep only. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to check for the existence of the property on. | | `key` | Array.<string> | An array of strings that make up the property. | ##### Returns boolean - True if the child has the property, otherwise false. Inherited From * [Phaser.Group#hasProperty](phaser.group#hasProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1104)) ### iterate(key, value, returnType, callback, callbackContext, args) → {any} Iterates over the children of the group performing one of several actions for matched children. A child is considered a match when it has a property, named `key`, whose value is equal to `value` according to a strict equality comparison. The result depends on the `returnType`: * [RETURN\_TOTAL](phaser.group#.RETURN_TOTAL): The callback, if any, is applied to all matching children. The number of matched children is returned. * [RETURN\_NONE](phaser.group#.RETURN_NONE): The callback, if any, is applied to all matching children. No value is returned. * [RETURN\_CHILD](phaser.group#.RETURN_CHILD): The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. If there is no matching child then null is returned. If `args` is specified it must be an array. The matched child will be assigned to the first element and the entire array will be applied to the callback function. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The child property to check, i.e. 'exists', 'alive', 'health' | | `value` | any | | | A child matches if `child[key] === value` is true. | | `returnType` | integer | | | How to iterate the children and what to return. | | `callback` | function | <optional> | null | Optional function that will be called on each matching child. The matched child is supplied as the first argument. | | `callbackContext` | object | <optional> | | The context in which the function should be called (usually 'this'). | | `args` | Array.<any> | <optional> | (none) | The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. | ##### Returns any - Returns either an integer (for RETURN\_TOTAL), the first matched child (for RETURN\_CHILD), or null. Inherited From * [Phaser.Group#iterate](phaser.group#iterate) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1976](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1976)) ### kill() → {[Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter)} Call this function to turn off all the particles and the emitter. ##### Returns [Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter) - This Emitter instance. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 407](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L407)) ### makeParticles(keys, frames, quantity, collide, collideWorldBounds) → {[Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter)} This function generates a new set of particles for use by this emitter. The particles are stored internally waiting to be emitted via Emitter.start. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `keys` | array | string | | | A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random. | | `frames` | array | number | <optional> | 0 | A frame number, or array of frames that the sprite will use. If an array one is picked at random. | | `quantity` | number | <optional> | | The number of particles to generate. If not given it will use the value of Emitter.maxParticles. If the value is greater than Emitter.maxParticles it will use Emitter.maxParticles as the quantity. | | `collide` | boolean | <optional> | false | If you want the particles to be able to collide with other Arcade Physics bodies then set this to true. | | `collideWorldBounds` | boolean | <optional> | false | A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. | ##### Returns [Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter) - This Emitter instance. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 335](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L335)) ### moveAll(group, silent) → {[Phaser.Group](phaser.group)} Moves all children from this Group to the Group given. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `group` | [Phaser.Group](phaser.group) | | | The new Group to which the children will be moved to. | | `silent` | boolean | <optional> | false | If true the children will not dispatch the `onAddedToGroup` event for the new Group. | ##### Returns [Phaser.Group](phaser.group) - The Group to which all the children were moved. Inherited From * [Phaser.Group#moveAll](phaser.group#moveAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2479](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2479)) ### moveDown(child) → {any} Moves the given child down one place in this group unless it's already at the bottom. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to move down in the group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#moveDown](phaser.group#moveDown) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 969](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L969)) ### moveUp(child) → {any} Moves the given child up one place in this group unless it's already at the top. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to move up in the group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#moveUp](phaser.group#moveUp) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 945](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L945)) ### multiplyAll(property, amount, checkAlive, checkVisible) Multiplies the given property by the amount on all children in this group. `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to multiply, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#multiplyAll](phaser.group#multiplyAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1420](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1420)) ### next() → {any} Advances the group cursor to the next (higher) object in the group. If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#next](phaser.group#next) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 833](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L833)) ### <internal> postUpdate() The core postUpdate - as called by World. Inherited From * [Phaser.Group#postUpdate](phaser.group#postUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1656](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1656)) ### <internal> preUpdate() The core preUpdate - as called by World. Inherited From * [Phaser.Group#preUpdate](phaser.group#preUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1611](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1611)) ### previous() → {any} Moves the group cursor to the previous (lower) child in the group. If the cursor is at the start of the group (bottom child) it is moved to the end (top child). ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#previous](phaser.group#previous) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 862](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L862)) ### remove(child, destroy, silent) → {boolean} Removes the given child from this group. This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. If the group cursor was referring to the removed child it is updated to refer to the next child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to remove. | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on the removed child. | | `silent` | boolean | <optional> | false | If true the the child will not dispatch the `onRemovedFromGroup` event. | ##### Returns boolean - true if the child was removed from this group, otherwise false. Inherited From * [Phaser.Group#remove](phaser.group#remove) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2431](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2431)) ### removeAll(destroy, silent, destroyTexture) Removes all children from this Group, but does not remove the group from its parent. The children can be optionally destroyed as they are removed. You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on each removed child. | | `silent` | boolean | <optional> | false | If true the children will not dispatch their `onRemovedFromGroup` events. | | `destroyTexture` | boolean | <optional> | false | If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Inherited From * [Phaser.Group#removeAll](phaser.group#removeAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2508](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2508)) ### removeBetween(startIndex, endIndex, destroy, silent) Removes all children from this group whose index falls beteen the given startIndex and endIndex values. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | | | The index to start removing children from. | | `endIndex` | integer | <optional> | | The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on each removed child. | | `silent` | boolean | <optional> | false | If true the children will not dispatch their `onRemovedFromGroup` events. | Inherited From * [Phaser.Group#removeBetween](phaser.group#removeBetween) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2556](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2556)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### removeFromHash(child) → {boolean} Removes a child of this Group from the hash array. This call will return false if the child is not in the hash. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The display object to remove from this Groups hash. Must be a member of this Group and in the hash. | ##### Returns boolean - True if the child was successfully removed from the hash, otherwise false. Inherited From * [Phaser.Group#removeFromHash](phaser.group#removeFromHash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 464](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L464)) ### replace(oldChild, newChild) → {any} Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `oldChild` | any | The child in this group that will be replaced. | | `newChild` | any | The child to be inserted into this group. | ##### Returns any - Returns the oldChild that was replaced within this group. Inherited From * [Phaser.Group#replace](phaser.group#replace) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1065](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1065)) ### resetChild(child, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | The child to reset and/or load the texture on. | | `x` | number | <optional> | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was reset: usually a [Phaser.Sprite](phaser.sprite). Inherited From * [Phaser.Group#resetChild](phaser.group#resetChild) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2165)) ### resetCursor(index) → {any} Sets the group cursor to the first child in the group. If the optional index parameter is given it sets the cursor to the object at that index instead. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `index` | integer | <optional> | 0 | Set the cursor to point to a specific index. | ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#resetCursor](phaser.group#resetCursor) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 806](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L806)) ### reverse() Reverses all children in this group. This operation applies only to immediate children and does not propagate to subgroups. Inherited From * [Phaser.Group#reverse](phaser.group#reverse) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1015](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1015)) ### revive() → {[Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter)} Handy for bringing game objects "back to life". Just sets alive and exists back to true. ##### Returns [Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter) - This Emitter instance. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 423](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L423)) ### sendToBack(child) → {any} Sends the given child to the bottom of this group so it renders below all other children. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to send to the bottom of this group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#sendToBack](phaser.group#sendToBack) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 926](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L926)) ### set(child, key, value, checkAlive, checkVisible, operation, force) → {boolean} Quickly set a property on a single child of this group to a new value. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [Phaser.Sprite](phaser.sprite) | | | The child to set the property on. | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then the child will only be updated if alive=true. | | `checkVisible` | boolean | <optional> | false | If set then the child will only be updated if visible=true. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | ##### Returns boolean - True if the property was set, false if not. Inherited From * [Phaser.Group#set](phaser.group#set) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1246](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1246)) ### setAll(key, value, checkAlive, checkVisible, operation, force) Quickly set the same property across all children of this group to a new value. This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. If you need that ability please see `Group.setAllChildren`. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be updated. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be updated. This includes any Groups that are children. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | Inherited From * [Phaser.Group#setAll](phaser.group#setAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1277](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1277)) ### setAllChildren(key, value, checkAlive, checkVisible, operation, force) Quickly set the same property across all children of this group, and any child Groups, to a new value. If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. Unlike with `setAll` the property is NOT set on child Groups itself. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be updated. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be updated. This includes any Groups that are children. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | Inherited From * [Phaser.Group#setAllChildren](phaser.group#setAllChildren) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1312](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1312)) ### setAlpha(min, max, rate, ease, yoyo) → {[Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter)} A more compact way of setting the alpha constraints of the particles. The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max. If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `min` | number | <optional> | 1 | The minimum value for this range. | | `max` | number | <optional> | 1 | The maximum value for this range. | | `rate` | number | <optional> | 0 | The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two. | | `ease` | function | <optional> | Phaser.Easing.Linear.None | If you've set a rate > 0 this is the easing formula applied between the min and max values. | | `yoyo` | boolean | <optional> | false | If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) | ##### Returns [Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter) - This Emitter instance. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 769](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L769)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setProperty(child, key, value, operation, force) → {boolean} Sets a property to the given value on the child. The operation parameter controls how the value is set. The operations are: * 0: set the existing value to the given value; if force is `true` a new property will be created if needed * 1: will add the given value to the value already present. * 2: will subtract the given value from the value already present. * 3: will multiply the value already present by the given value. * 4: will divide the value already present by the given value. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to set the property value on. | | `key` | array | | | An array of strings that make up the property that will be set. | | `value` | any | | | The value that will be set. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | ##### Returns boolean - True if the property was set, false if not. Inherited From * [Phaser.Group#setProperty](phaser.group#setProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1139)) ### setRotation(min, max) → {[Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter)} A more compact way of setting the angular velocity constraints of the particles. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `min` | number | <optional> | 0 | The minimum value for this range. | | `max` | number | <optional> | 0 | The maximum value for this range. | ##### Returns [Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter) - This Emitter instance. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 749](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L749)) ### setScale(minX, maxX, minY, maxY, rate, ease, yoyo) → {[Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter)} A more compact way of setting the scale constraints of the particles. The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis. If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `minX` | number | <optional> | 1 | The minimum value of Particle.scale.x. | | `maxX` | number | <optional> | 1 | The maximum value of Particle.scale.x. | | `minY` | number | <optional> | 1 | The minimum value of Particle.scale.y. | | `maxY` | number | <optional> | 1 | The maximum value of Particle.scale.y. | | `rate` | number | <optional> | 0 | The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two. | | `ease` | function | <optional> | Phaser.Easing.Linear.None | If you've set a rate > 0 this is the easing formula applied between the min and max values. | | `yoyo` | boolean | <optional> | false | If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) | ##### Returns [Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter) - This Emitter instance. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 811](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L811)) ### setSize(width, height) → {[Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter)} A more compact way of setting the width and height of the emitter. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | number | The desired width of the emitter (particles are spawned randomly within these dimensions). | | `height` | number | The desired height of the emitter. | ##### Returns [Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter) - This Emitter instance. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 694](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L694)) ### setXSpeed(min, max) → {[Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter)} A more compact way of setting the X velocity range of the emitter. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `min` | number | <optional> | 0 | The minimum value for this range. | | `max` | number | <optional> | 0 | The maximum value for this range. | ##### Returns [Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter) - This Emitter instance. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 711](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L711)) ### setYSpeed(min, max) → {[Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter)} A more compact way of setting the Y velocity range of the emitter. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `min` | number | <optional> | 0 | The minimum value for this range. | | `max` | number | <optional> | 0 | The maximum value for this range. | ##### Returns [Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter) - This Emitter instance. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 730](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L730)) ### sort(key, order) Sort the children in the group according to a particular key and ordering. Call this function to sort the group according to a particular key value and order. For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | <optional> | 'z' | The name of the property to sort on. Defaults to the objects z-depth value. | | `order` | integer | <optional> | Phaser.Group.SORT\_ASCENDING | Order ascending ([SORT\_ASCENDING](phaser.group#.SORT_ASCENDING)) or descending ([SORT\_DESCENDING](phaser.group#.SORT_DESCENDING)). | Inherited From * [Phaser.Group#sort](phaser.group#sort) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1855](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1855)) ### start(explode, lifespan, frequency, quantity, forceQuantity) → {[Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter)} Call this function to start emitting particles. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `explode` | boolean | <optional> | true | Whether the particles should all burst out at once (true) or at the frequency given (false). | | `lifespan` | number | <optional> | 0 | How long each particle lives once emitted in ms. 0 = forever. | | `frequency` | number | <optional> | 250 | Ignored if Explode is set to true. Frequency is how often to emit 1 particle. Value given in ms. | | `quantity` | number | <optional> | 0 | How many particles to launch. 0 = "all of the particles" which will keep emitting until Emitter.maxParticles is reached. | | `forceQuantity` | number | <optional> | false | If `true` and creating a particle flow, the quantity emitted will be forced to the be quantity given in this call. This can never exceed Emitter.maxParticles. | ##### Returns [Phaser.Particles.Arcade.Emitter](phaser.particles.arcade.emitter) - This Emitter instance. Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 503](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L503)) ### subAll(property, amount, checkAlive, checkVisible) Subtracts the amount from the given property on all children in this group. `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to decrement, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#subAll](phaser.group#subAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1403](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1403)) ### swap(child1, child2) Swaps the position of two children in this group. Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child1` | any | The first child to swap. | | `child2` | any | The second child to swap. | Inherited From * [Phaser.Group#swap](phaser.group#swap) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 891](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L891)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### update() Called automatically by the game loop, decides when to launch particles and when to "die". Source code: [particles/arcade/Emitter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js) ([Line 266](https://github.com/photonstorm/phaser/tree/v2.6.2/src/particles/arcade/Emitter.js#L266)) ### <internal> updateZ() Internal method that re-applies all of the children's Z values. This must be called whenever children ordering is altered so that their `z` indices are correctly updated. Inherited From * [Phaser.Group#updateZ](phaser.group#updateZ) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 663](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L663)) ### xy(index, x, y) Positions the child found at the given index within this group to the given x and y coordinates. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | integer | The index of the child in the group to set the position of. | | `x` | number | The new x position of the child. | | `y` | number | The new y position of the child. | Inherited From * [Phaser.Group#xy](phaser.group#xy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 993](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L993))
programming_docs
phaser Class: Phaser.Sprite Class: Phaser.Sprite ==================== Constructor ----------- ### new Sprite(game, x, y, key, frame) Sprites are the lifeblood of your game, used for nearly everything visual. At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas. They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | | `x` | number | The x coordinate (in world space) to position the Sprite at. | | `y` | number | The y coordinate (in world space) to position the Sprite at. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [PIXI.Texture](pixi.texture) | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. | | `frame` | string | number | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | Source code: [gameobjects/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js#L44)) Extends ------- * [PIXI.Sprite](pixi.sprite) * [Phaser.Component.Core](phaser.component.core) * [Phaser.Component.Angle](phaser.component.angle) * [Phaser.Component.Animation](phaser.component.animation) * [Phaser.Component.AutoCull](phaser.component.autocull) * [Phaser.Component.Bounds](phaser.component.bounds) * [Phaser.Component.BringToTop](phaser.component.bringtotop) * [Phaser.Component.Crop](phaser.component.crop) * [Phaser.Component.Delta](phaser.component.delta) * [Phaser.Component.Destroy](phaser.component.destroy) * [Phaser.Component.FixedToCamera](phaser.component.fixedtocamera) * [Phaser.Component.Health](phaser.component.health) * [Phaser.Component.InCamera](phaser.component.incamera) * [Phaser.Component.InputEnabled](phaser.component.inputenabled) * [Phaser.Component.InWorld](phaser.component.inworld) * [Phaser.Component.LifeSpan](phaser.component.lifespan) * [Phaser.Component.LoadTexture](phaser.component.loadtexture) * [Phaser.Component.Overlap](phaser.component.overlap) * [Phaser.Component.PhysicsBody](phaser.component.physicsbody) * [Phaser.Component.Reset](phaser.component.reset) * [Phaser.Component.ScaleMinMax](phaser.component.scaleminmax) * [Phaser.Component.Smoothed](phaser.component.smoothed) Public Properties ----------------- ### alive : boolean A useful flag to control if the Game Object is alive or dead. This is set automatically by the Health components `damage` method should the object run out of health. Or you can toggle it via your game code. This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. Inherited From * [Phaser.Component.LifeSpan#alive](phaser.component.lifespan#alive) Default Value * true Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L50)) ### anchor :Point The anchor sets the origin point of the texture. The default is 0,0 this means the texture's origin is the top left Setting than anchor to 0.5,0.5 means the textures origin is centered Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner Inherited From * [PIXI.Sprite#anchor](pixi.sprite#anchor) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L17)) ### angle : number The angle property is the rotation of the Game Object in *degrees* from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. If you wish to work in radians instead of degrees you can use the property `rotation` instead. Working in radians is slightly faster as it doesn't have to perform any calculations. Inherited From * [Phaser.Component.Angle#angle](phaser.component.angle#angle) Source code: [gameobjects/components/Angle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Angle.js#L29)) ### animations : [Phaser.AnimationManager](phaser.animationmanager) If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. Through it you can create, play, pause and stop animations. Inherited From * [Phaser.Component.Core#animations](phaser.component.core#animations) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 193](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L193)) See * [Phaser.AnimationManager](phaser.animationmanager) ### autoCull : boolean A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.AutoCull#autoCull](phaser.component.autocull#autoCull) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L28)) ### blendMode : number The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. Inherited From * [PIXI.Sprite#blendMode](pixi.sprite#blendMode) Default Value * PIXI.blendModes.NORMAL; Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L82)) ### body : [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated properties and methods via it. By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, so the physics body is centered on the Game Object. If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. ##### Type * [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | [Phaser.Physics.Ninja.Body](phaser.physics.ninja.body) | null Inherited From * [Phaser.Component.PhysicsBody#body](phaser.component.physicsbody#body) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L91)) ### bottom : number The sum of the y and height properties. This is the same as `y + height - offsetY`. Inherited From * [Phaser.Component.Bounds#bottom](phaser.component.bounds#bottom) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 168](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L168)) ### cameraOffset : [Phaser.Point](phaser.point) The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. Inherited From * [Phaser.Component.FixedToCamera#cameraOffset](phaser.component.fixedtocamera#cameraOffset) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L86)) ### centerX : number The center x coordinate of the Game Object. This is the same as `(x - offsetX) + (width / 2)`. Inherited From * [Phaser.Component.Bounds#centerX](phaser.component.bounds#centerX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L58)) ### centerY : number The center y coordinate of the Game Object. This is the same as `(y - offsetY) + (height / 2)`. Inherited From * [Phaser.Component.Bounds#centerY](phaser.component.bounds#centerY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L80)) ### checkWorldBounds : boolean If this is set to `true` the Game Object checks if it is within the World bounds each frame. When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. It also optionally kills the Game Object if `outOfBoundsKill` is `true`. When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Inherited From * [Phaser.Component.InWorld#checkWorldBounds](phaser.component.inworld#checkWorldBounds) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L98)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### <internal> components : Object The components this Game Object has installed. Inherited From * [Phaser.Component.Core#components](phaser.component.core#components) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L167)) ### cropRect : [Phaser.Rectangle](phaser.rectangle) The Rectangle used to crop the texture this Game Object uses. Set this property via `crop`. If you modify this property directly you must call `updateCrop` in order to have the change take effect. Inherited From * [Phaser.Component.Crop#cropRect](phaser.component.crop#cropRect) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L24)) ### damage Damages the Game Object. This removes the given amount of health from the `health` property. If health is taken below or is equal to zero then the `kill` method is called. Inherited From * [Phaser.Component.Health#damage](phaser.component.health#damage) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L46)) ### data : Object An empty Object that belongs to this Game Object. This value isn't ever used internally by Phaser, but may be used by your own code, or by Phaser Plugins, to store data that needs to be associated with the Game Object, without polluting the Game Object directly. Inherited From * [Phaser.Component.Core#data](phaser.component.core#data) Default Value * {} Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L160)) ### debug : boolean A debug flag designed for use with `Game.enableStep`. Inherited From * [Phaser.Component.Core#debug](phaser.component.core#debug) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L218)) ### [readonly] deltaX : number Returns the delta x value. The difference between world.x now and in the previous frame. The value will be positive if the Game Object has moved to the right or negative if to the left. Inherited From * [Phaser.Component.Delta#deltaX](phaser.component.delta#deltaX) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L24)) ### [readonly] deltaY : number Returns the delta y value. The difference between world.y now and in the previous frame. The value will be positive if the Game Object has moved down or negative if up. Inherited From * [Phaser.Component.Delta#deltaY](phaser.component.delta#deltaY) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L42)) ### [readonly] deltaZ : number Returns the delta z value. The difference between rotation now and in the previous frame. The delta value. Inherited From * [Phaser.Component.Delta#deltaZ](phaser.component.delta#deltaZ) Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L58)) ### [readonly] destroyPhase : boolean As a Game Object runs through its destroy method this flag is set to true, and can be checked in any sub-systems or plugins it is being destroyed from. Inherited From * [Phaser.Component.Destroy#destroyPhase](phaser.component.destroy#destroyPhase) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L22)) ### events : [Phaser.Events](phaser.events) All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this Game Object, or any of its components. Inherited From * [Phaser.Component.Core#events](phaser.component.core#events) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L185)) See * [Phaser.Events](phaser.events) ### exists : boolean Controls if this Sprite is processed by the core Phaser game loops and Group loops. Inherited From * [PIXI.Sprite#exists](pixi.sprite#exists) Default Value * true Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L103)) ### fixedToCamera : boolean A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering. The values are adjusted at the rendering stage, overriding the Game Objects actual world position. The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times regardless where in the world the camera is. The offsets are stored in the `cameraOffset` property. Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. Inherited From * [Phaser.Component.FixedToCamera#fixedToCamera](phaser.component.fixedtocamera#fixedToCamera) Source code: [gameobjects/components/FixedToCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/FixedToCamera.js#L56)) ### frame : integer Gets or sets the current frame index of the texture being used to render this Game Object. To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, for example: `player.frame = 4`. If the frame index given doesn't exist it will revert to the first frame found in the texture. If you are using a texture atlas then you should use the `frameName` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frame](phaser.component.loadtexture#frame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 254](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L254)) ### frameName : string Gets or sets the current frame name of the texture being used to render this Game Object. To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, for example: `player.frameName = "idle"`. If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. If you are using a sprite sheet then you should use the `frame` property instead. If you wish to fully replace the texture being used see `loadTexture`. Inherited From * [Phaser.Component.LoadTexture#frameName](phaser.component.loadtexture#frameName) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 279](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L279)) ### [readonly] fresh : boolean A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. This property is mostly used internally by the physics systems, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#fresh](phaser.component.core#fresh) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 248](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L248)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Component.Core#game](phaser.component.core#game) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L142)) ### heal Heal the Game Object. This adds the given amount of health to the `health` property. Inherited From * [Phaser.Component.Health#heal](phaser.component.health#heal) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 90](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L90)) ### health : number The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. It can be used in combination with the `damage` method or modified directly. Inherited From * [Phaser.Component.Health#health](phaser.component.health#health) Default Value * 1 Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L26)) ### height : number The height of the sprite, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.Sprite#height](pixi.sprite#height) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L144)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### [readonly] inCamera : boolean Checks if the Game Objects bounds intersect with the Game Camera bounds. Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. Inherited From * [Phaser.Component.AutoCull#inCamera](phaser.component.autocull#inCamera) Source code: [gameobjects/components/AutoCull.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/AutoCull.js#L37)) ### input : [Phaser.InputHandler](phaser.inputhandler) | null The Input Handler for this Game Object. By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. After you have done this, this property will be a reference to the Phaser InputHandler. ##### Type * [Phaser.InputHandler](phaser.inputhandler) | null Inherited From * [Phaser.Component.InputEnabled#input](phaser.component.inputenabled#input) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L24)) ### inputEnabled : boolean By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created for this Game Object and it will then start to process click / touch events and more. You can then access the Input Handler via `this.input`. Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. If you set this property to false it will stop the Input Handler from processing any more input events. If you want to *temporarily* disable input for a Game Object, then it's better to set `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. You can then toggle this back on as needed. Inherited From * [Phaser.Component.InputEnabled#inputEnabled](phaser.component.inputenabled#inputEnabled) Source code: [gameobjects/components/InputEnabled.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InputEnabled.js#L42)) ### [readonly] inWorld : boolean Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. Inherited From * [Phaser.Component.InWorld#inWorld](phaser.component.inworld#inWorld) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L129)) ### key : string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) The key of the image or texture used by this Game Object during rendering. If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. ##### Type * string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) Inherited From * [Phaser.Component.Core#key](phaser.component.core#key) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L203)) ### left : number The left coordinate of the Game Object. This is the same as `x - offsetX`. Inherited From * [Phaser.Component.Bounds#left](phaser.component.bounds#left) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L102)) ### lifespan : number The lifespan allows you to give a Game Object a lifespan in milliseconds. Once the Game Object is 'born' you can set this to a positive value. It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. When it reaches zero it will call the `kill` method. Very handy for particles, bullets, collectibles, or any other short-lived entity. Inherited From * [Phaser.Component.LifeSpan#lifespan](phaser.component.lifespan#lifespan) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 65](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L65)) ### maxHealth : number The Game Objects maximum health value. This works in combination with the `heal` method to ensure the health value never exceeds the maximum. Inherited From * [Phaser.Component.Health#maxHealth](phaser.component.health#maxHealth) Default Value * 100 Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L35)) ### name : string A user defined name given to this Game Object. This value isn't ever used internally by Phaser, it is meant as a game level property. Inherited From * [Phaser.Component.Core#name](phaser.component.core#name) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L150)) ### [readonly] offsetX : number The amount the Game Object is visually offset from its x coordinate. This is the same as `width * anchor.x`. It will only be > 0 if anchor.x is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetX](phaser.component.bounds#offsetX) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L24)) ### [readonly] offsetY : number The amount the Game Object is visually offset from its y coordinate. This is the same as `height * anchor.y`. It will only be > 0 if anchor.y is not equal to zero. Inherited From * [Phaser.Component.Bounds#offsetY](phaser.component.bounds#offsetY) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L42)) ### outOfBoundsKill : boolean If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. Inherited From * [Phaser.Component.InWorld#outOfBoundsKill](phaser.component.inworld#outOfBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L106)) ### outOfCameraBoundsKill : boolean If this and the `autoCull` property are both set to `true`, then the `kill` method is called as soon as the Game Object leaves the camera bounds. Inherited From * [Phaser.Component.InWorld#outOfCameraBoundsKill](phaser.component.inworld#outOfCameraBoundsKill) Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L115)) ### pendingDestroy : boolean A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. You can set it directly to allow you to flag an object to be destroyed on its next update. This is extremely useful if you wish to destroy an object from within one of its own callbacks such as with Buttons or other Input events. Inherited From * [Phaser.Component.Core#pendingDestroy](phaser.component.core#pendingDestroy) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L259)) ### [readonly] physicsType : number The const physics body type of this object. Source code: [gameobjects/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js#L61)) ### [readonly] previousPosition : [Phaser.Point](phaser.point) The position the Game Object was located in the previous frame. Inherited From * [Phaser.Component.Core#previousPosition](phaser.component.core#previousPosition) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L225)) ### [readonly] previousRotation : number The rotation the Game Object was in set to in the previous frame. Value is in radians. Inherited From * [Phaser.Component.Core#previousRotation](phaser.component.core#previousRotation) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L232)) ### [readonly] renderOrderID : number The render order ID is used internally by the renderer and Input Manager and should not be modified. This property is mostly used internally by the renderers, but is exposed for the use of plugins. Inherited From * [Phaser.Component.Core#renderOrderID](phaser.component.core#renderOrderID) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L240)) ### right : number The right coordinate of the Game Object. This is the same as `x + width - offsetX`. Inherited From * [Phaser.Component.Bounds#right](phaser.component.bounds#right) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L124)) ### scaleMax : [Phaser.Point](phaser.point) The maximum scale this Game Object will scale up to. It allows you to prevent a parent from scaling this Game Object higher than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMax](phaser.component.scaleminmax#scaleMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L46)) ### scaleMin : [Phaser.Point](phaser.point) The minimum scale this Game Object will scale down to. It allows you to prevent a parent from scaling this Game Object lower than the given value. Set it to `null` to remove the limit. Inherited From * [Phaser.Component.ScaleMinMax#scaleMin](phaser.component.scaleminmax#scaleMin) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L36)) ### setHealth Sets the health property of the Game Object to the given amount. Will never exceed the `maxHealth` value. Inherited From * [Phaser.Component.Health#setHealth](phaser.component.health#setHealth) Source code: [gameobjects/components/Health.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Health.js#L70)) ### shader : [PIXI.AbstractFilter](pixi.abstractfilter) The shader that will be used to render this Sprite. Set to null to remove a current shader. Inherited From * [PIXI.Sprite#shader](pixi.sprite#shader) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L93)) ### smoothed : boolean Enable or disable texture smoothing for this Game Object. It only takes effect if the Game Object is using an image based texture. Smoothing is enabled by default. Inherited From * [Phaser.Component.Smoothed#smoothed](phaser.component.smoothed#smoothed) Source code: [gameobjects/components/Smoothed.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Smoothed.js#L25)) ### texture : [PIXI.Texture](pixi.texture) The texture that the sprite is using Inherited From * [PIXI.Sprite#texture](pixi.sprite#texture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L28)) ### tint : number The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. Inherited From * [PIXI.Sprite#tint](pixi.sprite#tint) Default Value * 0xFFFFFF Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 54](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L54)) ### tintedTexture :Canvas A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) Inherited From * [PIXI.Sprite#tintedTexture](pixi.sprite#tintedTexture) Default Value * null Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L73)) ### top : number The y coordinate of the Game Object. This is the same as `y - offsetY`. Inherited From * [Phaser.Component.Bounds#top](phaser.component.bounds#top) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L146)) ### transformCallback : Function The callback that will apply any scale limiting to the worldTransform. Inherited From * [Phaser.Component.ScaleMinMax#transformCallback](phaser.component.scaleminmax#transformCallback) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L20)) ### transformCallbackContext : Object The context under which `transformCallback` is called. Inherited From * [Phaser.Component.ScaleMinMax#transformCallbackContext](phaser.component.scaleminmax#transformCallbackContext) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L26)) ### [readonly] type : number The const type of this object. Source code: [gameobjects/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js#L55)) ### width : number The width of the sprite, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.Sprite#width](pixi.sprite#width) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L125)) ### world : [Phaser.Point](phaser.point) The world coordinates of this Game Object in pixels. Depending on where in the display list this Game Object is placed this value can differ from `position`, which contains the x/y coordinates relative to the Game Objects parent. Inherited From * [Phaser.Component.Core#world](phaser.component.core#world) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 211](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L211)) ### x : number The position of the Game Object on the x axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#x](phaser.component.physicsbody#x) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L98)) ### y : number The position of the Game Object on the y axis relative to the local coordinates of the parent. Inherited From * [Phaser.Component.PhysicsBody#y](phaser.component.physicsbody#y) Source code: [gameobjects/components/PhysicsBody.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/PhysicsBody.js#L124)) ### [readonly] z : number The z depth of this Game Object within its parent Group. No two objects in a Group can have the same z value. This value is adjusted automatically whenever the Group hierarchy changes. If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. Inherited From * [Phaser.Component.Core#z](phaser.component.core#z) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L177)) Public Methods -------------- ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### alignIn(container, position, offsetX, offsetY) → {Object} Aligns this Game Object within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the container, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignIn](phaser.component.bounds#alignIn) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 223](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L223)) ### alignTo(parent, position, offsetX, offsetY) → {Object} Aligns this Game Object to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Sprite to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. The Game Objects are placed in such a way that their *bounds* align with the parent, taking into consideration rotation, scale and the anchor property. This allows you to neatly align Game Objects, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Game Object. For example: `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns Object - This Game Object. Inherited From * [Phaser.Component.Bounds#alignTo](phaser.component.bounds#alignTo) Source code: [gameobjects/components/Bounds.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js) ([Line 321](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Bounds.js#L321)) ### bringToTop() → {PIXI.DisplayObject} Brings this Game Object to the top of its parents display list. Visually this means it will render over the top of any old child in the same Group. If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#bringToTop](phaser.component.bringtotop#bringToTop) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L24)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### crop(rect, copy) Crop allows you to crop the texture being used to display this Game Object. Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, or by modifying `cropRect` property directly and then calling `updateCrop`. The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, in which case the values are duplicated to a local object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `rect` | [Phaser.Rectangle](phaser.rectangle) | | | The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. | | `copy` | boolean | <optional> | false | If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. | Inherited From * [Phaser.Component.Crop#crop](phaser.component.crop#crop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L49)) ### destroy(destroyChildren, destroyTexture) Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present and nulls its reference to `game`, freeing it up for garbage collection. If this Game Object has the Events component it will also dispatch the `onDestroy` event. You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | Should every child of this object have its destroy method called as well? | | `destroyTexture` | boolean | <optional> | false | Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Inherited From * [Phaser.Component.Destroy#destroy](phaser.component.destroy#destroy) Source code: [gameobjects/components/Destroy.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Destroy.js#L37)) ### getBounds(matrix) → {Rectangle} Returns the bounds of the Sprite as a rectangle. The bounds calculation takes the worldTransform into account. It is important to note that the transform is not updated when you call this method. So if this Sprite is the child of a Display Object which has had its transform updated since the last render pass, those changes will not yet have been applied to this Sprites worldTransform. If you need to ensure that all parent transforms are factored into this getBounds operation then you should call `updateTransform` on the root most object in this Sprites display list first. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `matrix` | Matrix | the transformation matrix of the sprite | ##### Returns Rectangle - the framing rectangle Inherited From * [PIXI.Sprite#getBounds](pixi.sprite#getBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 199](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L199)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.Sprite#getLocalBounds](pixi.sprite#getLocalBounds) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L315)) ### kill() → {PIXI.DisplayObject} Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. Note that killing a Game Object is a way for you to quickly recycle it in an object pool, it doesn't destroy the object or free it up from memory. If you don't need this Game Object any more you should call `destroy` instead. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#kill](phaser.component.lifespan#kill) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 113](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L113)) ### loadTexture(key, frame, stopAnimation) Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. You should only use `loadTexture` if you want to replace the base texture entirely. Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. Doing this then sets the key to be the `frame` argument (the frame is set to zero). This allows you to create sprites using `load.image` during development, and then change them to use a Texture Atlas later in development by simply searching your code for 'PENDING\_ATLAS' and swapping it to be the key of the atlas data. Note: You cannot use a RenderTexture as a texture for a TileSprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `stopAnimation` | boolean | <optional> | true | If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. | Inherited From * [Phaser.Component.LoadTexture#loadTexture](phaser.component.loadtexture#loadTexture) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L51)) ### moveDown() → {PIXI.DisplayObject} Moves this Game Object down one place in its parents display list. This call has no effect if the Game Object is already at the bottom of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveDown](phaser.component.bringtotop#moveDown) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L87)) ### moveUp() → {PIXI.DisplayObject} Moves this Game Object up one place in its parents display list. This call has no effect if the Game Object is already at the top of the display list. If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#moveUp](phaser.component.bringtotop#moveUp) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L66)) ### overlap(displayObject) → {boolean} Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. It should be fine for low-volume testing where physics isn't required. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.TileSprite](phaser.tilesprite) | [Phaser.Button](phaser.button) | PIXI.DisplayObject | The display object to check against. | ##### Returns boolean - True if the bounds of this Game Object intersects at any point with the bounds of the given display object. Inherited From * [Phaser.Component.Overlap#overlap](phaser.component.overlap#overlap) Source code: [gameobjects/components/Overlap.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Overlap.js#L29)) ### play(name, frameRate, loop, killOnComplete) → {[Phaser.Animation](phaser.animation)} Plays an Animation. The animation should have previously been created via `animations.add`. If the animation is already playing calling this again won't do anything. If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `name` | string | | | The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. | | `frameRate` | number | <optional> | null | The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. | | `loop` | boolean | <optional> | false | Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. | | `killOnComplete` | boolean | <optional> | false | If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. | ##### Returns [Phaser.Animation](phaser.animation) - A reference to playing Animation. Inherited From * [Phaser.Component.Animation#play](phaser.component.animation#play) Source code: [gameobjects/components/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js) ([Line 31](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Animation.js#L31)) ### <internal> postUpdate() Internal method called by the World postUpdate cycle. Inherited From * [Phaser.Component.Core#postUpdate](phaser.component.core#postUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L338)) ### preUpdate() → {boolean} Automatically called by World.preUpdate. ##### Returns boolean - True if the Sprite was rendered, otherwise false. Source code: [gameobjects/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/Sprite.js#L107)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### reset(x, y, health) → {PIXI.DisplayObject} Resets the Game Object. This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, `visible` and `renderable` to true. If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. If this Game Object has a Physics Body it will reset the Body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate (in world space) to position the Game Object at. | | `y` | number | | | The y coordinate (in world space) to position the Game Object at. | | `health` | number | <optional> | 1 | The health to give the Game Object if it has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.Reset#reset](phaser.component.reset#reset) Source code: [gameobjects/components/Reset.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Reset.js#L30)) ### resetFrame() Resets the texture frame dimensions that the Game Object uses for rendering. Inherited From * [Phaser.Component.LoadTexture#resetFrame](phaser.component.loadtexture#resetFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L232)) ### resizeFrame(parent, width, height) Resizes the Frame dimensions that the Game Object uses for rendering. You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData it can be useful to adjust the dimensions directly in this way. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `parent` | object | The parent texture object that caused the resize, i.e. a Phaser.Video object. | | `width` | integer | The new width of the texture. | | `height` | integer | The new height of the texture. | Inherited From * [Phaser.Component.LoadTexture#resizeFrame](phaser.component.loadtexture#resizeFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L220)) ### revive(health) → {PIXI.DisplayObject} Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `health` | number | <optional> | 100 | The health to give the Game Object. Only set if the GameObject has the Health component. | ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.LifeSpan#revive](phaser.component.lifespan#revive) Source code: [gameobjects/components/LifeSpan.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LifeSpan.js#L78)) ### sendToBack() → {PIXI.DisplayObject} Sends this Game Object to the bottom of its parents display list. Visually this means it will render below all other children in the same Group. If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, because the World is the root Group from which all Game Objects descend. ##### Returns PIXI.DisplayObject - This instance. Inherited From * [Phaser.Component.BringToTop#sendToBack](phaser.component.bringtotop#sendToBack) Source code: [gameobjects/components/BringToTop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/BringToTop.js#L45)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setFrame(frame) Sets the texture frame the Game Object uses for rendering. This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | [Phaser.Frame](phaser.frame) | The Frame to be used by the texture. | Inherited From * [Phaser.Component.LoadTexture#setFrame](phaser.component.loadtexture#setFrame) Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L155)) ### setScaleMinMax(minX, minY, maxX, maxY) Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. By setting these values you can carefully control how Game Objects deal with responsive scaling. If only one parameter is given then that value will be used for both scaleMin and scaleMax: `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, or pass `null` for the `maxX` and `maxY` parameters. Call `setScaleMinMax(null)` to clear all previously set values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `minX` | number | null | The minimum horizontal scale value this Game Object can scale down to. | | `minY` | number | null | The minimum vertical scale value this Game Object can scale down to. | | `maxX` | number | null | The maximum horizontal scale value this Game Object can scale up to. | | `maxY` | number | null | The maximum vertical scale value this Game Object can scale up to. | Inherited From * [Phaser.Component.ScaleMinMax#setScaleMinMax](phaser.component.scaleminmax#setScaleMinMax) Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L110)) ### setTexture(texture, destroy) Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous texture this Sprite was using. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `texture` | [PIXI.Texture](pixi.texture) | | | The PIXI texture that is displayed by the sprite | | `destroy` | Boolean | <optional> | false | Call Texture.destroy on the current texture before replacing it with the new one? | Inherited From * [PIXI.Sprite#setTexture](pixi.sprite#setTexture) Source code: [pixi/display/Sprite.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js) ([Line 163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/Sprite.js#L163)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### update() Override this method in your own custom objects to handle any update requirements. It is called immediately after `preUpdate` and before `postUpdate`. Remember if this Game Object has any children you should call update on those too. Inherited From * [Phaser.Component.Core#update](phaser.component.core#update) Source code: [gameobjects/components/Core.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js) ([Line 328](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Core.js#L328)) ### updateCrop() If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, or the rectangle it references, then you need to update the crop frame by calling this method. Inherited From * [Phaser.Component.Crop#updateCrop](phaser.component.crop#updateCrop) Source code: [gameobjects/components/Crop.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Crop.js#L86))
programming_docs
phaser Class: Phaser.PluginManager Class: Phaser.PluginManager =========================== Constructor ----------- ### new PluginManager(game) The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [core/PluginManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js) ([Line 16](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js#L16)) Public Properties ----------------- ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [core/PluginManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js#L21)) ### plugins : Array.<[Phaser.Plugin](phaser.plugin)> An array of all the plugins being managed by this PluginManager. ##### Type * Array.<[Phaser.Plugin](phaser.plugin)> Source code: [core/PluginManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js#L26)) Public Methods -------------- ### add(plugin, parameter) → {[Phaser.Plugin](phaser.plugin)} Add a new Plugin into the PluginManager. The Plugin must have 2 properties: game and parent. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `plugin` | object | [Phaser.Plugin](phaser.plugin) | | The Plugin to add into the PluginManager. This can be a function or an existing object. | | `parameter` | \* | <repeatable> | Additional arguments that will be passed to the Plugin.init method. | ##### Returns [Phaser.Plugin](phaser.plugin) - The Plugin that was added to the manager. Source code: [core/PluginManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js#L44)) ### destroy() Clear down this PluginManager, calls destroy on every plugin and nulls out references. Source code: [core/PluginManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js) ([Line 279](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js#L279)) ### postRender() Post-render is called after the Game Renderer and State.render have run. It only calls plugins who have visible=true. Source code: [core/PluginManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js#L259)) ### postUpdate() PostUpdate is the last thing to be called before the world render. In particular, it is called after the world postUpdate, which means the camera has been adjusted. It only calls plugins who have active=true. Source code: [core/PluginManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js#L218)) ### preUpdate() Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). It only calls plugins who have active=true. Source code: [core/PluginManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js) ([Line 178](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js#L178)) ### remove(plugin, destroy) Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `plugin` | [Phaser.Plugin](phaser.plugin) | | | The plugin to be removed. | | `destroy` | boolean | <optional> | true | Call destroy on the plugin that is removed? | Source code: [core/PluginManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js) ([Line 129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js#L129)) ### removeAll() Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager. Source code: [core/PluginManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js) ([Line 159](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js#L159)) ### render() Render is called right after the Game Renderer completes, but before the State.render. It only calls plugins who have visible=true. Source code: [core/PluginManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js) ([Line 239](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js#L239)) ### update() Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. It only calls plugins who have active=true. Source code: [core/PluginManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js) ([Line 198](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/PluginManager.js#L198)) phaser Class: PIXI.AbstractFilter Class: PIXI.AbstractFilter ========================== Constructor ----------- ### new AbstractFilter(fragmentSrc, uniforms) This is the base class for creating a PIXI filter. Currently only webGL supports filters. If you want to make a custom filter this should be your base class. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `fragmentSrc` | Array | The fragment source in an array of strings. | | `uniforms` | Object | An object containing the uniforms for this filter. | Source code: [pixi/filters/AbstractFilter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/filters/AbstractFilter.js) ([Line 5](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/filters/AbstractFilter.js#L5)) Public Properties ----------------- ### dirty : boolean Source code: [pixi/filters/AbstractFilter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/filters/AbstractFilter.js) ([Line 32](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/filters/AbstractFilter.js#L32)) ### padding : number Source code: [pixi/filters/AbstractFilter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/filters/AbstractFilter.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/filters/AbstractFilter.js#L38)) Public Methods -------------- ### syncUniforms() Syncs the uniforms between the class object and the shaders. Source code: [pixi/filters/AbstractFilter.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/filters/AbstractFilter.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/filters/AbstractFilter.js#L61)) phaser Class: Phaser.Input Class: Phaser.Input =================== Constructor ----------- ### new Input(game) Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer. The Input manager is updated automatically by the core game loop. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | Current game instance. | Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 15](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L15)) Public Properties ----------------- ### [static] MAX\_POINTERS : integer The maximum number of pointers that can be added. This excludes the mouse pointer. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 377](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L377)) ### [static] MOUSE\_OVERRIDES\_TOUCH : number Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 358](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L358)) ### [static] MOUSE\_TOUCH\_COMBINE : number Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 370](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L370)) ### [static] TOUCH\_OVERRIDES\_MOUSE : number Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 364](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L364)) ### activePointer : [Phaser.Pointer](phaser.pointer) The most recently active Pointer object. When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 223](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L223)) ### circle : [Phaser.Circle](phaser.circle) A Circle object centered on the x/y screen coordinates of the Input. Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L91)) ### doubleTapRate : number The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click. Default Value * 300 Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 114](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L114)) ### enabled : boolean When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves. When not enabled, *all* input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`. Default Value * true Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 67](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L67)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L20)) ### gamepad : [Phaser.Gamepad](phaser.gamepad) The Gamepad Input manager. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 274](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L274)) ### hitCanvas :HTMLCanvasElement The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L26)) ### hitContext :CanvasRenderingContext2D The context of the pixel perfect hit canvas. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 32](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L32)) ### holdRate : number The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event. Default Value * 2000 Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 120](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L120)) ### interactiveItems : [Phaser.ArraySet](phaser.arrayset) A list of interactive objects. The InputHandler components add and remove themselves from this list. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 320](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L320)) ### justPressedRate : number The number of milliseconds below which the Pointer is considered justPressed. Default Value * 200 Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 126](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L126)) ### justReleasedRate : number The number of milliseconds below which the Pointer is considered justReleased . Default Value * 200 Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L132)) ### keyboard : [Phaser.Keyboard](phaser.keyboard) The Keyboard Input manager. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 247](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L247)) ### maxPointers : integer The maximum number of Pointers allowed to be active at any one time. A value of -1 is only limited by the total number of pointers. For lots of games it's useful to set this to 1. Default Value * -1 (Limited by total pointers.) Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L102)) ### minPriorityID : number You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value. This is useful when stacking UI layers. Set to zero to disable. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 314](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L314)) ### mouse : [Phaser.Mouse](phaser.mouse) The Mouse Input manager. You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer which normalizes all the input values for you, regardless of browser. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 240](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L240)) ### mousePointer :Pointer The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 230](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L230)) ### <internal> moveCallbacks :array An array of callbacks that will be fired every time the activePointer receives a move event from the DOM. To add a callback to this array please use `Input.addMoveCallback`. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 40](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L40)) ### mspointer : [Phaser.MSPointer](phaser.mspointer) The MSPointer Input manager. You should not usually access this manager directly, but instead use Input.activePointer which normalizes all the input values for you, regardless of browser. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 267](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L267)) ### multiInputOverride : number Controls the expected behavior when using a mouse and touch together on a multi-input device. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L73)) ### onDown : [Phaser.Signal](phaser.signal) A Signal that is dispatched each time a pointer is pressed down. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 288](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L288)) ### onHold : [Phaser.Signal](phaser.signal) A Signal that is dispatched each time a pointer is held down. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 306](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L306)) ### onTap : [Phaser.Signal](phaser.signal) A Signal that is dispatched each time a pointer is tapped. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 300](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L300)) ### onUp : [Phaser.Signal](phaser.signal) A Signal that is dispatched each time a pointer is released. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 294](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L294)) ### pointer1 : [Phaser.Pointer](phaser.pointer) A Pointer object. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L160)) ### pointer2 : [Phaser.Pointer](phaser.pointer) A Pointer object. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L165)) ### pointer3 : [Phaser.Pointer](phaser.pointer) A Pointer object. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 170](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L170)) ### pointer4 : [Phaser.Pointer](phaser.pointer) A Pointer object. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 175](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L175)) ### pointer5 : [Phaser.Pointer](phaser.pointer) A Pointer object. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 180](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L180)) ### pointer6 : [Phaser.Pointer](phaser.pointer) A Pointer object. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 185](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L185)) ### pointer7 : [Phaser.Pointer](phaser.pointer) A Pointer object. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 190](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L190)) ### pointer8 : [Phaser.Pointer](phaser.pointer) A Pointer object. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 195](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L195)) ### pointer9 : [Phaser.Pointer](phaser.pointer) A Pointer object. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 200](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L200)) ### pointer10 : [Phaser.Pointer](phaser.pointer) A Pointer object. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 205](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L205)) ### [readonly] pointers : Array.<[Phaser.Pointer](phaser.pointer)> An array of non-mouse pointers that have been added to the game. The properties `pointer1..N` are aliases for `pointers[0..N-1]`. ##### Type * Array.<[Phaser.Pointer](phaser.pointer)> Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 214](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L214)) ### [readonly] pollLocked : boolean True if the Input is currently poll rate locked. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 1065](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L1065)) ### pollRate : number How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L58)) ### position : [Phaser.Point](phaser.point) A point object representing the current position of the Pointer. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 79](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L79)) ### recordLimit : number The total number of entries that can be recorded into the Pointer objects tracking history. If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history. Default Value * 100 Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L155)) ### recordPointerHistory : boolean Sets if the Pointer objects should record a history of x/y coordinates they have passed through. The history is cleared each time the Pointer is pressed down. The history is updated at the rate specified in Input.pollRate Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 141](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L141)) ### recordRate : number The rate in milliseconds at which the Pointer objects should update their tracking history. Default Value * 100 Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 147](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L147)) ### resetLocked : boolean If the Input Manager has been reset locked then all calls made to InputManager.reset, such as from a State change, are ignored. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 282](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L282)) ### scale : [Phaser.Point](phaser.point) The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 96](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L96)) ### speed : [Phaser.Point](phaser.point) A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 84](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L84)) ### tapRate : number The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click. Default Value * 200 Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 108](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L108)) ### [readonly] totalActivePointers : integers The total number of active Pointers, not counting the mouse pointer. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 1093](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L1093)) ### [readonly] totalInactivePointers : number The total number of inactive Pointers. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 1079](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L1079)) ### touch : [Phaser.Touch](phaser.touch) The Touch Input manager. You should not usually access this manager directly, but instead use Input.activePointer which normalizes all the input values for you, regardless of browser. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 257](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L257)) ### [readonly] worldX : number The world X coordinate of the most recently active pointer. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 1107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L1107)) ### [readonly] worldY : number The world Y coordinate of the most recently active pointer. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 1121](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L1121)) ### x : number The X coordinate of the most recently active pointer. This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 1029](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L1029)) ### y : number The Y coordinate of the most recently active pointer. This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 1047](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L1047)) Public Methods -------------- ### addMoveCallback(callback, context) Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove. The callback will be sent 4 parameters: A reference to the Phaser.Pointer object that moved, The x position of the pointer, The y position, A boolean indicating if the movement was the result of a 'click' event (such as a mouse click or touch down). It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best to only use if you've limited input to a single pointer (i.e. mouse or touch). The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `callback` | function | The callback that will be called each time the activePointer receives a DOM move event. | | `context` | object | The context in which the callback will be called. | Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 502](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L502)) ### addPointer() → {[Phaser.Pointer](phaser.pointer) | null} Add a new Pointer object to the Input Manager. By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`. This method adds an additional pointer, up to a maximum of Phaser.Input.MAX\_POINTERS (default of 10). ##### Returns [Phaser.Pointer](phaser.pointer) | null - The new Pointer object that was created; null if a new pointer could not be added. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 549](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L549)) ### <internal> boot() Starts the Input Manager running. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 381](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L381)) ### deleteMoveCallback(callback, context) Removes the callback from the Phaser.Input.moveCallbacks array. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `callback` | function | The callback to be removed. | | `context` | object | The context in which the callback exists. | Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 527](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L527)) ### destroy() Stops all of the Input Managers from running. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 444](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L444)) ### getLocalPosition(displayObject, pointer) → {[Phaser.Point](phaser.point)} This will return the local coordinates of the specified displayObject based on the given Pointer. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | The DisplayObject to get the local coordinates for. | | `pointer` | [Phaser.Pointer](phaser.pointer) | The Pointer to use in the check against the displayObject. | ##### Returns [Phaser.Point](phaser.point) - A point containing the coordinates of the Pointer position relative to the DisplayObject. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 902](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L902)) ### getPointer(isActive) → {[Phaser.Pointer](phaser.pointer)} Get the first Pointer with the given active state. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `isActive` | boolean | <optional> | false | The state the Pointer should be in - active or inactive? | ##### Returns [Phaser.Pointer](phaser.pointer) - A Pointer object or null if no Pointer object matches the requested state. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 824](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L824)) ### getPointerFromId(pointerId) → {[Phaser.Pointer](phaser.pointer)} Get the Pointer object whos `pointerId` property matches the given value. The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event. Also it can change every time you press the pointer down if the browser recycles it. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `pointerId` | number | The `pointerId` (not 'id') value to search for. | ##### Returns [Phaser.Pointer](phaser.pointer) - A Pointer object or null if no Pointer object matches the requested identifier. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 876](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L876)) ### getPointerFromIdentifier(identifier) → {[Phaser.Pointer](phaser.pointer)} Get the Pointer object whos `identifier` property matches the given identifier value. The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event. Also it can change every time you press the pointer down, and is not fixed once set. Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `identifier` | number | The Pointer.identifier value to search for. | ##### Returns [Phaser.Pointer](phaser.pointer) - A Pointer object or null if no Pointer object matches the requested identifier. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 849](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L849)) ### hitTest(displayObject, pointer, localPoint) Tests if the pointer hits the given object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `displayObject` | [DisplayObject](global#DisplayObject) | The displayObject to test for a hit. | | `pointer` | [Phaser.Pointer](phaser.pointer) | The pointer to use for the test. | | `localPoint` | [Phaser.Point](phaser.point) | The local translated point. | Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 924](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L924)) ### reset(hard) Reset all of the Pointers and Input states. The optional `hard` parameter will reset any events or callbacks that may be bound. Input.reset is called automatically during a State change or if a game loses focus / visibility. To control control the reset manually set Phaser.InputManager.resetLocked to `true`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `hard` | boolean | <optional> | false | A soft reset won't reset any events or callbacks that are bound. A hard reset will. | Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 614](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L614)) ### resetSpeed(x, y) Resets the speed and old position properties. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | Sets the oldPosition.x value. | | `y` | number | Sets the oldPosition.y value. | Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 673](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L673)) ### setInteractiveCandidateHandler(callback, context) Adds a callback that is fired every time `Pointer.processInteractiveObjects` is called. The purpose of `processInteractiveObjects` is to work out which Game Object the Pointer is going to interact with. It works by polling all of the valid game objects, and then slowly discounting those that don't meet the criteria (i.e. they aren't under the Pointer, are disabled, invisible, etc). Eventually a short-list of 'candidates' is created. These are all of the Game Objects which are valid for input and overlap with the Pointer. If you need fine-grained control over which of the items is selected then you can use this callback to do so. The callback will be sent 3 parameters: 1) A reference to the Phaser.Pointer object that is processing the Items. 2) An array containing all potential interactive candidates. This is an array of `InputHandler` objects, not Sprites. 3) The current 'favorite' candidate, based on its priorityID and position in the display list. Your callback MUST return one of the candidates sent to it. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `callback` | function | The callback that will be called each time `Pointer.processInteractiveObjects` is called. Set to `null` to disable. | | `context` | object | The context in which the callback will be called. | Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 473](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L473)) ### <internal> startPointer(event) → {[Phaser.Pointer](phaser.pointer)} Find the first free Pointer object and start it, passing in the event data. This is called automatically by Phaser.Touch and Phaser.MSPointer. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | any | The event data from the Touch event. | ##### Returns [Phaser.Pointer](phaser.pointer) - The Pointer object that was started or null if no Pointer object is available. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 687](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L687)) ### <internal> stopPointer(event) → {[Phaser.Pointer](phaser.pointer)} Stops the matching Pointer object, passing in the event data. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | any | The event data from the Touch event. | ##### Returns [Phaser.Pointer](phaser.pointer) - The Pointer object that was stopped or null if no Pointer object is available. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 762](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L762)) ### <internal> update() Updates the Input Manager. Called by the core Game loop. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 575](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L575)) ### <internal> updatePointer(event) → {[Phaser.Pointer](phaser.pointer)} Updates the matching Pointer object, passing in the event data. This is called automatically and should not normally need to be invoked. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `event` | any | The event data from the Touch event. | ##### Returns [Phaser.Pointer](phaser.pointer) - The Pointer object that was updated; null if no pointer was updated. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/Input.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js) ([Line 727](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/Input.js#L727))
programming_docs
phaser Class: Phaser.RenderTexture Class: Phaser.RenderTexture =========================== Constructor ----------- ### new RenderTexture(game, width, height, key, scaleMode, resolution) A RenderTexture is a special texture that allows any displayObject to be rendered to it. It allows you to take many complex objects and render them down into a single quad (on WebGL) which can then be used to texture other display objects with. A way of generating textures at run-time. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | Current game instance. | | `width` | number | <optional> | 100 | The width of the render texture. | | `height` | number | <optional> | 100 | The height of the render texture. | | `key` | string | <optional> | '' | The key of the RenderTexture in the Cache, if stored there. | | `scaleMode` | number | <optional> | Phaser.scaleModes.DEFAULT | One of the Phaser.scaleModes consts. | | `resolution` | number | <optional> | 1 | The resolution of the texture being generated. | Source code: [gameobjects/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js#L21)) Extends ------- * [PIXI.RenderTexture](pixi.rendertexture) Public Properties ----------------- ### baseTexture : [PIXI.BaseTexture](pixi.basetexture) The base texture object that this texture uses Inherited From * [PIXI.RenderTexture#baseTexture](pixi.rendertexture#baseTexture) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L78)) ### crop :Rectangle This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) Inherited From * [PIXI.RenderTexture#crop](pixi.rendertexture#crop) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L69)) ### frame :Rectangle The framing rectangle of the render texture Inherited From * [PIXI.RenderTexture#frame](pixi.rendertexture#frame) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L61)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [gameobjects/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js#L30)) ### height : number The height of the render texture Inherited From * [PIXI.RenderTexture#height](pixi.rendertexture#height) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L45)) ### isTiling : boolean Is this a tiling texture? As used by the likes of a TilingSprite. Inherited From * [PIXI.Texture#isTiling](pixi.texture#isTiling) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 79](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L79)) ### key : string The key of the RenderTexture in the Cache, if stored there. Source code: [gameobjects/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js) ([Line 35](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js#L35)) ### noFrame : boolean Does this Texture have any frame data assigned to it? Inherited From * [PIXI.Texture#noFrame](pixi.texture#noFrame) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L28)) ### renderer : [PIXI.CanvasRenderer](pixi.canvasrenderer) | [PIXI.WebGLRenderer](pixi.webglrenderer) The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL. ##### Type * [PIXI.CanvasRenderer](pixi.canvasrenderer) | [PIXI.WebGLRenderer](pixi.webglrenderer) Inherited From * [PIXI.RenderTexture#renderer](pixi.rendertexture#renderer) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 99](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L99)) ### requiresReTint : boolean This will let a renderer know that a tinted parent has updated its texture. Inherited From * [PIXI.Texture#requiresReTint](pixi.texture#requiresReTint) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 95](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L95)) ### requiresUpdate : boolean This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) Inherited From * [PIXI.Texture#requiresUpdate](pixi.texture#requiresUpdate) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L87)) ### resolution : number The Resolution of the texture. Inherited From * [PIXI.RenderTexture#resolution](pixi.rendertexture#resolution) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 53](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L53)) ### trim :Rectangle The texture trim data. Inherited From * [PIXI.Texture#trim](pixi.texture#trim) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L63)) ### type : number Base Phaser object type. Source code: [gameobjects/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js) ([Line 40](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js#L40)) ### valid : boolean Inherited From * [PIXI.RenderTexture#valid](pixi.rendertexture#valid) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L125)) ### width : number The with of the render texture Inherited From * [PIXI.RenderTexture#width](pixi.rendertexture#width) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 37](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L37)) Public Methods -------------- ### clear() Clears the RenderTexture. Inherited From * [PIXI.RenderTexture#clear](pixi.rendertexture#clear) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 175](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L175)) ### destroy(destroyBase) Destroys this texture ##### Parameters | Name | Type | Description | | --- | --- | --- | | `destroyBase` | Boolean | Whether to destroy the base texture as well | Inherited From * [PIXI.Texture#destroy](pixi.texture#destroy) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L165)) ### getBase64() → {String} Will return a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that. ##### Returns String - A base64 encoded string of the texture. Inherited From * [PIXI.RenderTexture#getBase64](pixi.rendertexture#getBase64) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 309](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L309)) ### getCanvas() → {HTMLCanvasElement} Creates a Canvas element, renders this RenderTexture to it and then returns it. ##### Returns HTMLCanvasElement - A Canvas element with the texture rendered on. Inherited From * [PIXI.RenderTexture#getCanvas](pixi.rendertexture#getCanvas) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 320](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L320)) ### getImage() → {Image} Will return a HTML Image of the texture ##### Returns Image - Inherited From * [PIXI.RenderTexture#getImage](pixi.rendertexture#getImage) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 296](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L296)) ### render(displayObject, matrix, clear) This function will draw the display object to the RenderTexture. In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object. This is now a Matrix allowing you much more control over how the Display Object is rendered. If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead. If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Group](phaser.group) | | | The display object to render to this texture. | | `matrix` | [Phaser.Matrix](phaser.matrix) | <optional> | | Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object. | | `clear` | boolean | <optional> | false | If true the texture will be cleared before the display object is drawn. | Source code: [gameobjects/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js) ([Line 117](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js#L117)) ### renderRawXY(displayObject, x, y, clear) This function will draw the display object to the RenderTexture at the given coordinates. When the display object is drawn it doesn't take into account scale, rotation or translation. If you need those then use RenderTexture.renderXY instead. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Group](phaser.group) | | | The display object to render to this texture. | | `x` | number | | | The x position to render the object at. | | `y` | number | | | The y position to render the object at. | | `clear` | boolean | <optional> | false | If true the texture will be cleared before the display object is drawn. | Source code: [gameobjects/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js) ([Line 89](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js#L89)) ### renderXY(displayObject, x, y, clear) This function will draw the display object to the RenderTexture at the given coordinates. When the display object is drawn it takes into account scale and rotation. If you don't want those then use RenderTexture.renderRawXY instead. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `displayObject` | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Group](phaser.group) | | | The display object to render to this texture. | | `x` | number | | | The x position to render the object at. | | `y` | number | | | The y position to render the object at. | | `clear` | boolean | <optional> | false | If true the texture will be cleared before the display object is drawn. | Source code: [gameobjects/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/RenderTexture.js#L57)) ### resize(width, height, updateBase) Resizes the RenderTexture. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | Number | The width to resize to. | | `height` | Number | The height to resize to. | | `updateBase` | Boolean | Should the baseTexture.width and height values be resized as well? | Inherited From * [PIXI.RenderTexture#resize](pixi.rendertexture#resize) Source code: [pixi/textures/RenderTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js) ([Line 139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/RenderTexture.js#L139)) ### setFrame(frame) Specifies the region of the baseTexture that this texture will use. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | Rectangle | The frame of the texture to set it to | Inherited From * [PIXI.Texture#setFrame](pixi.texture#setFrame) Source code: [pixi/textures/Texture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js) ([Line 178](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/textures/Texture.js#L178)) phaser Class: Phaser.SinglePad Class: Phaser.SinglePad ======================= Constructor ----------- ### new SinglePad(game, padParent) A single Phaser Gamepad ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | Current game instance. | | `padParent` | object | The parent Phaser.Gamepad object (all gamepads reside under this) | Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 16](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L16)) Public Properties ----------------- ### callbackContext : Object The context under which the callbacks are run. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L38)) ### [readonly] connected : boolean Whether or not this particular gamepad is connected or not. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L33)) ### deadZone : number Dead zone for axis feedback - within this value you won't trigger updates. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 73](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L73)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L21)) ### [readonly] index : number The gamepad index as per browsers data Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 27](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L27)) ### onAxisCallback : Function This callback is invoked every time an axis is changed. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L63)) ### onConnectCallback : Function This callback is invoked every time this gamepad is connected Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L43)) ### onDisconnectCallback : Function This callback is invoked every time this gamepad is disconnected Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 48](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L48)) ### onDownCallback : Function This callback is invoked every time a button is pressed down. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 53](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L53)) ### onFloatCallback : Function This callback is invoked every time a button is changed to a value where value > 0 and value < 1. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 68](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L68)) ### onUpCallback : Function This callback is invoked every time a gamepad button is released. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L58)) Public Methods -------------- ### addCallbacks(context, callbacks) Add callbacks to this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `context` | object | The context under which the callbacks are run. | | `callbacks` | object | Object that takes six different callbak methods:onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback | Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 121](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L121)) ### axis(axisCode) → {number} Returns value of requested axis. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `axisCode` | number | The index of the axis to check | ##### Returns number - Axis value if available otherwise false Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 432](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L432)) ### buttonValue(buttonCode) → {number} Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example analog trigger buttons on the XBOX 360 controller. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `buttonCode` | number | The buttonCode of the button to check. | ##### Returns number - Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 520](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L520)) ### connect(rawPad) Gamepad connect function, should be called by Phaser.Gamepad. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `rawPad` | object | The raw gamepad object | Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 216](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L216)) ### destroy() Destroys this object and associated callback references. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 298](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L298)) ### disconnect() Gamepad disconnect function, should be called by Phaser.Gamepad. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 260](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L260)) ### getButton(buttonCode) → {[Phaser.DeviceButton](phaser.devicebutton)} Gets a DeviceButton object from this controller to be stored and referenced locally. The DeviceButton object can then be polled, have events attached to it, etc. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `buttonCode` | number | The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON\_0, Phaser.Gamepad.XBOX360\_A, etc. | ##### Returns [Phaser.DeviceButton](phaser.devicebutton) - The DeviceButton object which you can store locally and reference directly. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L144)) ### isDown(buttonCode) → {boolean} Returns true if the button is pressed down. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `buttonCode` | number | The buttonCode of the button to check. | ##### Returns boolean - True if the button is pressed down. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 450](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L450)) ### isUp(buttonCode) → {boolean} Returns true if the button is not currently pressed. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `buttonCode` | number | The buttonCode of the button to check. | ##### Returns boolean - True if the button is not currently pressed down. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 468](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L468)) ### justPressed(buttonCode, duration) → {boolean} Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `buttonCode` | number | | | The buttonCode of the button to check for. | | `duration` | number | <optional> | 250 | The duration below which the button is considered as being just pressed. | ##### Returns boolean - True if the button is just pressed otherwise false. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 503](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L503)) ### justReleased(buttonCode, duration) → {boolean} Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms). ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `buttonCode` | number | | | The buttonCode of the button to check for. | | `duration` | number | <optional> | 250 | The duration below which the button is considered as being just released. | ##### Returns boolean - True if the button is just released otherwise false. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 486](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L486)) ### pollStatus() Main update function called by Phaser.Gamepad. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L165)) ### processAxisChange(axisState) Handles changes in axis. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `axisState` | object | State of the relevant axis | Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 327](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L327)) ### processButtonDown(buttonCode, value) Handles button down press. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `buttonCode` | number | Which buttonCode of this button | | `value` | object | Button value | Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 354](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L354)) ### processButtonFloat(buttonCode, value) Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `buttonCode` | number | Which buttonCode of this button | | `value` | object | Button value (will range somewhere between 0 and 1, but not specifically 0 or 1. | Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 406](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L406)) ### processButtonUp(buttonCode, value) Handles button release. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `buttonCode` | number | Which buttonCode of this button | | `value` | object | Button value | Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 380](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L380)) ### reset() Reset all buttons/axes of this gamepad. Source code: [input/SinglePad.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js) ([Line 539](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/SinglePad.js#L539))
programming_docs
phaser Class: Phaser.GameObjectCreator Class: Phaser.GameObjectCreator =============================== Constructor ----------- ### new GameObjectCreator(game) The GameObjectCreator is a quick way to create common game objects *without* adding them to the game world. The object creator can be accessed with [``game.make``](phaser.game#make). ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 15](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L15)) Public Properties ----------------- ### <internal> game : [Phaser.Game](phaser.game) A reference to the currently running Game. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L21)) ### <internal> world : [Phaser.World](phaser.world) A reference to the game world. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 27](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L27)) Public Methods -------------- ### audio(key, volume, loop, connect) → {[Phaser.Sound](phaser.sound)} Creates a new Sound object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The Game.cache key of the sound that this object will use. | | `volume` | number | <optional> | 1 | The volume at which the sound will be played. | | `loop` | boolean | <optional> | false | Whether or not the sound will loop. | | `connect` | boolean | <optional> | true | Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. | ##### Returns [Phaser.Sound](phaser.sound) - The newly created text object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 118](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L118)) ### audioSprite(key) → {[Phaser.AudioSprite](phaser.audiosprite)} Creates a new AudioSprite object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The Game.cache key of the sound that this object will use. | ##### Returns [Phaser.AudioSprite](phaser.audiosprite) - The newly created AudioSprite object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 134](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L134)) ### bitmapData(width, height, key, addToCache) → {[Phaser.BitmapData](phaser.bitmapdata)} Create a BitmpaData object. A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `width` | number | <optional> | 256 | The width of the BitmapData in pixels. | | `height` | number | <optional> | 256 | The height of the BitmapData in pixels. | | `key` | string | <optional> | '' | Asset key for the BitmapData when stored in the Cache (see addToCache parameter). | | `addToCache` | boolean | <optional> | false | Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) | ##### Returns [Phaser.BitmapData](phaser.bitmapdata) - The newly created BitmapData object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 379](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L379)) ### bitmapText(x, y, font, text, size, align) → {[Phaser.BitmapText](phaser.bitmaptext)} Create a new BitmapText object. BitmapText objects work by taking a texture file and an XML file that describes the font structure. It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to match the font structure. BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by processing the font texture in an image editor first, applying fills and any other effects required. To create multi-line text insert \r, \n or \r\n escape codes into the text string. To create a BitmapText data files you can use: BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner Littera (Web-based, free): http://kvazars.com/littera/ ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | X coordinate to display the BitmapText object at. | | `y` | number | | | Y coordinate to display the BitmapText object at. | | `font` | string | | | The key of the BitmapText as stored in Phaser.Cache. | | `text` | string | <optional> | '' | The text that will be rendered. This can also be set later via BitmapText.text. | | `size` | number | <optional> | 32 | The size the font will be rendered at in pixels. | | `align` | string | <optional> | 'left' | The alignment of multi-line text. Has no effect if there is only one line of text. | ##### Returns [Phaser.BitmapText](phaser.bitmaptext) - The newly created bitmapText object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 297](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L297)) ### button(x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) → {[Phaser.Button](phaser.button)} Creates a new Button object. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | <optional> | X position of the new button object. | | `y` | number | <optional> | Y position of the new button object. | | `key` | string | <optional> | The image key as defined in the Game.Cache to use as the texture for this button. | | `callback` | function | <optional> | The function to call when this button is pressed | | `callbackContext` | object | <optional> | The context in which the callback will be called (usually 'this') | | `overFrame` | string | number | <optional> | This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. | | `outFrame` | string | number | <optional> | This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. | | `downFrame` | string | number | <optional> | This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. | | `upFrame` | string | number | <optional> | This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. | ##### Returns [Phaser.Button](phaser.button) - The newly created button object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 215](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L215)) ### emitter(x, y, maxParticles) → {Phaser.Emitter} Creat a new Emitter. An Emitter is a lightweight particle emitter. It can be used for one-time explosions or for continuous effects like rain and fire. All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accorindgly. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | The x coordinate within the Emitter that the particles are emitted from. | | `y` | number | <optional> | 0 | The y coordinate within the Emitter that the particles are emitted from. | | `maxParticles` | number | <optional> | 50 | The total number of particles in this emitter. | ##### Returns Phaser.Emitter - The newly created emitter object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 250](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L250)) ### filter(filter) → {[Phaser.Filter](phaser.filter)} A WebGL shader/filter that can be applied to Sprites. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `filter` | string | The name of the filter you wish to create, for example HueRotate or SineWave. | | | any | Whatever parameters are needed to be passed to the filter init function. | ##### Returns [Phaser.Filter](phaser.filter) - The newly created Phaser.Filter object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 407](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L407)) ### graphics(x, y) → {[Phaser.Graphics](phaser.graphics)} Creates a new Graphics object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | <optional> | 0 | X position of the new graphics object. | | `y` | number | <optional> | 0 | Y position of the new graphics object. | ##### Returns [Phaser.Graphics](phaser.graphics) - The newly created graphics object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 236](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L236)) ### group(parent, name, addToStage, enableBody, physicsBodyType) → {[Phaser.Group](phaser.group)} A Group is a container for display objects that allows for fast pooling, recycling and collision checks. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | any | | | The parent Group or DisplayObjectContainer that will hold this group, if any. | | `name` | string | <optional> | 'group' | A name for this Group. Not used internally but useful for debugging. | | `addToStage` | boolean | <optional> | false | If set to true this Group will be added directly to the Game.Stage instead of Game.World. | | `enableBody` | boolean | <optional> | false | If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. | | `physicsBodyType` | number | <optional> | 0 | If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. | ##### Returns [Phaser.Group](phaser.group) - The newly created Group. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 83](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L83)) ### image(x, y, key, frame) → {[Phaser.Image](phaser.image)} Create a new Image object. An Image is a light-weight object you can use to display anything that doesn't need physics or animation. It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | X position of the image. | | `y` | number | | Y position of the image. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [PIXI.Texture](pixi.texture) | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. | | `frame` | string | number | <optional> | If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. | ##### Returns [Phaser.Image](phaser.image) - the newly created sprite object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L33)) ### renderTexture(width, height, key, addToCache) → {[Phaser.RenderTexture](phaser.rendertexture)} A dynamic initially blank canvas to which images can be drawn. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `width` | number | <optional> | 100 | the width of the RenderTexture. | | `height` | number | <optional> | 100 | the height of the RenderTexture. | | `key` | string | <optional> | '' | Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). | | `addToCache` | boolean | <optional> | false | Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) | ##### Returns [Phaser.RenderTexture](phaser.rendertexture) - The newly created RenderTexture object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 353](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L353)) ### retroFont(font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) → {[Phaser.RetroFont](phaser.retrofont)} Create a new RetroFont object. A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `font` | string | | | The key of the image in the Game.Cache that the RetroFont will use. | | `characterWidth` | number | | | The width of each character in the font set. | | `characterHeight` | number | | | The height of each character in the font set. | | `chars` | string | | | The characters used in the font set, in display order. You can use the TEXT\_SET consts for common font set arrangements. | | `charsPerRow` | number | | | The number of characters per row in the font set. | | `xSpacing` | number | <optional> | 0 | If the characters in the font set have horizontal spacing between them set the required amount here. | | `ySpacing` | number | <optional> | 0 | If the characters in the font set have vertical spacing between them set the required amount here. | | `xOffset` | number | <optional> | 0 | If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. | | `yOffset` | number | <optional> | 0 | If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. | ##### Returns [Phaser.RetroFont](phaser.retrofont) - The newly created RetroFont texture which can be applied to an Image or Sprite. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 269](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L269)) ### rope(x, y, width, height, key, frame) → {[Phaser.Rope](phaser.rope)} Creates a new Rope object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x coordinate (in world space) to position the Rope at. | | `y` | number | The y coordinate (in world space) to position the Rope at. | | `width` | number | The width of the Rope. | | `height` | number | The height of the Rope. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [PIXI.Texture](pixi.texture) | This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. | | `frame` | string | number | If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [Phaser.Rope](phaser.rope) - The newly created rope object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 181](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L181)) ### sound(key, volume, loop, connect) → {[Phaser.Sound](phaser.sound)} Creates a new Sound object. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The Game.cache key of the sound that this object will use. | | `volume` | number | <optional> | 1 | The volume at which the sound will be played. | | `loop` | boolean | <optional> | false | Whether or not the sound will loop. | | `connect` | boolean | <optional> | true | Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. | ##### Returns [Phaser.Sound](phaser.sound) - The newly created text object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 147](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L147)) ### sprite(x, y, key, frame) → {[Phaser.Sprite](phaser.sprite)} Create a new Sprite with specific position and sprite sheet key. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | X position of the new sprite. | | `y` | number | | Y position of the new sprite. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [PIXI.Texture](pixi.texture) | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. | | `frame` | string | number | <optional> | If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. | ##### Returns [Phaser.Sprite](phaser.sprite) - the newly created sprite object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 52](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L52)) ### spriteBatch(parent, name, addToStage) → {[Phaser.SpriteBatch](phaser.spritebatch)} Create a new SpriteBatch. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | any | | | The parent Group or DisplayObjectContainer that will hold this group, if any. | | `name` | string | <optional> | 'group' | A name for this Group. Not used internally but useful for debugging. | | `addToStage` | boolean | <optional> | false | If set to true this Group will be added directly to the Game.Stage instead of Game.World. | ##### Returns [Phaser.SpriteBatch](phaser.spritebatch) - The newly created group. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L100)) ### text(x, y, text, style) → {[Phaser.Text](phaser.text)} Creates a new Text object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | X position of the new text object. | | `y` | number | Y position of the new text object. | | `text` | string | The actual text that will be written. | | `style` | object | The style object containing style attributes like font, font size , etc. | ##### Returns [Phaser.Text](phaser.text) - The newly created text object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 199](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L199)) ### tilemap(key, tileWidth, tileHeight, width, height) Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file. To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. When using CSV data you must provide the key and the tileWidth and tileHeight parameters. If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | <optional> | | The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. | | `tileWidth` | number | <optional> | 32 | The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. | | `tileHeight` | number | <optional> | 32 | The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. | | `width` | number | <optional> | 10 | The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. | | `height` | number | <optional> | 10 | The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. | Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 331](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L331)) ### tileSprite(x, y, width, height, key, frame) → {[Phaser.TileSprite](phaser.tilesprite)} Creates a new TileSprite object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x coordinate (in world space) to position the TileSprite at. | | `y` | number | The y coordinate (in world space) to position the TileSprite at. | | `width` | number | The width of the TileSprite. | | `height` | number | The height of the TileSprite. | | `key` | string | [Phaser.BitmapData](phaser.bitmapdata) | [PIXI.Texture](pixi.texture) | This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. | | `frame` | string | number | If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [Phaser.TileSprite](phaser.tilesprite) - The newly created tileSprite object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L163)) ### tween(obj) → {[Phaser.Tween](phaser.tween)} Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `obj` | object | Object the tween will be run on. | ##### Returns [Phaser.Tween](phaser.tween) - The Tween object. Source code: [gameobjects/GameObjectCreator.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js) ([Line 68](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/GameObjectCreator.js#L68))
programming_docs
phaser Class: Phaser.Easing.Quartic Class: Phaser.Easing.Quartic ============================ Constructor ----------- ### new Quartic() Quartic easing. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 141](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L141)) Public Methods -------------- ### In(k) → {number} Quartic ease-in. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 143](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L143)) ### InOut(k) → {number} Quartic ease-in/out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 169](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L169)) ### Out(k) → {number} Quartic ease-out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 156](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L156)) phaser Class: Phaser.Component.InWorld Class: Phaser.Component.InWorld =============================== Constructor ----------- ### new InWorld() The InWorld component checks if a Game Object is within the Game World Bounds. An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds. If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well. Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 14](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L14)) Public Properties ----------------- ### checkWorldBounds : boolean If this is set to `true` the Game Object checks if it is within the World bounds each frame. When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. It also optionally kills the Game Object if `outOfBoundsKill` is `true`. When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, or you have tested performance and find it acceptable. Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 98](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L98)) ### [readonly] inWorld : boolean Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 129](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L129)) ### outOfBoundsKill : boolean If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L106)) ### outOfCameraBoundsKill : boolean If this and the `autoCull` property are both set to `true`, then the `kill` method is called as soon as the Game Object leaves the camera bounds. Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L115)) Public Methods -------------- ### <static> preUpdate() The InWorld component preUpdate handler. Called automatically by the Game Object. Source code: [gameobjects/components/InWorld.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InWorld.js#L22)) phaser Class: Phaser.Component.ScaleMinMax Class: Phaser.Component.ScaleMinMax =================================== Constructor ----------- ### new ScaleMinMax() The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent. Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L12)) Public Properties ----------------- ### scaleMax : [Phaser.Point](phaser.point) The maximum scale this Game Object will scale up to. It allows you to prevent a parent from scaling this Game Object higher than the given value. Set it to `null` to remove the limit. Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L46)) ### scaleMin : [Phaser.Point](phaser.point) The minimum scale this Game Object will scale down to. It allows you to prevent a parent from scaling this Game Object lower than the given value. Set it to `null` to remove the limit. Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L36)) ### transformCallback : Function The callback that will apply any scale limiting to the worldTransform. Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L20)) ### transformCallbackContext : Object The context under which `transformCallback` is called. Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L26)) Public Methods -------------- ### setScaleMinMax(minX, minY, maxX, maxY) Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. By setting these values you can carefully control how Game Objects deal with responsive scaling. If only one parameter is given then that value will be used for both scaleMin and scaleMax: `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, or pass `null` for the `maxX` and `maxY` parameters. Call `setScaleMinMax(null)` to clear all previously set values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `minX` | number | null | The minimum horizontal scale value this Game Object can scale down to. | | `minY` | number | null | The minimum vertical scale value this Game Object can scale down to. | | `maxX` | number | null | The maximum horizontal scale value this Game Object can scale up to. | | `maxY` | number | null | The maximum vertical scale value this Game Object can scale up to. | Source code: [gameobjects/components/ScaleMinMax.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/ScaleMinMax.js#L110)) phaser Class: Phaser.Physics.Arcade.Body Class: Phaser.Physics.Arcade.Body ================================= Constructor ----------- ### new Body(sprite) The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | The Sprite object this physics body belongs to. | Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 15](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L15)) Public Properties ----------------- ### acceleration : [Phaser.Point](phaser.point) The acceleration is the rate of change of the velocity. Measured in pixels per second squared. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L160)) ### allowGravity : boolean Allow this Body to be influenced by gravity? Either world or local. Default Value * true Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L171)) ### allowRotation : boolean Allow this Body to be rotated? (via angularVelocity, etc) Default Value * true Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L78)) ### [readonly] angle : number The angle of the Body's velocity in radians. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 288](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L288)) ### angularAcceleration : number The angular acceleration is the rate of change of the angular velocity. Measured in degrees per second squared. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 264](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L264)) ### angularDrag : number The drag applied during the rotation of the Body. Measured in degrees per second squared. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 270](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L270)) ### angularVelocity : number The angular velocity controls the rotation speed of the Body. It is measured in degrees per second. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 258](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L258)) ### blocked : Object This object is populated with boolean values when the Body collides with the World bounds or a Tile. For example if blocked.up is true then the Body cannot move up. An object containing on which faces this Body is blocked from moving, if any. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 390](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L390)) ### [readonly] bottom : number The bottom value of this Body (same as Body.y + Body.height) Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1370](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1370)) ### bounce : [Phaser.Point](phaser.point) The elasticity of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 181](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L181)) ### [readonly] center : [Phaser.Point](phaser.point) The center coordinate of the Physics Body. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L139)) ### checkCollision : Object Set the checkCollision properties to control which directions collision is processed for this Body. For example checkCollision.up = false means it won't collide when the collision happened while moving up. If you need to disable a Body entirely, use `body.enable = false`, this will also disable motion. If you need to disable just collision and/or overlap checks, but retain motion, set `checkCollision.none = true`. An object containing allowed collision. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 370](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L370)) ### collideWorldBounds : boolean A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. Should the Body collide with the World bounds? Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 361](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L361)) ### customSeparateX : boolean This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate. Used in combination with your own collision processHandler you can create whatever type of collision response you need. Use a custom separation system or the built-in one? Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 323](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L323)) ### customSeparateY : boolean This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate. Used in combination with your own collision processHandler you can create whatever type of collision response you need. Use a custom separation system or the built-in one? Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 331](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L331)) ### deltaMax : [Phaser.Point](phaser.point) The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L155)) ### dirty : boolean If this Body in a preUpdate (true) or postUpdate (false) state? Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 402](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L402)) ### drag : [Phaser.Point](phaser.point) The drag applied to the motion of the Body. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L165)) ### embedded : boolean If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true. Body embed value. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 355](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L355)) ### enable : boolean A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run. Default Value * true Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L36)) ### facing : number A const reference to the direction the Body is traveling or facing. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 300](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L300)) ### friction : [Phaser.Point](phaser.point) The amount of movement that will occur if another object 'rides' this one. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 252](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L252)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L25)) ### gravity : [Phaser.Point](phaser.point) A local gravity applied to this Body. If non-zero this over rides any world gravity, unless Body.allowGravity is set to false. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 176](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L176)) ### [readonly] halfHeight : number The calculated height / 2 of the physics body. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 133](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L133)) ### [readonly] halfWidth : number The calculated width / 2 of the physics body. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 127](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L127)) ### [readonly] height : number The calculated height of the physics body. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L103)) ### immovable : boolean An immovable Body will not receive any impacts from other bodies. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 306](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L306)) ### [readonly] isCircle : boolean If `true` this Body is using circular collision detection. If `false` it is using rectangular. Use `Body.setCircle` to control the collision shape this Body uses. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L45)) ### isMoving : boolean Set by the `moveTo` and `moveFrom` methods. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 422](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L422)) ### left : number The x position of the Body. The same as `Body.x`. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1327](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1327)) ### mass : number The mass of the Body. When two bodies collide their mass is used in the calculation to determine the exchange of velocity. Default Value * 1 Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 282](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L282)) ### maxAngular : number The maximum angular velocity in degrees per second that the Body can reach. Default Value * 1000 Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 276](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L276)) ### maxVelocity : [Phaser.Point](phaser.point) The maximum velocity in pixels per second sq. that the Body can reach. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 247](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L247)) ### movementCallback : Function Optional callback. If set, invoked during the running of `moveTo` or `moveFrom` events. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 467](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L467)) ### movementCallbackContext : Object Context in which to call the movementCallback. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 472](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L472)) ### moves : boolean If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen. If you want the physics system to move the body around, then set moves to true. Set to true to allow the Physics system to move this Body, otherwise false to move it manually. Default Value * true Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 315](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L315)) ### [readonly] newVelocity : [Phaser.Point](phaser.point) The new velocity. Calculated during the Body.preUpdate and applied to its position. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L150)) ### offset : [Phaser.Point](phaser.point) The offset of the Physics Body from the Sprite x/y position. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 60](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L60)) ### onCollide : [Phaser.Signal](phaser.signal) A Signal that is dispatched when this Body collides with another Body. You still need to call `game.physics.arcade.collide` in your `update` method in order for this signal to be dispatched. Usually you'd pass a callback to the `collide` method, but this signal provides for a different level of notification. Due to the potentially high volume of signals this could create it is disabled by default. To use this feature set this property to a Phaser.Signal: `sprite.body.onCollide = new Phaser.Signal()` and it will be called when a collision happens, passing two arguments: the sprites which collided. The first sprite in the argument is always the owner of this Body. If two Bodies with this Signal set collide, both will dispatch the Signal. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L221)) ### onMoveComplete : [Phaser.Signal](phaser.signal) Listen for the completion of `moveTo` or `moveFrom` events. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 462](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L462)) ### onOverlap : [Phaser.Signal](phaser.signal) A Signal that is dispatched when this Body overlaps with another Body. You still need to call `game.physics.arcade.overlap` in your `update` method in order for this signal to be dispatched. Usually you'd pass a callback to the `overlap` method, but this signal provides for a different level of notification. Due to the potentially high volume of signals this could create it is disabled by default. To use this feature set this property to a Phaser.Signal: `sprite.body.onOverlap = new Phaser.Signal()` and it will be called when a collision happens, passing two arguments: the sprites which collided. The first sprite in the argument is always the owner of this Body. If two Bodies with this Signal set collide, both will dispatch the Signal. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 241](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L241)) ### onWorldBounds : [Phaser.Signal](phaser.signal) A Signal that is dispatched when this Body collides with the world bounds. Due to the potentially high volume of signals this could create it is disabled by default. To use this feature set this property to a Phaser.Signal: `sprite.body.onWorldBounds = new Phaser.Signal()` and it will be called when a collision happens, passing five arguments: `onWorldBounds(sprite, up, down, left, right)` where the Sprite is a reference to the Sprite that owns this Body, and the other arguments are booleans indicating on which side of the world the Body collided. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 201](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L201)) ### overlapR : number If `Body.isCircle` is true, and this body collides with another circular body, the amount of overlap is stored here. The amount of overlap during the collision. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 349](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L349)) ### overlapX : number When this body collides with another, the amount of overlap is stored here. The amount of horizontal overlap during the collision. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 337](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L337)) ### overlapY : number When this body collides with another, the amount of overlap is stored here. The amount of vertical overlap during the collision. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 343](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L343)) ### [readonly] position : [Phaser.Point](phaser.point) The position of the physics body. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L66)) ### [readonly] preRotation : number The previous rotation of the physics body. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 91](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L91)) ### [readonly] prev : [Phaser.Point](phaser.point) The previous position of the physics body. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 72](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L72)) ### [readonly] radius : number The radius of the circular collision shape this Body is using if Body.setCircle has been enabled. If you wish to change the radius then call `setCircle` again with the new value. If you wish to stop the Body using a circle then call `setCircle` with a radius of zero (or undefined). Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L55)) ### [readonly] right : number The right value of this Body (same as Body.x + Body.width) Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1341](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1341)) ### rotation : number The Body's rotation in degrees, as calculated by its angularVelocity and angularAcceleration. Please understand that the collision Body itself never rotates, it is always axis-aligned. However these values are passed up to the parent Sprite and updates its rotation. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L85)) ### skipQuadTree : boolean If true and you collide this Sprite against a Group, it will disable the collision check from using a QuadTree. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 407](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L407)) ### [readonly] sourceHeight : number The un-scaled original size. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 115](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L115)) ### [readonly] sourceWidth : number The un-scaled original size. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 109](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L109)) ### [readonly] speed : number The speed of the Body as calculated by its velocity. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 294](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L294)) ### sprite : [Phaser.Sprite](phaser.sprite) Reference to the parent Sprite. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L20)) ### stopVelocityOnCollide : boolean Set by the `moveTo` and `moveFrom` methods. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 427](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L427)) ### syncBounds : boolean If true the Body will check itself against the Sprite.getBounds() dimensions and adjust its width and height accordingly. If false it will compare its dimensions against the Sprite scale instead, and adjust its width height if the scale has changed. Typically you would need to enable syncBounds if your sprite is the child of a responsive display object such as a FlexLayer, or in any situation where the Sprite scale doesn't change, but its parents scale is effecting the dimensions regardless. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 417](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L417)) ### tilePadding : [Phaser.Point](phaser.point) If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step. Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height. Extra padding to be added to this sprite's dimensions when checking for tile collision. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 397](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L397)) ### top : number The y position of the Body. The same as `Body.y`. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1356](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1356)) ### touching : Object This object is populated with boolean values when the Body collides with another. touching.up = true means the collision happened to the top of this Body for example. An object containing touching results. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 377](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L377)) ### type : number The type of physics system this body belongs to. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L30)) ### velocity : [Phaser.Point](phaser.point) The velocity, or rate of change in speed of the Body. Measured in pixels per second. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 144](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L144)) ### wasTouching : Object This object is populated with previous touching values from the bodies previous collision. An object containing previous touching results. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 383](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L383)) ### [readonly] width : number The calculated width of the physics body. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 97](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L97)) ### worldBounce : [Phaser.Point](phaser.point) The elasticity of the Body when colliding with the World bounds. By default this property is `null`, in which case `Body.bounce` is used instead. Set this property to a Phaser.Point object in order to enable a World bounds specific bounce value. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 189](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L189)) ### x : number The x position. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1385](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1385)) ### y : number The y position. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1404](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1404)) Public Methods -------------- ### <internal> checkWorldBounds() → {boolean} Internal method. ##### Returns boolean - True if the Body collided with the world bounds, otherwise false. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 795](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L795)) ### deltaAbsX() → {number} Returns the absolute delta x value. ##### Returns number - The absolute delta value. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1245](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1245)) ### deltaAbsY() → {number} Returns the absolute delta y value. ##### Returns number - The absolute delta value. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1257](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1257)) ### deltaX() → {number} Returns the delta x value. The difference between Body.x now and in the previous step. ##### Returns number - The delta value. Positive if the motion was to the right, negative if to the left. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1269](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1269)) ### deltaY() → {number} Returns the delta y value. The difference between Body.y now and in the previous step. ##### Returns number - The delta value. Positive if the motion was downwards, negative if upwards. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1281](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1281)) ### deltaZ() → {number} Returns the delta z value. The difference between Body.rotation now and in the previous step. ##### Returns number - The delta value. Positive if the motion was clockwise, negative if anti-clockwise. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1293](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1293)) ### destroy() Destroys this Body. First it calls Group.removeFromHash if the Game Object this Body belongs to is part of a Group. Then it nulls the Game Objects body reference, and nulls this Body.sprite reference. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1305](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1305)) ### getBounds(obj) → {object} Returns the bounds of this physics body. Only used internally by the World collision methods. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `obj` | object | The object in which to set the bounds values. | ##### Returns object - The object that was given to this method. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1165)) ### hitTest(x, y) → {boolean} Tests if a world point lies within this Body. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The world x coordinate to test. | | `y` | number | The world y coordinate to test. | ##### Returns boolean - True if the given coordinates are inside this Body, otherwise false. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1195](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1195)) ### moveFrom(duration, speed, direction) → {boolean} Note: This method is experimental, and may be changed or removed in a future release. This method moves the Body in the given direction, for the duration specified. It works by setting the velocity on the Body, and an internal timer, and then monitoring the duration each frame. When the duration is up the movement is stopped and the `Body.onMoveComplete` signal is dispatched. Movement also stops if the Body collides or overlaps with any other Body. You can control if the velocity should be reset to zero on collision, by using the property `Body.stopVelocityOnCollide`. Stop the movement at any time by calling `Body.stopMovement`. You can optionally set a speed in pixels per second. If not specified it will use the current `Body.speed` value. If this is zero, the function will return false. Please note that due to browser timings you should allow for a variance in when the duration will actually expire. Depending on system it may be as much as +- 50ms. Also this method doesn't take into consideration any other forces acting on the Body, such as Gravity, drag or maxVelocity, all of which may impact the movement. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `duration` | integer | | The duration of the movement, in ms. | | `speed` | integer | <optional> | The speed of the movement, in pixels per second. If not provided `Body.speed` is used. | | `direction` | integer | <optional> | The angle of movement. If not provided `Body.angle` is used. | ##### Returns boolean - True if the movement successfully started, otherwise false. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 879](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L879)) ### moveTo(duration, distance, direction) → {boolean} Note: This method is experimental, and may be changed or removed in a future release. This method moves the Body in the given direction, for the duration specified. It works by setting the velocity on the Body, and an internal distance counter. The distance is monitored each frame. When the distance equals the distance specified in this call, the movement is stopped, and the `Body.onMoveComplete` signal is dispatched. Movement also stops if the Body collides or overlaps with any other Body. You can control if the velocity should be reset to zero on collision, by using the property `Body.stopVelocityOnCollide`. Stop the movement at any time by calling `Body.stopMovement`. Please note that due to browser timings you should allow for a variance in when the distance will actually expire. Note: This method doesn't take into consideration any other forces acting on the Body, such as Gravity, drag or maxVelocity, all of which may impact the movement. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `duration` | integer | | The duration of the movement, in ms. | | `distance` | integer | | The distance, in pixels, the Body will move. | | `direction` | integer | <optional> | The angle of movement. If not provided `Body.angle` is used. | ##### Returns boolean - True if the movement successfully started, otherwise false. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 953](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L953)) ### onCeiling() → {boolean} Returns true if the top of this Body is in contact with either the world bounds or a tile. ##### Returns boolean - True if in contact with either the world bounds or a tile. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1221)) ### onFloor() → {boolean} Returns true if the bottom of this Body is in contact with either the world bounds or a tile. ##### Returns boolean - True if in contact with either the world bounds or a tile. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1209](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1209)) ### onWall() → {boolean} Returns true if either side of this Body is in contact with either the world bounds or a tile. ##### Returns boolean - True if in contact with either the world bounds or a tile. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1233](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1233)) ### <internal> postUpdate() Internal method. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 709](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L709)) ### <internal> preUpdate() Internal method. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 552](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L552)) ### render(context, body, color, filled) Render Sprite Body. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `context` | object | | | The context to render to. | | `body` | [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | | | The Body to render the info of. | | `color` | string | <optional> | 'rgba(0,255,0,0.4)' | color of the debug info to be rendered. (format is css color string). | | `filled` | boolean | <optional> | true | Render the objected as a filled (default, true) or a stroked (false) | Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1424](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1424)) ### renderBodyInfo(body, x, y, color) Render Sprite Body Physics Data as text. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `body` | [Phaser.Physics.Arcade.Body](phaser.physics.arcade.body) | | | The Body to render the info of. | | `x` | number | | | X position of the debug info to be rendered. | | `y` | number | | | Y position of the debug info to be rendered. | | `color` | string | <optional> | 'rgb(255,255,255)' | color of the debug info to be rendered. (format is css color string). | Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1470](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1470)) ### reset(x, y) Resets all Body values (velocity, acceleration, rotation, etc) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The new x position of the Body. | | `y` | number | The new y position of the Body. | Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1130)) ### setCircle(radius, offsetX, offsetY) Sets this Body as using a circle, of the given radius, for all collision detection instead of a rectangle. The radius is given in pixels and is the distance from the center of the circle to the edge. You can also control the x and y offset, which is the position of the Body relative to the top-left of the Sprite. To change a Body back to being rectangular again call `Body.setSize`. Note: Circular collision only happens with other Arcade Physics bodies, it does not work against tile maps, where rectangular collision is the only method supported. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `radius` | number | <optional> | The radius of the Body in pixels. Pass a value of zero / undefined, to stop the Body using a circle for collision. | | `offsetX` | number | <optional> | The X offset of the Body from the Sprite position. | | `offsetY` | number | <optional> | The Y offset of the Body from the Sprite position. | Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1084](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1084)) ### setSize(width, height, offsetX, offsetY) You can modify the size of the physics Body to be any dimension you need. This allows you to make it smaller, or larger, than the parent Sprite. You can also control the x and y offset of the Body. This is the position of the Body relative to the top-left of the Sprite *texture*. For example: If you have a Sprite with a texture that is 80x100 in size, and you want the physics body to be 32x32 pixels in the middle of the texture, you would do: `setSize(32, 32, 24, 34)` Where the first two parameters is the new Body size (32x32 pixels). 24 is the horizontal offset of the Body from the top-left of the Sprites texture, and 34 is the vertical offset. Calling `setSize` on a Body that has already had `setCircle` will reset all of the Circle properties, making this Body rectangular again. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `width` | number | | The width of the Body. | | `height` | number | | The height of the Body. | | `offsetX` | number | <optional> | The X offset of the Body from the top-left of the Sprites texture. | | `offsetY` | number | <optional> | The Y offset of the Body from the top-left of the Sprites texture. | Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 1040](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L1040)) ### stopMovement(stopVelocity) If this Body is moving as a result of a call to `moveTo` or `moveFrom` (i.e. it has Body.isMoving true), then calling this method will stop the movement before either the duration or distance counters expire. The `onMoveComplete` signal is dispatched. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `stopVelocity` | boolean | <optional> | Should the Body.velocity be set to zero? | Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 681](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L681)) ### <internal> updateBounds() Internal method. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 508](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L508)) ### <internal> updateMovement() Internal method. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [physics/arcade/Body.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js) ([Line 640](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/arcade/Body.js#L640))
programming_docs
phaser Class: Phaser.Easing.Elastic Class: Phaser.Easing.Elastic ============================ Constructor ----------- ### new Elastic() Elastic easing. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 393](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L393)) Public Methods -------------- ### In(k) → {number} Elastic ease-in. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 395](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L395)) ### InOut(k) → {number} Elastic ease-in/out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 431](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L431)) ### Out(k) → {number} Elastic ease-out. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `k` | number | The value to be tweened. | ##### Returns number - The tweened value. Source code: [tween/Easing.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js) ([Line 413](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/Easing.js#L413)) phaser Class: Phaser.Rectangle Class: Phaser.Rectangle ======================= Constructor ----------- ### new Rectangle(x, y, width, height) Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x coordinate of the top-left corner of the Rectangle. | | `y` | number | The y coordinate of the top-left corner of the Rectangle. | | `width` | number | The width of the Rectangle. Should always be either zero or a positive value. | | `height` | number | The height of the Rectangle. Should always be either zero or a positive value. | Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 18](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L18)) Public Properties ----------------- ### bottom : number The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 478](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L478)) ### bottomLeft : [Phaser.Point](phaser.point) The location of the Rectangles bottom left corner as a Point object. Gets or sets the location of the Rectangles bottom left corner as a Point object. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 504](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L504)) ### bottomRight : [Phaser.Point](phaser.point) The location of the Rectangles bottom right corner as a Point object. Gets or sets the location of the Rectangles bottom right corner as a Point object. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 522](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L522)) ### centerX : number The x coordinate of the center of the Rectangle. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 611](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L611)) ### centerY : number The y coordinate of the center of the Rectangle. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 628](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L628)) ### empty : boolean Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0. If set to true then all of the Rectangle properties are set to 0. Gets or sets the Rectangles empty state. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 736](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L736)) ### [readonly] halfHeight : number Half of the height of the Rectangle. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 465](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L465)) ### [readonly] halfWidth : number Half of the width of the Rectangle. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 452](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L452)) ### height : number The height of the Rectangle. This value should never be set to a negative. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 43](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L43)) ### left : number The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 540](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L540)) ### [readonly] perimeter : number The perimeter size of the Rectangle. This is the sum of all 4 sides. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 597](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L597)) ### randomX : number A random value between the left and right values (inclusive) of the Rectangle. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 645](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L645)) ### randomY : number A random value between the top and bottom values (inclusive) of the Rectangle. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 661](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L661)) ### right : number The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 562](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L562)) ### top : number The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. However it does affect the height property, whereas changing the y value does not affect the height property. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 677](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L677)) ### topLeft : [Phaser.Point](phaser.point) The location of the Rectangles top left corner as a Point object. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 700](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L700)) ### topRight : [Phaser.Point](phaser.point) The location of the Rectangles top right corner as a Point object. The location of the Rectangles top left corner as a Point object. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 718](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L718)) ### [readonly] type : number The const type of this object. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L49)) ### [readonly] volume : number The volume of the Rectangle derived from width \* height. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 583](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L583)) ### width : number The width of the Rectangle. This value should never be set to a negative. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L38)) ### x : number The x coordinate of the top-left corner of the Rectangle. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L28)) ### y : number The y coordinate of the top-left corner of the Rectangle. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L33)) Public Methods -------------- ### <static> clone(a, output) → {[Phaser.Rectangle](phaser.rectangle)} Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Rectangle](phaser.rectangle) | | The Rectangle object. | | `output` | [Phaser.Rectangle](phaser.rectangle) | <optional> | Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 815](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L815)) ### <static> contains(a, x, y) → {boolean} Determines whether the specified coordinates are contained within the region defined by this Rectangle object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Rectangle](phaser.rectangle) | The Rectangle object. | | `x` | number | The x coordinate of the point to test. | | `y` | number | The y coordinate of the point to test. | ##### Returns boolean - A value of true if the Rectangle object contains the specified point; otherwise false. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 837](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L837)) ### <static> containsPoint(a, point) → {boolean} Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Rectangle](phaser.rectangle) | The Rectangle object. | | `point` | [Phaser.Point](phaser.point) | The point object being checked. Can be Point or any object with .x and .y values. | ##### Returns boolean - A value of true if the Rectangle object contains the specified point; otherwise false. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 873](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L873)) ### <static> containsRaw(rx, ry, rw, rh, x, y) → {boolean} Determines whether the specified coordinates are contained within the region defined by the given raw values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `rx` | number | The x coordinate of the top left of the area. | | `ry` | number | The y coordinate of the top left of the area. | | `rw` | number | The width of the area. | | `rh` | number | The height of the area. | | `x` | number | The x coordinate of the point to test. | | `y` | number | The y coordinate of the point to test. | ##### Returns boolean - A value of true if the Rectangle object contains the specified point; otherwise false. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 856](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L856)) ### <static> containsRect(a, b) → {boolean} Determines whether the first Rectangle object is fully contained within the second Rectangle object. A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Rectangle](phaser.rectangle) | The first Rectangle object. | | `b` | [Phaser.Rectangle](phaser.rectangle) | The second Rectangle object. | ##### Returns boolean - A value of true if the Rectangle object contains the specified point; otherwise false. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 886](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L886)) ### <static> equals(a, b) → {boolean} Determines whether the two Rectangles are equal. This method compares the x, y, width and height properties of each Rectangle. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Rectangle](phaser.rectangle) | The first Rectangle object. | | `b` | [Phaser.Rectangle](phaser.rectangle) | The second Rectangle object. | ##### Returns boolean - A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 906](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L906)) ### <static> inflate(a, dx, dy) → {[Phaser.Rectangle](phaser.rectangle)} Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Rectangle](phaser.rectangle) | The Rectangle object. | | `dx` | number | The amount to be added to the left side of the Rectangle. | | `dy` | number | The amount to be added to the bottom side of the Rectangle. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - This Rectangle object. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 761](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L761)) ### <static> inflatePoint(a, point) → {[Phaser.Rectangle](phaser.rectangle)} Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Rectangle](phaser.rectangle) | The Rectangle object. | | `point` | [Phaser.Point](phaser.point) | The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - The Rectangle object. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 780](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L780)) ### <static> intersection(a, b, output) → {[Phaser.Rectangle](phaser.rectangle)} If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Rectangle](phaser.rectangle) | | The first Rectangle object. | | `b` | [Phaser.Rectangle](phaser.rectangle) | | The second Rectangle object. | | `output` | [Phaser.Rectangle](phaser.rectangle) | <optional> | Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 933](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L933)) ### <static> intersects(a, b) → {boolean} Determines whether the two Rectangles intersect with each other. This method checks the x, y, width, and height properties of the Rectangles. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | [Phaser.Rectangle](phaser.rectangle) | The first Rectangle object. | | `b` | [Phaser.Rectangle](phaser.rectangle) | The second Rectangle object. | ##### Returns boolean - A value of true if the specified object intersects with this Rectangle object; otherwise false. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 960](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L960)) ### <static> intersectsRaw(left, right, top, bottom, tolerance) → {boolean} Determines whether the object specified intersects (overlaps) with the given values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `left` | number | The x coordinate of the left of the area. | | `right` | number | The right coordinate of the area. | | `top` | number | The y coordinate of the area. | | `bottom` | number | The bottom coordinate of the area. | | `tolerance` | number | A tolerance value to allow for an intersection test with padding, default to 0 | ##### Returns boolean - A value of true if the specified object intersects with the Rectangle; otherwise false. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 979](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L979)) ### <static> sameDimensions(a, b) → {boolean} Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | Rectangle-like | The first Rectangle object. | | `b` | Rectangle-like | The second Rectangle object. | ##### Returns boolean - True if the object have equivalent values for the width and height properties. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 920](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L920)) ### <static> size(a, output) → {[Phaser.Point](phaser.point)} The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Rectangle](phaser.rectangle) | | The Rectangle object. | | `output` | [Phaser.Point](phaser.point) | <optional> | Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. | ##### Returns [Phaser.Point](phaser.point) - The size of the Rectangle object Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 793](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L793)) ### <static> union(a, b, output) → {[Phaser.Rectangle](phaser.rectangle)} Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `a` | [Phaser.Rectangle](phaser.rectangle) | | The first Rectangle object. | | `b` | [Phaser.Rectangle](phaser.rectangle) | | The second Rectangle object. | | `output` | [Phaser.Rectangle](phaser.rectangle) | <optional> | Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - A Rectangle object that is the union of the two Rectangles. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 997](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L997)) ### aabb(points, out) → {[Phaser.Rectangle](phaser.rectangle)} Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `points` | Array.<[Phaser.Point](phaser.point)> | | The array of one or more points. | | `out` | [Phaser.Rectangle](phaser.rectangle) | <optional> | Optional Rectangle to store the value in, if not supplied a new Rectangle object will be created. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - The new Rectangle object. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 1016](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L1016)) ### ceil() Runs Math.ceil() on both the x and y values of this Rectangle. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 163](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L163)) ### ceilAll() Runs Math.ceil() on the x, y, width and height values of this Rectangle. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 174](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L174)) ### centerOn(x, y) → {[Phaser.Rectangle](phaser.rectangle)} Centers this Rectangle so that the center coordinates match the given x and y values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x coordinate to place the center of the Rectangle at. | | `y` | number | The y coordinate to place the center of the Rectangle at. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - This Rectangle object Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 122](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L122)) ### clone(output) → {[Phaser.Rectangle](phaser.rectangle)} Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `output` | [Phaser.Rectangle](phaser.rectangle) | <optional> | Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 259](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L259)) ### contains(x, y) → {boolean} Determines whether the specified coordinates are contained within the region defined by this Rectangle object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x coordinate of the point to test. | | `y` | number | The y coordinate of the point to test. | ##### Returns boolean - A value of true if the Rectangle object contains the specified point; otherwise false. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 271](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L271)) ### containsRect(b) → {boolean} Determines whether the first Rectangle object is fully contained within the second Rectangle object. A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `b` | [Phaser.Rectangle](phaser.rectangle) | The second Rectangle object. | ##### Returns boolean - A value of true if the Rectangle object contains the specified point; otherwise false. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 284](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L284)) ### copyFrom(source) → {[Phaser.Rectangle](phaser.rectangle)} Copies the x, y, width and height properties from any given object to this Rectangle. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `source` | any | The object to copy from. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - This Rectangle object. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 187](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L187)) ### copyTo(source) → {object} Copies the x, y, width and height properties from this Rectangle to any given object. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `source` | any | The object to copy to. | ##### Returns object - This object. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 199](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L199)) ### equals(b) → {boolean} Determines whether the two Rectangles are equal. This method compares the x, y, width and height properties of each Rectangle. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `b` | [Phaser.Rectangle](phaser.rectangle) | The second Rectangle object. | ##### Returns boolean - A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 297](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L297)) ### floor() Runs Math.floor() on both the x and y values of this Rectangle. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L139)) ### floorAll() Runs Math.floor() on the x, y, width and height values of this Rectangle. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 150](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L150)) ### getPoint(position, out) → {[Phaser.Point](phaser.point)} Returns a point based on the given position constant, which can be one of: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. This method returns the same values as calling Rectangle.bottomLeft, etc, but those calls always create a new Point object, where-as this one allows you to use your own. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `position` | integer | <optional> | One of the Phaser position constants, such as `Phaser.TOP_RIGHT`. | | `out` | [Phaser.Point](phaser.point) | <optional> | A Phaser.Point that the values will be set in. If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. | ##### Returns [Phaser.Point](phaser.point) - An object containing the point in its `x` and `y` properties. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 386](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L386)) ### inflate(dx, dy) → {[Phaser.Rectangle](phaser.rectangle)} Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `dx` | number | The amount to be added to the left side of the Rectangle. | | `dy` | number | The amount to be added to the bottom side of the Rectangle. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - This Rectangle object. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 216](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L216)) ### intersection(b, out) → {[Phaser.Rectangle](phaser.rectangle)} If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `b` | [Phaser.Rectangle](phaser.rectangle) | The second Rectangle object. | | `out` | [Phaser.Rectangle](phaser.rectangle) | Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 310](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L310)) ### intersects(b) → {boolean} Determines whether this Rectangle and another given Rectangle intersect with each other. This method checks the x, y, width, and height properties of the two Rectangles. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `b` | [Phaser.Rectangle](phaser.rectangle) | The second Rectangle object. | ##### Returns boolean - A value of true if the specified object intersects with this Rectangle object; otherwise false. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 323](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L323)) ### intersectsRaw(left, right, top, bottom, tolerance) → {boolean} Determines whether the coordinates given intersects (overlaps) with this Rectangle. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `left` | number | The x coordinate of the left of the area. | | `right` | number | The right coordinate of the area. | | `top` | number | The y coordinate of the area. | | `bottom` | number | The bottom coordinate of the area. | | `tolerance` | number | A tolerance value to allow for an intersection test with padding, default to 0 | ##### Returns boolean - A value of true if the specified object intersects with the Rectangle; otherwise false. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 337](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L337)) ### offset(dx, dy) → {[Phaser.Rectangle](phaser.rectangle)} Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `dx` | number | Moves the x value of the Rectangle object by this amount. | | `dy` | number | Moves the y value of the Rectangle object by this amount. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - This Rectangle object. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L55)) ### offsetPoint(point) → {[Phaser.Rectangle](phaser.rectangle)} Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `point` | [Phaser.Point](phaser.point) | A Point object to use to offset this Rectangle object. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - This Rectangle object. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 71](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L71)) ### random(out) → {[Phaser.Point](phaser.point)} Returns a uniformly distributed random point from anywhere within this Rectangle. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `out` | [Phaser.Point](phaser.point) | object | <optional> | A Phaser.Point, or any object with public x/y properties, that the values will be set in. If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. | ##### Returns [Phaser.Point](phaser.point) - An object containing the random point in its `x` and `y` properties. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 367](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L367)) ### resize(width, height) → {[Phaser.Rectangle](phaser.rectangle)} Resize the Rectangle by providing a new width and height. The x and y positions remain unchanged. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | number | The width of the Rectangle. Should always be either zero or a positive value. | | `height` | number | The height of the Rectangle. Should always be either zero or a positive value. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - This Rectangle object Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 241](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L241)) ### scale(x, y) → {[Phaser.Rectangle](phaser.rectangle)} Scales the width and height of this Rectangle by the given amounts. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | The amount to scale the width of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the width, etc. | | `y` | number | <optional> | The amount to scale the height of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the height, etc. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - This Rectangle object Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L103)) ### setTo(x, y, width, height) → {[Phaser.Rectangle](phaser.rectangle)} Sets the members of Rectangle to the specified values. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | The x coordinate of the top-left corner of the Rectangle. | | `y` | number | The y coordinate of the top-left corner of the Rectangle. | | `width` | number | The width of the Rectangle. Should always be either zero or a positive value. | | `height` | number | The height of the Rectangle. Should always be either zero or a positive value. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - This Rectangle object Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 83](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L83)) ### size(output) → {[Phaser.Point](phaser.point)} The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `output` | [Phaser.Point](phaser.point) | <optional> | Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. | ##### Returns [Phaser.Point](phaser.point) - The size of the Rectangle object. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 229](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L229)) ### toString() → {string} Returns a string representation of this object. ##### Returns string - A string representation of the instance. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 439](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L439)) ### union(b, out) → {[Phaser.Rectangle](phaser.rectangle)} Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `b` | [Phaser.Rectangle](phaser.rectangle) | | The second Rectangle object. | | `out` | [Phaser.Rectangle](phaser.rectangle) | <optional> | Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. | ##### Returns [Phaser.Rectangle](phaser.rectangle) - A Rectangle object that is the union of the two Rectangles. Source code: [geom/Rectangle.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js) ([Line 354](https://github.com/photonstorm/phaser/tree/v2.6.2/src/geom/Rectangle.js#L354))
programming_docs
phaser Class: Phaser.InputHandler Class: Phaser.InputHandler ========================== Constructor ----------- ### new InputHandler(sprite) The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `sprite` | [Phaser.Sprite](phaser.sprite) | The Sprite object to which this Input Handler belongs. | Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 14](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L14)) Public Properties ----------------- ### allowHorizontalDrag : boolean Controls if the Sprite is allowed to be dragged horizontally. Default Value * true Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L69)) ### allowVerticalDrag : boolean Controls if the Sprite is allowed to be dragged vertically. Default Value * true Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 75](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L75)) ### boundsRect : [Phaser.Rectangle](phaser.rectangle) A region of the game world within which the sprite is restricted during drag. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L161)) ### boundsSprite : [Phaser.Sprite](phaser.sprite) A Sprite the bounds of which this sprite is restricted during drag. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L167)) ### bringToTop : boolean If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 81](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L81)) ### <internal> checked : boolean A disposable flag used by the Pointer class when performing priority checks. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 36](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L36)) ### downPoint : [Phaser.Point](phaser.point) A Point object containing the coordinates of the Pointer when it was first pressed down onto this Sprite. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 207](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L207)) ### dragDistanceThreshold : integer The distance, in pixels, the pointer has to move while being held down, before the Sprite thinks it is being dragged. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 197](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L197)) ### dragFromCenter : boolean Is the Sprite dragged from its center, or the point at which the Pointer was pressed down upon it? Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 182](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L182)) ### draggable : boolean Is this sprite allowed to be dragged by the mouse? true = yes, false = no Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L155)) ### dragOffset : [Phaser.Point](phaser.point) The offset from the Sprites position that dragging takes place from. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 177](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L177)) ### dragStartPoint : [Phaser.Point](phaser.point) The Point from which the most recent drag started from. Useful if you need to return an object to its starting position. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 192](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L192)) ### dragStopBlocksInputUp : boolean If enabled, when the Sprite stops being dragged, it will only dispatch the `onDragStop` event, and not the `onInputUp` event. If set to `false` it will dispatch both events. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 187](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L187)) ### dragTimeThreshold : integer The amount of time, in ms, the pointer has to be held down over the Sprite before it thinks it is being dragged. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 202](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L202)) ### enabled : boolean If enabled the Input Handler will process input requests and monitor pointer activity. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 30](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L30)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L24)) ### isDragged : boolean true if the Sprite is being currently dragged. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L63)) ### pixelPerfectAlpha : number The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit. Default Value * 255 Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L149)) ### pixelPerfectClick : boolean Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched. The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. Warning: This is expensive so only enable if you really need it. Use a pixel perfect check when testing for clicks or touches on the Sprite. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 143](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L143)) ### pixelPerfectOver : boolean Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite. The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick. Use a pixel perfect check when testing for pointer over. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 133](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L133)) ### priorityID : number The priorityID is used to determine which game objects should get priority when input events occur. For example if you have several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 45](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L45)) ### scaleLayer : boolean EXPERIMENTAL: Please do not use this property unless you know what it does. Likely to change in the future. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 172](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L172)) ### snapOffset : [Phaser.Point](phaser.point) A Point object that contains by how far the Sprite snap is offset. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L87)) ### snapOffsetX : number This defines the top-left X coordinate of the snap grid. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 117](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L117)) ### snapOffsetY : number This defines the top-left Y coordinate of the snap grid.. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 123](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L123)) ### snapOnDrag : boolean When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L93)) ### snapOnRelease : boolean When the Sprite is dragged this controls if the Sprite will be snapped on release. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 99](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L99)) ### snapPoint : [Phaser.Point](phaser.point) If the sprite is set to snap while dragging this holds the point of the most recent 'snap' event. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 212](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L212)) ### snapX : number When a Sprite has snapping enabled this holds the width of the snap grid. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 105](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L105)) ### snapY : number When a Sprite has snapping enabled this holds the height of the snap grid. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 111](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L111)) ### sprite : [Phaser.Sprite](phaser.sprite) The Sprite object to which this Input Handler belongs. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 19](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L19)) ### useHandCursor : boolean On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L51)) Public Methods -------------- ### checkBoundsRect() Bounds Rect check for the sprite drag Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1654](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1654)) ### checkBoundsSprite() Parent Sprite Bounds check for the sprite drag. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1704](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1704)) ### checkPixel(x, y, pointer) → {boolean} Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to. It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `x` | number | | The x coordinate to check. | | `y` | number | | The y coordinate to check. | | `pointer` | [Phaser.Pointer](phaser.pointer) | <optional> | The pointer to get the x/y coordinate from if not passed as the first two parameters. | ##### Returns boolean - true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 799](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L799)) ### checkPointerDown(pointer, fastTest) → {boolean} Checks if the given pointer is both down and over the Sprite this InputHandler belongs to. Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointer` | [Phaser.Pointer](phaser.pointer) | | | | | `fastTest` | boolean | <optional> | false | Force a simple hit area check even if `pixelPerfectOver` is true for this object? | ##### Returns boolean - True if the pointer is down, otherwise false. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 710](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L710)) ### checkPointerOver(pointer, fastTest) → {boolean} Checks if the given pointer is over the Sprite this InputHandler belongs to. Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointer` | [Phaser.Pointer](phaser.pointer) | | | | | `fastTest` | boolean | <optional> | false | Force a simple hit area check even if `pixelPerfectOver` is true for this object? | ##### Returns boolean - Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 755](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L755)) ### destroy() Clean up memory. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 430](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L430)) ### disableDrag() Stops this sprite from being able to be dragged. If it is currently the target of an active drag it will be stopped immediately; also disables any set callbacks. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1441](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1441)) ### disableSnap() Stops the sprite from snapping to a grid during drag or release. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1642](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1642)) ### downDuration(pointerId) → {number} If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | 0 | | ##### Returns number - The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1363](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1363)) ### enableDrag(lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) Allow this Sprite to be dragged by any valid pointer. When the drag begins the Sprite.events.onDragStart event will be dispatched. When the drag completes by way of the user letting go of the pointer that was dragging the sprite, the Sprite.events.onDragStop event is dispatched. You can control the thresholds over when a drag starts via the properties: `Pointer.dragDistanceThreshold` the distance, in pixels, that the pointer has to move before the drag will start. `Pointer.dragTimeThreshold` the time, in ms, that the pointer must be held down on the Sprite before the drag will start. You can set either (or both) of these properties after enabling a Sprite for drag. For the duration of the drag the Sprite.events.onDragUpdate event is dispatched. This event is only dispatched when the pointer actually changes position and moves. The event sends 5 parameters: `sprite`, `pointer`, `dragX`, `dragY` and `snapPoint`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `lockCenter` | boolean | <optional> | false | If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer. | | `bringToTop` | boolean | <optional> | false | If true the Sprite will be bought to the top of the rendering list in its current Group. | | `pixelPerfect` | boolean | <optional> | false | If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box. | | `alphaThreshold` | boolean | <optional> | 255 | If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed. | | `boundsRect` | [Phaser.Rectangle](phaser.rectangle) | <optional> | null | If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere. | | `boundsSprite` | [Phaser.Sprite](phaser.sprite) | <optional> | null | If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here. | Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1383](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1383)) ### enableSnap(snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) Make this Sprite snap to the given grid either during drag or when it's released. For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `snapX` | number | | | The width of the grid cell to snap to. | | `snapY` | number | | | The height of the grid cell to snap to. | | `onDrag` | boolean | <optional> | true | If true the sprite will snap to the grid while being dragged. | | `onRelease` | boolean | <optional> | false | If true the sprite will snap to the grid when released. | | `snapOffsetX` | number | <optional> | 0 | Used to offset the top-left starting point of the snap grid. | | `snapOffsetY` | number | <optional> | 0 | Used to offset the top-left starting point of the snap grid. | Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1614](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1614)) ### globalToLocalX(x) Warning: EXPERIMENTAL ##### Parameters | Name | Type | Description | | --- | --- | --- | | `x` | number | | Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1524](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1524)) ### globalToLocalY(y) Warning: EXPERIMENTAL ##### Parameters | Name | Type | Description | | --- | --- | --- | | `y` | number | | Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1542](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1542)) ### isPixelPerfect() → {boolean} Is this object using pixel perfect checking? ##### Returns boolean - True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 495](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L495)) ### justOut(pointerId, delay) → {boolean} Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second) ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | 0 | | | `delay` | number | | | The time below which the pointer is considered as just out. | ##### Returns boolean - Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1292](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1292)) ### justOver(pointerId, delay) → {boolean} Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second) ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | 0 | | | `delay` | number | | | The time below which the pointer is considered as just over. | ##### Returns boolean - Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1275](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1275)) ### justPressed(pointerId, delay) → {boolean} Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second) ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | 0 | | | `delay` | number | | | The time below which the pointer is considered as just over. | ##### Returns boolean - Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1309](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1309)) ### justReleased(pointerId, delay) → {boolean} Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second) ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | 0 | | | `delay` | number | | | The time below which the pointer is considered as just out. | ##### Returns boolean - Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1326](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1326)) ### overDuration(pointerId) → {number} If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | 0 | | ##### Returns number - The number of milliseconds the pointer has been over the Sprite, or -1 if not over. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1343](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1343)) ### pointerDown(pointerId) → {boolean} If the Pointer is down this returns true. This *only* checks if the Pointer is down, not if it's down over any specific Sprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | 0 | | ##### Returns boolean - * True if the given pointer is down, otherwise false. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 539](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L539)) ### pointerDragged(pointerId) → {boolean} Is this sprite being dragged by the mouse or not? ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | 0 | | ##### Returns boolean - True if the pointer is dragging an object, otherwise false. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 695](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L695)) ### pointerOut(pointerId) → {boolean} Is the Pointer outside of this Sprite? ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | (check all) | The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. | ##### Returns boolean - True if the given pointer (if a index was given, or any pointer if not) is out of this object. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 634](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L634)) ### pointerOver(pointerId) → {boolean} Is the Pointer over this Sprite? ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | (check all) | The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. | ##### Returns boolean - * True if the given pointer (if a index was given, or any pointer if not) is over this object. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 601](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L601)) ### pointerTimeDown(pointerId) → {number} A timestamp representing when the Pointer first touched the touchscreen. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | (check all) | | ##### Returns number - Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L571)) ### pointerTimeOut(pointerId) → {number} A timestamp representing when the Pointer left the touchscreen. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | 0 | | ##### Returns number - Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 680](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L680)) ### pointerTimeOver(pointerId) → {number} A timestamp representing when the Pointer first touched the touchscreen. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | 0 | | ##### Returns number - Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 665](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L665)) ### pointerTimeUp(pointerId) → {number} A timestamp representing when the Pointer left the touchscreen. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | 0 | | ##### Returns number - Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 586](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L586)) ### pointerUp(pointerId) → {boolean} If the Pointer is up this returns true. This *only* checks if the Pointer is up, not if it's up over any specific Sprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | 0 | | ##### Returns boolean - * True if the given pointer is up, otherwise false. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 555](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L555)) ### pointerX(pointerId) → {number} The x coordinate of the Input pointer, relative to the top-left of the parent Sprite. This value is only set when the pointer is over this Sprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | 0 | | ##### Returns number - The x coordinate of the Input pointer. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 507](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L507)) ### pointerY(pointerId) → {number} The y coordinate of the Input pointer, relative to the top-left of the parent Sprite This value is only set when the pointer is over this Sprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `pointerId` | integer | <optional> | 0 | | ##### Returns number - The y coordinate of the Input pointer. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 523](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L523)) ### reset() Resets the Input Handler and disables it. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 382](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L382)) ### setDragLock(allowHorizontal, allowVertical) Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move! ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `allowHorizontal` | boolean | <optional> | true | To enable the sprite to be dragged horizontally set to true, otherwise false. | | `allowVertical` | boolean | <optional> | true | To enable the sprite to be dragged vertically set to true, otherwise false. | Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1597](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1597)) ### start(priority, useHandCursor) → {[Phaser.Sprite](phaser.sprite)} Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `priority` | number | <optional> | 0 | Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other. | | `useHandCursor` | boolean | <optional> | false | If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers) | ##### Returns [Phaser.Sprite](phaser.sprite) - The Sprite object to which the Input Handler is bound. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 284](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L284)) ### startDrag(pointer) Called by Pointer when drag starts on this Sprite. Should not usually be called directly. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `pointer` | [Phaser.Pointer](phaser.pointer) | | Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1464](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1464)) ### stop() Stops the Input Handler from running. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 410](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L410)) ### stopDrag(pointer) Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `pointer` | [Phaser.Pointer](phaser.pointer) | | Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 1560](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L1560)) ### <internal> update(pointer) → {boolean} Internal Update method. This is called automatically and handles the Pointer and drag update loops. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `pointer` | [Phaser.Pointer](phaser.pointer) | | ##### Returns boolean - True if the pointer is still active, otherwise false. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 868](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L868)) ### <internal> validForInput(highestID, highestRenderID, includePixelPerfect) → {boolean} Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event. This is called by Phaser.Pointer and shouldn't typically be called directly. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `highestID` | number | | | The highest ID currently processed by the Pointer. | | `highestRenderID` | number | | | The highest Render Order ID currently processed by the Pointer. | | `includePixelPerfect` | boolean | <optional> | true | If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid? | ##### Returns boolean - True if the object this InputHandler is bound to should be considered as valid for input detection. Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [input/InputHandler.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js) ([Line 456](https://github.com/photonstorm/phaser/tree/v2.6.2/src/input/InputHandler.js#L456))
programming_docs
phaser Class: Phaser.SignalBinding Class: Phaser.SignalBinding =========================== Constructor ----------- ### new SignalBinding(signal, listener, isOnce, listenerContext, priority, args) Object that represents a binding between a Signal and a listener function. This is an internal constructor and shouldn't be created directly. Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `signal` | [Phaser.Signal](phaser.signal) | | | Reference to Signal object that listener is currently bound to. | | `listener` | function | | | Handler function bound to the signal. | | `isOnce` | boolean | | | If binding should be executed just once. | | `listenerContext` | object | <optional> | null | Context on which listener will be executed (object that should represent the `this` variable inside listener function). | | `priority` | number | <optional> | | The priority level of the event listener. (default = 0). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. | Source code: [core/SignalBinding.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js#L22)) Public Properties ----------------- ### active : boolean If binding is active and should be executed. Default Value * true Source code: [core/SignalBinding.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js#L93)) ### callCount : number The number of times the handler function has been called. Source code: [core/SignalBinding.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js#L86)) ### context : Object Context on which listener will be executed (object that should represent the `this` variable inside listener function). Source code: [core/SignalBinding.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js#L63)) ### params :array | null Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters). ##### Type * array | null Source code: [core/SignalBinding.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js#L100)) Public Methods -------------- ### detach() → {function | null} Detach binding from signal. alias to: @see mySignal.remove(myBinding.getListener()); ##### Returns function | null - Handler function bound to the signal or `null` if binding was previously detached. Source code: [core/SignalBinding.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js) ([Line 136](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js#L136)) ### execute(paramsArr) → {any} Call listener passing arbitrary parameters. If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `paramsArr` | Array.<any> | <optional> | Array of parameters that should be passed to the listener. | ##### Returns any - Value returned by the listener. Source code: [core/SignalBinding.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js#L102)) ### getListener() → {function} ##### Returns function - Handler function bound to the signal. Source code: [core/SignalBinding.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js) ([Line 162](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js#L162)) ### getSignal() → {[Phaser.Signal](phaser.signal)} ##### Returns [Phaser.Signal](phaser.signal) - Signal that listener is currently bound to. Source code: [core/SignalBinding.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js) ([Line 170](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js#L170)) ### isBound() → {boolean} ##### Returns boolean - True if binding is still bound to the signal and has a listener. Source code: [core/SignalBinding.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js#L146)) ### isOnce() → {boolean} ##### Returns boolean - If SignalBinding will only be executed once. Source code: [core/SignalBinding.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js) ([Line 154](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js#L154)) ### toString() → {string} ##### Returns string - String representation of the object. Source code: [core/SignalBinding.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js) ([Line 189](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/SignalBinding.js#L189)) phaser Class: Phaser.Physics.P2.RevoluteConstraint Class: Phaser.Physics.P2.RevoluteConstraint =========================================== Constructor ----------- ### new RevoluteConstraint(world, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) Connects two bodies at given offset points, letting them rotate relative to each other around this point. The pivot points are given in world (pixel) coordinates. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `world` | [Phaser.Physics.P2](phaser.physics.p2) | | | A reference to the P2 World. | | `bodyA` | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | First connected body. | | `pivotA` | Float32Array | | | The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `bodyB` | [p2.Body](http://phaser.io/docs/2.6.2/p2.Body.html) | | | Second connected body. | | `pivotB` | Float32Array | | | The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. | | `maxForce` | number | <optional> | 0 | The maximum force that should be applied to constrain the bodies. | | `worldPivot` | Float32Array | <optional> | null | A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. | Source code: [physics/p2/RevoluteConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/RevoluteConstraint.js) ([Line 21](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/RevoluteConstraint.js#L21)) Public Properties ----------------- ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [physics/p2/RevoluteConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/RevoluteConstraint.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/RevoluteConstraint.js#L29)) ### world : [Phaser.Physics.P2](phaser.physics.p2) Local reference to P2 World. Source code: [physics/p2/RevoluteConstraint.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/RevoluteConstraint.js) ([Line 34](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/RevoluteConstraint.js#L34)) phaser Class: Phaser.Physics.P2.BodyDebug Class: Phaser.Physics.P2.BodyDebug ================================== Constructor ----------- ### new BodyDebug(game, body, settings) Draws a P2 Body to a Graphics instance for visual debugging. Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead. So use sparingly and rarely (if ever) in production code. Also be aware that the Debug body is only updated when the Sprite it is connected to changes position. If you manipulate the sprite in any other way (such as moving it to another Group or bringToTop, etc) then you will need to manually adjust its BodyDebug as well. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | Game reference to the currently running game. | | `body` | [Phaser.Physics.P2.Body](phaser.physics.p2.body) | The P2 Body to display debug data for. | | `settings` | object | Settings object. | Source code: [physics/p2/BodyDebug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/BodyDebug.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/BodyDebug.js#L24)) Extends ------- * [Phaser.Group](phaser.group) Public Properties ----------------- ### alive : boolean The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. Inherited From * [Phaser.Group#alive](phaser.group#alive) Default Value * true Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L93)) ### alpha : number The alpha value of the group container. Inherited From * [Phaser.Group#alpha](phaser.group#alpha) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 3003](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L3003)) ### angle : number The angle of rotation of the group container, in degrees. This adjusts the group itself by modifying its local rotation transform. This has no impact on the rotation/angle properties of the children, but it will update their worldTransform and on-screen orientation and position. Inherited From * [Phaser.Group#angle](phaser.group#angle) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2682](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2682)) ### body : [Phaser.Physics.P2.Body](phaser.physics.p2.body) The P2 Body to display debug data for. Source code: [physics/p2/BodyDebug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/BodyDebug.js) ([Line 50](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/BodyDebug.js#L50)) ### bottom : number The bottom coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#bottom](phaser.group#bottom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2845](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2845)) ### cameraOffset : [Phaser.Point](phaser.point) If this object is [fixedToCamera](phaser.group#fixedToCamera) then this stores the x/y position offset relative to the top-left of the camera view. If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. Inherited From * [Phaser.Group#cameraOffset](phaser.group#cameraOffset) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 272](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L272)) ### canvas : [Phaser.Graphics](phaser.graphics) The canvas to render the debug info to. Source code: [physics/p2/BodyDebug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/BodyDebug.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/BodyDebug.js#L55)) ### centerX : number The center x coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#centerX](phaser.group#centerX) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2705](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2705)) ### centerY : number The center y coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#centerY](phaser.group#centerY) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2733](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2733)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### classType : Object The type of objects that will be created when using [create](phaser.group#create) or [createMultiple](phaser.group#createMultiple). Any object may be used but it should extend either Sprite or Image and accept the same constructor arguments: when a new object is created it is passed the following parameters to its constructor: `(game, x, y, key, frame)`. Inherited From * [Phaser.Group#classType](phaser.group#classType) Default Value * [Phaser.Sprite](phaser.sprite) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L130)) ### cursor : [DisplayObject](global#DisplayObject) The current display object that the group cursor is pointing to, if any. (Can be set manually.) The cursor is a way to iterate through the children in a Group using [next](phaser.group#next) and [previous](phaser.group#previous). Inherited From * [Phaser.Group#cursor](phaser.group#cursor) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L138)) ### [readonly] cursorIndex : integer The current index of the Group cursor. Advance it with Group.next. Inherited From * [Phaser.Group#cursorIndex](phaser.group#cursorIndex) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 255](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L255)) ### enableBody : boolean If true all Sprites created by, or added to this group, will have a physics body enabled on them. If there are children already in the Group at the time you set this property, they are not changed. The default body type is controlled with [physicsBodyType](phaser.group#physicsBodyType). Inherited From * [Phaser.Group#enableBody](phaser.group#enableBody) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 208](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L208)) ### enableBodyDebug : boolean If true when a physics body is created (via [enableBody](phaser.group#enableBody)) it will create a physics debug object as well. This only works for P2 bodies. Inherited From * [Phaser.Group#enableBodyDebug](phaser.group#enableBodyDebug) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L217)) ### exists : boolean If exists is true the group is updated, otherwise it is skipped. Inherited From * [Phaser.Group#exists](phaser.group#exists) Default Value * true Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L100)) ### fixedToCamera : boolean A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. Note that the cameraOffset values are in addition to any parent in the display list. So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x Inherited From * [Phaser.Group#fixedToCamera](phaser.group#fixedToCamera) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 265](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L265)) ### <internal> game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Group#game](phaser.group#game) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L38)) ### hash :array The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. Only children of this Group can be added to and removed from the hash. This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own sorting and filtering of Group children without touching their z-index (and therefore display draw order) Inherited From * [Phaser.Group#hash](phaser.group#hash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 285](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L285)) ### height : number The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#height](pixi.displayobjectcontainer#height) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L600)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### ignoreDestroy : boolean A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. Inherited From * [Phaser.Group#ignoreDestroy](phaser.group#ignoreDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L107)) ### inputEnableChildren : boolean A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` on any children *added* to, or *created by*, this Group. If there are children already in the Group at the time you set this property, they are not changed. Inherited From * [Phaser.Group#inputEnableChildren](phaser.group#inputEnableChildren) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L149)) ### left : number The left coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#left](phaser.group#left) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2761](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2761)) ### [readonly] length : integer Total number of children in this group, regardless of exists/alive status. Inherited From * [Phaser.Group#length](phaser.group#length) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2665](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2665)) ### name : string A name for this group. Not used internally but useful for debugging. Inherited From * [Phaser.Group#name](phaser.group#name) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L49)) ### onChildInputDown : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputDown](phaser.group#onChildInputDown) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L161)) ### onChildInputOut : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputOut](phaser.group#onChildInputOut) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 198](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L198)) ### onChildInputOver : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputOver](phaser.group#onChildInputOver) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 186](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L186)) ### onChildInputUp : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer is still over the Sprite or not. Inherited From * [Phaser.Group#onChildInputUp](phaser.group#onChildInputUp) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 174](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L174)) ### onDestroy : [Phaser.Signal](phaser.signal) This signal is dispatched when the group is destroyed. Inherited From * [Phaser.Group#onDestroy](phaser.group#onDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 249](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L249)) ### pendingDestroy : boolean A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method called on the next logic update. You can set it directly to flag the Group to be destroyed on its next update. This is extremely useful if you wish to destroy a Group from within one of its own callbacks or a callback of one of its children. Inherited From * [Phaser.Group#pendingDestroy](phaser.group#pendingDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L119)) ### physicsBodyType : integer If [enableBody](phaser.group#enableBody) is true this is the type of physics body that is created on new Sprites. The valid values are [Phaser.Physics.ARCADE](phaser.physics#.ARCADE), [Phaser.Physics.P2JS](phaser.physics#.P2JS), [Phaser.Physics.NINJA](phaser.physics#.NINJA), etc. Inherited From * [Phaser.Group#physicsBodyType](phaser.group#physicsBodyType) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L225)) ### physicsSortDirection : integer If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. It should be set to one of the Phaser.Physics.Arcade sort direction constants: Phaser.Physics.Arcade.SORT\_NONE Phaser.Physics.Arcade.LEFT\_RIGHT Phaser.Physics.Arcade.RIGHT\_LEFT Phaser.Physics.Arcade.TOP\_BOTTOM Phaser.Physics.Arcade.BOTTOM\_TOP If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. Inherited From * [Phaser.Group#physicsSortDirection](phaser.group#physicsSortDirection) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 243](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L243)) ### [readonly] physicsType : number The const physics body type of this object. Inherited From * [Phaser.Group#physicsType](phaser.group#physicsType) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L86)) ### ppu : number Pixels per Length Unit. Source code: [physics/p2/BodyDebug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/BodyDebug.js) ([Line 44](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/BodyDebug.js#L44)) ### right : number The right coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#right](phaser.group#right) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2789](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2789)) ### rotation : number The angle of rotation of the group container, in radians. This will adjust the group container itself by modifying its rotation. This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. Inherited From * [Phaser.Group#rotation](phaser.group#rotation) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2987](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2987)) ### top : number The top coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#top](phaser.group#top) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2817](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2817)) ### [readonly] total : integer Total number of existing children in the group. Inherited From * [Phaser.Group#total](phaser.group#total) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2648](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2648)) ### <internal> type : integer Internal Phaser Type value. Inherited From * [Phaser.Group#type](phaser.group#type) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L80)) ### visible : boolean The visible state of the group. Non-visible Groups and all of their children are not rendered. Inherited From * [Phaser.Group#visible](phaser.group#visible) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2996](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2996)) ### width : number The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#width](pixi.displayobjectcontainer#width) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L571)) ### x : number The x coordinate of the group container. You can adjust the group container itself by modifying its coordinates. This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. Inherited From * [Phaser.Group#x](phaser.group#x) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2969](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2969)) ### y : number The y coordinate of the group container. You can adjust the group container itself by modifying its coordinates. This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. Inherited From * [Phaser.Group#y](phaser.group#y) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2978](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2978)) ### [readonly] z : integer The z-depth value of this object within its parent container/Group - the World is a Group as well. This value must be unique for each child in a Group. Inherited From * [Phaser.Group#z](phaser.group#z) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L57)) Public Methods -------------- ### add(child, silent, index) → {[DisplayObject](global#DisplayObject)} Adds an existing object as the top child in this group. The child is automatically added to the top of the group, and is displayed above every previous child. Or if the *optional* index is specified, the child is added at the location specified by the index value, this allows you to control child ordering. If the child was already in this Group, it is simply returned, and nothing else happens to it. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. Use [addAt](phaser.group#addAt) to control where a child is added. Use [create](phaser.group#create) to create and add a new child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | | The display object to add as a child. | | `silent` | boolean | <optional> | false | If true the child will not dispatch the `onAddedToGroup` event. | | `index` | integer | <optional> | | The index within the group to insert the child to. Where 0 is the bottom of the Group. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added to the group. Inherited From * [Phaser.Group#add](phaser.group#add) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 341](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L341)) ### addAll(property, amount, checkAlive, checkVisible) Adds the amount to the given property on all children in this group. `Group.addAll('x', 10)` will add 10 to the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to increment, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#addAll](phaser.group#addAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1386](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1386)) ### addAt(child, index, silent) → {[DisplayObject](global#DisplayObject)} Adds an existing object to this group. The child is added to the group at the location specified by the index value, this allows you to control child ordering. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | | The display object to add as a child. | | `index` | integer | <optional> | 0 | The index within the group to insert the child to. | | `silent` | boolean | <optional> | false | If true the child will not dispatch the `onAddedToGroup` event. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added to the group. Inherited From * [Phaser.Group#addAt](phaser.group#addAt) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 418](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L418)) ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### addMultiple(children, silent) → {Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group)} Adds an array of existing Display Objects to this Group. The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. As well as an array you can also pass another Group as the first argument. In this case all of the children from that Group will be removed from it and added into this Group. If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `children` | Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group) | | | An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. | | `silent` | boolean | <optional> | false | If true the children will not dispatch the `onAddedToGroup` event. | ##### Returns Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group) - The array of children or Group of children that were added to this Group. Inherited From * [Phaser.Group#addMultiple](phaser.group#addMultiple) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 489](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L489)) ### addToHash(child) → {boolean} Adds a child of this Group into the hash array. This call will return false if the child is not a child of this Group, or is already in the hash. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. | ##### Returns boolean - True if the child was successfully added to the hash, otherwise false. Inherited From * [Phaser.Group#addToHash](phaser.group#addToHash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 439](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L439)) ### align(width, height, cellWidth, cellHeight, position, offset) → {boolean} This method iterates through all children in the Group (regardless if they are visible or exist) and then changes their position so they are arranged in a Grid formation. Children must have the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have this. The grid dimensions are determined by the first four arguments. The `width` and `height` arguments relate to the width and height of the grid respectively. For example if the Group had 100 children in it: `Group.align(10, 10, 32, 32)` This will align all of the children into a grid formation of 10x10, using 32 pixels per grid cell. If you want a wider grid, you could do: `Group.align(25, 4, 32, 32)` This will align the children into a grid of 25x4, again using 32 pixels per grid cell. You can choose to set *either* the `width` or `height` value to -1. Doing so tells the method to keep on aligning children until there are no children left. For example if this Group had 48 children in it, the following: `Group.align(-1, 8, 32, 32)` ... will align the children so that there are 8 children vertically (the second argument), and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) You can also do: `Group.align(10, -1, 32, 32)` In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit all of the children in. The `position` property allows you to control where in each grid cell the child is positioned. This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. The final argument; `offset` lets you start the alignment from a specific child index. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `width` | integer | | | The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. | | `height` | integer | | | The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. | | `cellWidth` | integer | | | The width of each grid cell, in pixels. | | `cellHeight` | integer | | | The height of each grid cell, in pixels. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offset` | integer | <optional> | 0 | Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. | ##### Returns boolean - True if the Group children were aligned, otherwise false. Inherited From * [Phaser.Group#align](phaser.group#align) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 682](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L682)) ### alignIn(container, position, offsetX, offsetY) → {[Phaser.Group](phaser.group)} Aligns this Group within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Groups within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Group to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. Groups are placed in such a way that their *bounds* align with the container, taking into consideration rotation and scale of its children. This allows you to neatly align Groups, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Group. For example: `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns [Phaser.Group](phaser.group) - This Group. Inherited From * [Phaser.Group#alignIn](phaser.group#alignIn) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2873](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2873)) ### alignTo(parent, position, offsetX, offsetY) → {[Phaser.Group](phaser.group)} Aligns this Group to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Groups within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Group to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. Groups are placed in such a way that their *bounds* align with the parent, taking into consideration rotation and scale of the children. This allows you to neatly align Groups, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Group. For example: `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns [Phaser.Group](phaser.group) - This Group. Inherited From * [Phaser.Group#alignTo](phaser.group#alignTo) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2915](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2915)) ### <internal> ascendingSortHandler(a, b) An internal helper function for the sort process. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | object | The first object being sorted. | | `b` | object | The second object being sorted. | Inherited From * [Phaser.Group#ascendingSortHandler](phaser.group#ascendingSortHandler) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1919](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1919)) ### bringToTop(child) → {any} Brings the given child to the top of this group so it renders above all other children. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to bring to the top of this group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#bringToTop](phaser.group#bringToTop) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 907](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L907)) ### callAll(method, context, args) Calls a function, specified by name, on all on children. The function is called for all children regardless if they are dead or alive (see callAllExists for different options). After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `method` | string | | | Name of the function on the child to call. Deep property lookup is supported. | | `context` | string | <optional> | null | A string containing the context under which the method will be executed. Set to null to default to the child. | | `args` | any | <repeatable> | | Additional parameters that will be passed to the method. | Inherited From * [Phaser.Group#callAll](phaser.group#callAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1538](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1538)) ### callAllExists(callback, existsValue, parameter) Calls a function, specified by name, on all children in the group who exist (or do not exist). After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `callback` | string | | Name of the function on the children to call. | | `existsValue` | boolean | | Only children with exists=existsValue will be called. | | `parameter` | any | <repeatable> | Additional parameters that will be passed to the callback. | Inherited From * [Phaser.Group#callAllExists](phaser.group#callAllExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1454](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1454)) ### <internal> callbackFromArray(child, callback, length) Returns a reference to a function that exists on a child of the group based on the given callback array. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | object | The object to inspect. | | `callback` | array | The array of function names. | | `length` | integer | The size of the array (pre-calculated in callAll). | Inherited From * [Phaser.Group#callbackFromArray](phaser.group#callbackFromArray) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1488](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1488)) ### checkAll(key, value, checkAlive, checkVisible, force) Quickly check that the same property across all children of this group is equal to the given value. This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be checked. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be checked. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be checked. This includes any Groups that are children. | | `force` | boolean | <optional> | false | If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned. | Inherited From * [Phaser.Group#checkAll](phaser.group#checkAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1353](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1353)) ### checkProperty(child, key, value, force) → {boolean} Checks a property for the given value on the child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to check the property value on. | | `key` | array | | | An array of strings that make up the property that will be set. | | `value` | any | | | The value that will be checked. | | `force` | boolean | <optional> | false | If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned. | ##### Returns boolean - True if the property was was equal to value, false if not. Inherited From * [Phaser.Group#checkProperty](phaser.group#checkProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1217)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### countDead() → {integer} Get the number of dead children in this group. ##### Returns integer - The number of children flagged as dead. Inherited From * [Phaser.Group#countDead](phaser.group#countDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2338)) ### countLiving() → {integer} Get the number of living children in this group. ##### Returns integer - The number of children flagged as alive. Inherited From * [Phaser.Group#countLiving](phaser.group#countLiving) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2326](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2326)) ### create(x, y, key, frame, exists, index) → {[DisplayObject](global#DisplayObject)} Creates a new Phaser.Sprite object and adds it to the top of this group. Use [classType](phaser.group#classType) to change the type of object created. The child is automatically added to the top of the group, and is displayed above every previous child. Or if the *optional* index is specified, the child is added at the location specified by the index value, this allows you to control child ordering. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. | | `y` | number | | | The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `exists` | boolean | <optional> | true | The default exists state of the Sprite. | | `index` | integer | <optional> | | The index within the group to insert the child to. Where 0 is the bottom of the Group. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was created: will be a [Phaser.Sprite](phaser.sprite) unless #classType has been changed. Inherited From * [Phaser.Group#create](phaser.group#create) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 544](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L544)) ### createMultiple(quantity, key, frame, exists) → {array} Creates multiple Phaser.Sprite objects and adds them to the top of this Group. This method is useful if you need to quickly generate a pool of sprites, such as bullets. Use [classType](phaser.group#classType) to change the type of object created. You can provide an array as the `key` and / or `frame` arguments. When you do this it will create `quantity` Sprites for every key (and frame) in the arrays. For example: `createMultiple(25, ['ball', 'carrot'])` In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be created in total, 25 of each. You can also have the `frame` as an array: `createMultiple(5, 'bricks', [0, 1, 2, 3])` In the above there is one key (bricks), which is a sprite sheet. The frames array tells this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with frame 1, and so on. If you set both the key and frame arguments to be arrays then understand it will create a total quantity of sprites equal to the size of both arrays times each other. I.e.: `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. In total it will have created 120 sprites. By default the Sprites will have their `exists` property set to `false`, and they will be positioned at 0x0, relative to the `Group.x / y` values. If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `quantity` | integer | | | The number of Sprites to create. | | `key` | string | array | | | The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. | | `frame` | integer | string | array | <optional> | 0 | If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. | | `exists` | boolean | <optional> | false | The default exists state of the Sprite. | ##### Returns array - An array containing all of the Sprites that were created. Inherited From * [Phaser.Group#createMultiple](phaser.group#createMultiple) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 581](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L581)) ### customSort(sortHandler, context) Sort the children in the group according to custom sort function. The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `sortHandler` | function | | The custom sort function. | | `context` | object | <optional> | The context in which the sortHandler is called. | Inherited From * [Phaser.Group#customSort](phaser.group#customSort) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1895](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1895)) ### <internal> descendingSortHandler(a, b) An internal helper function for the sort process. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | object | The first object being sorted. | | `b` | object | The second object being sorted. | Inherited From * [Phaser.Group#descendingSortHandler](phaser.group#descendingSortHandler) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1951](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1951)) ### destroy(destroyChildren, soft) Destroys this group. Removes all children, then removes this group from its parent and nulls references. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | If true `destroy` will be invoked on each removed child. | | `soft` | boolean | <optional> | false | A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does. | Inherited From * [Phaser.Group#destroy](phaser.group#destroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2611](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2611)) ### divideAll(property, amount, checkAlive, checkVisible) Divides the given property by the amount on all children in this group. `Group.divideAll('x', 2)` will half the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to divide, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#divideAll](phaser.group#divideAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1437)) ### draw() Draws the P2 shapes to the Graphics object. Source code: [physics/p2/BodyDebug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/BodyDebug.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/BodyDebug.js#L85)) ### filter(predicate, checkExists) → {[Phaser.ArraySet](phaser.arrayset)} Find children matching a certain predicate. For example: ``` var healthyList = Group.filter(function(child, index, children) { return child.health > 10 ? true : false; }, true); healthyList.callAll('attack'); ``` Note: Currently this will skip any children which are Groups themselves. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `predicate` | function | | | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third | | `checkExists` | boolean | <optional> | false | If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. | ##### Returns [Phaser.ArraySet](phaser.arrayset) - Returns an array list containing all the children that the predicate returned true for Inherited From * [Phaser.Group#filter](phaser.group#filter) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1677](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1677)) ### forEach(callback, callbackContext, checkExists, args) Call a function on each child in this group. Additional arguments for the callback can be specified after the `checkExists` parameter. For example, ``` Group.forEach(awardBonusGold, this, true, 100, 500) ``` would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. Note: This check will skip any children which are Groups themselves. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `checkExists` | boolean | <optional> | false | If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEach](phaser.group#forEach) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1717](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1717)) ### forEachAlive(callback, callbackContext, args) Call a function on each alive child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachAlive](phaser.group#forEachAlive) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1799](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1799)) ### forEachDead(callback, callbackContext, args) Call a function on each dead child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachDead](phaser.group#forEachDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1827](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1827)) ### forEachExists(callback, callbackContext, args) Call a function on each existing child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachExists](phaser.group#forEachExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1771](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1771)) ### getAll(property, value, startIndex, endIndex) → {any} Returns all children in this Group. You can optionally specify a matching criteria using the `property` and `value` arguments. For example: `getAll('exists', true)` would return only children that have their exists property set. Optionally you can specify a start and end index. For example if this Group had 100 children, and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only the first 50 children in the Group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `property` | string | <optional> | | An optional property to test against the value argument. | | `value` | any | <optional> | | If property is set then Child.property must strictly equal this value to be included in the results. | | `startIndex` | integer | <optional> | 0 | The first child index to start the search from. | | `endIndex` | integer | <optional> | | The last child index to search up until. | ##### Returns any - A random existing child of this Group. Inherited From * [Phaser.Group#getAll](phaser.group#getAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2392](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2392)) ### getAt(index) → {[DisplayObject](global#DisplayObject) | integer} Returns the child found at the given index within this group. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | integer | The index to return the child from. | ##### Returns [DisplayObject](global#DisplayObject) | integer - The child that was found at the given index, or -1 for an invalid index. Inherited From * [Phaser.Group#getAt](phaser.group#getAt) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 524](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L524)) ### getBottom() → {any} Returns the child at the bottom of this group. The bottom child the child being displayed (rendered) below every other child. ##### Returns any - The child at the bottom of the Group. Inherited From * [Phaser.Group#getBottom](phaser.group#getBottom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2221)) ### getBounds(targetCoordinateSpace) → {Rectangle} Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `targetCoordinateSpace` | PIXIDisplayObject | PIXIMatrix | <optional> | Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. | ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getBounds](pixi.displayobjectcontainer#getBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 280](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L280)) ### getByName(name) → {any} Searches the Group for the first instance of a child with the `name` property matching the given argument. Should more than one child have the same name only the first instance is returned. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The name to search for. | ##### Returns any - The first child with a matching name, or null if none were found. Inherited From * [Phaser.Group#getByName](phaser.group#getByName) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1042](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1042)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getClosestTo(object, callback, callbackContext) → {any} Get the closest child to given Object, with optional callback to filter children. This can be a Sprite, Group, Image or any object with public x and y properties. 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. You can use the optional `callback` argument to apply your own filter to the distance checks. If the child is closer then the previous child, it will be sent to `callback` as the first argument, with the distance as the second. The callback should return `true` if it passes your filtering criteria, otherwise it should return `false`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `object` | any | | The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. | | `callback` | function | <optional> | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. | | `callbackContext` | object | <optional> | The context in which the function should be called (usually 'this'). | ##### Returns any - The child closest to given object, or `null` if no child was found. Inherited From * [Phaser.Group#getClosestTo](phaser.group#getClosestTo) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2238](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2238)) ### getFirstAlive(createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first child that is alive (`child.alive === true`). This is handy for choosing a squad leader, etc. You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `createIfNull` | boolean | <optional> | false | If `true` and no alive children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The alive dead child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstAlive](phaser.group#getFirstAlive) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2105](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2105)) ### getFirstDead(createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first child that is dead (`child.alive === false`). This is handy for checking if everything has been wiped out and adding to the pool as needed. You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `createIfNull` | boolean | <optional> | false | If `true` and no dead children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The first dead child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstDead](phaser.group#getFirstDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2135)) ### getFirstExists(exists, createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first display object that exists, or doesn't exist. You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `exists` | boolean | <optional> | true | If true, find the first existing child; otherwise find the first non-existing child. | | `createIfNull` | boolean | <optional> | false | If `true` and no alive children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The first child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstExists](phaser.group#getFirstExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2071](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2071)) ### getFurthestFrom(object, callback, callbackContext) → {any} Get the child furthest away from the given Object, with optional callback to filter children. This can be a Sprite, Group, Image or any object with public x and y properties. 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. You can use the optional `callback` argument to apply your own filter to the distance checks. If the child is closer then the previous child, it will be sent to `callback` as the first argument, with the distance as the second. The callback should return `true` if it passes your filtering criteria, otherwise it should return `false`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `object` | any | | The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. | | `callback` | function | <optional> | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. | | `callbackContext` | object | <optional> | The context in which the function should be called (usually 'this'). | ##### Returns any - The child furthest from the given object, or `null` if no child was found. Inherited From * [Phaser.Group#getFurthestFrom](phaser.group#getFurthestFrom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2282](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2282)) ### getIndex(child) → {integer} Get the index position of the given child in this group, which should match the child's `z` property. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to get the index for. | ##### Returns integer - The index of the child or -1 if it's not a member of this group. Inherited From * [Phaser.Group#getIndex](phaser.group#getIndex) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1029](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1029)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getLocalBounds](pixi.displayobjectcontainer#getLocalBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L437)) ### getRandom(startIndex, length) → {any} Returns a random child from the group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | <optional> | 0 | Offset from the front of the group (lowest child). | | `length` | integer | <optional> | (to top) | Restriction on the number of values you want to randomly select from. | ##### Returns any - A random child of this Group. Inherited From * [Phaser.Group#getRandom](phaser.group#getRandom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2350](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2350)) ### getRandomExists(startIndex, endIndex) → {any} Returns a random child from the Group that has `exists` set to `true`. Optionally you can specify a start and end index. For example if this Group had 100 children, and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only the first 50 children in the Group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | <optional> | 0 | The first child index to start the search from. | | `endIndex` | integer | <optional> | | The last child index to search up to. | ##### Returns any - A random child of this Group that exists. Inherited From * [Phaser.Group#getRandomExists](phaser.group#getRandomExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2372](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2372)) ### getTop() → {any} Return the child at the top of this group. The top child is the child displayed (rendered) above every other child. ##### Returns any - The child at the top of the Group. Inherited From * [Phaser.Group#getTop](phaser.group#getTop) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2204](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2204)) ### hasProperty(child, key) → {boolean} Checks if the child has the given property. Will scan up to 4 levels deep only. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to check for the existence of the property on. | | `key` | Array.<string> | An array of strings that make up the property. | ##### Returns boolean - True if the child has the property, otherwise false. Inherited From * [Phaser.Group#hasProperty](phaser.group#hasProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1104)) ### iterate(key, value, returnType, callback, callbackContext, args) → {any} Iterates over the children of the group performing one of several actions for matched children. A child is considered a match when it has a property, named `key`, whose value is equal to `value` according to a strict equality comparison. The result depends on the `returnType`: * [RETURN\_TOTAL](phaser.group#.RETURN_TOTAL): The callback, if any, is applied to all matching children. The number of matched children is returned. * [RETURN\_NONE](phaser.group#.RETURN_NONE): The callback, if any, is applied to all matching children. No value is returned. * [RETURN\_CHILD](phaser.group#.RETURN_CHILD): The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. If there is no matching child then null is returned. If `args` is specified it must be an array. The matched child will be assigned to the first element and the entire array will be applied to the callback function. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The child property to check, i.e. 'exists', 'alive', 'health' | | `value` | any | | | A child matches if `child[key] === value` is true. | | `returnType` | integer | | | How to iterate the children and what to return. | | `callback` | function | <optional> | null | Optional function that will be called on each matching child. The matched child is supplied as the first argument. | | `callbackContext` | object | <optional> | | The context in which the function should be called (usually 'this'). | | `args` | Array.<any> | <optional> | (none) | The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. | ##### Returns any - Returns either an integer (for RETURN\_TOTAL), the first matched child (for RETURN\_CHILD), or null. Inherited From * [Phaser.Group#iterate](phaser.group#iterate) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1976](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1976)) ### moveAll(group, silent) → {[Phaser.Group](phaser.group)} Moves all children from this Group to the Group given. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `group` | [Phaser.Group](phaser.group) | | | The new Group to which the children will be moved to. | | `silent` | boolean | <optional> | false | If true the children will not dispatch the `onAddedToGroup` event for the new Group. | ##### Returns [Phaser.Group](phaser.group) - The Group to which all the children were moved. Inherited From * [Phaser.Group#moveAll](phaser.group#moveAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2479](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2479)) ### moveDown(child) → {any} Moves the given child down one place in this group unless it's already at the bottom. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to move down in the group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#moveDown](phaser.group#moveDown) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 969](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L969)) ### moveUp(child) → {any} Moves the given child up one place in this group unless it's already at the top. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to move up in the group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#moveUp](phaser.group#moveUp) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 945](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L945)) ### multiplyAll(property, amount, checkAlive, checkVisible) Multiplies the given property by the amount on all children in this group. `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to multiply, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#multiplyAll](phaser.group#multiplyAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1420](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1420)) ### next() → {any} Advances the group cursor to the next (higher) object in the group. If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#next](phaser.group#next) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 833](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L833)) ### <internal> postUpdate() The core postUpdate - as called by World. Inherited From * [Phaser.Group#postUpdate](phaser.group#postUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1656](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1656)) ### <internal> preUpdate() The core preUpdate - as called by World. Inherited From * [Phaser.Group#preUpdate](phaser.group#preUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1611](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1611)) ### previous() → {any} Moves the group cursor to the previous (lower) child in the group. If the cursor is at the start of the group (bottom child) it is moved to the end (top child). ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#previous](phaser.group#previous) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 862](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L862)) ### remove(child, destroy, silent) → {boolean} Removes the given child from this group. This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. If the group cursor was referring to the removed child it is updated to refer to the next child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to remove. | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on the removed child. | | `silent` | boolean | <optional> | false | If true the the child will not dispatch the `onRemovedFromGroup` event. | ##### Returns boolean - true if the child was removed from this group, otherwise false. Inherited From * [Phaser.Group#remove](phaser.group#remove) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2431](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2431)) ### removeAll(destroy, silent, destroyTexture) Removes all children from this Group, but does not remove the group from its parent. The children can be optionally destroyed as they are removed. You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on each removed child. | | `silent` | boolean | <optional> | false | If true the children will not dispatch their `onRemovedFromGroup` events. | | `destroyTexture` | boolean | <optional> | false | If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Inherited From * [Phaser.Group#removeAll](phaser.group#removeAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2508](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2508)) ### removeBetween(startIndex, endIndex, destroy, silent) Removes all children from this group whose index falls beteen the given startIndex and endIndex values. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | | | The index to start removing children from. | | `endIndex` | integer | <optional> | | The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on each removed child. | | `silent` | boolean | <optional> | false | If true the children will not dispatch their `onRemovedFromGroup` events. | Inherited From * [Phaser.Group#removeBetween](phaser.group#removeBetween) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2556](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2556)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### removeFromHash(child) → {boolean} Removes a child of this Group from the hash array. This call will return false if the child is not in the hash. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The display object to remove from this Groups hash. Must be a member of this Group and in the hash. | ##### Returns boolean - True if the child was successfully removed from the hash, otherwise false. Inherited From * [Phaser.Group#removeFromHash](phaser.group#removeFromHash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 464](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L464)) ### replace(oldChild, newChild) → {any} Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `oldChild` | any | The child in this group that will be replaced. | | `newChild` | any | The child to be inserted into this group. | ##### Returns any - Returns the oldChild that was replaced within this group. Inherited From * [Phaser.Group#replace](phaser.group#replace) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1065](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1065)) ### resetChild(child, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | The child to reset and/or load the texture on. | | `x` | number | <optional> | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was reset: usually a [Phaser.Sprite](phaser.sprite). Inherited From * [Phaser.Group#resetChild](phaser.group#resetChild) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2165)) ### resetCursor(index) → {any} Sets the group cursor to the first child in the group. If the optional index parameter is given it sets the cursor to the object at that index instead. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `index` | integer | <optional> | 0 | Set the cursor to point to a specific index. | ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#resetCursor](phaser.group#resetCursor) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 806](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L806)) ### reverse() Reverses all children in this group. This operation applies only to immediate children and does not propagate to subgroups. Inherited From * [Phaser.Group#reverse](phaser.group#reverse) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1015](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1015)) ### sendToBack(child) → {any} Sends the given child to the bottom of this group so it renders below all other children. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to send to the bottom of this group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#sendToBack](phaser.group#sendToBack) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 926](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L926)) ### set(child, key, value, checkAlive, checkVisible, operation, force) → {boolean} Quickly set a property on a single child of this group to a new value. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [Phaser.Sprite](phaser.sprite) | | | The child to set the property on. | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then the child will only be updated if alive=true. | | `checkVisible` | boolean | <optional> | false | If set then the child will only be updated if visible=true. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | ##### Returns boolean - True if the property was set, false if not. Inherited From * [Phaser.Group#set](phaser.group#set) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1246](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1246)) ### setAll(key, value, checkAlive, checkVisible, operation, force) Quickly set the same property across all children of this group to a new value. This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. If you need that ability please see `Group.setAllChildren`. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be updated. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be updated. This includes any Groups that are children. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | Inherited From * [Phaser.Group#setAll](phaser.group#setAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1277](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1277)) ### setAllChildren(key, value, checkAlive, checkVisible, operation, force) Quickly set the same property across all children of this group, and any child Groups, to a new value. If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. Unlike with `setAll` the property is NOT set on child Groups itself. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be updated. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be updated. This includes any Groups that are children. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | Inherited From * [Phaser.Group#setAllChildren](phaser.group#setAllChildren) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1312](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1312)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setProperty(child, key, value, operation, force) → {boolean} Sets a property to the given value on the child. The operation parameter controls how the value is set. The operations are: * 0: set the existing value to the given value; if force is `true` a new property will be created if needed * 1: will add the given value to the value already present. * 2: will subtract the given value from the value already present. * 3: will multiply the value already present by the given value. * 4: will divide the value already present by the given value. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to set the property value on. | | `key` | array | | | An array of strings that make up the property that will be set. | | `value` | any | | | The value that will be set. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | ##### Returns boolean - True if the property was set, false if not. Inherited From * [Phaser.Group#setProperty](phaser.group#setProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1139)) ### sort(key, order) Sort the children in the group according to a particular key and ordering. Call this function to sort the group according to a particular key value and order. For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | <optional> | 'z' | The name of the property to sort on. Defaults to the objects z-depth value. | | `order` | integer | <optional> | Phaser.Group.SORT\_ASCENDING | Order ascending ([SORT\_ASCENDING](phaser.group#.SORT_ASCENDING)) or descending ([SORT\_DESCENDING](phaser.group#.SORT_DESCENDING)). | Inherited From * [Phaser.Group#sort](phaser.group#sort) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1855](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1855)) ### subAll(property, amount, checkAlive, checkVisible) Subtracts the amount from the given property on all children in this group. `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to decrement, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#subAll](phaser.group#subAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1403](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1403)) ### swap(child1, child2) Swaps the position of two children in this group. Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child1` | any | The first child to swap. | | `child2` | any | The second child to swap. | Inherited From * [Phaser.Group#swap](phaser.group#swap) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 891](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L891)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### <internal> update() The core update - as called by World. Inherited From * [Phaser.Group#update](phaser.group#update) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1639](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1639)) ### updateSpriteTransform() Core update. Source code: [physics/p2/BodyDebug.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/BodyDebug.js) ([Line 72](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/BodyDebug.js#L72)) ### <internal> updateZ() Internal method that re-applies all of the children's Z values. This must be called whenever children ordering is altered so that their `z` indices are correctly updated. Inherited From * [Phaser.Group#updateZ](phaser.group#updateZ) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 663](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L663)) ### xy(index, x, y) Positions the child found at the given index within this group to the given x and y coordinates. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | integer | The index of the child in the group to set the position of. | | `x` | number | The new x position of the child. | | `y` | number | The new y position of the child. | Inherited From * [Phaser.Group#xy](phaser.group#xy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 993](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L993))
programming_docs
phaser Class: Phaser.Animation Class: Phaser.Animation ======================= Constructor ----------- ### new Animation(game, parent, name, frameData, frames, frameRate, loop) An Animation instance contains a single animation and the controls to play it. It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | A reference to the currently running game. | | `parent` | [Phaser.Sprite](phaser.sprite) | | | A reference to the owner of this Animation. | | `name` | string | | | The unique name for this animation, used in playback commands. | | `frameData` | [Phaser.FrameData](phaser.framedata) | | | The FrameData object that contains all frames used by this Animation. | | `frames` | Array.<number> | Array.<string> | | | An array of numbers or strings indicating which frames to play in which order. | | `frameRate` | number | <optional> | 60 | The speed at which the animation should play. The speed is given in frames per second. | | `loop` | boolean | <optional> | false | Whether or not the animation is looped or just plays once. | Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L22)) Public Properties ----------------- ### currentFrame : [Phaser.Frame](phaser.frame) The currently displayed frame of the Animation. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L125)) ### delay : number The delay in ms between each frame of the Animation, based on the given frameRate. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L58)) ### enableUpdate : boolean Gets or sets if this animation will dispatch the onUpdate events upon changing frame. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 800](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L800)) ### frame : number Gets or sets the current frame index and updates the Texture Cache for display. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 739](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L739)) ### [readonly] frameTotal : number The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 726](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L726)) ### game : [Phaser.Game](phaser.game) A reference to the currently running Game. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L29)) ### isFinished : boolean The finished state of the Animation. Set to true once playback completes, false during playback. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L80)) ### isPaused : boolean The paused state of the Animation. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 92](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L92)) ### isPlaying : boolean The playing state of the Animation. Set to false once playback completes, true during playback. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L86)) ### isReversed : boolean Indicates if the animation will play backwards. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 157](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L157)) ### killOnComplete : boolean Should the parent of this Animation be killed when the animation completes? Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 74](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L74)) ### loop : boolean The loop state of the Animation. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 63](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L63)) ### loopCount : number The number of times the animation has looped since it was last started. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 68](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L68)) ### name : string The user defined name given to this Animation. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L46)) ### onComplete : [Phaser.Signal](phaser.signal) This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onLoop instead. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 146](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L146)) ### onLoop : [Phaser.Signal](phaser.signal) This event is dispatched when this Animation loops. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 151](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L151)) ### onStart : [Phaser.Signal](phaser.signal) This event is dispatched when this Animation starts playback. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L130)) ### onUpdate : [Phaser.Signal](phaser.signal) | null This event is dispatched when the Animation changes frame. By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`. Note that the event is only dispatched with the current frame. In a low-FPS environment Animations will automatically frame-skip to try and claw back time, so do not base your code on expecting to receive a perfectly sequential set of frames from this event. ##### Type * [Phaser.Signal](phaser.signal) | null Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 141](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L141)) ### paused : boolean Gets and sets the paused state of this Animation. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 672](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L672)) ### reversed : boolean Gets and sets the isReversed state of this Animation. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 706](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L706)) ### speed : number Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Value must be greater than 0. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 777](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L777)) Public Methods -------------- ### <static> generateFrameNames(prefix, start, stop, suffix, zeroPad) → {Array.<string>} Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers. For example imagine you've got 30 frames named: 'explosion\_0001-large' to 'explosion*0030-large' You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion*', 1, 30, '-large', 4); ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `prefix` | string | | | The start of the filename. If the filename was 'explosion*0001-large' the prefix would be 'explosion*'. | | `start` | number | | | The number to start sequentially counting from. If your frames are named 'explosion\_0001' to 'explosion\_0034' the start is 1. | | `stop` | number | | | The number to count to. If your frames are named 'explosion\_0001' to 'explosion\_0034' the stop value is 34. | | `suffix` | string | <optional> | '' | The end of the filename. If the filename was 'explosion\_0001-large' the prefix would be '-large'. | | `zeroPad` | number | <optional> | 0 | The number of zeros to pad the min and max values with. If your frames are named 'explosion\_0001' to 'explosion\_0034' then the zeroPad is 4. | ##### Returns Array.<string> - An array of framenames. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 828](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L828)) ### complete() Called internally when the animation finishes playback. Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 642](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L642)) ### destroy() Cleans up this animation ready for deletion. Nulls all values and references. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 608](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L608)) ### next(quantity) Advances by the given number of frames in the Animation, taking the loop value into consideration. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `quantity` | number | <optional> | 1 | The number of frames to advance. | Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 531](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L531)) ### onPause() Called when the Game enters a paused state. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 365](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L365)) ### onResume() Called when the Game resumes from a paused state. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 379](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L379)) ### play(frameRate, loop, killOnComplete) → {[Phaser.Animation](phaser.animation)} Plays this animation. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `frameRate` | number | <optional> | null | The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. | | `loop` | boolean | <optional> | false | Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. | | `killOnComplete` | boolean | <optional> | false | If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. | ##### Returns [Phaser.Animation](phaser.animation) - * A reference to this Animation instance. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 167](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L167)) ### previous(quantity) Moves backwards the given number of frames in the Animation, taking the loop value into consideration. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `quantity` | number | <optional> | 1 | The number of frames to move back. | Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 563](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L563)) ### restart() Sets this animation back to the first frame and restarts the animation. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 218](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L218)) ### reverse() → {[Phaser.Animation](phaser.animation)} Reverses the animation direction. ##### Returns [Phaser.Animation](phaser.animation) - The animation instance. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 246](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L246)) ### reverseOnce() → {[Phaser.Animation](phaser.animation)} Reverses the animation direction for the current/next animation only Once the onComplete event is called this method will be called again and revert the reversed state. ##### Returns [Phaser.Animation](phaser.animation) - The animation instance. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 260](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L260)) ### setFrame(frameId, useLocalFrameIndex) Sets this animations playback to a given frame with the given ID. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `frameId` | string | number | <optional> | | The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index. | | `useLocalFrameIndex` | boolean | <optional> | false | If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation. | Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 276](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L276)) ### stop(resetFrame, dispatchComplete) Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation. If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `resetFrame` | boolean | <optional> | false | If true after the animation stops the currentFrame value will be set to the first frame in this animation. | | `dispatchComplete` | boolean | <optional> | false | Dispatch the Animation.onComplete and parent.onAnimationComplete events? | Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 334](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L334)) ### update() Updates this animation. Called automatically by the AnimationManager. Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 393](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L393)) ### updateFrameData(frameData) Changes the FrameData object this Animation is using. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frameData` | [Phaser.FrameData](phaser.framedata) | The FrameData object that contains all frames used by this Animation. | Source code: [animation/Animation.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js) ([Line 595](https://github.com/photonstorm/phaser/tree/v2.6.2/src/animation/Animation.js#L595)) phaser Class: Phaser.RequestAnimationFrame Class: Phaser.RequestAnimationFrame =================================== Constructor ----------- ### new RequestAnimationFrame(game, forceSetTimeOut) Abstracts away the use of RAF or setTimeOut for the core game update loop. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | A reference to the currently running game. | | `forceSetTimeOut` | boolean | <optional> | false | Tell Phaser to use setTimeOut even if raf is available. | Source code: [utils/RequestAnimationFrame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js) ([Line 15](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js#L15)) Public Properties ----------------- ### forceSetTimeOut : boolean Tell Phaser to use setTimeOut even if raf is available. Source code: [utils/RequestAnimationFrame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js#L33)) ### game : [Phaser.Game](phaser.game) The currently running game. Source code: [utils/RequestAnimationFrame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js#L22)) ### isRunning : boolean true if RequestAnimationFrame is running, otherwise false. Source code: [utils/RequestAnimationFrame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js) ([Line 28](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js#L28)) Public Methods -------------- ### isRAF() → {boolean} Is the browser using requestAnimationFrame? ##### Returns boolean - Source code: [utils/RequestAnimationFrame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js) ([Line 162](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js#L162)) ### isSetTimeOut() → {boolean} Is the browser using setTimeout? ##### Returns boolean - Source code: [utils/RequestAnimationFrame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js#L153)) ### start() Starts the requestAnimationFrame running or setTimeout if unavailable in browser Source code: [utils/RequestAnimationFrame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js) ([Line 70](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js#L70)) ### stop() Stops the requestAnimationFrame from running. Source code: [utils/RequestAnimationFrame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js) ([Line 134](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js#L134)) ### updateRAF() The update method for the requestAnimationFrame Source code: [utils/RequestAnimationFrame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js) ([Line 103](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js#L103)) ### updateSetTimeout() The update method for the setTimeout. Source code: [utils/RequestAnimationFrame.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/utils/RequestAnimationFrame.js#L119))
programming_docs
phaser Class: PIXI.GraphicsData Class: PIXI.GraphicsData ======================== Constructor ----------- ### new GraphicsData() A GraphicsData object. Source code: [pixi/primitives/GraphicsData.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/GraphicsData.js) ([Line 1](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/primitives/GraphicsData.js#L1)) phaser Class: Phaser.StateManager Class: Phaser.StateManager ========================== Constructor ----------- ### new StateManager(game, pendingState) The State Manager is responsible for loading, setting up and switching game states. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | | | A reference to the currently running game. | | `pendingState` | [Phaser.State](phaser.state) | Object | <optional> | null | A State object to seed the manager with. | Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L17)) Public Properties ----------------- ### [readonly] created : boolean True if the current state has had its `create` method run (if it has one, if not this is true by default). Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 774](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L774)) ### current : string The current active State object. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 68](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L68)) ### game : [Phaser.Game](phaser.game) A reference to the currently running game. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L22)) ### onCreateCallback : Function This is called when the state preload has finished and creation begins. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L100)) ### onInitCallback : Function This is called when the state is set as the active state. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 88](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L88)) ### onLoadRenderCallback : Function This is called when the State is rendered during the preload phase. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 136](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L136)) ### onLoadUpdateCallback : Function This is called when the State is updated during the preload phase. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L130)) ### onPausedCallback : Function This is called when the game is paused. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 142](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L142)) ### onPauseUpdateCallback : Function This is called every frame while the game is paused. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 154](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L154)) ### onPreloadCallback : Function This is called when the state starts to load assets. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 94](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L94)) ### onPreRenderCallback : Function This is called before the state is rendered and before the stage is cleared but after all game objects have had their final properties adjusted. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 124](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L124)) ### onRenderCallback : Function This is called post-render. It doesn't happen during preload (see onLoadRenderCallback). Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L112)) ### onResizeCallback : Function This is called if ScaleManager.scalemode is RESIZE and a resize event occurs. It's passed the new width and height. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 118](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L118)) ### onResumedCallback : Function This is called when the game is resumed from a paused state. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 148](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L148)) ### onShutDownCallback : Function This is called when the state is shut down (i.e. swapped to another state). Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 160](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L160)) ### onStateChange : [Phaser.Signal](phaser.signal) onStateChange is a Phaser.Signal that is dispatched whenever the game changes state. It is dispatched only when the new state is started, which isn't usually at the same time as StateManager.start is called because state swapping is done in sync with the game loop. It is dispatched *before* any of the new states methods (such as preload and create) are called, and *after* the previous states shutdown method has been run. The callback you specify is sent two parameters: the string based key of the new state, and the second parameter is the string based key of the old / previous state. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 82](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L82)) ### onUpdateCallback : Function This is called when the state is updated, every game loop. It doesn't happen during preload (@see onLoadUpdateCallback). Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 106](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L106)) ### states : Object The object containing Phaser.States. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 27](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L27)) Public Methods -------------- ### add(key, state, autoStart) Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it. The State can be either a Phaser.State object (or an object that extends it), a plain JavaScript object or a function. If a function is given a new state object will be created by calling it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | A unique key you use to reference this state, i.e. "MainMenu", "Level1". | | `state` | [Phaser.State](phaser.state) | object | function | | | The state you want to switch to. | | `autoStart` | boolean | <optional> | false | If true the State will be started immediately after adding it. | Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 183](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L183)) ### checkState(key) → {boolean} Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | The key of the state you want to check. | ##### Returns boolean - true if the State has the required functions, otherwise false. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 423](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L423)) ### clearCurrentState() This method clears the current State, calling its shutdown callback. The process also removes any active tweens, resets the camera, resets input, clears physics, removes timers and if set clears the world and cache too. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 378](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L378)) ### destroy() Removes all StateManager callback references to the State object, nulls the game reference and clears the States object. You don't recover from this without rebuilding the Phaser instance again. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 736](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L736)) ### getCurrentState() → {[Phaser.State](phaser.state)} Gets the current State. ##### Returns [Phaser.State](phaser.state) - Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 569](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L569)) ### <internal> link(key) Links game properties to the State given by the key. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | State key. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 452](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L452)) ### <internal> loadComplete() Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 580](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L580)) ### <internal> pause() Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 604](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L604)) ### <internal> pauseUpdate() Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 653](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L653)) ### <internal> preRender(elapsedTime) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `elapsedTime` | number | The time elapsed since the last update. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 676](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L676)) ### preUpdate() preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 324](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L324)) ### remove(key) Delete the given state. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | A unique key you use to reference this state, i.e. "MainMenu", "Level1". | Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 231](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L231)) ### <internal> render() Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 703](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L703)) ### <internal> resize() Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 690](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L690)) ### restart(clearWorld, clearCache, parameter) Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `clearWorld` | boolean | <optional> | true | Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) | | `clearCache` | boolean | <optional> | false | Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. | | `parameter` | \* | <repeatable> | | Additional parameters that will be passed to the State.init function if it has one. | Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 291](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L291)) ### <internal> resume() Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 617](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L617)) ### start(key, clearWorld, clearCache, parameter) Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The key of the state you want to start. | | `clearWorld` | boolean | <optional> | true | Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) | | `clearCache` | boolean | <optional> | false | Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. | | `parameter` | \* | <repeatable> | | Additional parameters that will be passed to the State.init function (if it has one). | Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 262](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L262)) ### <internal> unlink(key) Nulls all State level Phaser properties, including a reference to Game. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `key` | string | State key. | Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 483](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L483)) ### <internal> update() Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/StateManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js) ([Line 630](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/StateManager.js#L630)) phaser Class: Phaser.TweenManager Class: Phaser.TweenManager ========================== Constructor ----------- ### new TweenManager(game) Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated. Tweens are hooked into the game clock and pause system, adjusting based on the game state. TweenManager is based heavily on tween.js by http://soledadpenades.com. The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object. It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors. Please see https://github.com/sole/tween.js for a full list of contributors. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | [Phaser.Game](phaser.game) | A reference to the currently running game. | Source code: [tween/TweenManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js) ([Line 20](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js#L20)) Public Properties ----------------- ### frameBased : boolean Are all newly created Tweens frame or time based? A frame based tween will use the physics elapsed timer when updating. This means it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should be given in frames. If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween has actually been through. For very short tweens you may wish to experiment with a frame based update instead. Source code: [tween/TweenManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js#L38)) ### game : [Phaser.Game](phaser.game) Local reference to game. Source code: [tween/TweenManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js#L25)) Public Methods -------------- ### add(tween) → {[Phaser.Tween](phaser.tween)} Add a new tween into the TweenManager. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `tween` | [Phaser.Tween](phaser.tween) | The tween object you want to add. | ##### Returns [Phaser.Tween](phaser.tween) - The tween object you added to the manager. Source code: [tween/TweenManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js) ([Line 189](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js#L189)) ### create(object) → {[Phaser.Tween](phaser.tween)} Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `object` | object | Object the tween will be run on. | ##### Returns [Phaser.Tween](phaser.tween) - The newly created tween object. Source code: [tween/TweenManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js) ([Line 203](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js#L203)) ### getAll() → {Array.<[Phaser.Tween](phaser.tween)>} Get all the tween objects in an array. ##### Returns Array.<[Phaser.Tween](phaser.tween)> - Array with all tween objects. Source code: [tween/TweenManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js) ([Line 114](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js#L114)) ### isTweening(object) → {boolean} Checks to see if a particular Sprite is currently being tweened. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `object` | object | The object to check for tweens against. | ##### Returns boolean - Returns true if the object is currently being tweened, false if not. Source code: [tween/TweenManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js) ([Line 285](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js#L285)) ### pauseAll() Pauses all currently running tweens. Source code: [tween/TweenManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js) ([Line 330](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js#L330)) ### remove(tween) Remove a tween from this manager. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `tween` | [Phaser.Tween](phaser.tween) | The tween object you want to remove. | Source code: [tween/TweenManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js) ([Line 216](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js#L216)) ### removeAll() Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events. Source code: [tween/TweenManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js#L125)) ### removeFrom(obj, children) Remove all tweens from a specific object, array of objects or Group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `obj` | object | Array.<object> | [Phaser.Group](phaser.group) | | | The object you want to remove the tweens from. | | `children` | boolean | <optional> | true | If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself. | Source code: [tween/TweenManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js) ([Line 140](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js#L140)) ### resumeAll() Resumes all currently paused tweens. Source code: [tween/TweenManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js) ([Line 344](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js#L344)) ### update() → {boolean} Update all the tween objects you added to this manager. ##### Returns boolean - Return false if there's no tween to update, otherwise return true. Source code: [tween/TweenManager.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js) ([Line 242](https://github.com/photonstorm/phaser/tree/v2.6.2/src/tween/TweenManager.js#L242))
programming_docs
phaser Class: Phaser.Physics.P2.Material Class: Phaser.Physics.P2.Material ================================= Constructor ----------- ### new Material(name) A P2 Material. \o/ ~ "Because I'm a Material girl" ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The user defined name given to this Material. | Source code: [physics/p2/Material.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Material.js) ([Line 16](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Material.js#L16)) Public Properties ----------------- ### name : string The user defined name given to this Material. Source code: [physics/p2/Material.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Material.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/physics/p2/Material.js#L22)) phaser Class: Phaser.Component.Delta Class: Phaser.Component.Delta ============================= Constructor ----------- ### new Delta() The Delta component provides access to delta values between the Game Objects current and previous position. Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L12)) Public Properties ----------------- ### [readonly] deltaX : number Returns the delta x value. The difference between world.x now and in the previous frame. The value will be positive if the Game Object has moved to the right or negative if to the left. Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 24](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L24)) ### [readonly] deltaY : number Returns the delta y value. The difference between world.y now and in the previous frame. The value will be positive if the Game Object has moved down or negative if up. Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L42)) ### [readonly] deltaZ : number Returns the delta z value. The difference between rotation now and in the previous frame. The delta value. Source code: [gameobjects/components/Delta.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js) ([Line 58](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/Delta.js#L58)) phaser Class: PIXI.CanvasRenderer Class: PIXI.CanvasRenderer ========================== Constructor ----------- ### new CanvasRenderer(game) The CanvasRenderer draws the Stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :) ##### Parameters | Name | Type | Description | | --- | --- | --- | | `game` | PhaserGame | A reference to the Phaser Game instance | Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 5](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L5)) Public Properties ----------------- ### autoResize : boolean Whether the render view should be resized automatically Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L61)) ### CanvasMaskManager : [PIXI.CanvasMaskManager](pixi.canvasmaskmanager) Instance of a PIXI.CanvasMaskManager, handles masking when using the canvas renderer Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 118](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L118)) ### clearBeforeRender : boolean This sets if the CanvasRenderer will clear the canvas or not before the new render pass. If the Stage is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color. If the Stage is transparent Pixi will use clearRect to clear the canvas every frame. Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set. Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 41](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L41)) ### context :CanvasRenderingContext2D The canvas 2d context that everything is drawn with Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 95](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L95)) ### count : number Internal var. Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 110](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L110)) ### game :PhaserGame Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 15](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L15)) ### height : number The height of the canvas view Default Value * 600 Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 78](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L78)) ### refresh : boolean Boolean flag controlling canvas refresh. Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 102](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L102)) ### renderSession : Object The render session is just a bunch of parameter used for rendering Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 125](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L125)) ### resolution : number The resolution of the canvas. Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 33](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L33)) ### transparent : boolean Whether the render view is transparent Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 53](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L53)) ### type : number The renderer type. Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 25](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L25)) ### view :HTMLCanvasElement The canvas element that everything is drawn to. Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 87](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L87)) ### width : number The width of the canvas view Default Value * 800 Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 69](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L69)) Public Methods -------------- ### destroy(removeView) Removes everything from the renderer and optionally removes the Canvas DOM element. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `removeView` | Boolean | <optional> | true | Removes the Canvas element from the DOM. | Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 194](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L194)) ### render(root) Renders the DisplayObjectContainer, usually the Phaser.Stage, to this canvas view. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `root` | PhaserStage | PIXIDisplayObjectContainer | The root element to be rendered. | Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 152](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L152)) ### resize(width, height) Resizes the canvas view to the specified width and height ##### Parameters | Name | Type | Description | | --- | --- | --- | | `width` | Number | the new width of the canvas view | | `height` | Number | the new height of the canvas view | Source code: [pixi/renderers/canvas/CanvasRenderer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js) ([Line 216](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/renderers/canvas/CanvasRenderer.js#L216)) phaser Class: Phaser.Component.LoadTexture Class: Phaser.Component.LoadTexture =================================== Constructor ----------- ### new LoadTexture() The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames. Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L12)) Public Properties ----------------- ### frame : integer Gets or sets the current frame index of the texture being used to render this Game Object. To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, for example: `player.frame = 4`. If the frame index given doesn't exist it will revert to the first frame found in the texture. If you are using a texture atlas then you should use the `frameName` property instead. If you wish to fully replace the texture being used see `loadTexture`. Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 254](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L254)) ### frameName : string Gets or sets the current frame name of the texture being used to render this Game Object. To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, for example: `player.frameName = "idle"`. If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. If you are using a sprite sheet then you should use the `frame` property instead. If you wish to fully replace the texture being used see `loadTexture`. Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 279](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L279)) Public Methods -------------- ### loadTexture(key, frame, stopAnimation) Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. You should only use `loadTexture` if you want to replace the base texture entirely. Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. Doing this then sets the key to be the `frame` argument (the frame is set to zero). This allows you to create sprites using `load.image` during development, and then change them to use a Texture Atlas later in development by simply searching your code for 'PENDING\_ATLAS' and swapping it to be the key of the atlas data. Note: You cannot use a RenderTexture as a texture for a TileSprite. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `stopAnimation` | boolean | <optional> | true | If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. | Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L51)) ### resetFrame() Resets the texture frame dimensions that the Game Object uses for rendering. Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 232](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L232)) ### resizeFrame(parent, width, height) Resizes the Frame dimensions that the Game Object uses for rendering. You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData it can be useful to adjust the dimensions directly in this way. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `parent` | object | The parent texture object that caused the resize, i.e. a Phaser.Video object. | | `width` | integer | The new width of the texture. | | `height` | integer | The new height of the texture. | Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 220](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L220)) ### setFrame(frame) Sets the texture frame the Game Object uses for rendering. This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `frame` | [Phaser.Frame](phaser.frame) | The Frame to be used by the texture. | Source code: [gameobjects/components/LoadTexture.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js) ([Line 155](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/LoadTexture.js#L155)) phaser Class: Phaser.FlexLayer Class: Phaser.FlexLayer ======================= Constructor ----------- ### new FlexLayer(manager, position, bounds, scale) WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. Please try to avoid using in production games with a long time to build. This is also why the documentation is incomplete. A responsive grid layer. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `manager` | [Phaser.FlexGrid](phaser.flexgrid) | The FlexGrid that owns this FlexLayer. | | `position` | [Phaser.Point](phaser.point) | A reference to the Point object used for positioning. | | `bounds` | [Phaser.Rectangle](phaser.rectangle) | A reference to the Rectangle used for the layer bounds. | | `scale` | [Phaser.Point](phaser.point) | A reference to the Point object used for layer scaling. | Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 22](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L22)) Extends ------- * [Phaser.Group](phaser.group) Public Properties ----------------- ### alive : boolean The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. Inherited From * [Phaser.Group#alive](phaser.group#alive) Default Value * true Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L93)) ### alpha : number The alpha value of the group container. Inherited From * [Phaser.Group#alpha](phaser.group#alpha) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 3003](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L3003)) ### angle : number The angle of rotation of the group container, in degrees. This adjusts the group itself by modifying its local rotation transform. This has no impact on the rotation/angle properties of the children, but it will update their worldTransform and on-screen orientation and position. Inherited From * [Phaser.Group#angle](phaser.group#angle) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2682](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2682)) ### bottom : number The bottom coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#bottom](phaser.group#bottom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2845](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2845)) ### bottomLeft : [Phaser.Point](phaser.point) Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 76](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L76)) ### bottomMiddle : [Phaser.Point](phaser.point) Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 81](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L81)) ### bottomRight : [Phaser.Point](phaser.point) Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L86)) ### bounds : [Phaser.Rectangle](phaser.rectangle) Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 51](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L51)) ### cameraOffset : [Phaser.Point](phaser.point) If this object is [fixedToCamera](phaser.group#fixedToCamera) then this stores the x/y position offset relative to the top-left of the camera view. If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. Inherited From * [Phaser.Group#cameraOffset](phaser.group#cameraOffset) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 272](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L272)) ### centerX : number The center x coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#centerX](phaser.group#centerX) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2705](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2705)) ### centerY : number The center y coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#centerY](phaser.group#centerY) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2733](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2733)) ### [readonly] children : Array.<[DisplayObject](global#DisplayObject)> [read-only] The array of children of this container. ##### Type * Array.<[DisplayObject](global#DisplayObject)> Inherited From * [PIXI.DisplayObjectContainer#children](pixi.displayobjectcontainer#children) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 17](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L17)) ### classType : Object The type of objects that will be created when using [create](phaser.group#create) or [createMultiple](phaser.group#createMultiple). Any object may be used but it should extend either Sprite or Image and accept the same constructor arguments: when a new object is created it is passed the following parameters to its constructor: `(game, x, y, key, frame)`. Inherited From * [Phaser.Group#classType](phaser.group#classType) Default Value * [Phaser.Sprite](phaser.sprite) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 130](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L130)) ### cursor : [DisplayObject](global#DisplayObject) The current display object that the group cursor is pointing to, if any. (Can be set manually.) The cursor is a way to iterate through the children in a Group using [next](phaser.group#next) and [previous](phaser.group#previous). Inherited From * [Phaser.Group#cursor](phaser.group#cursor) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 138](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L138)) ### [readonly] cursorIndex : integer The current index of the Group cursor. Advance it with Group.next. Inherited From * [Phaser.Group#cursorIndex](phaser.group#cursorIndex) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 255](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L255)) ### enableBody : boolean If true all Sprites created by, or added to this group, will have a physics body enabled on them. If there are children already in the Group at the time you set this property, they are not changed. The default body type is controlled with [physicsBodyType](phaser.group#physicsBodyType). Inherited From * [Phaser.Group#enableBody](phaser.group#enableBody) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 208](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L208)) ### enableBodyDebug : boolean If true when a physics body is created (via [enableBody](phaser.group#enableBody)) it will create a physics debug object as well. This only works for P2 bodies. Inherited From * [Phaser.Group#enableBodyDebug](phaser.group#enableBodyDebug) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L217)) ### exists : boolean If exists is true the group is updated, otherwise it is skipped. Inherited From * [Phaser.Group#exists](phaser.group#exists) Default Value * true Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 100](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L100)) ### fixedToCamera : boolean A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. Note that the cameraOffset values are in addition to any parent in the display list. So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x Inherited From * [Phaser.Group#fixedToCamera](phaser.group#fixedToCamera) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 265](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L265)) ### <internal> game : [Phaser.Game](phaser.game) A reference to the currently running Game. Inherited From * [Phaser.Group#game](phaser.group#game) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 38](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L38)) ### grid : [Phaser.FlexGrid](phaser.flexgrid) A reference to the FlexGrid that owns this layer. Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 34](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L34)) ### hash :array The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. Only children of this Group can be added to and removed from the hash. This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own sorting and filtering of Group children without touching their z-index (and therefore display draw order) Inherited From * [Phaser.Group#hash](phaser.group#hash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 285](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L285)) ### height : number The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#height](pixi.displayobjectcontainer#height) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 600](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L600)) ### ignoreChildInput : boolean If `ignoreChildInput` is `false` it will allow this objects *children* to be considered as valid for Input events. If this property is `true` then the children will *not* be considered as valid for Input events. Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. Inherited From * [PIXI.DisplayObjectContainer#ignoreChildInput](pixi.displayobjectcontainer#ignoreChildInput) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L26)) ### ignoreDestroy : boolean A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. Inherited From * [Phaser.Group#ignoreDestroy](phaser.group#ignoreDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 107](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L107)) ### inputEnableChildren : boolean A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` on any children *added* to, or *created by*, this Group. If there are children already in the Group at the time you set this property, they are not changed. Inherited From * [Phaser.Group#inputEnableChildren](phaser.group#inputEnableChildren) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 149](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L149)) ### left : number The left coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#left](phaser.group#left) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2761](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2761)) ### [readonly] length : integer Total number of children in this group, regardless of exists/alive status. Inherited From * [Phaser.Group#length](phaser.group#length) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2665](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2665)) ### manager ##### Properties: | Name | Type | Description | | --- | --- | --- | | `scale` | [Phaser.ScaleManager](phaser.scalemanager) | A reference to the ScaleManager. | Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 29](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L29)) ### name : string A name for this group. Not used internally but useful for debugging. Inherited From * [Phaser.Group#name](phaser.group#name) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 49](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L49)) ### onChildInputDown : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputDown](phaser.group#onChildInputDown) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 161](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L161)) ### onChildInputOut : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputOut](phaser.group#onChildInputOut) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 198](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L198)) ### onChildInputOver : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and a reference to the Pointer that caused it. Inherited From * [Phaser.Group#onChildInputOver](phaser.group#onChildInputOver) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 186](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L186)) ### onChildInputUp : [Phaser.Signal](phaser.signal) This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result of having been interacted with by a Pointer. You can bind functions to this Signal instead of to every child Sprite. This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer is still over the Sprite or not. Inherited From * [Phaser.Group#onChildInputUp](phaser.group#onChildInputUp) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 174](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L174)) ### onDestroy : [Phaser.Signal](phaser.signal) This signal is dispatched when the group is destroyed. Inherited From * [Phaser.Group#onDestroy](phaser.group#onDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 249](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L249)) ### pendingDestroy : boolean A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method called on the next logic update. You can set it directly to flag the Group to be destroyed on its next update. This is extremely useful if you wish to destroy a Group from within one of its own callbacks or a callback of one of its children. Inherited From * [Phaser.Group#pendingDestroy](phaser.group#pendingDestroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 119](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L119)) ### persist : boolean Should the FlexLayer remain through a State swap? Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 41](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L41)) ### physicsBodyType : integer If [enableBody](phaser.group#enableBody) is true this is the type of physics body that is created on new Sprites. The valid values are [Phaser.Physics.ARCADE](phaser.physics#.ARCADE), [Phaser.Physics.P2JS](phaser.physics#.P2JS), [Phaser.Physics.NINJA](phaser.physics#.NINJA), etc. Inherited From * [Phaser.Group#physicsBodyType](phaser.group#physicsBodyType) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 225](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L225)) ### physicsSortDirection : integer If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. It should be set to one of the Phaser.Physics.Arcade sort direction constants: Phaser.Physics.Arcade.SORT\_NONE Phaser.Physics.Arcade.LEFT\_RIGHT Phaser.Physics.Arcade.RIGHT\_LEFT Phaser.Physics.Arcade.TOP\_BOTTOM Phaser.Physics.Arcade.BOTTOM\_TOP If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. Inherited From * [Phaser.Group#physicsSortDirection](phaser.group#physicsSortDirection) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 243](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L243)) ### [readonly] physicsType : number The const physics body type of this object. Inherited From * [Phaser.Group#physicsType](phaser.group#physicsType) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 86](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L86)) ### position : [Phaser.Point](phaser.point) Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 46](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L46)) ### right : number The right coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#right](phaser.group#right) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2789](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2789)) ### rotation : number The angle of rotation of the group container, in radians. This will adjust the group container itself by modifying its rotation. This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. Inherited From * [Phaser.Group#rotation](phaser.group#rotation) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2987](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2987)) ### scale : [Phaser.Point](phaser.point) Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 56](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L56)) ### top : number The top coordinate of this Group. It is derived by calling `getBounds`, calculating the Groups dimensions based on its visible children. Inherited From * [Phaser.Group#top](phaser.group#top) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2817](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2817)) ### topLeft : [Phaser.Point](phaser.point) Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 61](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L61)) ### topMiddle : [Phaser.Point](phaser.point) Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 66](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L66)) ### topRight : [Phaser.Point](phaser.point) Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 71](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L71)) ### [readonly] total : integer Total number of existing children in the group. Inherited From * [Phaser.Group#total](phaser.group#total) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2648](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2648)) ### <internal> type : integer Internal Phaser Type value. Inherited From * [Phaser.Group#type](phaser.group#type) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 80](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L80)) ### visible : boolean The visible state of the group. Non-visible Groups and all of their children are not rendered. Inherited From * [Phaser.Group#visible](phaser.group#visible) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2996](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2996)) ### width : number The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set Inherited From * [PIXI.DisplayObjectContainer#width](pixi.displayobjectcontainer#width) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 571](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L571)) ### x : number The x coordinate of the group container. You can adjust the group container itself by modifying its coordinates. This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. Inherited From * [Phaser.Group#x](phaser.group#x) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2969](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2969)) ### y : number The y coordinate of the group container. You can adjust the group container itself by modifying its coordinates. This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. Inherited From * [Phaser.Group#y](phaser.group#y) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2978](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2978)) ### [readonly] z : integer The z-depth value of this object within its parent container/Group - the World is a Group as well. This value must be unique for each child in a Group. Inherited From * [Phaser.Group#z](phaser.group#z) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 57](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L57)) Public Methods -------------- ### add(child, silent, index) → {[DisplayObject](global#DisplayObject)} Adds an existing object as the top child in this group. The child is automatically added to the top of the group, and is displayed above every previous child. Or if the *optional* index is specified, the child is added at the location specified by the index value, this allows you to control child ordering. If the child was already in this Group, it is simply returned, and nothing else happens to it. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. Use [addAt](phaser.group#addAt) to control where a child is added. Use [create](phaser.group#create) to create and add a new child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | | The display object to add as a child. | | `silent` | boolean | <optional> | false | If true the child will not dispatch the `onAddedToGroup` event. | | `index` | integer | <optional> | | The index within the group to insert the child to. Where 0 is the bottom of the Group. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added to the group. Inherited From * [Phaser.Group#add](phaser.group#add) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 341](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L341)) ### addAll(property, amount, checkAlive, checkVisible) Adds the amount to the given property on all children in this group. `Group.addAll('x', 10)` will add 10 to the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to increment, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#addAll](phaser.group#addAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1386](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1386)) ### addAt(child, index, silent) → {[DisplayObject](global#DisplayObject)} Adds an existing object to this group. The child is added to the group at the location specified by the index value, this allows you to control child ordering. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | | The display object to add as a child. | | `index` | integer | <optional> | 0 | The index within the group to insert the child to. | | `silent` | boolean | <optional> | false | If true the child will not dispatch the `onAddedToGroup` event. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added to the group. Inherited From * [Phaser.Group#addAt](phaser.group#addAt) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 418](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L418)) ### addChild(child) → {[DisplayObject](global#DisplayObject)} Adds a child to the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to add to the container | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChild](pixi.displayobjectcontainer#addChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 42](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L42)) ### addChildAt(child, index) → {[DisplayObject](global#DisplayObject)} Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child to add | | `index` | Number | The index to place the child in | ##### Returns [DisplayObject](global#DisplayObject) - The child that was added. Inherited From * [PIXI.DisplayObjectContainer#addChildAt](pixi.displayobjectcontainer#addChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 55](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L55)) ### addMultiple(children, silent) → {Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group)} Adds an array of existing Display Objects to this Group. The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. As well as an array you can also pass another Group as the first argument. In this case all of the children from that Group will be removed from it and added into this Group. If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `children` | Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group) | | | An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. | | `silent` | boolean | <optional> | false | If true the children will not dispatch the `onAddedToGroup` event. | ##### Returns Array.<[DisplayObject](global#DisplayObject)> | [Phaser.Group](phaser.group) - The array of children or Group of children that were added to this Group. Inherited From * [Phaser.Group#addMultiple](phaser.group#addMultiple) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 489](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L489)) ### addToHash(child) → {boolean} Adds a child of this Group into the hash array. This call will return false if the child is not a child of this Group, or is already in the hash. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. | ##### Returns boolean - True if the child was successfully added to the hash, otherwise false. Inherited From * [Phaser.Group#addToHash](phaser.group#addToHash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 439](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L439)) ### align(width, height, cellWidth, cellHeight, position, offset) → {boolean} This method iterates through all children in the Group (regardless if they are visible or exist) and then changes their position so they are arranged in a Grid formation. Children must have the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have this. The grid dimensions are determined by the first four arguments. The `width` and `height` arguments relate to the width and height of the grid respectively. For example if the Group had 100 children in it: `Group.align(10, 10, 32, 32)` This will align all of the children into a grid formation of 10x10, using 32 pixels per grid cell. If you want a wider grid, you could do: `Group.align(25, 4, 32, 32)` This will align the children into a grid of 25x4, again using 32 pixels per grid cell. You can choose to set *either* the `width` or `height` value to -1. Doing so tells the method to keep on aligning children until there are no children left. For example if this Group had 48 children in it, the following: `Group.align(-1, 8, 32, 32)` ... will align the children so that there are 8 children vertically (the second argument), and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) You can also do: `Group.align(10, -1, 32, 32)` In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit all of the children in. The `position` property allows you to control where in each grid cell the child is positioned. This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. The final argument; `offset` lets you start the alignment from a specific child index. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `width` | integer | | | The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. | | `height` | integer | | | The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. | | `cellWidth` | integer | | | The width of each grid cell, in pixels. | | `cellHeight` | integer | | | The height of each grid cell, in pixels. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offset` | integer | <optional> | 0 | Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. | ##### Returns boolean - True if the Group children were aligned, otherwise false. Inherited From * [Phaser.Group#align](phaser.group#align) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 682](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L682)) ### alignIn(container, position, offsetX, offsetY) → {[Phaser.Group](phaser.group)} Aligns this Group within another Game Object, or Rectangle, known as the 'container', to one of 9 possible positions. The container must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Groups within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Group to another Game Object does **not** make it a child of the container. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. Groups are placed in such a way that their *bounds* align with the container, taking into consideration rotation and scale of its children. This allows you to neatly align Groups, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Group. For example: `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `container` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns [Phaser.Group](phaser.group) - This Group. Inherited From * [Phaser.Group#alignIn](phaser.group#alignIn) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2873](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2873)) ### alignTo(parent, position, offsetX, offsetY) → {[Phaser.Group](phaser.group)} Aligns this Group to the side of another Game Object, or Rectangle, known as the 'parent', in one of 11 possible positions. The parent must be a Game Object, or Phaser.Rectangle object. This can include properties such as `World.bounds` or `Camera.view`, for aligning Groups within the world and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, TileSprites or Buttons. Please note that aligning a Group to another Game Object does **not** make it a child of the parent. It simply modifies its position coordinates so it aligns with it. The position constants you can use are: `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. Groups are placed in such a way that their *bounds* align with the parent, taking into consideration rotation and scale of the children. This allows you to neatly align Groups, irrespective of their position value. The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final aligned position of the Group. For example: `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive one expands it. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `parent` | [Phaser.Rectangle](phaser.rectangle) | [Phaser.Sprite](phaser.sprite) | [Phaser.Image](phaser.image) | [Phaser.Text](phaser.text) | [Phaser.BitmapText](phaser.bitmaptext) | [Phaser.Button](phaser.button) | [Phaser.Graphics](phaser.graphics) | [Phaser.TileSprite](phaser.tilesprite) | | | The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. | | `position` | integer | <optional> | | The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. | | `offsetX` | integer | <optional> | 0 | A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | | `offsetY` | integer | <optional> | 0 | A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. | ##### Returns [Phaser.Group](phaser.group) - This Group. Inherited From * [Phaser.Group#alignTo](phaser.group#alignTo) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2915](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2915)) ### <internal> ascendingSortHandler(a, b) An internal helper function for the sort process. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | object | The first object being sorted. | | `b` | object | The second object being sorted. | Inherited From * [Phaser.Group#ascendingSortHandler](phaser.group#ascendingSortHandler) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1919](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1919)) ### bringToTop(child) → {any} Brings the given child to the top of this group so it renders above all other children. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to bring to the top of this group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#bringToTop](phaser.group#bringToTop) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 907](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L907)) ### callAll(method, context, args) Calls a function, specified by name, on all on children. The function is called for all children regardless if they are dead or alive (see callAllExists for different options). After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `method` | string | | | Name of the function on the child to call. Deep property lookup is supported. | | `context` | string | <optional> | null | A string containing the context under which the method will be executed. Set to null to default to the child. | | `args` | any | <repeatable> | | Additional parameters that will be passed to the method. | Inherited From * [Phaser.Group#callAll](phaser.group#callAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1538](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1538)) ### callAllExists(callback, existsValue, parameter) Calls a function, specified by name, on all children in the group who exist (or do not exist). After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `callback` | string | | Name of the function on the children to call. | | `existsValue` | boolean | | Only children with exists=existsValue will be called. | | `parameter` | any | <repeatable> | Additional parameters that will be passed to the callback. | Inherited From * [Phaser.Group#callAllExists](phaser.group#callAllExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1454](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1454)) ### <internal> callbackFromArray(child, callback, length) Returns a reference to a function that exists on a child of the group based on the given callback array. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | object | The object to inspect. | | `callback` | array | The array of function names. | | `length` | integer | The size of the array (pre-calculated in callAll). | Inherited From * [Phaser.Group#callbackFromArray](phaser.group#callbackFromArray) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1488](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1488)) ### checkAll(key, value, checkAlive, checkVisible, force) Quickly check that the same property across all children of this group is equal to the given value. This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be checked. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be checked. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be checked. This includes any Groups that are children. | | `force` | boolean | <optional> | false | If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned. | Inherited From * [Phaser.Group#checkAll](phaser.group#checkAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1353](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1353)) ### checkProperty(child, key, value, force) → {boolean} Checks a property for the given value on the child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to check the property value on. | | `key` | array | | | An array of strings that make up the property that will be set. | | `value` | any | | | The value that will be checked. | | `force` | boolean | <optional> | false | If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned. | ##### Returns boolean - True if the property was was equal to value, false if not. Inherited From * [Phaser.Group#checkProperty](phaser.group#checkProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1217](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1217)) ### contains(child) → {Boolean} Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | ##### Returns Boolean - Inherited From * [PIXI.DisplayObjectContainer#contains](pixi.displayobjectcontainer#contains) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 449](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L449)) ### countDead() → {integer} Get the number of dead children in this group. ##### Returns integer - The number of children flagged as dead. Inherited From * [Phaser.Group#countDead](phaser.group#countDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2338](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2338)) ### countLiving() → {integer} Get the number of living children in this group. ##### Returns integer - The number of children flagged as alive. Inherited From * [Phaser.Group#countLiving](phaser.group#countLiving) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2326](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2326)) ### create(x, y, key, frame, exists, index) → {[DisplayObject](global#DisplayObject)} Creates a new Phaser.Sprite object and adds it to the top of this group. Use [classType](phaser.group#classType) to change the type of object created. The child is automatically added to the top of the group, and is displayed above every previous child. Or if the *optional* index is specified, the child is added at the location specified by the index value, this allows you to control child ordering. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `x` | number | | | The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. | | `y` | number | | | The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | | `exists` | boolean | <optional> | true | The default exists state of the Sprite. | | `index` | integer | <optional> | | The index within the group to insert the child to. Where 0 is the bottom of the Group. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was created: will be a [Phaser.Sprite](phaser.sprite) unless #classType has been changed. Inherited From * [Phaser.Group#create](phaser.group#create) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 544](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L544)) ### createMultiple(quantity, key, frame, exists) → {array} Creates multiple Phaser.Sprite objects and adds them to the top of this Group. This method is useful if you need to quickly generate a pool of sprites, such as bullets. Use [classType](phaser.group#classType) to change the type of object created. You can provide an array as the `key` and / or `frame` arguments. When you do this it will create `quantity` Sprites for every key (and frame) in the arrays. For example: `createMultiple(25, ['ball', 'carrot'])` In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be created in total, 25 of each. You can also have the `frame` as an array: `createMultiple(5, 'bricks', [0, 1, 2, 3])` In the above there is one key (bricks), which is a sprite sheet. The frames array tells this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with frame 1, and so on. If you set both the key and frame arguments to be arrays then understand it will create a total quantity of sprites equal to the size of both arrays times each other. I.e.: `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. In total it will have created 120 sprites. By default the Sprites will have their `exists` property set to `false`, and they will be positioned at 0x0, relative to the `Group.x / y` values. If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `quantity` | integer | | | The number of Sprites to create. | | `key` | string | array | | | The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. | | `frame` | integer | string | array | <optional> | 0 | If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. | | `exists` | boolean | <optional> | false | The default exists state of the Sprite. | ##### Returns array - An array containing all of the Sprites that were created. Inherited From * [Phaser.Group#createMultiple](phaser.group#createMultiple) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 581](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L581)) ### customSort(sortHandler, context) Sort the children in the group according to custom sort function. The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `sortHandler` | function | | The custom sort function. | | `context` | object | <optional> | The context in which the sortHandler is called. | Inherited From * [Phaser.Group#customSort](phaser.group#customSort) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1895](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1895)) ### debug() Debug. Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 101](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L101)) ### <internal> descendingSortHandler(a, b) An internal helper function for the sort process. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `a` | object | The first object being sorted. | | `b` | object | The second object being sorted. | Inherited From * [Phaser.Group#descendingSortHandler](phaser.group#descendingSortHandler) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1951](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1951)) ### destroy(destroyChildren, soft) Destroys this group. Removes all children, then removes this group from its parent and nulls references. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroyChildren` | boolean | <optional> | true | If true `destroy` will be invoked on each removed child. | | `soft` | boolean | <optional> | false | A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does. | Inherited From * [Phaser.Group#destroy](phaser.group#destroy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2611](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2611)) ### divideAll(property, amount, checkAlive, checkVisible) Divides the given property by the amount on all children in this group. `Group.divideAll('x', 2)` will half the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to divide, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#divideAll](phaser.group#divideAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1437)) ### filter(predicate, checkExists) → {[Phaser.ArraySet](phaser.arrayset)} Find children matching a certain predicate. For example: ``` var healthyList = Group.filter(function(child, index, children) { return child.health > 10 ? true : false; }, true); healthyList.callAll('attack'); ``` Note: Currently this will skip any children which are Groups themselves. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `predicate` | function | | | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third | | `checkExists` | boolean | <optional> | false | If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. | ##### Returns [Phaser.ArraySet](phaser.arrayset) - Returns an array list containing all the children that the predicate returned true for Inherited From * [Phaser.Group#filter](phaser.group#filter) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1677](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1677)) ### forEach(callback, callbackContext, checkExists, args) Call a function on each child in this group. Additional arguments for the callback can be specified after the `checkExists` parameter. For example, ``` Group.forEach(awardBonusGold, this, true, 100, 500) ``` would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. Note: This check will skip any children which are Groups themselves. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `checkExists` | boolean | <optional> | false | If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEach](phaser.group#forEach) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1717](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1717)) ### forEachAlive(callback, callbackContext, args) Call a function on each alive child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachAlive](phaser.group#forEachAlive) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1799](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1799)) ### forEachDead(callback, callbackContext, args) Call a function on each dead child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachDead](phaser.group#forEachDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1827](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1827)) ### forEachExists(callback, callbackContext, args) Call a function on each existing child in this group. See [forEach](phaser.group#forEach) for details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `callback` | function | | | The function that will be called for each applicable child. The child will be passed as the first argument. | | `callbackContext` | object | | | The context in which the function should be called (usually 'this'). | | `args` | any | <optional> <repeatable> | (none) | Additional arguments to pass to the callback function, after the child item. | Inherited From * [Phaser.Group#forEachExists](phaser.group#forEachExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1771](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1771)) ### getAll(property, value, startIndex, endIndex) → {any} Returns all children in this Group. You can optionally specify a matching criteria using the `property` and `value` arguments. For example: `getAll('exists', true)` would return only children that have their exists property set. Optionally you can specify a start and end index. For example if this Group had 100 children, and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only the first 50 children in the Group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `property` | string | <optional> | | An optional property to test against the value argument. | | `value` | any | <optional> | | If property is set then Child.property must strictly equal this value to be included in the results. | | `startIndex` | integer | <optional> | 0 | The first child index to start the search from. | | `endIndex` | integer | <optional> | | The last child index to search up until. | ##### Returns any - A random existing child of this Group. Inherited From * [Phaser.Group#getAll](phaser.group#getAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2392](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2392)) ### getAt(index) → {[DisplayObject](global#DisplayObject) | integer} Returns the child found at the given index within this group. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | integer | The index to return the child from. | ##### Returns [DisplayObject](global#DisplayObject) | integer - The child that was found at the given index, or -1 for an invalid index. Inherited From * [Phaser.Group#getAt](phaser.group#getAt) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 524](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L524)) ### getBottom() → {any} Returns the child at the bottom of this group. The bottom child the child being displayed (rendered) below every other child. ##### Returns any - The child at the bottom of the Group. Inherited From * [Phaser.Group#getBottom](phaser.group#getBottom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2221](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2221)) ### getBounds(targetCoordinateSpace) → {Rectangle} Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `targetCoordinateSpace` | PIXIDisplayObject | PIXIMatrix | <optional> | Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. | ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getBounds](pixi.displayobjectcontainer#getBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 280](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L280)) ### getByName(name) → {any} Searches the Group for the first instance of a child with the `name` property matching the given argument. Should more than one child have the same name only the first instance is returned. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `name` | string | The name to search for. | ##### Returns any - The first child with a matching name, or null if none were found. Inherited From * [Phaser.Group#getByName](phaser.group#getByName) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1042](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1042)) ### getChildAt(index) → {[DisplayObject](global#DisplayObject)} Returns the child at the specified index ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child at the given index, if any. Inherited From * [PIXI.DisplayObjectContainer#getChildAt](pixi.displayobjectcontainer#getChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 153](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L153)) ### getChildIndex(child) → {Number} Returns the index position of a child DisplayObject instance ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject instance to identify | ##### Returns Number - The index position of the child display object to identify Inherited From * [PIXI.DisplayObjectContainer#getChildIndex](pixi.displayobjectcontainer#getChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 112](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L112)) ### getClosestTo(object, callback, callbackContext) → {any} Get the closest child to given Object, with optional callback to filter children. This can be a Sprite, Group, Image or any object with public x and y properties. 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. You can use the optional `callback` argument to apply your own filter to the distance checks. If the child is closer then the previous child, it will be sent to `callback` as the first argument, with the distance as the second. The callback should return `true` if it passes your filtering criteria, otherwise it should return `false`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `object` | any | | The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. | | `callback` | function | <optional> | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. | | `callbackContext` | object | <optional> | The context in which the function should be called (usually 'this'). | ##### Returns any - The child closest to given object, or `null` if no child was found. Inherited From * [Phaser.Group#getClosestTo](phaser.group#getClosestTo) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2238](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2238)) ### getFirstAlive(createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first child that is alive (`child.alive === true`). This is handy for choosing a squad leader, etc. You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `createIfNull` | boolean | <optional> | false | If `true` and no alive children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The alive dead child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstAlive](phaser.group#getFirstAlive) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2105](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2105)) ### getFirstDead(createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first child that is dead (`child.alive === false`). This is handy for checking if everything has been wiped out and adding to the pool as needed. You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `createIfNull` | boolean | <optional> | false | If `true` and no dead children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The first dead child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstDead](phaser.group#getFirstDead) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2135](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2135)) ### getFirstExists(exists, createIfNull, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Get the first display object that exists, or doesn't exist. You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `exists` | boolean | <optional> | true | If true, find the first existing child; otherwise find the first non-existing child. | | `createIfNull` | boolean | <optional> | false | If `true` and no alive children are found a new one is created. | | `x` | number | <optional> | | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The first child, or `null` if none found and `createIfNull` was false. Inherited From * [Phaser.Group#getFirstExists](phaser.group#getFirstExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2071](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2071)) ### getFurthestFrom(object, callback, callbackContext) → {any} Get the child furthest away from the given Object, with optional callback to filter children. This can be a Sprite, Group, Image or any object with public x and y properties. 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. You can use the optional `callback` argument to apply your own filter to the distance checks. If the child is closer then the previous child, it will be sent to `callback` as the first argument, with the distance as the second. The callback should return `true` if it passes your filtering criteria, otherwise it should return `false`. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `object` | any | | The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. | | `callback` | function | <optional> | The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. | | `callbackContext` | object | <optional> | The context in which the function should be called (usually 'this'). | ##### Returns any - The child furthest from the given object, or `null` if no child was found. Inherited From * [Phaser.Group#getFurthestFrom](phaser.group#getFurthestFrom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2282](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2282)) ### getIndex(child) → {integer} Get the index position of the given child in this group, which should match the child's `z` property. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to get the index for. | ##### Returns integer - The index of the child or -1 if it's not a member of this group. Inherited From * [Phaser.Group#getIndex](phaser.group#getIndex) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1029](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1029)) ### getLocalBounds() → {Rectangle} Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. ##### Returns Rectangle - The rectangular bounding area Inherited From * [PIXI.DisplayObjectContainer#getLocalBounds](pixi.displayobjectcontainer#getLocalBounds) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 437](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L437)) ### getRandom(startIndex, length) → {any} Returns a random child from the group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | <optional> | 0 | Offset from the front of the group (lowest child). | | `length` | integer | <optional> | (to top) | Restriction on the number of values you want to randomly select from. | ##### Returns any - A random child of this Group. Inherited From * [Phaser.Group#getRandom](phaser.group#getRandom) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2350](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2350)) ### getRandomExists(startIndex, endIndex) → {any} Returns a random child from the Group that has `exists` set to `true`. Optionally you can specify a start and end index. For example if this Group had 100 children, and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only the first 50 children in the Group. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | <optional> | 0 | The first child index to start the search from. | | `endIndex` | integer | <optional> | | The last child index to search up to. | ##### Returns any - A random child of this Group that exists. Inherited From * [Phaser.Group#getRandomExists](phaser.group#getRandomExists) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2372](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2372)) ### getTop() → {any} Return the child at the top of this group. The top child is the child displayed (rendered) above every other child. ##### Returns any - The child at the top of the Group. Inherited From * [Phaser.Group#getTop](phaser.group#getTop) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2204](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2204)) ### hasProperty(child, key) → {boolean} Checks if the child has the given property. Will scan up to 4 levels deep only. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to check for the existence of the property on. | | `key` | Array.<string> | An array of strings that make up the property. | ##### Returns boolean - True if the child has the property, otherwise false. Inherited From * [Phaser.Group#hasProperty](phaser.group#hasProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1104](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1104)) ### iterate(key, value, returnType, callback, callbackContext, args) → {any} Iterates over the children of the group performing one of several actions for matched children. A child is considered a match when it has a property, named `key`, whose value is equal to `value` according to a strict equality comparison. The result depends on the `returnType`: * [RETURN\_TOTAL](phaser.group#.RETURN_TOTAL): The callback, if any, is applied to all matching children. The number of matched children is returned. * [RETURN\_NONE](phaser.group#.RETURN_NONE): The callback, if any, is applied to all matching children. No value is returned. * [RETURN\_CHILD](phaser.group#.RETURN_CHILD): The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. If there is no matching child then null is returned. If `args` is specified it must be an array. The matched child will be assigned to the first element and the entire array will be applied to the callback function. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The child property to check, i.e. 'exists', 'alive', 'health' | | `value` | any | | | A child matches if `child[key] === value` is true. | | `returnType` | integer | | | How to iterate the children and what to return. | | `callback` | function | <optional> | null | Optional function that will be called on each matching child. The matched child is supplied as the first argument. | | `callbackContext` | object | <optional> | | The context in which the function should be called (usually 'this'). | | `args` | Array.<any> | <optional> | (none) | The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. | ##### Returns any - Returns either an integer (for RETURN\_TOTAL), the first matched child (for RETURN\_CHILD), or null. Inherited From * [Phaser.Group#iterate](phaser.group#iterate) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1976](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1976)) ### moveAll(group, silent) → {[Phaser.Group](phaser.group)} Moves all children from this Group to the Group given. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `group` | [Phaser.Group](phaser.group) | | | The new Group to which the children will be moved to. | | `silent` | boolean | <optional> | false | If true the children will not dispatch the `onAddedToGroup` event for the new Group. | ##### Returns [Phaser.Group](phaser.group) - The Group to which all the children were moved. Inherited From * [Phaser.Group#moveAll](phaser.group#moveAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2479](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2479)) ### moveDown(child) → {any} Moves the given child down one place in this group unless it's already at the bottom. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to move down in the group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#moveDown](phaser.group#moveDown) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 969](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L969)) ### moveUp(child) → {any} Moves the given child up one place in this group unless it's already at the top. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to move up in the group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#moveUp](phaser.group#moveUp) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 945](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L945)) ### multiplyAll(property, amount, checkAlive, checkVisible) Multiplies the given property by the amount on all children in this group. `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to multiply, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#multiplyAll](phaser.group#multiplyAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1420](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1420)) ### next() → {any} Advances the group cursor to the next (higher) object in the group. If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#next](phaser.group#next) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 833](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L833)) ### <internal> postUpdate() The core postUpdate - as called by World. Inherited From * [Phaser.Group#postUpdate](phaser.group#postUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1656](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1656)) ### <internal> preUpdate() The core preUpdate - as called by World. Inherited From * [Phaser.Group#preUpdate](phaser.group#preUpdate) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1611](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1611)) ### previous() → {any} Moves the group cursor to the previous (lower) child in the group. If the cursor is at the start of the group (bottom child) it is moved to the end (top child). ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#previous](phaser.group#previous) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 862](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L862)) ### remove(child, destroy, silent) → {boolean} Removes the given child from this group. This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. If the group cursor was referring to the removed child it is updated to refer to the next child. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to remove. | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on the removed child. | | `silent` | boolean | <optional> | false | If true the the child will not dispatch the `onRemovedFromGroup` event. | ##### Returns boolean - true if the child was removed from this group, otherwise false. Inherited From * [Phaser.Group#remove](phaser.group#remove) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2431](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2431)) ### removeAll(destroy, silent, destroyTexture) Removes all children from this Group, but does not remove the group from its parent. The children can be optionally destroyed as they are removed. You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've more than one Game Object sharing the same BaseTexture. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on each removed child. | | `silent` | boolean | <optional> | false | If true the children will not dispatch their `onRemovedFromGroup` events. | | `destroyTexture` | boolean | <optional> | false | If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. | Inherited From * [Phaser.Group#removeAll](phaser.group#removeAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2508](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2508)) ### removeBetween(startIndex, endIndex, destroy, silent) Removes all children from this group whose index falls beteen the given startIndex and endIndex values. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `startIndex` | integer | | | The index to start removing children from. | | `endIndex` | integer | <optional> | | The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. | | `destroy` | boolean | <optional> | false | If true `destroy` will be invoked on each removed child. | | `silent` | boolean | <optional> | false | If true the children will not dispatch their `onRemovedFromGroup` events. | Inherited From * [Phaser.Group#removeBetween](phaser.group#removeBetween) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2556](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2556)) ### removeChild(child) → {[DisplayObject](global#DisplayObject)} Removes a child from the container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The DisplayObject to remove | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChild](pixi.displayobjectcontainer#removeChild) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 171](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L171)) ### removeChildAt(index) → {[DisplayObject](global#DisplayObject)} Removes a child from the specified index position. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | Number | The index to get the child from | ##### Returns [DisplayObject](global#DisplayObject) - The child that was removed. Inherited From * [PIXI.DisplayObjectContainer#removeChildAt](pixi.displayobjectcontainer#removeChildAt) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 191](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L191)) ### removeChildren(beginIndex, endIndex) Removes all children from this container that are within the begin and end indexes. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `beginIndex` | Number | The beginning position. Default value is 0. | | `endIndex` | Number | The ending position. Default value is size of the container. | Inherited From * [PIXI.DisplayObjectContainer#removeChildren](pixi.displayobjectcontainer#removeChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 213](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L213)) ### removeFromHash(child) → {boolean} Removes a child of this Group from the hash array. This call will return false if the child is not in the hash. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The display object to remove from this Groups hash. Must be a member of this Group and in the hash. | ##### Returns boolean - True if the child was successfully removed from the hash, otherwise false. Inherited From * [Phaser.Group#removeFromHash](phaser.group#removeFromHash) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 464](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L464)) ### replace(oldChild, newChild) → {any} Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `oldChild` | any | The child in this group that will be replaced. | | `newChild` | any | The child to be inserted into this group. | ##### Returns any - Returns the oldChild that was replaced within this group. Inherited From * [Phaser.Group#replace](phaser.group#replace) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1065](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1065)) ### resetChild(child, x, y, key, frame) → {[DisplayObject](global#DisplayObject)} Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. ##### Parameters | Name | Type | Argument | Description | | --- | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | | The child to reset and/or load the texture on. | | `x` | number | <optional> | The x coordinate to reset the child to. The value is in relation to the group.x point. | | `y` | number | <optional> | The y coordinate to reset the child to. The value is in relation to the group.y point. | | `key` | string | [Phaser.RenderTexture](phaser.rendertexture) | [Phaser.BitmapData](phaser.bitmapdata) | [Phaser.Video](phaser.video) | [PIXI.Texture](pixi.texture) | <optional> | This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. | | `frame` | string | number | <optional> | If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. | ##### Returns [DisplayObject](global#DisplayObject) - The child that was reset: usually a [Phaser.Sprite](phaser.sprite). Inherited From * [Phaser.Group#resetChild](phaser.group#resetChild) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 2165](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L2165)) ### resetCursor(index) → {any} Sets the group cursor to the first child in the group. If the optional index parameter is given it sets the cursor to the object at that index instead. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `index` | integer | <optional> | 0 | Set the cursor to point to a specific index. | ##### Returns any - The child the cursor now points to. Inherited From * [Phaser.Group#resetCursor](phaser.group#resetCursor) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 806](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L806)) ### resize() Resize. Source code: [core/FlexLayer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js) ([Line 93](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/FlexLayer.js#L93)) ### reverse() Reverses all children in this group. This operation applies only to immediate children and does not propagate to subgroups. Inherited From * [Phaser.Group#reverse](phaser.group#reverse) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1015](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1015)) ### sendToBack(child) → {any} Sends the given child to the bottom of this group so it renders below all other children. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | any | The child to send to the bottom of this group. | ##### Returns any - The child that was moved. Inherited From * [Phaser.Group#sendToBack](phaser.group#sendToBack) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 926](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L926)) ### set(child, key, value, checkAlive, checkVisible, operation, force) → {boolean} Quickly set a property on a single child of this group to a new value. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | [Phaser.Sprite](phaser.sprite) | | | The child to set the property on. | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then the child will only be updated if alive=true. | | `checkVisible` | boolean | <optional> | false | If set then the child will only be updated if visible=true. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | ##### Returns boolean - True if the property was set, false if not. Inherited From * [Phaser.Group#set](phaser.group#set) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1246](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1246)) ### setAll(key, value, checkAlive, checkVisible, operation, force) Quickly set the same property across all children of this group to a new value. This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. If you need that ability please see `Group.setAllChildren`. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be updated. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be updated. This includes any Groups that are children. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | Inherited From * [Phaser.Group#setAll](phaser.group#setAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1277](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1277)) ### setAllChildren(key, value, checkAlive, checkVisible, operation, force) Quickly set the same property across all children of this group, and any child Groups, to a new value. If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. Unlike with `setAll` the property is NOT set on child Groups itself. The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | | | The property, as a string, to be set. For example: 'body.velocity.x' | | `value` | any | | | The value that will be set. | | `checkAlive` | boolean | <optional> | false | If set then only children with alive=true will be updated. This includes any Groups that are children. | | `checkVisible` | boolean | <optional> | false | If set then only children with visible=true will be updated. This includes any Groups that are children. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | Inherited From * [Phaser.Group#setAllChildren](phaser.group#setAllChildren) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1312](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1312)) ### setChildIndex(child, index) Changes the position of an existing child in the display object container ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | The child DisplayObject instance for which you want to change the index number | | `index` | Number | The resulting index number for the child display object | Inherited From * [PIXI.DisplayObjectContainer#setChildIndex](pixi.displayobjectcontainer#setChildIndex) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 132](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L132)) ### setProperty(child, key, value, operation, force) → {boolean} Sets a property to the given value on the child. The operation parameter controls how the value is set. The operations are: * 0: set the existing value to the given value; if force is `true` a new property will be created if needed * 1: will add the given value to the value already present. * 2: will subtract the given value from the value already present. * 3: will multiply the value already present by the given value. * 4: will divide the value already present by the given value. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `child` | any | | | The child to set the property value on. | | `key` | array | | | An array of strings that make up the property that will be set. | | `value` | any | | | The value that will be set. | | `operation` | integer | <optional> | 0 | Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. | | `force` | boolean | <optional> | false | If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. | ##### Returns boolean - True if the property was set, false if not. Inherited From * [Phaser.Group#setProperty](phaser.group#setProperty) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1139](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1139)) ### sort(key, order) Sort the children in the group according to a particular key and ordering. Call this function to sort the group according to a particular key value and order. For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. ##### Parameters | Name | Type | Argument | Default | Description | | --- | --- | --- | --- | --- | | `key` | string | <optional> | 'z' | The name of the property to sort on. Defaults to the objects z-depth value. | | `order` | integer | <optional> | Phaser.Group.SORT\_ASCENDING | Order ascending ([SORT\_ASCENDING](phaser.group#.SORT_ASCENDING)) or descending ([SORT\_DESCENDING](phaser.group#.SORT_DESCENDING)). | Inherited From * [Phaser.Group#sort](phaser.group#sort) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1855](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1855)) ### subAll(property, amount, checkAlive, checkVisible) Subtracts the amount from the given property on all children in this group. `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `property` | string | The property to decrement, for example 'body.velocity.x' or 'angle'. | | `amount` | number | The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. | | `checkAlive` | boolean | If true the property will only be changed if the child is alive. | | `checkVisible` | boolean | If true the property will only be changed if the child is visible. | Inherited From * [Phaser.Group#subAll](phaser.group#subAll) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1403](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1403)) ### swap(child1, child2) Swaps the position of two children in this group. Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child1` | any | The first child to swap. | | `child2` | any | The second child to swap. | Inherited From * [Phaser.Group#swap](phaser.group#swap) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 891](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L891)) ### swapChildren(child, child2) Swaps the position of 2 Display Objects within this container. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `child` | [DisplayObject](global#DisplayObject) | - | | `child2` | [DisplayObject](global#DisplayObject) | - | Inherited From * [PIXI.DisplayObjectContainer#swapChildren](pixi.displayobjectcontainer#swapChildren) Source code: [pixi/display/DisplayObjectContainer.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js) ([Line 85](https://github.com/photonstorm/phaser/tree/v2.6.2/src/pixi/display/DisplayObjectContainer.js#L85)) ### <internal> update() The core update - as called by World. Inherited From * [Phaser.Group#update](phaser.group#update) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 1639](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L1639)) ### <internal> updateZ() Internal method that re-applies all of the children's Z values. This must be called whenever children ordering is altered so that their `z` indices are correctly updated. Inherited From * [Phaser.Group#updateZ](phaser.group#updateZ) Internal: * This member is *internal (protected)* and may be modified or removed in the future. Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 663](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L663)) ### xy(index, x, y) Positions the child found at the given index within this group to the given x and y coordinates. ##### Parameters | Name | Type | Description | | --- | --- | --- | | `index` | integer | The index of the child in the group to set the position of. | | `x` | number | The new x position of the child. | | `y` | number | The new y position of the child. | Inherited From * [Phaser.Group#xy](phaser.group#xy) Source code: [core/Group.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js) ([Line 993](https://github.com/photonstorm/phaser/tree/v2.6.2/src/core/Group.js#L993))
programming_docs
phaser Class: Phaser.Component.InCamera Class: Phaser.Component.InCamera ================================ Constructor ----------- ### new InCamera() The InCamera component checks if the Game Object intersects with the Game Camera. Source code: [gameobjects/components/InCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InCamera.js) ([Line 12](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InCamera.js#L12)) Public Properties ----------------- ### [readonly] inCamera : boolean Checks if this Game Objects bounds intersects with the Game Cameras bounds. It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds. An object outside the bounds can be considered for camera culling if it has the AutoCull component. Source code: [gameobjects/components/InCamera.js](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InCamera.js) ([Line 26](https://github.com/photonstorm/phaser/tree/v2.6.2/src/gameobjects/components/InCamera.js#L26)) flow Flow Enums Flow Enums ========== Flow Enums define a fixed set of constants which create their own type. Unlike other features of Flow, Flow Enums exist as values at runtime, as well as existing as types. [Read how to enable Flow Enums in your project](enabling-enums). Benefits -------- Enums provide several benefits over existing patterns: * Reduce repetition: Enum declarations provide both the type and the value of the enum. * Improve Flow performance: Enums are guaranteed to have good type-checking performance, unlike unions which may be expensive to type-check in certain situations. * Enable new functionality: Enums come with a `cast` [method](using-enums#toc-methods), which converts from a primitive type to an enum type safely. * Enhance safety: Enums define their own type which does not implicitly coerce to and from other types (e.g. from `string`s), and are required to be [exhaustively checked in switch statements](using-enums#toc-exhaustively-checking-enums-with-a-switch). These properties can help prevent logic bugs. Quickstart ---------- ### [Defining enums](defining-enums) An enum named `Status` with three members: `Active`, `Paused`, and `Off`. ``` enum Status { Active, Paused, Off, } ``` By default, enums define members with string values which mirror their names. You can also explicitly set values: ``` enum Status { Active = 'active', Paused = 'paused', Off = 'off', } ``` You can use numbers as well: ``` enum Status { Active = 1, Paused = 2, Off = 3, } ``` Values must be unique, literals, and all of the same type. Check out the [full docs on defining enums](defining-enums) to learn more. ### [Using enums](using-enums) To access an enum member, use dot access: ``` Status.Active ``` To use the enum type as an annotation, use the enum name: ``` const status: Status = Status.Active; ``` Cast from the representation type (in this case, a `string`) to the enum type: ``` const status: Status | void = Status.cast(someString); ``` You can easily provide a default value with the `??` operator: ``` const status: Status = Status.cast(someString) ?? Status.Off; ``` Read more about the [other methods enums provide](using-enums#toc-methods), including `isValid`, `members`, and `getName`. Cast an enum type to its representation type (must be done explicitly): ``` (status: string) ``` Checks of enums in `switch` statements are exhaustive - we ensure you check all members: ``` // ERROR: Incomplete exhaustive check: the member `Off` of enum `Status` // has not been considered in check of `status`. switch (status) { case Status.Active: ...; break; case Status.Paused: ...; break; // We forgot to add `case: Status.Off:` here, resulting in error above. // Using `default:` would also work to check all remaining members. } ``` Read more about [exhaustively checking enums](using-enums#toc-exhaustively-checking-enums-with-a-switch). Check out the [the full docs on using enums](using-enums) to learn more. When to use Flow Enums ---------------------- If you previously defined a union type of literals, you can use an enum to define that type instead. Instead of ``` type Status = | 'Active' | 'Paused' | 'Off'; const x: Status = 'Active'; ``` or ``` const Status = Object.freeze({ Active: 'Active', Paused: 'Paused', Off: 'Off', }); type StatusType = $Keys<typeof Status>; const x: StatusType = Status.Active; ``` you can use: ``` enum Status { Active, Paused, Off, } const x: Status = Status.Active; ``` See [migrating from legacy patterns](migrating-legacy-patterns) to learn more about migrating legacy JavaScript enum patterns to Flow Enums. When to not use Flow Enums -------------------------- Enums are designed to cover many use cases and exhibit certain benefits. The design makes a variety of trade-offs to make this happen, and in certain situations, these trade-offs might not be right for you. In those cases, you can continue to use existing patterns to satisfy your use cases. [Read more about those situations](using-enums#toc-when-to-not-use-enums). flow Flow Flow ==== #### [Getting Started](getting-started) Never used a type system before or just new to Flow? Let's get you up and running in a few minutes. #### [FAQ](faq) Have a question about using Flow? Check here first! #### [Type Annotations](types) Learn how to add Flow type annotations to your code: Primitives, Objects, Functions, Classes, and more. #### [Flow Enums](enums) Define a fixed set of constants which create their own type. Exhaustively checked in switch statements. #### [Type System](lang) Learn how the type system in Flow works: Subtyping, Variance, Refinements, and more. #### [CLI Commands](cli) How to use Flow from the command line. Including how to manage the Flow background process. #### [Configuration](config) Flow tries to work out of the box as much as possible, but can be configured to work with any codebase. #### [Library Definitions](libdefs) Learn how to create and use library definitions for the third-party code your code depends on. #### [Declaration Files](declarations) Learn how to write types in .flow files. #### [Error Suppressions](errors) Learn how to suppress Flow's type errors. #### [React](react) Learn how to use Flow to effectively type common and advanced React patterns. #### [Tools](tools) Detailed guides, tips, and resources on how to integrate Flow with different JavaScript tools. #### [Editors](editors) Detailed guides, tips, and resources on how to integrate Flow with different code editors. #### [Linting](linting) Learn how to configure Flow's linter to find potentially harmful code. #### [Flow Strict](strict) Learn how to enable stricter type checking on a file-by-file basis. flow Declaration Files Declaration Files ================= What’s a Declaration File? -------------------------- Let’s look at a more general, and sometimes more convenient way to declare types for modules: `.flow` files. There are two possible use cases, depending on whether an implementation file exists or not. In the first case, the exported types of a module are declared in a *declaration file* `<FILENAME>.flow`, that is located in the same directory as the corresponding *implementation file* `<FILENAME>`. The declaration file completely shadows the colocated implementation. In other words, Flow will completely ignore `<FILENAME>` and just read `<FILENAME>.flow` instead. In the second case, the implementation file is missing entirely. `<FILENAME>.flow` is treated as if it is named `<FILENAME>`. Note that the `.flow` extension applies both to `.js` files as well as `.json` ones. The corresponding declaration files have extensions `.js.flow` and `.json.flow`, respectively. Now let’s see an example of the first case documented above. Suppose we have the following code in a file `src/LookBeforeYouLeap.js`: ``` // @flow import { isLeapYear } from "./Misc"; if (isLeapYear("2020")) console.log("Yay!"); ``` and suppose that `src/Misc.js` has an incompatible implementation of `isLeapYear`: ``` // @flow export function isLeapYear(year: number): boolean { return year % 4 == 0; // yeah, this is approximate } ``` If we now create a declaration file `src/Misc.js.flow`, the declarations in it will be used instead of the code in `src/Misc.js`. Let’s say we have the following declarations in `src/Misc.js.flow`. > NOTE: The syntax for declarations in a declaration file is the same as we’ve seen in [Creating Library Definitions section](https://flow.org/en/libdefs/creation). > > ``` // @flow declare export function isLeapYear(year: string): boolean; ``` What do you think will happen? Right, the `isLeapYear` call in `src/LookBeforeYouLeap.js` will typecheck, since the `year` parameter expects a `string` in the declaration file. As this example shows, declaration files must be written with care: it is up to the programmer to ensure they are correct, otherwise they may hide type errors. Inlining declarations in regular code ------------------------------------- Sometimes it is useful to make declarations inline, as part of the source of an implementation file. In the following example, say you want to finish writing the function `fooList` without bothering to mock up its dependencies first: a function `foo` that takes a `number` and returns a `string`, and a class `List` that has a `map` method. You can do this by including declarations for `List` and `foo`: ``` declare class List<T> { map<U>(f: (x: T) => U): List<U>; } declare function foo(n: number): string; function fooList(ns: List<number>): List<string> { return ns.map(foo); } ``` Just don’t forget to replace the declarations with proper implementations. flow Editors Editors ======= You can benefit from having Flow run as you develop by integrating into your editor. Editor plugins are provided and maintained by the community. If you have trouble configuring or using a specific plugin for your IDE, please visit the project’s repo or search for a community provided answer. flow Type System Type System =========== ### JavaScript: The Good and the Bad Developers like coding in JavaScript because it helps them move fast. The language facilitates fast prototyping of ideas via dynamic typing. The runtime provides the means for fast iteration on those ideas via dynamic compilation. This fuels a fast edit-refresh cycle, which promises an immersive coding experience that is quite appealing to creative developers. However, evolving and growing a JavaScript codebase is notoriously challenging. Developers cannot move fast when they break stuff. They hit frequent interruptions, spending a lot of time debugging silly mistakes, unraveling assumptions and guarantees made by libraries written by others, etc. In principle, this overhead can be mitigated by adding a layer of types to the codebase, and building tools that use type information to solve the above problems. For example, types can be used to identify bugs, to document interfaces of libraries, and so on. The idea of using types to manage code evolution and growth in JavaScript (and related languages) is not new. In fact, several useful type systems have been built for JavaScript in recent years. However, type systems differ in their goals. On one end of the spectrum are permissive type systems that provide some degree of linting against likely errors, without regard for correctness. On the other end of the spectrum are restrictive type systems that can guarantee the correctness of static code optimizations, at the cost of interoperability. Another area that has not seen a lot of focus is the performance of type checking itself. Flow: Goals ----------- Flow is a static type checker for JavaScript that we built at Facebook. The overall mission of Flow is to deliver an immersive coding experience for JavaScript developers—a fast edit-refresh cycle—even as the codebase evolves and grows. In engineering terms, we identify two concrete goals that are important to this mission: *precision* and *speed*. These goals pervasively drive the design and implementation. #### Precision JavaScript bugs can have significant impact at Facebook. Developers want to find and fix as many bugs as they can by the time their code rolls out into production. So we must care about soundness. At the same time, we must also care about not reporting too many spurious errors, because a low signal/noise ratio implies a low fix rate. In other words, we want Flow’s analysis to be precise in practice—it must model essential characteristics of the language accurately enough to understand the difference between idiomatic code and unintentional mistakes. Precision also has other desirable consequences. When types are trustworthy, developers tend to rely on them to structure their code and reason about it, leading to cleaner and more efficient code with fewer dynamic checks. When type errors are trustworthy, developers can focus on what their code does rather than thinking about how to rewrite their code to satisfy (or work around) the type system. Finally, precision enables useful developer tools to be built. In particular, the quality of results reported by Flow when the developer asks for the type of an expression, the definition reaching a reference, or the set of possible completions at a point through an IDE is correlated with the precision of Flow’s analysis. #### Speed Precision usually comes at the cost of speed. But while a precise analysis is desirable, most of the appeal of JavaScript is lost if we slow down the edit-refresh cycle by making developers wait as we compile. In other words, we must engineer Flow’s analysis to be extremely fast—it must respond to code changes without noticeable delay, while still being precise enough in practice. Like precision, speed also has other significant effects. When bugs are reported as the developer makes changes to code, they become part of the editing process—the developer doesn’t need to run the code to detect bugs, and tracing bugs back to the code becomes simpler. Similarly, when the IDE can show the type of an expression, the definition reaching a reference, etc. as the developer is coding, we have observed that productivity can improve dramatically. #### What makes Flow precise? One of the main contributors of Flow’s precision is path-sensitivity: the way types interact with runtime tests. The essence of many JavaScript idioms is to put together ad hoc sets of runtime values and to take them apart with shallow, structural (in)equality checks. In Flow, the set of runtime values that a variable may contain is described by its type, and a runtime test on that variable refines the type to a smaller set. This ability turns out to be quite powerful and general in practice. #### What makes Flow fast? The key to Flow’s speed is modularity: the ability to break the analysis into file-sized chunks that can be assembled later. Fortunately, JavaScript is already written using files as modules, so we modularize our analysis simply by asking that modules have explicitly typed signatures. (We still infer types for the vast majority of code “local” to modules.) Coincidentally, developers consider this good software engineering practice anyway. With modularity, we can aggressively parallelize our analysis. Furthermore, when files change, we can incrementally analyze only those files that depend on the changed files. Together, these choices have helped scale the analysis to millions of lines of code. Under the hood, Flow relies on a high-throughput low-latency systems infrastructure that enables distribution of tasks among parallel workers, and communication of results in parallel via shared memory. Combined with an architecture where the analysis of a codebase is updated automatically in the background on file system changes, Flow delivers near-instantaneous feedback as the developer edits and rebases code, even in a large repository. flow Getting Started Getting Started =============== Developers will often use Flow and React together, so it is important that Flow can effectively type both common and advanced React patterns. This guide will teach you how to use Flow to create safer React applications. In this guide we will assume you know [the React basics](https://facebook.github.io/react/docs/hello-world.html) and focus on adding types for patterns you are already familiar with. We will be using examples based on `react-dom`, but all of these patterns work in other environments like `react-native` as well. Setup Flow with React --------------------- Flow and Babel work well together, so it doesn’t take much to adopt Flow as a React user who already uses Babel. If you need to setup Babel with Flow, you can follow [this guide](https://flow.org/en/tools/babel/). Babel also [works out of the box with Create React App](https://flow.org/en/tools/create-react-app/), just install Flow and create a `.flowconfig`. React Runtimes -------------- Flow supports the `@babel/plugin-transform-react-jsx` runtime options required to use JSX without explicitly importing the React namespace. If you are using the new automatic runtime, use this configuration in your `.flowconfig` so that Flow knows to auto-import `jsx`: ``` [options] react.runtime=automatic ``` flow Flow Strict Flow Strict =========== You can enable stronger safety guarantees in Flow (such as banning `any`/`Object`/`Function` types and requiring all dependencies to be typed) by adding **`@flow strict`** to your files. Overview -------- Flow was designed for easy adoption, so it allows you opt-out of type checking in certain situations, permitting unsafe behaviors. But since many codebases now have a high adoption of Flow types, this trade-off can be flipped. You can use *Flow Strict* to disallow previously-allowed unsafe patterns. This gives you improved safety guarantees that catch more bugs and make refactoring easier. And you can implement these stronger guarantees incrementally, on a file-by-file basis. Features -------- Enabling Flow Strict for a file means that several previously-allowed patterns will now trigger a Flow error. Each disallowed pattern has a corresponding [Flow Lint](https://flow.org/en/linting/) rule which triggers the error. The list of rules enabled for `@flow strict` is configured in each `.flowconfig`. Here are the recommended rules: * [`nonstrict-import`](https://flow.org/en/linting/rule-reference/#toc-nonstrict-import): Triggers an error when importing from a module which is not also `@flow strict`. This is very important, because it means that when a file is marked as strict, all of its dependencies are strict as well. * [`unclear-type`](https://flow.org/en/linting/rule-reference/#toc-unclear-type): Triggers an error when using `Object`, `Function`, or `any` in a type annotation. * [`untyped-import`](https://flow.org/en/linting/rule-reference/#toc-untyped-import): Triggers an error when importing from an untyped module. * [`untyped-type-import`](https://flow.org/en/linting/rule-reference/#toc-untyped-type-import): Triggers an error when importing a type from an untyped module. * [`unsafe-getters-setters`](https://flow.org/en/linting/rule-reference/#toc-unsafe-getters-setters): Triggers an error when using getters and setters, which can be unsafe. * [`sketchy-null`](https://flow.org/en/linting/rule-reference/#toc-sketchy-null): Triggers an error when doing an existence check on a value that could be null/undefined or falsey. For a full list of available lint rules, see the [Lint Rule Reference](https://flow.org/en/linting/rule-reference/). Additionally, note that function parameters are considered const (i.e., treated as if they were declared with `const` rather than `let`). This feature is not yet configurable in Flow Strict; it is always on. Enabling Flow Strict in a .flowconfig ------------------------------------- Flow Strict is configured in each `.flowconfig`. To enable: 1. Add a `[strict]` section to the `.flowconfig`. 2. List the lint rules to enable . These are strongly recommended: ``` [strict] nonstrict-import unclear-type unsafe-getters-setters untyped-import untyped-type-import ``` Also recommended, but optional as it may be too noisy in some codebases: `sketchy-null` We recommend you enable all your desired rules from the beginning, then adopt Flow Strict file-by-file. This works better than enabling a single rule, adding `@flow strict` to many files, and then adding more rules to the config. Adoption -------- Add `@flow strict` to a file and fix all errors that appear. Because Flow Strict requires dependencies to also be strict (if the `nonstrict-import` rule is enabled), start at the leaves of the dependency tree and work up from there. Do not add `$FlowFixMe` to suppress the new errors as they appear; just add `@flow strict` once all issues have been resolved. Since the most common reasons for using `$FlowFixMe` stem from reliance on untyped dependencies or behavior, future issues should be greatly reduced once Flow Strict is enabled. Be liberal with enabling Flow Strict. Unlike adding or removing `@flow`, adding or removing `@flow strict` (by itself) does not change Flow coverage. It only prevents or allows certain new unsafe behavior from being added in the future. Even if in the future Flow Strict has to be disabled for the file, at least unsafe behavior was prevented from being added in the meantime. Library definitions are considered strict (as they can be included in many different projects with contradicting strict configurations). Strict Local ------------ If you enable the `nonstrict-import` rule in your Flow Strict configuration (recommended), then all dependencies of a strict file must also be strict. While this the optimal goal, for large pre-existing codebases it may be beneficial to allow some of the benefits of Flow Strict to be put in use before all dependencies are strict. `@flow strict-local` is the same as `@flow strict`, except it does not require its dependencies to also be strict (i.e. it is “locally” strict). It does not have a separate configuration: it uses the same configuration as Flow Strict, just without the `nonstrict-import` rule. Once all the dependencies of a `@flow strict-local` file are strict, the file can be upgraded to a `@flow strict` file. A `@flow strict` file cannot depend on a `@flow strict-local` file as this would break the `nonstrict-import` rule. What’s Ahead ------------ Eventually, some features of Flow Strict could become the default behavior of Flow, if those features prove successful and achieve widespread adoption.
programming_docs
flow Flow CLI Flow CLI ======== The flow command line tool is made to be easy-to-use for simple cases. Using the command `flow` will type-check your current directory if the `.flowconfig` file is present. A flow server will automatically be started if needed. The CLI tool also provides several other options and commands that allow you to control the server and build tools that integrate with Flow. For example, this is how the [Nuclide](https://nuclide.io/) editor integrates with Flow to provide autocompletion, type errors, etc. in its UI. To find out more about the CLI just type: ``` flow --help ``` This will give you information about everything that flow can do. Running this command should print something like this: ``` Usage: flow [COMMAND] [PROJECT_ROOT] Valid values for COMMAND: ast Print the AST autocomplete Queries autocompletion information batch-coverage Shows aggregate coverage information for a group of files or directories check Does a full Flow check and prints the results check-contents Run typechecker on contents from stdin config Read or write the .flowconfig file coverage Shows coverage information for a given file cycle Output .dot file for cycle containing the given file find-module Resolves a module reference to a file find-refs Gets the reference locations of a variable or property force-recheck Forces the server to recheck a given list of files get-def Gets the definition location of a variable or property get-imports Get names of all modules imported by one or more given modules graph Outputs dependency graphs of flow repositories init Initializes a directory to be used as a flow root directory ls Lists files visible to Flow lsp Acts as a server for the Language Server Protocol over stdin/stdout [experimental] print-signature Prints the type signature of a file as extracted in types-first mode server Runs a Flow server in the foreground start Starts a Flow server status (default) Shows current Flow errors by asking the Flow server stop Stops a Flow server type-at-pos Shows the type at a given file and position version Print version information Default values if unspecified: COMMAND status PROJECT_ROOT current folder Status command options: --color Display terminal output in color. never, always, auto (default: auto) --from Specify client (for use by editor plugins) --help This list of options --json Output results in JSON format --no-auto-start If the server is not running, do not start it; just exit --old-output-format Use old output format (absolute file names, line and column numbers) --one-line Escapes newlines so that each error prints on one line --quiet Suppresses the server-status information that would have been printed to stderr --retries Set the number of retries. (default: 3) --show-all-errors Print all errors (the default is to truncate after 50 errors) --strip-root Print paths without the root --temp-dir Directory in which to store temp files (default: /tmp/flow/) --timeout Maximum time to wait, in seconds --version Print version number and exit ``` Example with custom project root: ``` mydir ├── frontend │ ├── .flowconfig │ └── app.js └── backend ``` ``` flow check frontend ``` You can then, further dig into particular COMMANDs by adding the `--help` flag. So, for example, if you want to know more about how the autocomplete works, you can use this command: ``` flow autocomplete --help ``` flow Getting Started Getting Started =============== Flow is a static type checker for your JavaScript code. It does a lot of work to make you more productive. Making you code faster, smarter, more confidently, and to a bigger scale. Flow checks your code for errors through **static type annotations**. These *types* allow you to tell Flow how you want your code to work, and Flow will make sure it does work that way. ``` // @flow function square(n: number): number { return n * n; } square("2"); // Error! ``` flow Library Definitions Library Definitions =================== What’s a “Library Definition”? ------------------------------ Most real JavaScript programs depend on third-party code and not just code immediately under the control of the project. That means a project using Flow may need to reference outside code that either doesn’t have type information or doesn’t have accurate and/or precise type information. In order to handle this, Flow supports the concept of a “library definition” (AKA “libdef”). A libdef is a special file that informs Flow about the type signature of some specific third-party module or package of modules that your application uses. If you’re familiar with languages that have header files (like `C++`), you can think of libdefs as a similar concept. These special files use the same `.js` extension as normal JS code, but they are placed in a directory called `flow-typed` in the root directory of your project. Placement in this directory tells Flow to interpret them as libdefs rather than normal JS files. > NOTE: Using the `/flow-typed` directory for libdefs is a convention that enables Flow to JustWork™ out of the box and encourages consistency across projects that use Flow, but it is also possible to explicitly configure Flow to look elsewhere for libdefs using the [`[libs]` section of your `.flowconfig`](https://flow.org/en/config/libs). > > General Best Practices ---------------------- **Try to provide a libdef for each third-party library your project uses** If a third-party library that has no type information is used by your project, Flow will treat it like any other untyped dependency and mark all of its exports as `any`. Interestingly, this is the only place that Flow will implicitly inject `any` into your program. Because of this behavior, it is a best practice to find or write libdefs for as many of the third-party libraries that you use as you can. We recommend checking out the `flow-typed` [tool and repository](https://github.com/flowtype/flow-typed/blob/master/README.md) , which helps you quickly find and install pre-existing libdefs for your third-party dependencies. flow .flowconfig .flowconfig =========== Every Flow project contains a `.flowconfig` file. You can configure Flow by modifying `.flowconfig`. New projects or projects that are starting to use Flow can generate a default `.flowconfig` by running `flow init`. `.flowconfig` format --------------------- The `.flowconfig` uses a custom format that vaguely resembles INI files. The `.flowconfig` consists of different sections: * [`[include]`](include) * [`[ignore]`](ignore) * [`[untyped]`](untyped) * [`[libs]`](https://flow.org/en/docs/libs) * [`[lints]`](lints) * [`[options]`](options) * [`[version]`](version) * [`[declarations]`](declarations) * [`[strict]`](https://flow.org/en/strict/#toc-enabling-flow-strict-in-a-flowconfig) Comments -------- Comment support was added in v0.23.0. Lines beginning with zero or more spaces followed by an `#` or `;` or `💩` are ignored. For example: ``` # This is a comment # This is a comment ; This is a comment ; This is a comment 💩 This is a comment 💩 This is a comment ``` Where to put the `.flowconfig` ------------------------------ The location of the `.flowconfig` is significant. Flow treats the directory that contains the `.flowconfig` as the *project root*. By default Flow includes all the source code under the project root. The paths in the [[include] section](include) are relative to the project root. Some other configuration also lets you reference the project root via the macro `<PROJECT_ROOT>`. Most people put the `.flowconfig` in the root of their project (i.e. next to the `package.json`). Some people put all their code in a `src/` directory and therefore put the `.flowconfig` at `src/.flowconfig`. Example ------- Say you have the following directory structure, with your `.flowconfig` in `mydir`: ``` otherdir └── src ├── othercode.js mydir ├── .flowconfig ├── build │ ├── first.js │ └── shim.js ├── lib │ └── flow ├── node_modules │ └── es6-shim └── src ├── first.js └── shim.js ``` Here is an example of how you could use the `.flowconfig` directives. ``` [include] ../otherdir/src [ignore] .*/build/.* [libs] ./lib ``` Now `flow` will include a directory outside the `.flowconfig` path in its check, ignore the `build` directory and use the declarations in `lib`. flow Tools Tools ===== [### Babel Learn how to use Flow with Babel](tools/babel) [### ESLint Learn how to use Flow with ESLint](tools/eslint) [### flow-remove-types Learn how to use Flow with flow-remove-types](tools/flow-remove-types) [### Create React App Learn how to use Flow with Create React App](tools/create-react-app) flow Type Annotations Type Annotations ================ Adding type annotations is an important part of your interaction with Flow. Flow has a powerful ability to infer the types of your programs. The majority of your code can rely on it. Still, there are places where you’ll want to add types. Imagine the following `concat` function for concatenating two strings together. ``` function concat(a, b) { return a + b; } ``` When you use this function, Flow knows exactly what is going on. ``` concat("A", "B"); // Works! ``` However, you can use the `+` operator on strings or numbers, so this would also be valid. ``` concat(1, 2); // Works! ``` But suppose you only want to allow strings in your function. For that you can add types. ``` function concat(a: string, b: string) { return a + b; } ``` Now you’ll get a warning from Flow if you try to use numbers. ``` // @flow function concat(a: string, b: string) { return a + b; } concat("A", "B"); // Works! concat(1, 2); // Error! ``` Setting up “boundaries” with your types means you can tell Flow your intent on top of the inference it already does. This guide will teach you the syntax and semantics of all the different types you can have in Flow. flow Error Suppressions Error Suppressions ================== Flow reports many different kinds of errors for many common programming mistakes, but not every JavaScript pattern can be understood by Flow. If you are confident your code is correct, and that Flow is erroring too conservatively, you can suppress the error so that Flow does not report it. What is a Suppression? ---------------------- A suppression is a special kind of comment that you can place on the line before a type error. It tells Flow not to report that error when checking your code. Suppression comments look like the following: ``` // <SUPPRESSOR>[<CODE>] extra text ``` A suppressor can be one of the following: * `$FlowFixMe`: for type errors that you intend to fix later * `$FlowIssue`: for a type error that you suspect is an issue with Flow * `$FlowExpectedError`: for a location where you expect Flow to produce a type error (for instance, when performing an invalid type cast). * `$FlowIgnore`: for locations where you want Flow to ignore your code Note that all of the suppressors behave identically; we simply recommend using them as described here for your own ease of reference. The `<CODE>` portion of a suppression is optional, but when included specifies which [error code](#toc-making-suppressions-more-granular-with-error-codes) the suppression affects. Some examples of suppression comments: ``` // $FlowFixMe // $FlowIssue[incompatible-type] /* $FlowIgnore[prop-missing] some other text here */ /* $FlowFixMe[incompatible-cast] this is a multi-line comment */ { /* $FlowIssue this is how you suppress errors inside JSX */ } ``` In order to be a valid suppression comment, there are also some conditions that must be true: * No text can precede the suppressor, or come between the suppressor and the code. For example: `// some text then $FlowFixMe` is not a valid suppression, nor is `// $FlowIssue some text [incompatible-type]` or ` //$FlowFixMe [prop-missing]` (note the space here!). * Suppressions must be on the line immediately before the error they suppress, otherwise they will not apply. Making Suppressions More Granular with Error Codes -------------------------------------------------- Suppressible Flow errors will also have an error code associated with them (after version 0.127). This code concisely describes the type of issue the error is reporting, and is different between different kinds of errors. In order to prevent suppressions from suppressing different kinds of type errors on the same line (by default suppressions without codes suppress every error on the following line), you can add an error code to your suppression. For example: `// $FlowFixMe[incompatible-type]` would only suppress errors with the `incompatible-type` code. So: ``` //$FlowFixMe[incompatible-type] (3 : string); ``` would report no errors, but ``` //$FlowFixMe[prop-missing] (3 : string); ``` would still report a type incompatibility. To suppress multiple error codes on the same line, you can stack suppression comments one after another, and they will all apply to the first non-comment line like so: ``` let y : number | { x : number } = 1; // $FlowFixMe[incompatible-type] // $FlowFixMe[prop-missing] (y.x : string); ``` This will suppress both of the two errors on this line. flow Linting Overview Linting Overview ================ Flow contains a linting framework that can tell you about more than just type errors. This framework is highly configurable in order to show you the information you want and hide the information you don’t. Configuring Lints in the `.flowconfig` -------------------------------------- Lint settings can be specified in the `.flowconfig` [lints] section as a list of `rule=severity` pairs. These settings apply globally to the entire project. **Example:** ``` [lints] # all=off by default all=warn untyped-type-import=error sketchy-null-bool=off ``` Configuring Lints from the CLI ------------------------------ Lint settings can be specified using the `--lints` flag of a Flow server command as a comma-delimited list of `rule=severity` pairs. These settings apply globally to the entire project. **Example:** ``` flow start --lints "all=warn, untyped-type-import=error, sketchy-null-bool=off" ``` Configuring Lints with Comments ------------------------------- Lint settings can be specified inside a file using `flowlint` comments. These settings apply to a region of a file, or a single line, or part of a line. For more details see [Flowlint Comments](flowlint-comments). **Example:** ``` /* flowlint * sketchy-null:error, * untyped-type-import:error */ const x: ?number = 0; if (x) {} // Error import type {Foo} from './untyped.js'; // Error // flowlint-next-line sketchy-null:off if (x) {} // No Error if (x) {} /* flowlint-line sketchy-null:off */ // No Error // flowlint sketchy-null:off if (x) {} // No Error if (x) {} // No Error import type {Bar} from './untyped.js'; // Error; unlike a $FlowFixMe, a flowlint comment only suppresses one particular type of error. // flowlint sketchy-null:error ``` Lint Settings Precedence ------------------------ Lint settings in `flowlint` comments have the highest priority, followed by lint rules in the `--lints` flag, followed by the `.flowconfig`. This order allows you to use `flowlint` comments for fine-grained linting control, the `--lints` flag for trying out new lint settings, and the `.flowconfig` for stable project-wide settings. Within the -lints flag and the flowconfig, rules lower down override rules higher up, allowing you to write things like ``` [lints] sketchy-null=warn sketchy-null-bool=off ``` The lint settings parser is fairly intelligent and will stop you if you write a redundant rule, a rule that gets completely overwritten, or an unused suppression. This should prevent most accidental misconfigurations of lint rules. Severity Levels and Meanings ---------------------------- **off:** The lint is ignored. Setting a lint to `off` is similar to suppressing a type error with a suppression comment, except with much more granularity. **warn:** Warnings are a new severity level introduced by the linting framework. They are treated differently than errors in a couple of ways: * Warnings don’t affect the exit code of Flow. If Flow finds warnings but no errors, it still returns 0. * Warnings aren’t shown on the CLI by default, to avoid spew. CLI warnings can be enabled by passing the –include-warnings flag to the Flow server or the Flow client, or by setting “include\_warnings=true” in the `.flowconfig`. This is good for smaller projects that want to see all project warnings at once. * Warnings have special [IDE Integration](ide-integration). **error:** Lints with severity `error` are treated exactly the same as any other Flow error. flow Usage Usage ===== Once you have [installed](https://flow.org/en/install/) Flow, you will want to get a feel of how to use Flow at the most basic level. For most new Flow projects, you will follow this general pattern: * [Initialize your project](#toc-initialize-your-project) with `flow init`. * Start the [Flow background process](#toc-run-the-flow-background-process) with `flow`. * [Determine](#toc-prepare-your-code-for-flow) which files Flow will monitor with `// @flow`. * [Write Flow code](#toc-write-flow-code) for your project. * [Check your code](#toc-check-your-code) for type errors. Initialize Your Project ----------------------- Preparing a project for Flow requires only one command: ``` flow init ``` Run this command at the top level of your project to create one, empty file called [`.flowconfig`](https://flow.org/en/config/). At its most basic level, `.flowconfig` tells the Flow background process the root of where to begin checking Flow code for errors. And that is it. Your project is now Flow-enabled. > It is common to have an empty `.flowconfig` file for your project. However, you can [configure and customize Flow](https://flow.org/en/config/) in many ways through options available to be added to `.flowconfig`. > > Run the Flow Background Process ------------------------------- The core benefit to Flow is its ability to quickly check your code for errors. Once you have enabled your project for Flow, you can start the process that allows Flow to check your code incrementally and with great speed. ``` flow status ``` This command first starts a background process that will check all [Flow files](#toc-prepare-your-code-for-flow) for errors. The background process continues running, monitoring changes to your code and checking those changes incrementally for errors. > You can also type `flow` to accomplish the same effect as `status` is the default flag to the `flow` binary. > > > Only one background process will be running at any given time, so if you run `flow status` multiple times, it will use the same process. > > > To stop the background process, run `flow stop`. > > Prepare Your Code for Flow -------------------------- The Flow background process monitors all Flow files. However, how does it know which files are Flow files and, thus, should be checked? Placing the following **before any code** in a JavaScript file is the flag the process uses to answer that question. ``` // @flow ``` This flag is in the form of a normal JavaScript comment annotated with `@flow`. The Flow background process gathers all the files with this flag and uses the type information available from all of these files to ensure consistency and error free programming. > You can also use the form `/* @flow */` for the flag as well. > > > For files in your project without this flag, the Flow background process skips and ignores the code (unless you call `flow check --all`, which is beyond the scope of basic usage). > > Write Flow Code --------------- Now that all the setup and initialization is complete, you are ready to write actual Flow code. For each file that you have flagged with `// @flow`, you now have the full power of Flow and its type-checking available to you. Here is an example Flow file: ``` // @flow function foo(x: ?number): string { if (x) { return x; } return "default string"; } ``` Notice the types added to the parameter of the function along with a return type at the end of the function. You might be able to tell from looking at this code that there is an error in the return type since the function can also return a `number`. However, you do not need to visually inspect the code since the Flow background process will be able to catch this error for you when you [check your code](#toc-check-your-code). Check Your Code --------------- The great thing about Flow is that you can get near real-time feedback on the state of your code. At any point that you want to check for errors, just run: ``` # equivalent to `flow status` flow ``` The first time this is run, the [Flow background process](#toc-run-flow-background-process) will be spawned and all of your Flow files will be checked. Then, as you continue to iterate on your project, the background process will continuously monitor your code such that when you run `flow` again, the updated result will be near instantaneous. For the [code above](#toc-write-flow-code), running `flow` will yield: ``` test.js:5 5: return x; ^ number. This type is incompatible with the expected return type of 3: function foo(x: ?number): string { ^^^^^^ string ```
programming_docs
flow FAQ FAQ === I checked that `foo.bar` is not `null`, but Flow still thinks it is. Why does this happen and how can I fix it? --------------------------------------------------------------------------------------------------------------- Flow does not keep track of side effects, so any function call may potentially nullify your check. This is called [refinement invalidation](lang/refinements#toc-refinement-invalidations). Example ([https://flow.org/try](https://flow.org/try/#0C4TwDgpgBACghgJzgWygXigbwFBSgI0QC4oB+AZ2AQEsA7AcwBpsBfbAMwFdaBjYagPa0oyEADFuPABTsBAkvCTIAlCUo0GWXFGrsoMuQDpCCZVrx4eQ8gIA2EQ7YH0pAIh4ALCDwDWEACYAhK7KANzaAJAIEMCcCMKyAsaIoVAA9GlQ7E4A7lAQCAgCCOSGUACSeiACnFBWyMgQtMBQwF511nYOTkw6LTnFPuTabHja0bHxUK7+EOxwnLYt6nT0ruEsQA)): ``` // @flow type Param = { bar: ?string, } function myFunc(foo: Param): string { if (foo.bar) { console.log("checked!"); return foo.bar; // Flow errors. If you remove the console.log, it works } return "default string"; } ``` You can get around this by storing your checked values in local variables: ``` // @flow type Param = { bar: ?string, } function myFunc(foo: Param): string { if (foo.bar) { const bar = foo.bar; console.log("checked!"); return bar; // Ok! } return "default string"; } ``` I checked that my object is of type A, so why does Flow still believe it’s A | B? --------------------------------------------------------------------------------- Refinement invalidation can also happen with [disjoint unions](types/unions#toc-disjoint-unions). Any function call will invalidate any refinement. Example ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQAXAngBwKagEqYM7qwB2+2AvKIqKAD6gDeoaWAXKAOT4CuAxrwXwcANKABuAQ2jdM7fMgBOAS2IBzUAF9qdRswyzOmBQtgKRoIyYXsAosdOaA3IkS8S80AAsJxACbRMPEJ3ClAACgUCIlIDIOiyAEpQcgA+Rm0lSHDI4JiAOhYKckouPgF8ISSGbRoyZAAVJQBbTFhuZDCwpNT0mj7QN1JYALy4VTCAAwASBhz4zDzJaUwNUABGCYSazVE1gAYDhOcaLQ1HIA)): ``` // @flow type Response = | { type: 'success', value: string } | { type: 'error', error: Error }; const handleResponse = (response: Response) => { if (response.type === 'success') { setTimeout(() => { console.log(`${response.value} 1`) }, 1000); } }; ``` Here, a work around would be to extract the part of the value you’re interested in, or to move the if check inside the `setTimeout` call: Example ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQAXAngBwKagEqYM7qwB2+2AvKIqKAD6gDeoaWAXKAOT4CuAxrwXwcANKABuAQ2jdM7fMgBOAS2IBzUAF9qdRswyzOmBQtgKRoIyYXsAosdOaA3IkS8S80AAsJxACbRMPEJ3ClAACgUCIlIDIOiyAEpQcgA+Rm0lSHDI4JiAOhYKckouPgF8ISSGbRo3UmRxKRlk0Bz4zDzJaUwa0DJkABUlAFtMWG5kMLCk1PSaedA6-FgAvLhVMIADABIGLpkNUABGTYTejVEjgAYbhOcaLQ1HIA)): ``` // @flow type Response = | { type: 'success', value: string } | { type: 'error', error: Error }; const handleResponse = (response: Response) => { if (response.type === 'success') { const value = response.value setTimeout(() => { console.log(`${value} 1`) }, 1000); } }; ``` I’m in a closure and Flow ignores the if check that asserts that `foo.bar` is defined. Why? ------------------------------------------------------------------------------------------- In the previous section we showed how refinement is lost after a function call. The exact same thing happens within closures, since Flow does not track how your value might change before the closure is called. Example ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQAXAngBwKagAqYE4DOsAdqALygDeAhgOaYBcoA-CQK4C2ARgQL6IAxqULJQWWOmjZKAbVoNmARgBMfADTV6TUEoAcGrYtAqALHwC6AbiEixsaABM8RUsxfEylBToDsABj4bAEtIUAAKB2cCTwA6bQBKakRQcUxJaVjIWHwAURpBAAtwrFcvAD5k1NThEmJMuDpwgAMAFULsUs9QYMJQABIqLtJ4hj5QGhJHUGQO0Cj5kmxegaoojxHtPmaEm1S+BMQ+IA)): ``` // @flow type Person = {age: ?number} const people = [{age: 12}, {age: 18}, {age: 24}]; const oldPerson: Person = {age: 70}; if (oldPerson.age) { people.forEach(person => { console.log(`The person is ${person.age} and the old one is ${oldPerson.age}`); }) } ``` The solution here is to move the if check in the `forEach`, or to assign the `age` to an intermediate variable. Example ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQAXAngBwKagAqYE4DOsAdqALygDeAhgOaYBcoA-CQK4C2ARgQL6IAxqULJQWWOmjZKAbVoNmARgBMfADTV6TUEoAcGrYtAqALHwC6AbiEixsaABM8RUsxfEylBToDsABj4bAEtIUAAKB2cCTwA6bQBKakRQUGESUVBtClAoj1J4hhtUiSlMWMhYfABRGkEAC3CsVy8APmTU1PTiaVi4OnCAAwAVeuxmz1BgwlAAEioJgu0+LJJHUGQx3KdckmxpuZ8+QYTi0D4ExD4gA)): ``` // @flow type Person = {age: ?number} const people = [{age: 12}, {age: 18}, {age: 24}]; const oldPerson: Person = {age: 70}; if (oldPerson.age) { const age = oldPerson.age; people.forEach(person => { console.log(`The person is ${person.age} and the old one is ${age}`); }) } ``` But Flow should understand that this function cannot invalidate this refinement, right? --------------------------------------------------------------------------------------- Flow is not [complete](https://flow.org/en/lang/types-and-expressions/#soundness-and-completeness), so it cannot check all code perfectly. Instead, Flow will make conservative assumptions to try to be sound. Why can’t I use a function in my if-clause to check the type of a property? --------------------------------------------------------------------------- Flow doesn’t track refinements made in separated function calls. Example ([https://flow.org/try](https://flow.org/try/#0MYewdgzgLgBAhgEwTAvDAFAMwJYCdoBcMYArgLYBGAprgDQwRWhgJGmU0CUqAfDDvlgBqBk3AIA3AChm0GADc4AGyLRc2MAHMYAH2LlquVDACM02bGwQAcgZrH0ipSSoAVEACUqOMFTZ2jPTUNTW4UPigATwAHKhBMBWUXdy8fKlQUNABydkMs6WwE9CtbDlxHZU5uRAQKpXoAJk4JIA)) ``` // @flow const add = (first: number, second: number) => first + second; const val: string | number = ... const isNumber = (valueToRefine: ?number) => typeof valueToRefine === 'number'; if (isNumber(val)) add(val, 2); ``` However, Flow has [predicates functions](types/functions#toc-predicate-functions) that can do these checks via `%checks`. Example ([https://flow.org/try](https://flow.org/try/#0MYewdgzgLgBAhgEwTAvDAFAMwJYCdoBcMYArgLYBGAprgDQwRWhgJGmU0CUqAfDDvlgBqBk3AIA3AChm0GADc4AGyLRc2MAHMYAH2LlquVDACM02bGwQAcgZrH0ipSSoAVEACUqOMFTZ2jPTUNTU4iAFJgAAsmAGsIXhgoAE8AByoQTAVlF3cvHypUFDQAcnZDEulsLPQrWw5cR2VObkQEJqV6ACZOCSA)) ``` // @flow const add = (first: number, second: number) => first + second; const val: string | number = ... const isNumber = (valueToRefine: ?number): %checks => typeof valueToRefine === 'number'; if (isNumber(val)) add(val, 2); ``` Why can’t I pass an `Array<string>` to a function that takes an `Array<string | number>` ---------------------------------------------------------------------------------------- The function’s argument allows `string` values in its array, but in this case Flow prevents the original array from receiving a `number`. Inside the function, you would be able to push a `number` to the argument array, causing the type of the original array to no longer be accurate. You can fix this error by changing the type of the argument to `$ReadOnlyArray<string | number>`. This prevents the function body from pushing anything to the array, allowing it to accept narrower types. As an example, this would not work: ``` // @flow const fn = (arr: Array<string | number>) => { // arr.push(123) NOTE! Array<string> passed in and after this it would also include numbers if allowed return arr; }; const arr: Array<string> = ['abc']; fn(arr); // Error! ``` but with `$ReadOnlyArray` you can achieve what you were looking for: ``` // @flow const fn = (arr: $ReadOnlyArray<string | number>) => { // arr.push(321) NOTE! Since you are using $ReadOnlyArray<...> you cannot push anything to it return arr; }; const arr: Array<string> = ['abc']; fn(arr); ``` Example ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQiSgOoEsAuALWBXLUAJwFMBDAE1gDtoBPALmQGNaBnIyGgRlAF5QACnLFijUAEEx5egB5OxDDQDmoAD4ACmvgC2AI1LEAfAEoBx0AG9EASFSjiAOgAO+djiE8ATAGZzqAByAPIAKgCiAIRSMvKKyiqWLuTs7KSUoMqg5DQZ5JBYRqC4GOyZRPAE0HnQ7LCZNCzQ+JSkoDoGRmUYkNnQcPDpdmRY+MQ02WIA3IgAvqwcRI48EtLEsgpYSqqWggDaAOTk+iwHALozKGDcPCJiplOgqHIAtG+g+I2wurqkNFywYigIzEQHsSKRZCoN4w2Fw+EIxFIqFgABKFGodHoLwAbl0MLRmIg2DROKBuN4BMJHBIACToqjBLFrDbxVQabR6Qwmcz8Sw2UCCp5gRyudyeXzeHgBMAhCLRADKyhYbXoBEmbXcCVA9IxTIYLPkTmNljV+FALByNFgRDcHmyNHoJXZWHq2GGpFG40mxDmC1JSzE3lWsU220SVMOx1OF2QFLuxG8DyAA)) Why can’t I pass `{ a: string }` to a function that takes `{ a: string | number }` ---------------------------------------------------------------------------------- The function argument allows `string` values in its field, but in this case Flow prevents the original object from having a `number` written to it. Within the body of the function you would be able to mutate the object so that the property `a` would receive a `number`, causing the type of the original object to no longer be accurate. You can fix this error by making the property covariant (read-only): `{ +a: string | number }`. This prevents the function body from writing to the property, making it safe to pass more restricted types to the function. As an example, this would not work: ``` // @flow const fn = (obj: {| a: string | number |}) => { // obj.a = 123; return obj; }; const object: {| a: string |} = {a: 'str' }; fn(object); // Error! ``` but with a covariant property you can achieve what you were looking for: ``` // @flow const fn = (obj: {| +a: string | number |}) => { // obj.a = 123 NOTE! Since you are using covariant {| +a: string | number |}, you can't mutate it return obj; }; const object: {| a: string |} = { a: 'str' }; fn(object); ``` Example ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQiSgOoEsAuALWBXLUAJwFMBDAE1gDtoBPALmQGNaBnIyGgRlAF5QAClgAjAFaNQAbwA+oclM7EMNAOahZAApr4AtqNLEtsgL4BKAQD4ZiAJCox4gHTkBoHgCYAzKBAA5AHkAFQBRAEIZbUVQZVUNM1AAB3J2dlJKUFUFGkzySCwjUFwMdiyieAJoTMNQXQMijEgFaDh4DPsyLHxiGlAnAG5EU1YOIidSFiweKTktGLj1TVN3aRiAcmV10FMhlDBuHhEJSenzAb8wAB4AWjvQfBo2PT1SGiJsyFhiUCNib-Y4XCyFQdzB4IhkKh0JhILAACUKNQ6PQbgA3IzsDC0ZiINg0TigbiedzHSRRUAAagWWBUS209UMPzMln4NmkiFAoAcYCcrncXl8ARCEVAAGVVCxSKB6AQFGQHlilmw0eQVOR3lEtNSlLT4podPomcsADQyuUsDXrIh6QjkQrlTqkbq9foSIYjPFjN3iU6eWbyGl0hIrQTSBRSTa07a7ZDEsl+85AA)) Why can’t I refine a union of objects? -------------------------------------- There are two potential reasons: 1. You are using inexact objects. 2. You are destructuring the object. When destructuring, Flow loses track of object properties. Broken example: ``` /* @flow */ type Action = | {type: 'A', payload: string} | {type: 'B', payload: number}; // Not OK const fn = ({type, payload}: Action) => { switch (type) { case 'A': return payload.length; case 'B': return payload + 10; } } ``` Fixed example: ``` /* @flow */ type Action = | {type: 'A', payload: string} | {type: 'B', payload: number}; // OK const fn = (action: Action) => { switch (action.type) { case 'A': return action.payload.length; case 'B': return action.payload + 10; } } ``` ([https://flow.org/try](https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVAXAngBwKZgCCAxhgJZwB2YAvGKmGAD5gDe2+AXGAOSE8AaMDgCGWeCIAm3AM4YATmUoBzAL6MGzNhzzceAIUHCxE6WEoBXALYAjPPNUBudMGBgA8gGlUxKnLBQAIy0YAAUIqQUlNwk5FQAlLQAfGyaMghkGMQAFmERcZQAdDqJrJqMxCIyBHw83PJ4GBby1PlRhaLicFKFMHgqGNnOjBVVNYb1jc2tkVQdJt2SYADUYIEADMNgqqg7Lm4AcnAYHp5gFpS+Vlb9J1Bw8mD28g8yAISorr6U-lAATCFQuxcHghJ1TKoYrNKIkaCkyq5GOlMjkwiVUoiRpVqrx+JMmi1jF0en0BkNPm4sWNeBMwA0CdRwYsVmtNhTGDtEaogA)) Second example: * broken: [https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQBLAtgB1gJwC6gFSgCGAzqAEoCmRAxnpFrKqAORbV0uKI4Ce6lUAGUArgCMAjAAVG6MgF5QAb2IAuUADsRqMZSwAaUGPVade0AF8A3D36DRYgEwzYc0IpVF1JHFmQaAc0Mab19-AMsbRBpYDR9hcQl3UAAKdFkSdQdpDIBKdwA+UAAeABNkADdQYAKbGLi8B0dktIys8Wc8wpLyqpqo+viAYSYWpURQUBJKaEo6bH0J0AA6VfTXEkQLdRVp2fmsdV8RSkNV5eyXNwtQAB9lKZm5nGx1SCJoabPVpquyC3y8gKSz2z2woAA-CVsspzus5DcaqB1MUmrC1hlEbUgA) * fixed: [https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQBLAtgB1gJwC6gFSgCGAzqAEoCmRAxnpFrKqAORbV0uKI4Ce6lUAGUArgCMAjAAVG6MgF5QAbwA+xAFygAdiNRjKWADSgxmnXoOgVAXwDcPfoNFiATDNhzQi1RtAkcWMhaAObGNJr+gSFWdtw0sFr+wuISXqAAFOiyJJrO0tkAlF4AfKAAPAAmyABuoMDF9vGJeM4uaZnZueJuhSXlVbX19ohNSQDCTO1ZHjnKaiSU0JR02JoBIpTGAHQ7ee6eNlZzfovLOKugkETQC9u73ftkNkXypUqIoKDIkBnTclsLJYrLBFd6fT5LPBKQFnbB3LbsfzWNJ-Ej2cGgdg4ERYLTlPLKHYIyhIuoND6gZGLBbKCkQyhQmHA+GInDIxSo9HgrE4vFlVqEnas5FDCnWRDWIA) I got a “Missing type annotation” error. Where does it come from? ----------------------------------------------------------------- Flow requires type annotations at module boundaries to make sure it can scale. To read more about that, check out our [blog post](https://medium.com/flow-type/asking-for-required-annotations-64d4f9c1edf8) about that. The most common case you’ll encounter is when exporting a function or React component. Flow requires you to annotate inputs. For instance, in this [example](https://flow.org/try/#0PTAEAEDMBsHsHcBQBTAHgB1gJwC6gMawB2AzngIYAmloAvKOXQHwOgDUoAjANxA), flow will complain: ``` export const add = a => a + 1; ``` The fix here is to add types to the parameters of `add`. Example ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQBTAHgB1gJwC6gMawB2AzngIYAmloAvKABTkBcoRArgLYBGyWAlHQB8ocqADUoAIwBuIA)): ``` export const add = (a: number) => a + 1; ``` To see how you can annotate exported React components, check out our docs on [HOCs](https://flow.org/en/react/hoc/#toc-exporting-wrapped-components). There are other cases where this happens, and they might be harder to understand. You’ll get an error like `Missing type annotation for U` For instance, you wrote this [code](https://flow.org/try/#0PTAEAEDMBsHsHcBQiDGsB2BnALqAhgE4F4CeoAvKANoDkeNANKDQEY0C6iApgB4AOsArjRZcAcy7ouBAJYoAgkVIV8SkgDoAtnj4AKPBQB8+AJRA): ``` const array = ['a', 'b'] export const genericArray = array.map(a => a) ``` Here, Flow will complain on the `export`, asking for a type annotation. Flow wants you to annotate exports returned by a generic function. The type of `Array.prototype.map` is `map<U>(callbackfn: (value: T, index: number, array: Array<T>) => U, thisArg?: any): Array<U>`. The `<U>` corresponds to what is called a [generic](types/generics), to express the fact that the type of the function passed to map is linked to the type of the array. Understanding the logic behind generics might be useful, but what you really need to know to make your typings valid is that you need to help Flow to understand the type of `genericArray`. You can do that by adding an explicit type argument: ``` const array = ['a', 'b']; export const genericArray = array.map<string>(a => a); ``` or by annotating the exported constant ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQBjWA7AzgF1AQwE764CeoAvKANoDku1ANKNQEbUC6iApgB4AOs+HKkw4A5pzSd8AS2QBBQiQBcoBUWIAebDLSiAfOTyLiAOgC2uXgApc5A7gCUQA)): ``` const array = ['a', 'b'] export const genericArray: Array<string> = array.map(a => a) ``` Flow cannot understand the types of my higher order React component, how can I help it? --------------------------------------------------------------------------------------- Typings HOCs can be complicated. While you can follow the [docs about it](react/hoc), sometimes it can be easier to type the returned component. For instance, in this [example](https://flow.org/try/#0PTAEAEDMBsHsHcBQBLAtgB1gJwC6gFSgCGAzqAEoCmRAxnpFrKqAORbV0sDciiNsAOxJ4SlHABUAnukqgAvKABCpSgGEmmAZQF45APlDpG6MvtAAeZaPUZB2vAG8AdC6OwTAX1A5plOQCIAIwBXHBxBf1BgPR5+ITwAcW1KLGQaRVDwgXlQAAoHHxkAGlAaAAtkaAATdgEPAEp5A3MQsMFvXzkC3y9BVWg0gGsu3MazOJJYaEonOABzXJYaAZpByiqWeo89B3LKmu0Pc2BWrJjeCbwMtoEALgoOHCcbTXspGXNdiura+6paJ4AOVgVUo2xyogkvlySS0qXSmUE9S4QA), we don’t type the HOC (setType), but the component created with it, `Button`. To do so, we use the type `React.ComponentType`. ``` // @flow import * as React from 'react'; const setType = BaseComponent => props => <BaseComponent {...props} type="button" />; const GenericButton = ({type, children}) => <button type={type} onClick={() => console.log('clicked')}>{children}</button>; const Button: React.ComponentType<{children: React.Node}> = setType(GenericButton); ``` flow Lint Rule Reference Lint Rule Reference =================== Available Lint Rules -------------------- * [`all`](#toc-all) * [`ambiguous-object-type`](#toc-ambiguous-object-type) * [`deprecated-type`](#toc-deprecated-type) * [`deprecated-utility`](#toc-deprecated-utility) * [`implicit-inexact-object`](#toc-implicit-inexact-object) * [`nonstrict-import`](#toc-nonstrict-import) * [`sketchy-null`](#toc-sketchy-null) * [`sketchy-number`](#toc-sketchy-number) * [`unclear-type`](#toc-unclear-type) * [`unnecessary-invariant`](#toc-unnecessary-invariant) * [`unnecessary-optional-chain`](#toc-unnecessary-optional-chain) * [`unsafe-getters-setters`](#toc-unsafe-getters-setters) * [`untyped-import`](#toc-untyped-import) * [`untyped-type-import`](#toc-untyped-type-import) ### `all` While `all` isn’t technically a lint rule, it’s worth mentioning here. `all` sets the default level for lint rules that don’t have a level set explicitly. `all` can only occur as the first entry in a `.flowconfig` or as the first rule in a `--lints` flag. It’s not allowed in comments at all because it would have different semantics than would be expected. ### `ambiguous-object-type` Like [`implicit-inexact-object`](#toc-implicit-inexact-object), except triggers even when the `exact_by_default` option is set to `true`. ### `deprecated-type` Triggers when you use the `*` (existential) type, as this type is unsafe and usually just equivalent to `any`. The effect of `*` can generally be achieved by simply not providing a type annotation. ### `deprecated-utility` Triggers when you use the `$Supertype` or `$Subtype` utility types, as these types are unsafe and equivalent to `any`. ### `implicit-inexact-object` Triggers when you use object type syntax without explicitly specifying exactness or inexactness. This lint setting is ignored when `exact_by_default` is set to `true`. ``` type A = {x: number}; // Error type B = {x: number, ...} // Ok type C = {| x: number |} // Ok ``` ### `nonstrict-import` Used in conjuction with [Flow Strict](https://flow.org/en/strict/). Triggers when importing a non `@flow strict` module. When enabled, dependencies of a `@flow strict` module must also be `@flow strict`. ### `sketchy-null` Triggers when you do an existence check on a value that can be either null/undefined or falsey. For example: ``` const x: ?number = 5; if (x) {} // sketchy because x could be either null or 0. const y: number = 5; if (y) {} // not sketchy because y can't be null, only 0. const z: ?{foo: number} = {foo: 5}; if (z) {} // not sketchy, because z can't be falsey, only null/undefined. ``` Setting `sketchy-null` sets the level for all sketchy null checks, but there are more granular rules for particular types. These are: * `sketchy-null-bool` * `sketchy-null-number` * `sketchy-null-string` * `sketchy-null-mixed` The type-specific variants are useful for specifying that some types of sketchy null checks are acceptable while others should be errors/warnings. For example, if you want to allow boolean sketchy null checks (for the pattern of treating undefined optional booleans as false) but forbid other types of sketchy null checks, you can do so with this `.flowconfig` `[lints]` section: ``` [lints] sketchy-null=warn sketchy-null-bool=off ``` and now ``` function foo (bar: ?bool): void { if (bar) { ... } else { ... } } ``` doesn’t report a warning. Suppressing one type of sketchy null check only suppresses that type, so, for example ``` // flowlint sketchy-null:warn, sketchy-null-bool:off const x: ?(number | bool) = 0; if (x) {} ``` would still have a sketchy-null-number warning on line 3. ### `sketchy-number` Triggers when a `number` is used in a manner which may lead to unexpected results if the value is falsy. Currently, this lint triggers if a `number` appears in: * the left-hand side of an `&&` expression. As a motivating example, consider this common idiom in React: ``` {showFoo && <Foo />} ``` Here, `showFoo` is a boolean which controls whether or not to display the `<Foo />` element. If `showFoo` is true, then this evaluates to `{<Foo />}`. If `showFoo` is false, then this evaluates to `{false}`, which doesn’t display anything. Now suppose that instead of a boolean, we have a numerical value representing, say, the number of comments on a post. We want to display a count of the comments, unless there are no comments. We might naively try to do something similar to the boolean case: ``` {count && <>[{count} comments]</>} ``` If `count` is, say, `5`, then this displays “[5 comments]”. However, if `count` is `0`, then this displays “0” instead of displaying nothing. (This problem is unique to `number` because `0` and `NaN` are the only falsy values which React renders with a visible result.) This could be subtly dangerous: if this immediately follows another numerical value, it might appear to the user that we have multiplied that value by 10! Instead, we should do a proper conditional check: ``` {count ? <>[{count} comments]</> : null} ``` ### `unclear-type` Triggers when you use `any`, `Object`, or `Function` as type annotations. These types are unsafe. ### `unnecessary-invariant` Triggers when you use `invariant` to check a condition which we know must be truthy based on the available type information. This is quite conservative: for example, if all we know about the condition is that it is a `boolean`, then the lint will not fire even if the condition must be `true` at runtime. Note that this lint does not trigger when we know a condition is always `false`. It is a common idiom to use `invariant()` or `invariant(false, ...)` to throw in code that should be unreachable. ### `unnecessary-optional-chain` Triggers when you use `?.` where it isn’t needed. This comes in two main flavors. The first is when the left-hand-side cannot be nullish: ``` type Foo = { bar: number } declare var foo: Foo; foo?.bar; // Lint: unnecessary-optional-chain ``` The second is when the left-hand-side could be nullish, but the short-circuiting behavior of `?.` is sufficient to handle it anyway: ``` type Foo = { bar: { baz: number } } declare var foo: ?Foo; foo?.bar?.baz; // Lint: unnecessary-optional-chain ``` In the second example, the first use of `?.` is valid, since `foo` is potentially nullish, but the second use of `?.` is unnecessary. The left-hand-side of the second `?.` (`foo?.bar`) can only be nullish as a result of `foo` being nullish, and when `foo` is nullish, short-circuiting lets us avoid the second `?.` altogether! ``` foo?.bar.baz; ``` This makes it clear to the reader that `bar` is not a potentially nullish property. ### `unsafe-getters-setters` Triggers when you use getters or setters. Getters and setters can have side effects and are unsafe. For example: ``` const o = { get a() { return 4; }, // Error: unsafe-getters-setters set b(x: number) { this.c = x; }, // Error: unsafe-getters-setters c: 10, }; ``` ### `untyped-import` Triggers when you import from an untyped file. Importing from an untyped file results in those imports being typed as `any`, which is unsafe. ### `untyped-type-import` Triggers when you import a type from an untyped file. Importing a type from an untyped file results in an `any` alias, which is typically not the intended behavior. Enabling this lint brings extra attention to this case and can help improve Flow coverage of typed files by limiting the spread of implicit `any` types.
programming_docs
flow Flowlint Comments Flowlint Comments ================= Configuring lint settings with `flowlint` comments allows you to specify different settings within a file and different settings to different regions of different files. These comments come in three forms: * [flowlint](#toc-flowlint) * [flowlint-line](#toc-flowlint-line) * [flowlint-next-line](#toc-flowlint-next-line) In all forms, whitespace and asterisks between words are ignored, allowing for flexible formatting. flowlint -------- The basic `flowlint` comment takes a comma-delimited list of `rule:severity` pairs and applies those settings for the rest of the source file until overridden. This has three primary purposes: applying settings over a block, applying settings over a file, and applying settings over part of a line. **settings over a block of code:** A pair of `flowlint` comments can be used to apply a certain setting over a block of code. For example, to disabling the untyped-type-import lint over a block of type imports would look like this: ``` import type { // flowlint untyped-type-import:off Foo, Bar, Baz, // flowlint untyped-type-import:error } from './untyped.js'; ``` **settings over a file:** A `flowlint` comment doesn’t have to have a matching comment to form a block. An unmatched comment simply applies its settings to the rest of the file. You could use this, for example, to suppress all sketchy-null-check lints in a particular file: ``` // flowlint sketchy-null:off ... ``` **settings over part of a line:** The settings applied by `flowlint` start and end right at the comment itself. This means that you can do things like ``` function (a: ?boolean, b: ?boolean) { if (/* flowlint sketchy-null-bool:off */a/* flowlint sketchy-null-bool:warn */ && b) { ... } else { ... } } ``` if you want control at an even finer level than you get from the line-based comments. flowlint-line ------------- A `flowlint-line` comment works similarly to a `flowlint` comment, except it only applies its settings to the current line instead of applying them for the rest of the file. The primary use for `flowlint-line` comments is to suppress a lint on a particular line: ``` function (x: ?boolean) { if (x) { // flowlint-line sketchy-null-bool:off ... } else { ... } } ``` flowlint-next-line ------------------ `flowlint-next-line` works the same as `flowlint-line`, except it applies its settings to the next line instead of the current line: ``` function (x: ?boolean) { // flowlint-next-line sketchy-null-bool:off if (x) { ... } else { ... } } ``` flow IDE Integration IDE Integration =============== In most editors, Flow warnings are likely to be rendered the same way as other warnings are rendered by that editor. Most editors will likely display all Flow warnings, which is fine for small- to medium-scale projects, or projects with fewer unsuppressed warnings. flow Creating Library Definitions Creating Library Definitions ============================ Before spending the time to write your own libdef, we recommend that you look to see if there is already a libdef for the third-party code that you’re addressing. `flow-typed` is a [tool and repository](https://github.com/flowtype/flow-typed/) for sharing common libdefs within the Flow community – so it’s a good way to knock out a good chunk of any public libdefs you might need for your project. However sometimes there isn’t a pre-existing libdef or you have third-party code that isn’t public and/or you really just need to write a libdef yourself. To do this you’ll start by creating a `.js` file for each libdef you’re going to write and put them in the `/flow-typed` directory at the root of your project. In these libdef file(s) you’ll use a special set of Flow syntax (explained below) to describe the interfaces of the relevant third-party code. Declaring A Global Function --------------------------- To declare a global function that should be accessible throughout your project, use the `declare function` syntax in a libdef file: **flow-typed/myLibDef.js** ``` declare function foo(a: number): string; ``` This tells Flow that any code within the project can reference the `foo` global function, and that the function takes one argument (a `number`) and it returns a `string`. Declaring A Global Class ------------------------ To declare a global class that should be accessible throughout your project, use the `declare class` syntax in a libdef file: **flow-typed/myLibDef.js** ``` declare class URL { constructor(urlStr: string): URL; toString(): string; static compare(url1: URL, url2: URL): boolean; } ``` This tells Flow that any code within the project can reference the `URL` global class. Note that this class definition does not have any implementation details – it exclusively defines the interface of the class. Declaring A Global Variable --------------------------- To declare a global variable that should be accessible throughout your project, use the `declare var` syntax in a libdef file: **flow-typed/myLibDef.js** ``` declare var PI: number; ``` This tells Flow that any code within the project can reference the `PI` global variable – which, in this case, is a `number`. Declaring A Global Type ----------------------- To declare a global type that should be accessible throughout your project, use the `declare type` syntax in a libdef file: **flow-typed/myLibDef.js** ``` declare type UserID = number; ``` This tells Flow that any code within the project can reference the `UserID` global type – which, in this case, is just an alias for `number`. Declaring A Module ------------------ Often, third-party code is organized in terms of modules rather than globals. To write a libdef that declares the presence of a module you’ll want to use the `declare module` syntax: ``` declare module "some-third-party-library" { // This is where we'll list the module's exported interface(s) } ``` The name specified in quotes after `declare module` can be any string, but it should correspond to the same string you’d use to `require` or `import` the third-party module into your project. For defining modules that are accessed via a relative `require`/`import` path, please see the docs on the [`.flow` files](https://flow.org/en/declarations) Within the body of a `declare module` block, you can specify the set of exports for that module. However, before we start talking about exports we have to talk about the two kinds of modules that Flow supports: CommonJS and ES modules. Flow can handle both CommonJS and ES modules, but there are some relevant differences between the two that need to be considered when using `declare module`. ### Declaring An ES Module [ES modules](http://exploringjs.com/es6/ch_modules.html) have two kinds of exports: A **named** export and a **default** export. Flow supports the ability to declare either or both of these kinds of exports within a `declare module` body as follows: ###### Named Exports **flow-typed/some-es-module.js** ``` declare module "some-es-module" { // Declares a named "concatPath" export declare export function concatPath(dirA: string, dirB: string): string; } ``` Note that you can also declare other things inside the body of the `declare module`, and those things will be scoped to the body of the `declare module` – **but they will not be exported from the module**: **flow-typed/some-es-module.js** ``` declare module "some-es-module" { // Defines the type of a Path class within this `declare module` body, but // does not export it. It can only be referenced by other things inside the // body of this `declare module` declare class Path { toString(): string; } // Declares a named "concatPath" export which returns an instance of the // `Path` class (defined above) declare export function concatPath(dirA: string, dirB: string): Path; } ``` ###### Default Exports **flow-typed/some-es-module.js** ``` declare module "some-es-module" { declare class URL { constructor(urlStr: string): URL; toString(): string; static compare(url1: URL, url2: URL): boolean; } // Declares a default export whose type is `typeof URL` declare export default typeof URL; } ``` It is also possible to declare both **named** and **default** exports in the same `declare module` body. ### Declaring A CommonJS Module CommonJS modules have a single value that is exported (the `module.exports` value). To describe the type of this single value within a `declare module` body, you’ll use the `declare module.exports` syntax: **flow-typed/some-commonjs-module.js** ``` declare module "some-commonjs-module" { // The export of this module is an object with a "concatPath" method declare module.exports: { concatPath(dirA: string, dirB: string): string; }; } ``` Note that you can also declare other things inside the body of the `declare module`, and those things will be scoped to the body of the `declare module`, **but they will not be exported from the module**: **flow-typed/some-commonjs-module.js** ``` declare module "some-commonjs-module" { // Defines the type of a Path class within this `declare module` body, but // does not export it. It can only be referenced by other things inside the // body of this `declare module` declare class Path { toString(): string; } // The "concatPath" function now returns an instance of the `Path` class // (defined above). declare module.exports: { concatPath(dirA: string, dirB: string): Path }; } ``` NOTE: Because a given module cannot be both an ES module and a CommonJS module, it is an error to mix `declare export [...]` with `declare module.exports: ...` in the same `declare module` body. flow Create React App Create React App ================ [Create React App](https://github.com/facebookincubator/create-react-app) already supports Flow by default. All you need to do is [install Flow](https://flow.org/en/install/) and create a `.flowconfig` file by running `flow init`. ``` create-react-app my-app && cd my-app yarn add --dev flow-bin yarn run flow init ``` Flow will be run as part of create-react-app’s scripts. flow Babel Babel ===== Flow and [Babel](http://babeljs.io/) are designed to work great together. It takes just a few steps to set them up together. If you don’t have Babel setup already, you can do that by following [this guide](http://babeljs.io/docs/setup/). Once you have Babel setup, install `@babel/preset-flow` with either [Yarn](https://yarnpkg.com/) or [npm](https://www.npmjs.com/). ``` yarn add --dev @babel/preset-flow # or npm install --save-dev @babel/preset-flow ``` Then add `flow` to your Babel presets config. ``` { "presets": ["@babel/preset-flow"] } ``` flow flow-remove-types flow-remove-types ================= [`flow-remove-types`](https://github.com/facebook/flow/tree/master/packages/flow-remove-types) is a small CLI tool for stripping Flow type annotations from files. It’s a lighter-weight alternative to Babel for projects that don’t need everything Babel provides. First install `flow-remove-types` with either [Yarn](https://yarnpkg.com/) or [npm](https://www.npmjs.com/). ``` yarn add --dev flow-remove-types # or npm install --save-dev flow-remove-types ``` If you then put all your source files in a `src` directory you can compile them to another directory by running: ``` yarn run flow-remove-types src/ -d lib/ ``` You can add this to your `package.json` scripts easily. ``` { "name": "my-project", "main": "lib/index.js", "scripts": { "build": "flow-remove-types src/ -d lib/", "prepublish": "yarn run build" } } ``` > **Note:** You’ll probably want to add a `prepublish` script that runs this transform as well, so that it runs before you publish your code to the npm registry. > > flow ESLint ESLint ====== ESLint is a static analysis tool which can help you quickly find and fix bugs and stylistic errors in your code. The rules ESLint provide complement the checks provided by Flow’s type system. You can quick-start setup ESLint, install `hermes-eslint` with either [Yarn](https://yarnpkg.com/) or [npm](https://www.npmjs.com/). ``` yarn add --dev eslint hermes-eslint eslint-plugin-ft-flow # or npm install --save-dev eslint hermes-eslint eslint-plugin-ft-flow ``` Then create a `.eslintrc.js` file in your project root with the following: ``` module.exports = { root: true, parser: 'hermes-eslint', plugins: [ 'ft-flow' ], extends: [ 'eslint:recommended', 'plugin:ft-flow/recommended', ], }; ``` For more information about configuring ESLint, [check out the ESLint docs](https://eslint.org/). You can then lint your codebase with: ``` yarn run eslint . --ext .js,.jsx # or npm run eslint . --ext .js,.jsx ``` Usage With Prettier ------------------- If you use [`prettier`](https://www.npmjs.com/package/prettier), there is also a helpful config to help ensure ESLint doesn’t report on formatting issues that prettier will fix: [`eslint-config-prettier`](https://www.npmjs.com/package/eslint-config-prettier). Using this config by adding it to the ***end*** of your `extends`: ``` module.exports = { root: true, parser: 'hermes-eslint', plugins: [ 'ft-flow' ], extends: [ 'eslint:recommended', 'plugin:ft-flow/recommended', + 'prettier', ], }; ``` Additional Plugins ------------------ ESLint plugins provide additional rules and other functionality on top of ESLint. Below are just a few examples that might be useful: * Helpful language rules by the Flow team: [`eslint-plugin-fb-flow`](https://www.npmjs.com/package/eslint-plugin-fb-flow) * React best practices: [`eslint-plugin-react`](https://www.npmjs.com/package/eslint-plugin-react) and [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks) * Jest testing: [`eslint-plugin-jest`](https://www.npmjs.com/package/eslint-plugin-jest) * Import/export conventions : [`eslint-plugin-import`](https://www.npmjs.com/package/eslint-plugin-import) * NodeJS best practices: [`eslint-plugin-node`](https://www.npmjs.com/package/eslint-plugin-node) * ESLint comment restrictions: [`eslint-plugin-eslint-comments`](https://www.npmjs.com/package/eslint-plugin-eslint-comments) Every plugin that is out there includes documentation on the various configurations and rules they offer. A typical plugin might be used like: ``` module.exports = { root: true, parser: 'hermes-eslint', plugins: [ 'ft-flow' + 'jest', ], extends: [ 'eslint:recommended', 'plugin:ft-flow/recommended', + 'plugin:jest/recommended', ], }; ``` Search [“eslint-plugin” on npm](https://www.npmjs.com/search?q=eslint-plugin) for more. flow Generic Types Generic Types ============= Generics (sometimes referred to as polymorphic types) are a way of abstracting a type away. Imagine writing the following `identity` function which returns whatever value was passed. ``` function identity(value) { return value; } ``` We would have a lot of trouble trying to write specific types for this function since it could be anything. ``` function identity(value: string): string { return value; } ``` Instead we can create a generic (or polymorphic type) in our function and use it in place of other types. ``` function identity<T>(value: T): T { return value; } ``` Generics can be used within functions, function types, classes, type aliases, and interfaces. > **Warning:** Flow does not infer generic types. If you want something to have a generic type, **annotate it**. Otherwise, Flow may infer a type that is less polymorphic than you expect. > > In the following example, we forget to properly annotate `identity` with a generic type, so we run into trouble when we try to assign it to `func`. On the other hand, `genericIdentity` is properly typed, and we are able to use it as expected. ``` // @flow type IdentityWrapper = { func<T>(T): T } function identity(value) { return value; } function genericIdentity<T>(value: T): T { return value; } // $ExpectError const bad: IdentityWrapper = { func: identity }; // Error! const good: IdentityWrapper = { func: genericIdentity }; // Works! ``` ### Syntax of generics There are a number of different places where generic types appear in syntax. ##### Functions with generics Functions can create generics by adding the type parameter list `<T>` before the function parameter list. You can use generics in the same places you’d add any other type in a function (parameter or return types). ``` function method<T>(param: T): T { // ... } function<T>(param: T): T { // ... } ``` ##### Function types with generics Function types can create generics in the same way as normal functions, by adding the type parameter list `<T>` before the function type parameter list. You can use generics in the same places you’d add any other type in a function type (parameter or return types). ``` <T>(param: T) => T ``` Which then gets used as its own type. ``` function method(func: <T>(param: T) => T) { // ... } ``` ##### Classes with generics Classes can create generics by placing the type parameter list before the body of the class. ``` class Item<T> { // ... } ``` You can use generics in the same places you’d add any other type in a class (property types and method parameter/return types). ``` class Item<T> { prop: T; constructor(param: T) { this.prop = param; } method(): T { return this.prop; } } ``` ##### Type aliases with generics ``` type Item<T> = { foo: T, bar: T, }; ``` ##### Interfaces with generics ``` interface Item<T> { foo: T, bar: T, } ``` ##### Supplying Type Arguments to Callables You can give callable entities type arguments for their generics directly in the call: ``` //@flow function doSomething<T>(param: T): T { // ... return param; } doSomething<number>(3); ``` You can also give generic classes type arguments directly in the `new` expression: ``` //@flow class GenericClass<T> {} const c = new GenericClass<number>(); ``` If you only want to specify some of the type arguments, you can use `_` to let flow infer a type for you: ``` //@flow class GenericClass<T, U, V>{} const c = new GenericClass<_, number, _>() ``` > **Warning:** For performance purposes, we always recommend you annotate with concrete arguments when you can. `_` is not unsafe, but it is slower than explicitly specifying the type arguments. > > Behavior of generics -------------------- #### Generics act like variables Generic types work a lot like variables or function parameters except that they are used for types. You can use them whenever they are in scope. ``` function constant<T>(value: T): () => T { return function(): T { return value; }; } ``` #### Create as many generics as you need You can have as many of these generics as you need in the type parameter list, naming them whatever you want: ``` function identity<One, Two, Three>(one: One, two: Two, three: Three) { // ... } ``` #### Generics track values around When using a generic type for a value, Flow will track the value and make sure that you aren’t replacing it with something else. ``` // @flow function identity<T>(value: T): T { // $ExpectError return "foo"; // Error! } function identity<T>(value: T): T { // $ExpectError value = "foo"; // Error! // $ExpectError return value; // Error! } ``` Flow tracks the specific type of the value you pass through a generic, letting you use it later. ``` // @flow function identity<T>(value: T): T { return value; } let one: 1 = identity(1); let two: 2 = identity(2); // $ExpectError let three: 3 = identity(42); ``` #### Adding types to generics Similar to `mixed`, generics have an “unknown” type. You’re not allowed to use a generic as if it were a specific type. ``` // @flow function logFoo<T>(obj: T): T { // $ExpectError console.log(obj.foo); // Error! return obj; } ``` You could refine the type, but the generic will still allow any type to be passed in. ``` // @flow function logFoo<T>(obj: T): T { if (obj && obj.foo) { console.log(obj.foo); // Works. } return obj; } logFoo({ foo: 'foo', bar: 'bar' }); // Works. logFoo({ bar: 'bar' }); // Works. :( ``` Instead, you could add a type to your generic like you would with a function parameter. ``` // @flow function logFoo<T: { foo: string }>(obj: T): T { console.log(obj.foo); // Works! return obj; } logFoo({ foo: 'foo', bar: 'bar' }); // Works! // $ExpectError logFoo({ bar: 'bar' }); // Error! ``` This way you can keep the behavior of generics while only allowing certain types to be used. ``` // @flow function identity<T: number>(value: T): T { return value; } let one: 1 = identity(1); let two: 2 = identity(2); // $ExpectError let three: "three" = identity("three"); ``` #### Generic types act as bounds ``` // @flow function identity<T>(val: T): T { return val; } let foo: 'foo' = 'foo'; // Works! let bar: 'bar' = identity('bar'); // Works! ``` In Flow, most of the time when you pass one type into another you lose the original type. So that when you pass a specific type into a less specific one Flow “forgets” it was once something more specific. ``` // @flow function identity(val: string): string { return val; } let foo: 'foo' = 'foo'; // Works! // $ExpectError let bar: 'bar' = identity('bar'); // Error! ``` Generics allow you to hold onto the more specific type while adding a constraint. In this way types on generics act as “bounds”. ``` // @flow function identity<T: string>(val: T): T { return val; } let foo: 'foo' = 'foo'; // Works! let bar: 'bar' = identity('bar'); // Works! ``` Note that when you have a value with a bound generic type, you can’t use it as if it were a more specific type. ``` // @flow function identity<T: string>(val: T): T { let str: string = val; // Works! // $ExpectError let bar: 'bar' = val; // Error! return val; } identity('bar'); ``` #### Parameterized generics Generics sometimes allow you to pass types in like arguments to a function. These are known as parameterized generics (or parametric polymorphism). For example, a type alias with a generic is parameterized. When you go to use it you will have to provide a type argument. ``` type Item<T> = { prop: T, } let item: Item<string> = { prop: "value" }; ``` You can think of this like passing arguments to a function, only the return value is a type that you can use. Classes (when being used as a type), type aliases, and interfaces all require that you pass type arguments. Functions and function types do not have parameterized generics. ***Classes*** ``` // @flow class Item<T> { prop: T; constructor(param: T) { this.prop = param; } } let item1: Item<number> = new Item(42); // Works! // $ExpectError let item2: Item = new Item(42); // Error! ``` ***Type Aliases*** ``` // @flow type Item<T> = { prop: T, }; let item1: Item<number> = { prop: 42 }; // Works! // $ExpectError let item2: Item = { prop: 42 }; // Error! ``` ***Interfaces*** ``` // @flow interface HasProp<T> { prop: T, } class Item { prop: string; } (Item.prototype: HasProp<string>); // Works! // $ExpectError (Item.prototype: HasProp); // Error! ``` ##### Adding defaults to parameterized generics You can also provide defaults for parameterized generics just like parameters of a function. ``` type Item<T: number = 1> = { prop: T, }; let foo: Item<> = { prop: 1 }; let bar: Item<2> = { prop: 2 }; ``` You must always include the brackets `<>` when using the type (just like parentheses for a function call). #### Variance Sigils You can also specify the subtyping behavior of a generic via variance sigils. By default, generics behave invariantly, but you may add a `+` to their declaration to make them behave covariantly, or a `-` to their declaration to make them behave contravariantly. See [our docs on variance](https://flow.org/en/lang/variance) for a more information on variance in Flow. Variance sigils allow you to be more specific about how you intend to use your generics, giving Flow the power to do more precise type checking. For example, you may want this relationship to hold: ``` //@flow type GenericBox<+T> = T; var x: GenericBox<number> = 3; (x: GenericBox<number| string>); ``` The example above could not be accomplished without the `+` variance sigil: ``` //@flow type GenericBoxError<T> = T; var x: GenericBoxError<number> = 3; (x: GenericBoxError<number| string>); // number | string is not compatible with number. ``` Note that if you annotate your generic with variance sigils then Flow will check to make sure those types only appear in positions that make sense for that variance sigil. For example, you cannot declare a generic type parameter to behave covariantly and use it in a contravariant position: ``` //@flow type NotActuallyCovariant<+T> = (T) => void; ```
programming_docs
flow Any Types Any Types ========= > **Warning:** Do not mistake `any` with `mixed`. [Read more](../mixed) > > If you want a way to opt-out of using the type checker, `any` is the way to do it. **Using `any` is completely unsafe, and should be avoided whenever possible.** For example, the following code will not report any errors: ``` // @flow function add(one: any, two: any): number { return one + two; } add(1, 2); // Works. add("1", "2"); // Works. add({}, []); // Works. ``` Even code that will cause runtime errors will not be caught by Flow: ``` // @flow function getNestedProperty(obj: any) { return obj.foo.bar.baz; } getNestedProperty({}); ``` There are only a couple of scenarios where you might consider using `any`: 1. When you are in the process of converting existing code to using Flow types and you are currently blocked on having the code type checked (maybe other code needs to be converted first). 2. When you are certain your code works and for some reason Flow is unable to type check it correctly. There are a (decreasing) number of idioms in JavaScript that Flow is unable to statically type. Avoid leaking `any` ------------------- When you have a value with the type `any`, you can cause Flow to infer `any` for the results of all of the operations you perform. For example, if you get a property on an object typed `any`, the resulting value will also have the type `any`. ``` // @flow function fn(obj: any) { let foo /* (:any) */ = obj.foo; } ``` You could then use the resulting value in another operation, such as adding it as if it were a number and the result will also be `any`. ``` // @flow function fn(obj: any) { let foo /* (:any) */ = obj.foo; let bar /* (:any) */ = foo * 2; } ``` You could continue this process until `any` has leaked all over your code. ``` // @flow function fn(obj: any) /* (:any) */ { let foo /* (:any) */ = obj.foo; let bar /* (:any) */ = foo * 2; return bar; } let bar /* (:any) */ = fn({ foo: 2 }); let baz /* (:any) */ = "baz:" + bar; ``` Prevent this from happening by cutting `any` off as soon as possible by casting it to another type. ``` // @flow function fn(obj: any) { let foo: number = obj.foo; } ``` Now your code will not leak `any`. ``` // @flow function fn(obj: any) /* (:number) */ { let foo: number = obj.foo; let bar /* (:number) */ = foo * 2; return bar; } let bar /* (:number) */ = fn({ foo: 2 }); let baz /* (:string) */ = "baz:" + bar; ``` flow Object Types Object Types ============ Objects can be used in many different ways in JavaScript. There are a number of different ways to type them in order to support all the different use cases. In Flow, there are two different kinds of object types: exact object types and inexact object types. In general, we recommend using [exact object types](#toc-exact-object-types) whenever possible. Exact object types are more precise and interact better with other type system features, like spreads. Object type syntax ------------------ Object types try to match the syntax for objects in JavaScript as much as possible. Using curly braces `{}` and name-value pairs using a colon `:` split by commas `,`. ``` // @flow var obj1: { foo: boolean } = { foo: true }; var obj2: { foo: number, bar: boolean, baz: string, } = { foo: 1, bar: true, baz: 'three', }; ``` > **Note:** Previously object types used semicolons `;` for splitting name-value pairs. While the syntax is still valid, you should use commas `,`. > > #### Optional object type properties In JavaScript, accessing a property that doesn’t exist evaluates to `undefined`. This is a common source of errors in JavaScript programs, so Flow turns these into type errors. ``` // @flow var obj = { foo: "bar" }; // $ExpectError obj.bar; // Error! ``` If you have an object that sometimes does not have a property you can make it an *optional property* by adding a question mark `?` after the property name in the object type. ``` // @flow var obj: { foo?: boolean } = {}; obj.foo = true; // Works! // $ExpectError obj.foo = 'hello'; // Error! ``` In addition to their set value type, these optional properties can either be `void` or omitted altogether. However, they cannot be `null`. ``` // @flow function acceptsObject(value: { foo?: string }) { // ... } acceptsObject({ foo: "bar" }); // Works! acceptsObject({ foo: undefined }); // Works! // $ExpectError acceptsObject({ foo: null }); // Error! acceptsObject({}); // Works! ``` ### Object methods Method syntax in objects has the same runtime behavior as a function property. These two objects are equivalent at runtime: ``` // @flow let a = { foo : function () { return 3; } }; let b = { foo() { return 3; } } ``` However, despite their equivalent runtime behavior, Flow checks them slightly differently. In particular, object properties written with method syntax are read-only; Flow will not allow you to write a new value to them. ``` // @flow let b = { foo() { return 3; } } b.foo = () => { return 2; } // Error! ``` Additionally, object methods do not allow the use of `this` in their bodies, in order to guarantee simple behavior for their `this` parameters. Prefer to reference the object by name instead of using `this`. ``` // @flow let a = { x : 3, foo() { return this.x; } // error! } let b = { x : 3, foo() { return b.x; } // works! } ``` Object type inference --------------------- Flow can infer the type of object literals in two different ways depending on how they are used. ### Sealed objects When you create an object with its properties, you create a *sealed* object type in Flow. These sealed objects will know all of the properties you declared them with and the types of their values. ``` // @flow var obj = { foo: 1, bar: true, baz: 'three' }; var foo: number = obj.foo; // Works! var bar: boolean = obj.bar; // Works! // $ExpectError var baz: null = obj.baz; // Error! var bat: string = obj.bat; // Error! ``` But when objects are sealed, Flow will not allow you to add new properties to them. ``` // @flow var obj = { foo: 1 }; // $ExpectError obj.bar = true; // Error! // $ExpectError obj.baz = 'three'; // Error! ``` The workaround here might be to turn your object into an *unsealed object*. ### Unsealed objects When you create an object without any properties, you create an *unsealed* object type in Flow. These unsealed objects will not know all of their properties and will allow you to add new ones. ``` // @flow var obj = {}; obj.foo = 1; // Works! obj.bar = true; // Works! obj.baz = 'three'; // Works! ``` The inferred type of the property becomes what you set it to. ``` // @flow var obj = {}; obj.foo = 42; var num: number = obj.foo; ``` ##### Reassigning unsealed object properties Similar to [`var` and `let` variables](../variables#toc-reassigning-variables) if you reassign a property of an unsealed object, by default Flow will give it the type of all possible assignments. ``` // @flow var obj = {}; if (Math.random()) obj.prop = true; else obj.prop = "hello"; // $ExpectError var val1: boolean = obj.prop; // Error! // $ExpectError var val2: string = obj.prop; // Error! var val3: boolean | string = obj.prop; // Works! ``` Sometimes Flow is able to figure out (with certainty) the type of a property after reassignment. In that case, Flow will give it the known type. ``` // @flow var obj = {}; obj.prop = true; obj.prop = "hello"; // $ExpectError var val1: boolean = obj.prop; // Error! var val2: string = obj.prop; // Works! ``` As Flow gets smarter and smarter, it will figure out the types of properties in more scenarios. ##### Unknown property lookup on unsealed objects is unsafe Unsealed objects allow new properties to be written at any time. Flow ensures that reads are compatible with writes, but does not ensure that writes happen before reads (in the order of execution). This means that reads from unsealed objects with no matching writes are never checked. This is an unsafe behavior of Flow which may be improved in the future. ``` var obj = {}; obj.foo = 1; obj.bar = true; var foo: number = obj.foo; // Works! var bar: boolean = obj.bar; // Works! var baz: string = obj.baz; // Works? ``` Exact object types ------------------ In Flow, it is considered safe to pass an object with extra properties where a normal object type is expected. ``` // @flow function method(obj: { foo: string }) { // ... } method({ foo: "test", // Works! bar: 42 // Works! }); ``` > **Note:** This is because of [“width subtyping”](https://flow.org/en/lang/width-subtyping/). > > Sometimes it is useful to disable this behavior and only allow a specific set of properties. For this, Flow supports “exact” object types. ``` {| foo: string, bar: number |} ``` Unlike regular object types, it is not valid to pass an object with “extra” properties to an exact object type. ``` // @flow var foo: {| foo: string |} = { foo: "Hello", bar: "World!" }; // Error! ``` Intersections of exact object types may not work as you expect. If you need to combine exact object types, use object type spread: ``` // @flow type FooT = {| foo: string |}; type BarT = {| bar: number |}; type FooBarFailT = FooT & BarT; type FooBarT = {| ...FooT, ...BarT |}; const fooBarFail: FooBarFailT = { foo: '123', bar: 12 }; // Error! const fooBar: FooBarT = { foo: '123', bar: 12 }; // Works! ``` Explicit inexact object types ----------------------------- In addition to the default `{}` syntax, you can explicitly indicate an inexact object by using an ellipsis at the end of your property list: ``` // @flow type Inexact = {foo: number, ...}; ``` [Flow is planning to make object types exact by default](https://medium.com/flow-type/on-the-roadmap-exact-objects-by-default-16b72933c5cf). This is available via an [option in your flowconfig](https://flow.org/en/config/options/#toc-exact-by-default-boolean). You can also read our [upgrade guide](https://medium.com/flow-type/how-to-upgrade-to-exact-by-default-object-type-syntax-7aa44b4d08ab) for steps to enable this option in your own project. In a project using exact-by-default syntax, the explicit inexact object type syntax is the only way to express an inexact object type. Objects as maps --------------- Newer versions of the JavaScript standard include a `Map` class, but it is still very common to use objects as maps as well. In this use case, an object will likely have properties added to it and retrieved throughout its lifecycle. Furthermore, the property keys may not even be known statically, so writing out a type annotation would not be possible. For objects like these, Flow provides a special kind of property, called an “indexer property.” An indexer property allows reads and writes using any key that matches the indexer key type. ``` // @flow var o: { [string]: number } = {}; o["foo"] = 0; o["bar"] = 1; var foo: number = o["foo"]; ``` An indexer can be optionally named, for documentation purposes: ``` // @flow var obj: { [user_id: number]: string } = {}; obj[1] = "Julia"; obj[2] = "Camille"; obj[3] = "Justin"; obj[4] = "Mark"; ``` When an object type has an indexer property, property accesses are assumed to have the annotated type, even if the object does not have a value in that slot at runtime. It is the programmer’s responsibility to ensure the access is safe, as with arrays. ``` var obj: { [number]: string } = {}; obj[42].length; // No type error, but will throw at runtime ``` Indexer properties can be mixed with named properties: ``` // @flow var obj: { size: number, [id: number]: string } = { size: 0 }; function add(id: number, name: string) { obj[id] = name; obj.size++; } ``` ### `Object` Type > NOTE: For new code, prefer `any` or `{ [key: string]: any}`. `Object` is an alias to [`any`](../any) and will be deprecated and removed in a future version of Flow. > > Sometimes it is useful to write types that accept arbitrary objects, for those you should write `{}` like this: ``` function method(obj: {}) { // ... } ``` However, if you need to opt-out of the type checker, and don’t want to go all the way to `any`, you could use `{ [key: string]: any}`. (Note that [`any`](../any) is unsafe and should be avoided). For historical reasons, the `Object` keyword is still available. In previous versions of Flow, `Object` was the same as `{ [key: string]: any}`. For example, the following code will not report any errors: ``` function method(obj: { [key: string]: any }) { obj.foo = 42; // Works. let bar: boolean = obj.bar; // Works. obj.baz.bat.bam.bop; // Works. } method({ baz: 3.14, bar: "hello" }); ``` Neither will this: ``` function method(obj: Object) { obj = 10; } method({ baz: 3.14, bar: "hello" }); ``` flow Function Types Function Types ============== Functions have two places where types are applied: Parameters (input) and the return value (output). ``` // @flow function concat(a: string, b: string): string { return a + b; } concat("foo", "bar"); // Works! // $ExpectError concat(true, false); // Error! ``` Using inference, these types are often optional: ``` // @flow function concat(a, b) { return a + b; } concat("foo", "bar"); // Works! // $ExpectError concat(true, false); // Error! ``` Sometimes Flow’s inference will create types that are more permissive than you want them to be. ``` // @flow function concat(a, b) { return a + b; } concat("foo", "bar"); // Works! concat(1, 2); // Works! ``` For that reason (and others), it’s useful to write types for important functions. Syntax of functions ------------------- There are three forms of functions that each have their own slightly different syntax. ### Function Declarations Here you can see the syntax for function declarations with and without types added. ``` function method(str, bool, ...nums) { // ... } function method(str: string, bool?: boolean, ...nums: Array<number>): void { // ... } ``` ### Arrow Functions Here you can see the syntax for arrow functions with and without types added. ``` let method = (str, bool, ...nums) => { // ... }; let method = (str: string, bool?: boolean, ...nums: Array<number>): void => { // ... }; ``` ### Function Types Here you can see the syntax for writing types that are functions. ``` (str: string, bool?: boolean, ...nums: Array<number>) => void ``` You may also optionally leave out the parameter names. ``` (string, boolean | void, Array<number>) => void ``` You might use these functions types for something like a callback. ``` function method(callback: (error: Error | null, value: string | null) => void) { // ... } ``` Function Parameters ------------------- Function parameters can have types by adding a colon `:` followed by the type after the name of the parameter. ``` function method(param1: string, param2: boolean) { // ... } ``` Optional Parameters ------------------- You can also have optional parameters by adding a question mark `?` after the name of the parameter and before the colon `:`. ``` function method(optionalValue?: string) { // ... } ``` Optional parameters will accept missing, `undefined`, or matching types. But they will not accept `null`. ``` // @flow function method(optionalValue?: string) { // ... } method(); // Works. method(undefined); // Works. method("string"); // Works. // $ExpectError method(null); // Error! ``` ### Rest Parameters JavaScript also supports having rest parameters or parameters that collect an array of arguments at the end of a list of parameters. These have an ellipsis `...` before them. You can also add type annotations for rest parameters using the same syntax but with an `Array`. ``` function method(...args: Array<number>) { // ... } ``` You can pass as many arguments as you want into a rest parameter. ``` // @flow function method(...args: Array<number>) { // ... } method(); // Works. method(1); // Works. method(1, 2); // Works. method(1, 2, 3); // Works. ``` > Note: If you add a type annotation to a rest parameter, it must always explicitly be an `Array` type. > > ### Function Returns Function returns can also add a type using a colon `:` followed by the type after the list of parameters. ``` function method(): number { // ... } ``` Return types ensure that every branch of your function returns the same type. This prevents you from accidentally not returning a value under certain conditions. ``` // @flow // $ExpectError function method(): boolean { if (Math.random() > 0.5) { return true; } } ``` Async functions implicitly return a promise, so the return type must always be a `Promise`. ``` // @flow async function method(): Promise<number> { return 123; } ``` ### Function `this` Every function in JavaScript can be called with a special context named `this`. You can call a function with any context that you want. Flow allows you to annotate the type for this context by adding a special parameter at the start of the function’s parameter list: ``` // @flow function method<T>(this: { x: T }) : T { return this.x; } var num: number = method.call({x : 42}); var str: string = method.call({x : 42}); // error ``` This parameter has no effect at runtime, and is erased along with types when Flow is transformed into JavaScript. When present, `this` parameters must always appear at the very beginning of the function’s parameter list, and must have an annotation. Additionally, [arrow functions](../types#toc-arrow-functions) may not have a `this` parameter annotation, as these functions bind their `this` parameter at the definition site, rather than the call site. If an explicit `this` parameter is not provided, Flow will attempt to infer one based on usage. If `this` is not mentioned in the body of the function, Flow will infer `mixed` for its `this` parameter. ### Predicate Functions Sometimes you will want to move the condition from an `if` statement into a function: ``` function concat(a: ?string, b: ?string): string { if (a && b) { return a + b; } return ''; } ``` However, Flow will flag an error in the code below: ``` function truthy(a, b): boolean { return a && b; } function concat(a: ?string, b: ?string): string { if (truthy(a, b)) { // $ExpectError return a + b; } return ''; } ``` You can fix this by making `truthy` a *predicate function*, by using the `%checks` annotation like so: ``` function truthy(a, b): boolean %checks { return !!a && !!b; } function concat(a: ?string, b: ?string): string { if (truthy(a, b)) { return a + b; } return ''; } ``` #### Limitations of predicate functions The body of these predicate functions need to be expressions (i.e. local variable declarations are not supported). But it’s possible to call other predicate functions inside a predicate function. For example: ``` function isString(y): %checks { return typeof y === "string"; } function isNumber(y): %checks { return typeof y === "number"; } function isNumberOrString(y): %checks { return isString(y) || isNumber(y); } function foo(x): string | number { if (isNumberOrString(x)) { return x + x; } else { return x.length; // no error, because Flow infers that x can only be an array } } foo('a'); foo(5); foo([]); ``` Another limitation is on the range of predicates that can be encoded. The refinements that are supported in a predicate function must refer directly to the value that is passed in as an argument to the respective call. For example, consider the *inlined* refinement ``` declare var obj: { n?: number }; if (obj.n) { const n: number = obj.n; } ``` Here, Flow will let you refine `obj.n` from `?number` to `number`. Note that the refinement here is on the property `n` of `obj`, rather than `obj` itself. If you tried to create a *predicate* function ``` function bar(a): %checks { return a.n; } ``` to encode the same condition, then the following refinement would fail ``` if (bar(obj)) { // $ExpectError const n: number = obj.n; } ``` This is because the only refinements supported through `bar` would be on `obj` itself. ### Callable Objects Callable objects can be typed, for example: ``` type CallableObj = { (number, number): number, bar: string }; function add(x, y) { return x + y; } // $ExpectError (add: CallableObj); add.bar = "hello world"; (add: CallableObj); ``` ### `Function` Type > NOTE: For new code prefer `any` or `(...args: Array<any>) => any`. `Function` has become an alias to `any` and will be deprecated and removed in a future version of Flow. > > Sometimes it is useful to write types that accept arbitrary functions, for those you should write `() => mixed` like this: ``` function method(func: () => mixed) { // ... } ``` However, if you need to opt-out of the type checker, and don’t want to go all the way to `any`, you can instead use `(...args: Array<any>) => any`. (Note that [`any`](../any) is unsafe and should be avoided). For historical reasons, the `Function` keyword is still available. For example, the following code will not report any errors: ``` function method(func: (...args: Array<any>) => any) { func(1, 2); // Works. func("1", "2"); // Works. func({}, []); // Works. } method(function(a: number, b: number) { // ... }); ``` Neither will this: ``` function method(obj: Function) { obj = 10; } method(function(a: number, b: number) { // ... }); ``` > ***You should follow [all the same rules](../any) as `any` when using `Function`.*** > >
programming_docs
flow Module Types Module Types ============ Importing and exporting types ----------------------------- It is often useful to share types in between modules (files). In Flow, you can export type aliases, interfaces, and classes from one file and import them in another. **`exports.js`** ``` // @flow export default class Foo {}; export type MyObject = { /* ... */ }; export interface MyInterface { /* ... */ }; ``` **`imports.js`** ``` // @flow import type Foo, {MyObject, MyInterface} from './exports'; ``` > ***Don’t forget to mention `@flow` on top of file, otherwise flow won’t report errors***. > > Importing and exporting values ------------------------------ Flow also supports importing the type of values exported by other modules using [`typeof`](../typeof). **`exports.js`** ``` // @flow const myNumber = 42; export default myNumber; export class MyClass { // ... } ``` **`imports.js`** ``` // @flow import typeof myNumber from './exports'; import typeof {MyClass} from './exports'; ``` Just like other type imports, this code will be stripped away by a compiler and will not add a dependency on the other module. flow Variable Types Variable Types ============== When you are declaring a new variable, you may optionally declare its type. JavaScript has three ways of declaring local variables: * `var` - declares a variable, optionally assigning a value. ([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)) * `let` - declares a block-scoped variable, optionally assigning a value. ([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let)) * `const` - declares a block-scoped variable, assigning a value that cannot be re-assigned. ([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)) In Flow these fall into two groups: * `let` and `var` - variables that **can** be reassigned. * `const` - variables that **cannot** be reassigned. ``` var varVariable = 1; let letVariable = 1; const constVariable = 1; varVariable = 2; // Works! letVariable = 2; // Works! // $ExpectError constVariable = 2; // Error! ``` `const` -------- Since a `const` variable cannot be re-assigned at a later time it is fairly simple. Flow can either infer the type from the value you are assigning to it or you can provide it with a type. ``` // @flow const foo /* : number */ = 1; const bar: number = 2; ``` `var` and `let` ---------------- Since `var` and `let` can be re-assigned, there’s a few more rules you’ll need to know about. Similar to `const`, Flow can either infer the type from the value you are assigning to it or you can provide it with a type: ``` // @flow var fooVar /* : number */ = 1; let fooLet /* : number */ = 1; var barVar: number = 2; let barLet: number = 2; ``` When you provide a type, you will be able to re-assign the value, but it must always be of a compatible type. ``` // @flow let foo: number = 1; foo = 2; // Works! // $ExpectError foo = "3"; // Error! ``` When you do not provide a type, the inferred type will do one of two things if you re-assign it. Reassigning variables --------------------- By default when you re-assign a variable, Flow will give it the type of all possible assignments. ``` let foo = 42; if (Math.random()) foo = true; if (Math.random()) foo = "hello"; let isOneOf: number | boolean | string = foo; // Works! ``` Sometimes Flow is able to figure out (with certainty) the type of a variable after re-assignment. In that case, Flow will give it the known type. ``` // @flow let foo = 42; let isNumber: number = foo; // Works! foo = true; let isBoolean: boolean = foo; // Works! foo = "hello"; let isString: string = foo; // Works! ``` If statements, functions, and other conditionally run code can all prevent Flow from being able to figure out precisely what a type will be. ``` // @flow let foo = 42; function mutate() { foo = true; foo = "hello"; } mutate(); // $ExpectError let isString: string = foo; // Error! ``` As Flow gets smarter and smarter, there should be fewer instances of these scenarios. flow Literal Types Literal Types ============= Flow has [primitive types](../primitives) for literal values, but can also use literal values as types. For example, instead of accepting `number` type, we could accept only the literal value `2`. ``` // @flow function acceptsTwo(value: 2) { // ... } acceptsTwo(2); // Works! // $ExpectError acceptsTwo(3); // Error! // $ExpectError acceptsTwo("2"); // Error! ``` You can use primitive values for these types: * Booleans: like `true` or `false` * Numbers: like `42` or `3.14` * Strings: like `"foo"` or `"bar"` Using these with [union types](../unions) is powerful: ``` // @flow function getColor(name: "success" | "warning" | "danger") { switch (name) { case "success" : return "green"; case "warning" : return "yellow"; case "danger" : return "red"; } } getColor("success"); // Works! getColor("danger"); // Works! // $ExpectError getColor("error"); // Error! ``` flow Tuple Types Tuple Types =========== Tuples are a sort of list but with a limited set of items. In JavaScript, tuples are created using arrays. In Flow you can create tuples using the `[type, type, type]` syntax. ``` let tuple1: [number] = [1]; let tuple2: [number, boolean] = [1, true]; let tuple3: [number, boolean, string] = [1, true, "three"]; ``` When you are getting a value from a tuple at a specific index, it will return the type at that index. ``` // @flow let tuple: [number, boolean, string] = [1, true, "three"]; let num : number = tuple[0]; // Works! let bool : boolean = tuple[1]; // Works! let str : string = tuple[2]; // Works! ``` Trying to access an index that does not exist results in an index-out-of-bounds error. ``` // @flow let tuple: [number, boolean, string] = [1, true, "three"]; let none = tuple[3]; // Error! ``` If Flow doesn’t know which index you are trying to access it will return all possible types. ``` // @flow let tuple: [number, boolean, string] = [1, true, "three"]; function getItem(n: number) { let val: number | boolean | string = tuple[n]; // ... } ``` When setting a new value inside a tuple, the new value must match the type at that index. ``` // @flow let tuple: [number, boolean, string] = [1, true, "three"]; tuple[0] = 2; // Works! tuple[1] = false; // Works! tuple[2] = "foo"; // Works! // $ExpectError tuple[0] = "bar"; // Error! // $ExpectError tuple[1] = 42; // Error! // $ExpectError tuple[2] = false; // Error! ``` Strictly enforced tuple length (arity) -------------------------------------- The length of the tuple is known as the “arity”. The length of a tuple is strictly enforced in Flow. #### Tuples only match tuples with same length This means that a shorter tuple can’t be used in place of a longer one. ``` // @flow let tuple1: [number, boolean] = [1, true]; // $ExpectError let tuple2: [number, boolean, void] = tuple1; // Error! ``` Also, a longer tuple can’t be used in place of a shorter one. ``` // @flow let tuple1: [number, boolean, void] = [1, true]; // $ExpectError let tuple2: [number, boolean] = tuple1; // Error! ``` #### Tuples don’t match array types Since Flow does not know the length of an array, an `Array<T>` type cannot be passed into a tuple. ``` // @flow let array: Array<number> = [1, 2]; // $ExpectError let tuple: [number, number] = array; // Error! ``` Also a tuple type cannot be passed into to an `Array<T>` type, since then you could mutate the tuple in an unsafe way. ``` // @flow let tuple: [number, number] = [1, 2]; // $ExpectError let array: Array<number> = tuple; // Error! ``` #### Cannot use mutating array methods on tuples You cannot use `Array.prototype` methods that mutate the tuple, only ones that do not. ``` // @flow let tuple: [number, number] = [1, 2]; tuple.join(', '); // Works! // $ExpectError tuple.push(3); // Error! ``` flow Utility Types Utility Types ============= Flow provides a set of utility types to operate on other types, and can be useful for different scenarios. Table of contents: * [`$Keys<T>`](#toc-keys) * [`$Values<T>`](#toc-values) * [`$ReadOnly<T>`](#toc-readonly) * [`$Exact<T>`](#toc-exact) * [`$Diff<A, B>`](#toc-diff) * [`$Rest<A, B>`](#toc-rest) * [`$PropertyType<T, k>`](#toc-propertytype) * [`$ElementType<T, K>`](#toc-elementtype) * [`$NonMaybeType<T>`](#toc-nonmaybe) * [`$ObjMap<T, F>`](#toc-objmap) * [`$ObjMapi<T, F>`](#toc-objmapi) * [`$ObjMapConst<O, T>`](#toc-objmapconst) * [`$KeyMirror<O>`](#toc-keymirror) * [`$TupleMap<T, F>`](#toc-tuplemap) * [`$Call<F, T...>`](#toc-call) * [`Class<T>`](#toc-class) * [`$Shape<T>`](#toc-shape) * [`$Exports<T>`](#toc-exports) * [`$Supertype<T>`](#toc-supertype) * [`$Subtype<T>`](#toc-subtype) * [`Existential Type (*)`](#toc-existential-type) `$Keys<T>` ----------- In Flow you can [use union types similar to enums](../literals): ``` // @flow type Suit = "Diamonds" | "Clubs" | "Hearts" | "Spades"; const clubs: Suit = 'Clubs'; const wrong: Suit = 'wrong'; // 'wrong' is not a Suit ``` This is very handy, but sometimes you need to access the enum definition at runtime (i.e. at a value level). Suppose for example that you want to associate a value to each suit of the previous example. You could do ``` // @flow type Suit = "Diamonds" | "Clubs" | "Hearts" | "Spades"; const suitNumbers = { Diamonds: 1, Clubs: 2, Hearts: 3, Spades: 4 }; function printSuitNumber(suit: Suit) { console.log(suitNumbers[suit]); } printSuitNumber('Diamonds'); // 1 printSuitNumber('foo'); // 'foo' is not a Suit ``` but this doesn’t feel very DRY, as we had to explicitly define the suit names twice. In situations like this one, you can leverage the `$Keys<T>` operator. Let’s see another example, this time using `$Keys`: ``` // @flow const countries = { US: "United States", IT: "Italy", FR: "France" }; type Country = $Keys<typeof countries>; const italy: Country = 'IT'; const nope: Country = 'nope'; // 'nope' is not a Country ``` In the example above, the type of `Country` is equivalent to `type Country = 'US' | 'IT' | 'FR'`, but Flow was able to extract it from the keys of `countries`. `$Values<T>` ------------- `$Values<T>` represents the union type of all the value types (not the values, but their *types*!) of the enumerable properties in an [Object Type](../objects) `T`. For example: ``` // @flow type Props = { name: string, age: number, }; // The following two types are equivalent: type PropValues = string | number; type Prop$Values = $Values<Props>; const name: Prop$Values = 'Jon'; // OK const age: Prop$Values = 42; // OK const fn: Prop$Values = () => {}; // Error! function is not part of the union type ``` `$ReadOnly<T>` --------------- `$ReadOnly<T>` is a type that represents the read-only version of a given [object type](../objects) `T`. A read-only object type is an object type whose keys are all [read-only](../interfaces#toc-interface-property-variance-read-only-and-write-only). This means that the following 2 types are equivalent: ``` type ReadOnlyObj = { +key: any, // read-only field, marked by the `+` annotation }; ``` ``` type ReadOnlyObj = $ReadOnly<{ key: any, }>; ``` This is useful when you need to use a read-only version of an object type you’ve already defined, without manually having to re-define and annotate each key as read-only. For example: ``` // @flow type Props = { name: string, age: number, // ... }; type ReadOnlyProps = $ReadOnly<Props>; function render(props: ReadOnlyProps) { const {name, age} = props; // OK to read props.age = 42; // Error when writing // ... } ``` Additionally, other utility types, such as [`$ObjMap<T>`](#toc-objmap), may strip any read/write annotations, so `$ReadOnly<T>` is a handy way to quickly make the object read-only again after operating on it: ``` type Obj = { +key: any, }; type MappedObj = $ReadOnly<$ObjMap<Obj, TypeFn>> // Still read-only ``` > Note: `$ReadOnly` is only for making read-only *object* types. See the Array docs for how to [type read-only arrays with `$ReadOnlyArray`](../arrays#toc-readonlyarray). > > `$Exact<T>` ------------ `$Exact<{name: string}>` is a synonym for `{| name: string |}` as in the [Object documentation](../objects#toc-exact-object-types). ``` // @flow type ExactUser = $Exact<{name: string}>; type ExactUserShorthand = {| name: string |}; const user2 = {name: 'John Wilkes Booth'}; // These will both be satisfied because they are equivalent (user2: ExactUser); (user2: ExactUserShorthand); ``` `$Diff<A, B>` -------------- As the name hints, `$Diff<A, B>` is the type representing the set difference of `A` and `B`, i.e. `A \ B`, where `A` and `B` are both [object types](../objects). Here’s an example: ``` // @flow type Props = { name: string, age: number }; type DefaultProps = { age: number }; type RequiredProps = $Diff<Props, DefaultProps>; function setProps(props: RequiredProps) { // ... } setProps({ name: 'foo' }); setProps({ name: 'foo', age: 42, baz: false }); // you can pass extra props too setProps({ age: 42 }); // error, name is required ``` As you may have noticed, the example is not a random one. `$Diff` is exactly what the React definition file uses to define the type of the props accepted by a React Component. Note that `$Diff<A, B>` will error if the object you are removing properties from does not have the property being removed, i.e. if `B` has a key that doesn’t exist in `A`: ``` // @flow type Props = { name: string, age: number }; type DefaultProps = { age: number, other: string }; // Will error due to this `other` property not being in Props. type RequiredProps = $Diff<Props, DefaultProps>; function setProps(props: RequiredProps) { props.name; // ... } ``` As a workaround, you can specify the property not present in `A` as optional. For example: ``` type A = $Diff<{}, {nope: number}>; // Error type B = $Diff<{}, {nope: number | void}>; // OK ``` `$Rest<A, B>` -------------- `$Rest<A, B>` is the type that represents the runtime object rest operation, e.g.: `const {foo, ...rest} = obj`, where `A` and `B` are both [object types](../objects). The resulting type from this operation will be an object type containing `A`’s *own* properties that are not *own* properties in `B`. In flow, we treat all properties on [exact object types](../objects#toc-exact-object-types) as [own](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty). In in-exact objects, a property may or may not be own. For example: ``` // @flow type Props = { name: string, age: number }; const props: Props = {name: 'Jon', age: 42}; const {age, ...otherProps} = props; (otherProps: $Rest<Props, {|age: number|}>); otherProps.age; // Error ``` The main difference with [`$Diff<A, B>`](#toc-diff), is that `$Rest<A, B>` aims to represent the true runtime rest operation, which implies that exact object types are treated differently in `$Rest<A, B>`. For example, `$Rest<{|n: number|}, {}>` will result in `{|n?: number|}` because an in-exact empty object may have an `n` property, while `$Diff<{|n: number|}, {}>` will result in `{|n: number|}`. `$PropertyType<T, k>` ---------------------- **WARNING:** `$PropertyType` is deprecated as of Flow version 0.155, and will be removed in a future version of Flow. Use [Indexed Access Types](../indexed-access) instead. `$PropertyType<T, 'k'>` is now `T['k']`. A `$PropertyType<T, k>` is the type at a given key `k`. As of Flow v0.36.0, `k` must be a literal string. ``` // @flow type Person = { name: string, age: number, parent: Person }; const newName: $PropertyType<Person, 'name'> = 'Toni Braxton'; const newAge: $PropertyType<Person, 'age'> = 51; const newParent: $PropertyType<Person, 'parent'> = 'Evelyn Braxton'; ``` This can be especially useful for referring to the type of React props, or, even the entire `props` type itself. ``` // @flow import React from 'react'; type Props = { text: string, onMouseOver: ({x: number, y: number}) => void } class Tooltip extends React.Component<Props> { props: Props; } const someProps: $PropertyType<Tooltip, 'props'> = { text: 'foo', onMouseOver: (data: {x: number, y: number}) => undefined }; const otherProps: $PropertyType<Tooltip, 'props'> = { text: 'foo' // Missing the `onMouseOver` definition }; ``` You can even nest lookups: ``` // @flow type PositionHandler = $PropertyType<$PropertyType<Tooltip, 'props'>, 'onMouseOver'>; const handler: PositionHandler = (data: {x: number, y: number}) => undefined; const handler2: PositionHandler = (data: string) => undefined; // wrong parameter types ``` You can use this in combination with `Class<T>` to get static props: ``` // @flow class BackboneModel { static idAttribute: string | false; } type ID = $PropertyType<Class<BackboneModel>, 'idAttribute'>; const someID: ID = '1234'; const someBadID: ID = true; ``` `$ElementType<T, K>` --------------------- **WARNING:** `$ElementType` is deprecated as of Flow version 0.155, and will be removed in a future version of Flow. Use [Indexed Access Types](../indexed-access) instead. `$ElementType<T, K>` is now `T[K]`. `$ElementType<T, K>` is the type that represents the type of every element inside an [array](../arrays), [tuple](../tuples) or [object](../objects) type `T`, that matches the given *key* type `K`. For example: ``` // @flow // Using objects: type Obj = { name: string, age: number, } ('Jon': $ElementType<Obj, 'name'>); (42: $ElementType<Obj, 'age'>); (true: $ElementType<Obj, 'name'>); // Nope, `name` is not a boolean (true: $ElementType<Obj, 'other'>); // Nope, property `other` is not in Obj // Using tuples: type Tuple = [boolean, string]; (true: $ElementType<Tuple, 0>); ('foo': $ElementType<Tuple, 1>); ('bar': $ElementType<Tuple, 2>); // Nope, can't access position 2 ``` In the above case, we’re using literal values as `K`, similarly to [`$PropertyType<T, k>`](#toc-propertytype). However, when using `$ElementType<T, K>`, `K` is allowed to be any type, as long as that type exists on the keys of `T`. For example: ``` // @flow // Using objects type Obj = { [key: string]: number }; (42: $ElementType<Obj, string>); (42: $ElementType<Obj, boolean>); // Nope, object keys aren't booleans (true: $ElementType<Obj, string>); // Nope, elements are numbers // Using arrays, we don't statically know the size of the array, so you can just use the `number` type as the key: type Arr = Array<boolean>; (true: $ElementType<Arr, number>); (true: $ElementType<Arr, boolean>); // Nope, array indices aren't booleans ('foo': $ElementType<Arr, number>); // Nope, elements are booleans ``` You can also nest calls to `$ElementType<T, K>`, which is useful when you need to access the types inside nested structures: ``` // @flow type NumberObj = { nums: Array<number>, }; (42: $ElementType<$ElementType<NumberObj, 'nums'>, number>); ``` Additionally, one of the things that also makes `$ElementType<T, K>` more powerful than [`$PropertyType<T, k>`](#toc-propertytype) is that you can use it with generics. For example: ``` // @flow function getProp<O: {+[string]: mixed}, P: $Keys<O>>(o: O, p: P): $ElementType<O, P> { return o[p]; } (getProp({a: 42}, 'a'): number); // OK (getProp({a: 42}, 'a'): string); // Error: number is not a string getProp({a: 42}, 'b'); // Error: `b` does not exist ``` `$NonMaybeType<T>` ------------------- `$NonMaybeType<T>` converts a type `T` to a non-maybe type. In other words, the values of `$NonMaybeType<T>` are the values of `T` except for `null` and `undefined`. ``` // @flow type MaybeName = ?string; type Name = $NonMaybeType<MaybeName>; ('Gabriel': MaybeName); // Ok (null: MaybeName); // Ok ('Gabriel': Name); // Ok (null: Name); // Error! null can't be annotated as Name because Name is not a maybe type ``` `$ObjMap<T, F>` ---------------- `ObjMap<T, F>` takes an [object type](../objects) `T`, and a [function type](../functions) `F`, and returns the object type obtained by mapping the type of each value in the object with the provided function type `F`. In other words, `$ObjMap` will [call](#toc-call) (at the type level) the given function type `F` for every property value type in `T`, and return the resulting object type from those calls. Let’s see an example. Suppose you have a function called `run` that takes an object of thunks (functions in the form `() => A`) as input: ``` // @flow function run<O: {[key: string]: Function}>(o: O) { return Object.keys(o).reduce((acc, k) => Object.assign(acc, { [k]: o[k]() }), {}); } ``` The function’s purpose is to run all the thunks and return an object made of values. What’s the return type of this function? The keys are the same, but the values have a different type, namely the return type of each function. At a value level (the implementation of the function) we’re essentially mapping over the object to produce new values for the keys. How to express this at a type level? This is where `ObjMap<T, F>` comes in handy. ``` // @flow // let's write a function type that takes a `() => V` and returns a `V` (its return type) type ExtractReturnType = <V>(() => V) => V; declare function run<O: {[key: string]: Function}>(o: O): $ObjMap<O, ExtractReturnType>; const o = { a: () => true, b: () => 'foo' }; (run(o).a: boolean); // Ok (run(o).b: string); // Ok // $ExpectError (run(o).b: boolean); // Nope, b is a string // $ExpectError run(o).c; // Nope, c was not in the original object ``` This is extremely useful for expressing the return type of functions that manipulate objects values. You could use a similar approach (for instance) to provide the return type of bluebird’s [`Promise.props`](http://bluebirdjs.com/docs/api/promise.props.html) function, which is like `Promise.all` but takes an object as input. Here’s a possible declaration of this function, which is very similar to our first example: ``` // @flow declare function props<A, O: { [key: string]: A }>(promises: O): Promise<$ObjMap<O, typeof $await>>; ``` And use: ``` // @flow const promises = { a: Promise.resolve(42) }; props(promises).then(o => { (o.a: 42); // Ok // $ExpectError (o.a: 43); // Error, flow knows it's 42 }); ``` `$ObjMapi<T, F>` ----------------- `ObjMapi<T, F>` is similar to [`ObjMap<T, F>`](#toc-objmap). The difference is that function type `F` will be [called](#toc-call) with both the key and value types of the elements of the object type `T`, instead of just the value types. For example: ``` // @flow const o = { a: () => true, b: () => 'foo' }; type ExtractReturnObjectType = <K, V>(K, () => V) => { k: K, v: V }; declare function run<O: {...}>(o: O): $ObjMapi<O, ExtractReturnObjectType>; (run(o).a: { k: 'a', v: boolean }); // Ok (run(o).b: { k: 'b', v: string }); // Ok // $ExpectError (run(o).a: { k: 'b', v: boolean }); // Nope, a.k is "a" // $ExpectError (run(o).b: { k: 'b', v: number }); // Nope, b.v is a string // $ExpectError run(o).c; // Nope, c was not in the original object ``` `$ObjMapConst<O, T>` --------------------- `$ObjMapConst<Obj, T>` is a special case of `$ObjMap<Obj, F>`, when `F` is a constant function type, e.g. `() => T`. Instead of writing `$ObjMap<Obj, () => T>`, you can write `$ObjMapConst<Obj, T>`. For example: ``` // @flow const obj = { a: true, b: 'foo' }; declare function run<O: {...}>(o: O): $ObjMapConst<O, number>; // newObj is of type {a: number, b: number} const newObj = run(obj); (newObj.a: number); // Ok // $ExpectedError (newObj.b: string); // Error property b is a number ``` Tip: Prefer using `$ObjMapConst` instead of `$ObjMap` (if possible) to fix certain kinds of `[invalid-exported-annotation]` errors. `$KeyMirror<O>` ---------------- `$KeyMirror<Obj>` is a special case of `$ObjMapi<Obj, F>`, when `F` is the identity function type, ie. `<K>(K) => K`. In other words, it maps each property of an object to the type of the property key. Instead of writing `$ObjMapi<Obj, <K>(K) => K>`, you can write `$KeyMirror<Obj>`. For example: ``` // @flow const obj = { a: true, b: 'foo' }; declare function run<O: {...}>(o: O): $KeyMirror<O>; // newObj is of type {a: 'a', b: 'b'} const newObj = run(obj); (newObj.a: 'a'); // Ok // $ExpectedError (newObj.b: 'a'); // Error string 'b' is incompatible with 'a' ``` Tip: Prefer using `$KeyMirror` instead of `$ObjMapi` (if possible) to fix certain kinds of `[invalid-exported-annotation]` errors. `$TupleMap<T, F>` ------------------ `$TupleMap<T, F>` takes an iterable type `T` (e.g.: [`Tuple`](../tuples) or [`Array`](../arrays)), and a [function type](../functions) `F`, and returns the iterable type obtained by mapping the type of each value in the iterable with the provided function type `F`. This is analogous to the Javascript function `map`. Following our example from [`$ObjMap<T>`](#toc-objmap), let’s assume that `run` takes an array of functions, instead of an object, and maps over them returning an array of the function call results. We could annotate its return type like this: ``` // @flow // Function type that takes a `() => V` and returns a `V` (its return type) type ExtractReturnType = <V>(() => V) => V function run<A, I: Array<() => A>>(iter: I): $TupleMap<I, ExtractReturnType> { return iter.map(fn => fn()); } const arr = [() => 'foo', () => 'bar']; (run(arr)[0]: string); // OK (run(arr)[1]: string); // OK (run(arr)[1]: boolean); // Error ``` `$Call<F, T...>` ----------------- `$Call<F, T...>` is a type that represents the result of calling the given [function type](../functions) `F` with 0 or more arguments `T...`. This is analogous to calling a function at runtime (or more specifically, it’s analogous to calling [`Function.prototype.call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call)), but at the type level; this means that function type calls happens statically, i.e. not at runtime. Let’s see a couple of examples: ``` // @flow // Takes an object type, returns the type of its `prop` key type ExtractPropType = <T>({prop: T}) => T; type Obj = {prop: number}; type PropType = $Call<ExtractPropType, Obj>; // Call `ExtractPropType` with `Obj` as an argument type Nope = $Call<ExtractPropType, {nope: number}>; // Error: argument doesn't match `Obj`. (5: PropType); // OK (true: PropType); // Error: PropType is a number (5: Nope); // Error ``` ``` // @flow // Takes a function type, and returns its return type // This is useful if you want to get the return type of some function without actually calling it at runtime. type ExtractReturnType = <R>(() => R) => R; type Fn = () => number; type ReturnType = $Call<ExtractReturnType, Fn> // Call `ExtractReturnType` with `Fn` as an argument (5: ReturnType); // OK (true: ReturnType); // Error: ReturnType is a number ``` `$Call` can be very powerful because it allows you to make calls in type-land that you would otherwise have to do at runtime. The type-land calls happen statically and will be erased at runtime. Let’s look at a couple of more advanced examples: ``` // @flow // Extracting deeply nested types: type NestedObj = {| +status: ?number, +data: ?$ReadOnlyArray<{| +foo: ?{| +bar: number, |}, |}>, |}; // If you wanted to extract the type for `bar`, you could use $Call: type BarType = $Call< <T>({ +data: ?$ReadOnlyArray<{ +foo: ?{ +bar: ?T }, }>, }) => T, NestedObj, >; (5: BarType); (true: BarType); // Error: `bar` is not a boolean ``` ``` // @flow // Getting return types: function getFirstValue<V>(map: Map<string, V>): ?V { for (const [key, value] of map.entries()) { return value; } return null; } // Using $Call, we can get the actual return type of the function above, without calling it at runtime: type Value = $Call<typeof getFirstValue, Map<string, number>>; (5: Value); (true: Value); // Error: Value is a `number` // We could generalize it further: type GetMapValue<M> = $Call<typeof getFirstValue, M>; (5: GetMapValue<Map<string, number>>); (true: GetMapValue<Map<string, boolean>>); (true: GetMapValue<Map<string, number>>); // Error: value is a `number` ``` `Class<T>` ----------- Given a type `T` representing instances of a class `C`, the type `Class<T>` is the type of the class `C`. For example: ``` // @flow class Store {} class ExtendedStore extends Store {} class Model {} function makeStore(storeClass: Class<Store>) { return new storeClass(); } (makeStore(Store): Store); (makeStore(ExtendedStore): Store); (makeStore(Model): Model); // error (makeStore(ExtendedStore): Model); // Flow infers the return type ``` For classes that take type parameters, you must also provide the parameter. For example: ``` // @flow class ParamStore<T> { constructor(data: T) {} } function makeParamStore<T>(storeClass: Class<ParamStore<T>>, data: T): ParamStore<T> { return new storeClass(data); } (makeParamStore(ParamStore, 1): ParamStore<number>); (makeParamStore(ParamStore, 1): ParamStore<boolean>); // failed because of the second parameter ``` `$Shape<T>` ------------ A variable of type `$Shape<T>`, where `T` is some object type, can be assigned objects `o` that contain a subset of the properties included in `T`. For each property `p: S` of `T`, the type of a potential binding of `p` in `o` must be compatible with `S`. For example ``` // @flow type Person = { age: number, name: string, } type PersonDetails = $Shape<Person>; const person1: Person = {age: 28}; // Error: missing `name` const person2: Person = {name: 'a'}; // Error: missing `age` const person3: PersonDetails = {age: 28}; // OK const person4: PersonDetails = {name: 'a'}; // OK const person5: PersonDetails = {age: 28, name: 'a'}; // OK const person6: PersonDetails = {age: '28'}; // Error: string is incompatible with number ``` > Note: `$Shape<T>` is **not** equivalent to `T` with all its fields marked as optional. In particular, Flow unsoundly allows `$Shape<T>` to be used as a `T` in several contexts. For example in > > > ``` > const personShape: PersonDetails = {age: 28}; > (personShape: Person); > ``` > Flow will unsoundly allow this last cast to succeed. If this behavior is not wanted, then this utility type should be avoided. > > `$Exports<T>` -------------- The following are functionally equivalent ``` import typeof * as T from 'my-module'; ``` ``` type T = $Exports<'my-module'>; ``` The advantage of the `$Exports` syntax is that you can `export` the type on the same line ``` export type T = $Exports<'my-module'>; ``` where as you would otherwise need to export an alias in the `import typeof` case ``` import typeof * as T from 'my-module'; export type MyModuleType = T; ``` `$Supertype<T>` ---------------- This utility has been deprecated and should be avoided. See [here](https://flow.org/en/linting/rule-reference/#toc-deprecated-utility) for details. `$Subtype<T>` -------------- This utility has been deprecated and should be avoided. See [here](https://flow.org/en/linting/rule-reference/#toc-deprecated-utility) for details. Existential Type (`*`) ---------------------- This utility has been deprecated and should be avoided. See [here](https://flow.org/en/linting/rule-reference/#toc-deprecated-type) for details.
programming_docs
flow Interface Types Interface Types =============== Classes in Flow are nominally typed. This means that when you have two separate classes you cannot use one in place of the other even when they have the same exact properties and methods. ``` // @flow class Foo { serialize() { return '[Foo]'; } } class Bar { serialize() { return '[Bar]'; } } // $ExpectError const foo: Foo = new Bar(); // Error! ``` Instead, you can use `interface` in order to declare the structure of the class that you are expecting. ``` // @flow interface Serializable { serialize(): string; } class Foo { serialize() { return '[Foo]'; } } class Bar { serialize() { return '[Bar]'; } } const foo: Serializable = new Foo(); // Works! const bar: Serializable = new Bar(); // Works! ``` You can also declare an anonymous interface: ``` // @flow class Foo { a : number } (new Foo() : interface { a : number }); ``` You can also use `implements` to tell Flow that you want the class to match an interface. This prevents you from making incompatible changes when editing the class. ``` // @flow interface Serializable { serialize(): string; } class Foo implements Serializable { serialize() { return '[Foo]'; } // Works! } class Bar implements Serializable { // $ExpectError serialize() { return 42; } // Error! } ``` You can also use `implements` with multiple interfaces. ``` class Foo implements Bar, Baz { // ... } ``` Interface Syntax ---------------- Interfaces are created using the keyword `interface` followed by its name and a block which contains the body of the type definition. ``` interface MyInterface { // ... } ``` The syntax of the block matches the syntax of object types and has all of the same features. #### Interface Methods You can add methods to interfaces following the same syntax as class methods. Any `this` parameters you provide are also subject to the same restrictions as class methods. ``` interface MyInterface { method(value: string): number; } ``` Also like [class methods](../classes#toc-class-methods), interface methods must also remain bound to the interface on which they were defined. #### Interface Properties You can add properties to interfaces following the same syntax as class properties. ``` interface MyInterface { property: string; } ``` Interface properties can be optional as well. ``` interface MyInterface { property?: string; } ``` #### Interfaces as maps You can create [“indexer properties”](../objects#toc-objects-as-maps) the same way as with objects. ``` interface MyInterface { [key: string]: number; } ``` ### Interface Generics Interfaces can also have their own [generics](../generics). ``` interface MyInterface<A, B, C> { property: A; method(val: B): C; } ``` Interface generics are [parameterized](../generics#toc-parameterized-generics). When you use an interface you need to pass parameters for each of its generics. ``` // @flow interface MyInterface<A, B, C> { foo: A; bar: B; baz: C; } var val: MyInterface<number, boolean, string> = { foo: 1, bar: true, baz: 'three', }; ``` Interface property variance (read-only and write-only) ------------------------------------------------------ Interface properties are [invariant](https://flow.org/en/lang/variance/) by default. But you can add modifiers to make them covariant (read-only) or contravariant (write-only). ``` interface MyInterface { +covariant: number; // read-only -contravariant: number; // write-only } ``` ### Covariant (read-only) properties on interfaces You can make a property covariant by adding a plus symbol `+` in front of the property name. ``` interface MyInterface { +readOnly: number | string; } ``` This allows you to pass a more specific type in place of that property. ``` // @flow interface Invariant { property: number | string } interface Covariant { +readOnly: number | string } var x : { property : number } = { property : 42 }; var y : { readOnly : number } = { readOnly : 42 }; var value1: Invariant = x; // Error! var value2: Covariant = y; // Works ``` Because of how covariance works, covariant properties also become read-only when used. Which can be useful over normal properties. ``` // @flow interface Invariant { property: number | string } interface Covariant { +readOnly: number | string } function method1(value: Invariant) { value.property; // Works! value.property = 3.14; // Works! } function method2(value: Covariant) { value.readOnly; // Works! // $ExpectError value.readOnly = 3.14; // Error! } ``` ### Contravariant (write-only) properties on interfaces You can make a property contravariant by adding a minus symbol - in front of the property name. ``` interface InterfaceName { -writeOnly: number; } ``` This allows you to pass a less specific type in place of that property. ``` // @flow interface Invariant { property: number } interface Contravariant { -writeOnly: number } var numberOrString = Math.random() > 0.5 ? 42 : 'forty-two'; // $ExpectError var value1: Invariant = { property: numberOrString }; // Error! var value2: Contravariant = { writeOnly: numberOrString }; // Works! ``` Because of how contravariance works, contravariant properties also become write-only when used. Which can be useful over normal properties. ``` interface Invariant { property: number } interface Contravariant { -writeOnly: number } function method1(value: Invariant) { value.property; // Works! value.property = 3.14; // Works! } function method2(value: Contravariant) { // $ExpectError value.writeOnly; // Error! value.writeOnly = 3.14; // Works! } ``` flow Maybe Types Maybe Types =========== It’s common for JavaScript code to introduce “optional” values so that you have the option of leaving out the value or passing `null` instead. Using Flow you can use Maybe types for these values. Maybe types work with any other type by simply prefixing it with a question mark `?` such as `?number` as a sort of modifier. Maybe types accept the provided type as well as `null` or `undefined`. So `?number` would mean `number`, `null`, or `undefined`. ``` // @flow function acceptsMaybeNumber(value: ?number) { // ... } acceptsMaybeNumber(42); // Works! acceptsMaybeNumber(); // Works! acceptsMaybeNumber(undefined); // Works! acceptsMaybeNumber(null); // Works! acceptsMaybeNumber("42"); // Error! ``` In the case of objects, a **missing** property is not the same thing as an explicitly `undefined` property. ``` // @flow function acceptsMaybeProp({ value }: { value: ?number }) { // ... } acceptsMaybeProp({ value: undefined }); // Works! acceptsMaybeProp({}); // Error! ``` If you want to allow missing properties, use [optional property](../objects#toc-optional-object-type-properties) syntax, where the `?` is placed *before* the colon. It is also possible to combine both syntaxes for an optional maybe type, for example `{ value?: ?number }`. Refining Maybe types -------------------- Imagine we have the type `?number`, if we want to use that value as a `number` we’ll need to first check that it is not `null` or `undefined`. ``` // @flow function acceptsMaybeNumber(value: ?number) { if (value !== null && value !== undefined) { return value * 2; } } ``` You can simplify the two checks against `null` and `undefined` using a single `!= null` check which will do both. ``` // @flow function acceptsMaybeNumber(value: ?number) { if (value != null) { return value * 2; } } ``` You could also flip it around, and check to make sure that the value has a type of `number` before using it. ``` // @flow function acceptsMaybeNumber(value: ?number) { if (typeof value === 'number') { return value * 2; } } ``` However, type refinements can be lost. For instance, calling a function after refining the type of an object’s property will invalidate this refinement. Consult the [Refinement Invalidations](https://flow.org/en/lang/refinements/#toc-refinement-invalidations) docs for more details, to understand why Flow works this way, and how you can avoid this common pitfall. flow Opaque Type Aliases Opaque Type Aliases =================== Opaque type aliases are type aliases that do not allow access to their underlying type outside of the file in which they are defined. ``` opaque type ID = string; ``` Opaque type aliases, like regular type aliases, may be used anywhere a type can be used. ``` // @flow opaque type ID = string; function identity(x: ID): ID { return x; } export type {ID}; ``` Opaque Type Alias Syntax ------------------------ Opaque type aliases are created using the words `opaque type` followed by its name, an equals sign `=`, and a type definition. ``` opaque type Alias = Type; ``` You can optionally add a subtyping constraint to an opaque type alias by adding a colon `:` and a type after the name. ``` opaque type Alias: SuperType = Type; ``` Any type can appear as the super type or type of an opaque type alias. ``` opaque type StringAlias = string; opaque type ObjectAlias = { property: string, method(): number, }; opaque type UnionAlias = 1 | 2 | 3; opaque type AliasAlias: ObjectAlias = ObjectAlias; opaque type VeryOpaque: AliasAlias = ObjectAlias; ``` Opaque Type Alias Type Checking ------------------------------- ### Within the Defining File When in the same file the alias is defined, opaque type aliases behave exactly as regular [type aliases](../aliases) do. ``` //@flow opaque type NumberAlias = number; (0: NumberAlias); function add(x: NumberAlias, y: NumberAlias): NumberAlias { return x + y; } function toNumberAlias(x: number): NumberAlias { return x; } function toNumber(x: NumberAlias): number { return x; } ``` ### Outside the Defining File When importing an opaque type alias, it behaves like a [nominal type](https://flow.org/en/lang/nominal-structural/#toc-nominal-typing), hiding its underlying type. **`exports.js`** ``` export opaque type NumberAlias = number; ``` **`imports.js`** ``` import type {NumberAlias} from './exports'; (0: NumberAlias) // Error: 0 is not a NumberAlias! function convert(x: NumberAlias): number { return x; // Error: x is not a number! } ``` ### Subtyping Constraints When you add a subtyping constraint to an opaque type alias, we allow the opaque type to be used as the super type when outside of the defining file. **`exports.js`** ``` export opaque type ID: string = string; ``` **`imports.js`** ``` import type {ID} from './exports'; function formatID(x: ID): string { return "ID: " + x; // Ok! IDs are strings. } function toID(x: string): ID { return x; // Error: strings are not IDs. } ``` When you create an opaque type alias with a subtyping constraint, the type in the type position must be a subtype of the type in the super type position. ``` //@flow opaque type Bad: string = number; // Error: number is not a subtype of string opaque type Good: {x: string} = {x: string, y: number}; ``` ### Generics Opaque type aliases can also have their own [generics](../generics), and they work exactly as generics do in regular [type aliases](../aliases#toc-type-alias-generics) ``` // @flow opaque type MyObject<A, B, C>: { foo: A, bar: B } = { foo: A, bar: B, baz: C, }; var val: MyObject<number, boolean, string> = { foo: 1, bar: true, baz: 'three', }; ``` ### Library Definitions You can also declare opaque type aliases in [libdefs](../libdefs). There, you omit the underlying type, but may still optionally include a super type. ``` declare opaque type Foo; declare opaque type PositiveNumber: number; ``` flow Intersection Types Intersection Types ================== Sometimes it is useful to create a type which is ***all of*** a set of other types. For example, you might want to write a function which accepts an object which is the combination of other object types. For this, Flow supports **intersection types**. ``` // @flow type A = { a: number }; type B = { b: boolean }; type C = { c: string }; function method(value: A & B & C) { // ... } // $ExpectError method({ a: 1 }); // Error! // $ExpectError method({ a: 1, b: true }); // Error! method({ a: 1, b: true, c: 'three' }); // Works! ``` Intersection type syntax ------------------------ Intersection types are any number of types which are joined by an ampersand `&`. ``` Type1 & Type2 & ... & TypeN ``` You may also add a leading ampersand which is useful when breaking intersection types onto multiple lines. ``` type Foo = & Type1 & Type2 & ... & TypeN ``` Each of the members of a intersection type can be any type, even another intersection type. ``` type Foo = Type1 & Type2; type Bar = Type3 & Type4; type Baz = Foo & Bar; ``` Intersection types require all in, but one out ---------------------------------------------- Intersection types are the opposite of union types. When calling a function that accepts an intersection type, we must pass in ***all of those types***. But inside of our function we only have to treat it as ***any one of those types***. ``` // @flow type A = { a: number }; type B = { b: boolean }; type C = { c: string }; function method(value: A & B & C) { var a: A = value; var b: B = value; var c: C = value; } ``` Even as we treat our value as just one of the types, we do not get an error because it satisfies all of them. Intersection of function types ------------------------------ A common use of intersection types is to express functions that return different results based on the input we pass in. Suppose for example that we want to write the type of a function that * returns a string, when we pass in the value `"string"`, * returns a number, when we pass in the value `"number"`, and * returns any possible type (`mixed`), when we pass in any other string. The type of this function will be ``` type Fn = & ((x: "string") => string) & ((x: "number") => number) & ((x: string) => null); ``` Each line in the above definition is called an *overload*, and we say that functions of type `Fn` are *overloaded*. Note the use of parentheses around the arrow types. These are necessary to override the precedence of the “arrow” constructor over the intersection. ### Calling an overloaded function Using the above definition we can declare a function `fn` that has the following behavior: ``` declare var fn: Fn; var n: string = fn("string"); // okay var n: number = fn("number"); // okay var n: boolean = fn("boolean"); // error: null is incompatible with number ``` Flow achieves this behavior by matching the type of the argument to the *first* overload with a compatible parameter type. Notice for example that the argument `"string"` matches both the first and the last overload. Flow will just pick the first one. If no overload matches, Flow will raise an error at the call site. ### Declaring overloaded functions An equivalent way to declare the same function `fn` would be by using consecutive “declare function” statements ``` declare function fn(x: "string"): string; declare function fn(x: "number"): number; declare function fn(x: string): null; ``` A limitation in Flow is that it can’t *check* the body of a function against an intersection type. In other words, if we provided the following implementation for `fn` right after the above declarations ``` function fn(x) { if (x === "string") { return ""; } else if (x === "number") { return 0; } else { return null; } } ``` Flow silently accepts it (and uses `Fn` as the inferred type), but does not check the implementation against this signature. This makes this kind of declaration a better suited candidate for library definitions, where implementations are omitted. Intersections of object types ----------------------------- When you create an intersection of object types, you merge all of their properties together. For example, when you create an intersection of two objects with different sets of properties, it will result in an object with all of the properties. ``` // @flow type One = { foo: number }; type Two = { bar: boolean }; type Both = One & Two; var value: Both = { foo: 1, bar: true }; ``` When you have properties that overlap by having the same name, Flow follows the same strategy as with overloaded functions: it will return the type of the first property that matches this name. For example, if you merge two objects with a property named `prop`, first with a type of number and second with a type of boolean, accessing `prop` will return `number`. ``` type One = { prop: number }; type Two = { prop: boolean }; declare var both: One & Two; var prop1: number = both.prop; // okay var prop2: boolean = both.prop; // Error: number is incompatible with boolean ``` **Note:** When it comes to objects, the order-specific way in which intersection types are implemented in Flow, may often seem counterintuitive from a set theoretic point of view. In sets, the operands of intersection can change order arbitrarily (commutative property). For this reason, it is a better practice to define this kind of operation over object types using the *spread* operator, e.g. `{ ...One, ...Two }`, where the ordering semantics are better specified. Impossible intersection types ----------------------------- Using intersection types, it is possible to create types which are impossible to create at runtime. Intersection types will allow you to combine any set of types, even ones that conflict with one another. For example, you can create an intersection of a number and a string. ``` // @flow type NumberAndString = number & string; function method(value: NumberAndString) { // ... } // $ExpectError method(3.14); // Error! // $ExpectError method('hi'); // Error! ``` But you can’t possibly create a value which is both a *number and a string*, but you can create a type for it. There’s no practical use for creating types like this, but it’s a side effect of how intersection types work. flow Union Types Union Types =========== Sometimes it’s useful to create a type which is ***one of*** a set of other types. For example, you might want to write a function which accepts a set of primitive value types. For this Flow supports **union types**. ``` // @flow function toStringPrimitives(value: number | boolean | string) { return String(value); } toStringPrimitives(1); // Works! toStringPrimitives(true); // Works! toStringPrimitives('three'); // Works! // $ExpectError toStringPrimitives({ prop: 'val' }); // Error! // $ExpectError toStringPrimitives([1, 2, 3, 4, 5]); // Error! ``` Union type syntax ----------------- Union types are any number of types which are joined by a vertical bar `|`. ``` Type1 | Type2 | ... | TypeN ``` You may also add a leading vertical bar which is useful when breaking union types onto multiple lines. ``` type Foo = | Type1 | Type2 | ... | TypeN ``` Each of the members of a union type can be any type, even another union type. ``` type Numbers = 1 | 2; type Colors = 'red' | 'blue' type Fish = Numbers | Colors; ``` If you have enabled [Flow Enums](https://flow.org/en/enums/), they may be an alternative to unions of primitive values. Union types requires one in, but all out ---------------------------------------- When calling our function that accepts a union type we must pass in ***one of those types***. But inside of our function we are required to handle ***all of the possible types***. Let’s rewrite our function to handle each type individually. ``` // @flow // $ExpectError function toStringPrimitives(value: number | boolean | string): string { // Error! if (typeof value === 'number') { return String(value); } else if (typeof value === 'boolean') { return String(value); } } ``` You’ll notice that if we do not handle each possible type of our value, Flow will give us an error. Unions & Refinements -------------------- When you have a value which is a union type it’s often useful to break it apart and handle each individual type separately. With union types in Flow you can “refine” the value down to a single type. For example, if we have a value with a union type that is a `number`, a `boolean`, or a `string`, we can treat the number case separately by using JavaScript’s `typeof` operator. ``` // @flow function toStringPrimitives(value: number | boolean | string) { if (typeof value === 'number') { return value.toLocaleString([], { maximumSignificantDigits: 3 }); // Works! } // ... } ``` By checking the typeof our value and testing to see if it is a number, Flow knows that inside of that block it is only a number. We can then write code which treats our value as a number inside of that block. ### Disjoint Object Unions There’s a special type of union in Flow known as a “disjoint object union” which can be used in [refinements](https://flow.org/en/lang/refinements/). These disjoint object unions are made up of any number of object types which are each tagged by a single property. For example, imagine we have a function for handling a response from a server after we’ve sent it a request. When the request is successful, we’ll get back an object with a `type` property set to `'success'` and a `value` that we’ve updated. ``` { type: 'success', value: 23 }; ``` When the request fails, we’ll get back an object with `type` set to `'error'` and an `error` property describing the error. ``` { type: 'error', error: 'Bad request' }; ``` We can try to express both of these objects in a single object type. However, we’ll quickly run into issues where we know a property exists based on the `type` property but Flow does not. ``` // @flow type Response = { type: 'success' | 'error', value?: number, error?: string }; function handleResponse(response: Response) { if (response.type === 'success') { // $ExpectError const value: number = response.value; // Error! } else { // $ExpectError const error: string = response.error; // Error! } } ``` Trying to combine these two separate types into a single one will only cause us trouble. Instead, if we create a union type of both object types, Flow will be able to know which object we’re using based on the `type` property. ``` // @flow type Response = | { type: 'success', value: 23 } | { type: 'error', error: string }; function handleResponse(response: Response) { if (response.type === 'success') { const value: number = response.value; // Works! } else { const error: string = response.error; // Works! } } ``` In order to use this pattern, there must be a key that is in every object in your union (in our example above, `type`), and every object must set a different [literal type](../literals) for that key (in our example, the string `'success'`, and the string `'error'`). You can use any kind of literal type, including numbers and booleans. ### Disjoint unions with exact types Disjoint unions require you to use a single property to distinguish each object type. You cannot distinguish two different objects by different properties. ``` // @flow type Success = { success: true, value: boolean }; type Failed = { error: true, message: string }; function handleResponse(response: Success | Failed) { if (response.success) { // $ExpectError var value: boolean = response.value; // Error! } } ``` This is because in Flow it is okay to pass an object value with more properties than the object type expects (because of width subtyping). ``` // @flow type Success = { success: true, value: boolean }; type Failed = { error: true, message: string }; function handleResponse(response: Success | Failed) { // ... } handleResponse({ success: true, error: true, value: true, message: 'hi' }); ``` Unless the objects somehow conflict with one another there is no way to distinguish them. However, to get around this you could use **exact object types**. ``` // @flow type Success = {| success: true, value: boolean |}; type Failed = {| error: true, message: string |}; type Response = Success | Failed; function handleResponse(response: Response) { if (response.success) { var value: boolean = response.value; } else { var message: string = response.message; } } ``` With exact object types, we cannot have additional properties, so the objects conflict with one another and we are able to distinguish which is which.
programming_docs
flow Indexed Access Types Indexed Access Types ==================== Flow’s Indexed Access Types allow you to get the type of a property from an [object](../objects), [array](../arrays), or [tuple](../tuples) type. Indexed Access Types are a replacement for the [`$PropertyType`](../utilities#toc-propertytype) and [`$ElementType`](../utilities#toc-elementtype) utility types. If you’re familiar with those utility types already, here is a quick conversion guide: * `$PropertyType<Obj, 'prop'>` → `Obj['prop']` * `$ElementType<Obj, T>` → `Obj[T]` * `$ElementType<$PropertyType<Obj, 'prop'>, T>` → `Obj['prop'][T]` Indexed Access Type Usage ------------------------- Access an object type’s property: ``` // @flow type Cat = { name: string, age: number, hungry: boolean, }; type Hungry = Cat['hungry']; // type Hungry = boolean const isHungry: Hungry = true; // OK - `Hungry` is an alias for `boolean` // The index can be a type, not just a literal: type AgeProp = 'age'; type Age = Cat[AgeProp]; // type Age = number const catAge: Age = 6; // OK - `Age` is an alias for `number` ``` Access an array type’s element, by getting the type at the array’s indices (which are `number`s): ``` // @flow type CatNames = Array<string>; type CatName = CatNames[number]; // type CatName = string const myCatsName: CatName = 'whiskers'; // OK - `CatName` is an alias for `string` ``` Access a tuple type’s elements: ``` // @flow type Pair = [string, number]; const name: Pair[0] = 'whiskers'; // OK - `Pair[0]` is an alias for `string` const age: Pair[1] = 6; // OK - `Pair[1]` is an alias for `number` const wrong: Pair[2] = true; // Error - `Pair` only has two elements ``` The index can be a union, including the result of calling [`$Keys<...>`](../utilities#toc-keys): ``` // @flow type Cat = { name: string, age: number, hungry: boolean, }; type Values = Cat[$Keys<Cat>]; // type Values = string | number | boolean ``` The index can also be a generic: ``` // @flow function getProp<O: {+[string]: mixed}, K: $Keys<O>>(o: O, k: K): O[K] { return o[k]; } const x: number = getProp({a: 42}, 'a'); // OK const y: string = getProp({a: 42}, 'a'); // Error - `number` is not a `string` getProp({a: 42}, 'b'); // Error - `b` does not exist in object type ``` You can nest these accesses: ``` // @flow type Cat = { name: string, age: number, hungry: boolean, personality: { friendly: boolean, hungerLevel: number, } }; type Friendly = Cat['personality']['friendly']; // type Friendly = boolean const isFriendly: Friendly = true; // Pet the cat ``` Optional Indexed Access Types ----------------------------- Optional Indexed Access Types work like optional chaining. They allow you to access properties from nullable object types. If before you did: ``` type T = $ElementType<$NonMaybeType<Obj>, 'prop'> | void; ``` You can now do: ``` type T = Obj?.['prop']; ``` Like optional chaining, the resulting types of Optional Indexed Access Types include `void`. If you have a long chain of nested optional accesses, you can wrap the entire thing with a `$NonMaybeType<...>` if you don’t want `void` in your resulting type. Example: ``` // @flow type TasksContent = ?{ tasks?: Array<{ items?: { metadata?: { title: string, completed: boolean, }, }, }>, }; type TaskData = TasksContent?.['tasks']?.[number]?.['items']?.['metadata']; ``` There is one small difference between optional chaining and Optional Indexed Access Types. If the object type you access is not nullable, the resulting type in optional chaining will not include `void`. With Optional Indexed Access Types, for implementation reasons, the resulting type will always include `void`. However, if your object type is not nullable then you don’t need to use an Optional Indexed Access Type, but should just use a regular Indexed Access Type. Adoption -------- To use Indexed Access Types, you need to upgrade your infrastructure so that it supports the syntax: * `flow` and `flow-parser`: 0.155 * `prettier`: 2.3.2 * `babel`: 7.14 We have created an ESLint rule that warns on `$ElementType` and `$PropertyType` usage and recommends Indexed Access Types instead. It includes an auto-fixer that can handle most cases. You can simply enable this rule on your codebase and autofix all existing issues. Install [`eslint-plugin-fb-flow`](https://www.npmjs.com/package/eslint-plugin-fb-flow), and add `fb-flow` to your ESLint plugin list. Then enable the rule in your ESLint config: ``` 'fb-flow/use-indexed-access-type': 1, ``` flow Typeof Types Typeof Types ============ JavaScript has a `typeof` operator which returns a string describing a value. ``` typeof 1 === 'number' typeof true === 'boolean' typeof 'three' === 'string' ``` However it is limited in that this string only describes so much about the type. ``` typeof { foo: true } === 'object' typeof { bar: true } === 'object' typeof [true, false] === 'object' ``` In Flow, there is a similar `typeof` operator, but it’s much more powerful. `typeof` type syntax --------------------- The `typeof` operator returns the Flow type of a given value to be used as a type. ``` // @flow let num1 = 42; let num2: typeof num1 = 3.14; // Works! // $ExpectError let num3: typeof num1 = 'world'; // Error! let bool1 = true; let bool2: typeof bool1 = false; // Works! // $ExpectError let bool3: typeof bool1 = 42; // Error! let str1 = 'hello'; let str2: typeof str1 = 'world'; // Works! // $ExpectError let str3: typeof str1 = false; // Error! ``` You can use any value with `typeof`: ``` // @flow let obj1 = { foo: 1, bar: true, baz: 'three' }; let obj2: typeof obj1 = { foo: 42, bar: false, baz: 'hello' }; let arr1 = [1, 2, 3]; let arr2: typeof arr1 = [3, 2, 1]; ``` `typeof` inherits behaviors of inference ----------------------------------------- Flow does all sorts of type inference on your code so that you don’t have to type annotate anything. Generally, inference avoids getting in your way while still preventing you from introducing bugs. But when you use `typeof`, you’re taking the results of Flow’s inference and asserting it as a type. While this can be very useful, it can also lead to some unexpected results. For example, when you use literal values in Flow, their inferred type is the primitive that it belongs to. Thus, the number 42 has the inferred type of `number`. You can see this when you use `typeof`. ``` // @flow let num1 = 42; let num2: typeof num1 = 3.14; // Works! let bool1 = true; let bool2: typeof bool1 = false; // Works! let str1 = 'hello'; let str2: typeof str1 = 'world'; // Works! ``` However, this only happens with the inferred type. If you specify the literal type, it will be used in `typeof`. ``` // @flow let num1: 42 = 42; // $ExpectError let num2: typeof num1 = 3.14; // Error! let bool1: true = true; // $ExpectError let bool2: typeof bool1 = false; // Error! let str1: 'hello' = 'hello'; // $ExpectError let str2: typeof str1 = 'world'; // Error! ``` `typeof` inherits behaviors of other types ------------------------------------------- There are many different types in Flow, some of these types behave differently than others. These differences make sense for that particular type but not for others. When you use `typeof`, you’re inserting another type with all of its behaviors. This can make `typeof` seem inconsistent where it is not. For example, if you use `typeof` with a class you need to remember that classes are *nominally* typed instead of *structurally* typed. So that two classes with the same exact shape are not considered equivalent. ``` // @flow class MyClass { method(val: number) { /* ... */ } } class YourClass { method(val: number) { /* ... */ } } // $ExpectError let test1: typeof MyClass = YourClass; // Error! let test2: typeof MyClass = MyClass; // Works! ``` flow Mixed Types Mixed Types =========== In general, programs have several different categories of types: **A single type:** Here the input value can only be a `number`. ``` function square(n: number) { return n * n; } ``` **A group of different possible types:** Here the input value could be either a `string` or a `number`. ``` function stringifyBasicValue(value: string | number) { return '' + value; } ``` **A type based on another type:** Here the return type will be the same as the type of whatever value is passed into the function. ``` function identity<T>(value: T): T { return value; } ``` These three are the most common categories of types. They will make up the majority of the types you’ll be writing. However, there is also a fourth category. **An arbitrary type that could be anything:** Here the passed in value is an unknown type, it could be any type and the function would still work. ``` function getTypeOf(value: mixed): string { return typeof value; } ``` These unknown types are less common, but are still useful at times. You should represent these values with `mixed`. Anything goes in, Nothing comes out ----------------------------------- `mixed` will accept any type of value. Strings, numbers, objects, functions– anything will work. ``` // @flow function stringify(value: mixed) { // ... } stringify("foo"); stringify(3.14); stringify(null); stringify({}); ``` When you try to use a value of a `mixed` type you must first figure out what the actual type is or you’ll end up with an error. ``` // @flow function stringify(value: mixed) { // $ExpectError return "" + value; // Error! } stringify("foo"); ``` Instead you must ensure the value is a certain type by refining it. ``` // @flow function stringify(value: mixed) { if (typeof value === 'string') { return "" + value; // Works! } else { return ""; } } stringify("foo"); ``` Because of the `typeof value === 'string'` check, Flow knows the `value` can only be a `string` inside of the `if` statement. This is known as a [refinement](https://flow.org/en/lang/refinements/). flow Class Types Class Types =========== JavaScript [classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) in Flow operate both as a value and a type. You write classes the same way you would without Flow, but then you can use the name of the class as a type. ``` class MyClass { // ... } let myInstance: MyClass = new MyClass(); ``` This is because classes in Flow are [nominally typed](https://flow.org/en/lang/nominal-structural). Class Syntax ------------ Classes in Flow are identical to normal JavaScript classes, but with added types. #### Class Methods Just like in functions, class methods can have annotations for both parameters (input) and returns (output). ``` class MyClass { method(value: string): number { /* ... */ } } ``` Also just like regular functions, class methods may have `this` annotations as well. However, if one is not provided, Flow will infer the class instance type (or the class type for static methods) instead of `mixed`. When an explicit `this` parameter is provided, it must be a [supertype](https://flow.org/en/lang/subtypes/) of the class instance type (or class type for static methods). ``` class MyClass { method(this : interface { x : string }): void { /* ... */ } // x is missing in `MyClass` } ``` Unlike class properties, however, class methods cannot be unbound or rebound from the class on which you defined them. So all of the following are errors in Flow: ``` let c = new MyClass(); c.method; let {method} = c; c.method.bind({}); ``` #### Class Fields (Properties) Whenever you want to use a class field in Flow you must first give it an annotation. ``` // @flow class MyClass { method() { // $ExpectError this.prop = 42; // Error! } } ``` Fields are annotated within the body of the class with the field name followed by a colon `:` and the type. ``` // @flow class MyClass { prop: number; method() { this.prop = 42; } } ``` Fields added outside of the class definition need to be annotated within the body of the class. ``` // @flow function func_we_use_everywhere (x: number): number { return x + 1; } class MyClass { static constant: number; static helper: (number) => number; function_property: number => number; } MyClass.helper = func_we_use_everywhere MyClass.constant = 42 MyClass.prototype.function_property = func_we_use_everywhere ``` Flow also supports using the [class properties syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#field_declarations). ``` class MyClass { prop = 42; } ``` When using this syntax, you are not required to give it a type annotation. But you still can if you need to. ``` class MyClass { prop: number = 42; } ``` #### Class Constructors You can initialize your class properties in class constructors. ``` class MyClass { foo: number; constructor() { this.foo = 1; } } ``` You must first call `super(...)` in a derived class before you can access `this` and `super`. ``` class Base { bar: number; } class MyClass extends Base { foo: number; constructor() { this.foo; // Error this.bar; // Error super.bar; // Error super(); this.foo; // OK this.bar; // OK super.bar; // OK } } ``` However, Flow will not enforce that all class properties are initialized in constructors. ``` class MyClass { foo: number; bar: number; constructor() { this.foo = 1; } useBar() { (this.bar: number); // No errors. } } ``` #### Class Generics Classes can also have their own [generics](../generics). ``` class MyClass<A, B, C> { property: A; method(val: B): C { // ... } } ``` Class generics are [parameterized](../generics#toc-parameterized-generics). When you use a class as a type you need to pass parameters for each of its generics. ``` // @flow class MyClass<A, B, C> { constructor(arg1: A, arg2: B, arg3: C) { // ... } } var val: MyClass<number, boolean, string> = new MyClass(1, true, 'three'); ``` Classes in annotations ---------------------- When you use the name of your class in an annotation, it means an *instance* of your class: ``` //@flow class MyClass {} (MyClass: MyClass); // Error (new MyClass(): MyClass); // Ok ``` See [here](../utilities#toc-class) for details on `Class<T>`, which allows you to refer to the type of the class in an annotation. flow Type Aliases Type Aliases ============ When you have complicated types that you want to reuse in multiple places, you can alias them in Flow using a **type alias**. ``` // @flow type MyObject = { foo: number, bar: boolean, baz: string, }; ``` These type aliases can be used anywhere a type can be used. ``` // @flow type MyObject = { // ... }; var val: MyObject = { /* ... */ }; function method(val: MyObject) { /* ... */ } class Foo { constructor(val: MyObject) { /* ... */ } } ``` Type Alias Syntax ----------------- Type aliases are created using the keyword `type` followed by its name, an equals sign `=`, and a type definition. ``` type Alias = Type; ``` Any type can appear inside a type alias. ``` type NumberAlias = number; type ObjectAlias = { property: string, method(): number, }; type UnionAlias = 1 | 2 | 3; type AliasAlias = ObjectAlias; ``` ### Type Alias Generics Type aliases can also have their own [generics](../generics). ``` type MyObject<A, B, C> = { property: A, method(val: B): C, }; ``` Type alias generics are [parameterized](../generics#toc-parameterized-generics). When you use a type alias you need to pass parameters for each of its generics. ``` // @flow type MyObject<A, B, C> = { foo: A, bar: B, baz: C, }; var val: MyObject<number, boolean, string> = { foo: 1, bar: true, baz: 'three', }; ``` flow Comment Types Comment Types ============= Flow supports a comment-based syntax, which makes it possible to use Flow without having to compile your files. ``` // @flow /*:: type MyAlias = { foo: number, bar: boolean, baz: string, }; */ function method(value /*: MyAlias */) /*: boolean */ { return value.bar; } method({ foo: 1, bar: true, baz: ["oops"] }); ``` These comments allow Flow to work in plain JavaScript files without any additional work. Comment types syntax -------------------- There are two primary pieces of the syntax: type includes and type annotations. ### Comment type include If you want to have Flow treat a comment as if it were normal syntax, you can do so by adding a double colon `::` to the start of the comment. ``` /*:: type Foo = { foo: number, bar: boolean, baz: string }; */ class MyClass { /*:: prop: string; */ } ``` This includes the code into the syntax that Flow sees. ``` type Foo = { foo: number, bar: boolean, baz: string }; class MyClass { prop: string; } ``` But JavaScript ignores these comments, so all it has is the valid syntax. ``` class MyClass { } ``` This syntax is also available in a `flow-include` form. ``` /*flow-include type Foo = { foo: number, bar: boolean, baz: string }; */ class MyClass { /*flow-include prop: string; */ } ``` ### Comment type annotation Instead of typing out a full include every time, you can also use the type annotation shorthand with a single colon `:` at the start of the comment. ``` function method(param /*: string */) /*: number */ { // ... } ``` This would be the same as including a type annotation inside an include comment. ``` function method(param /*:: : string */) /*:: : number */ { // ... } ``` > **Note:** If you want to use optional function parameters you’ll need to use the include comment form. > > > **Special thanks to**: [Jarno Rantanen](https://github.com/jareware) for building [flotate](https://github.com/jareware/flotate) and supporting us merging his syntax upstream into Flow. > > flow Array Types Array Types =========== > **Note:** Arrays are also sometimes used as tuples in JavaScript, these are annotated differently in Flow. See the Tuple docs for more information. > > Arrays are a special list-like type of object in JavaScript. You can create arrays a couple different ways. ``` new Array(1, 2, 3); // [1, 2, 3]; new Array(3); // [undefined, undefined, undefined] [1, 2, 3]; // [1, 2, 3]; ``` You can also create arrays and add values to them later on: ``` let arr = []; // [] arr[0] = 1; // [1] arr[1] = 2; // [1, 2] arr[2] = 3; // [1, 2, 3] ``` `Array` Type ------------- To create an array type you can use `Array<Type>` type where `Type` is the type of elements in the array. For example, to create a type for an array of numbers you use `Array<number>`. ``` let arr: Array<number> = [1, 2, 3]; ``` You can put any type within `Array<Type>`. ``` let arr1: Array<boolean> = [true, false, true]; let arr2: Array<string> = ["A", "B", "C"]; let arr3: Array<mixed> = [1, true, "three"] ``` `Array` Type Shorthand Syntax ------------------------------ There’s also a slightly shorter form of this syntax: `Type[]`. ``` let arr: number[] = [0, 1, 2, 3]; ``` Just note that `?Type[]` is the equivalent of `?Array<T>` and not `Array<?T>`. ``` // @flow let arr1: ?number[] = null; // Works! let arr2: ?number[] = [1, 2]; // Works! let arr3: ?number[] = [null]; // Error! ``` If you want to make it `Array<?T>` you can use parenthesis like: `(?Type)[]` ``` // @flow let arr1: (?number)[] = null; // Error! let arr2: (?number)[] = [1, 2]; // Works! let arr3: (?number)[] = [null]; // Works! ``` Array access is unsafe ---------------------- When you retrieve an element from an array there is always a possibility that it is `undefined`. You could have either accessed an index which is out of the bounds of the array, or the element could not exist because it is a “sparse array”. For example, you could be accessing an element that is out of the bounds of the array. ``` // @flow let array: Array<number> = [0, 1, 2]; let value: number = array[3]; // Works. // ^ undefined ``` Or you could be accessing an element that does not exist if it is a “sparse array”. ``` // @flow let array: Array<number> = []; array[0] = 0; array[2] = 2; let value: number = array[1]; // Works. // ^ undefined ``` In order to make this safe, Flow would have to mark every single array access as “*possibly undefined”*. Flow does not do this because it would be extremely inconvenient to use. You would be forced to refine the type of every value you get when accessing an array. ``` let array: Array<number> = [0, 1, 2]; let value: number | void = array[1]; if (value !== undefined) { // number } ``` As Flow is made to be smarter it may be possible in the future to fix this problem, but for now you should be aware of it. `$ReadOnlyArray<T>` -------------------- Similar to [`$ReadOnly<T>`](../utilities#toc-readonly), it is the supertype of all arrays and all tuples and represents a read-only view of an array. It does not contain any methods that will allow an object of this type to be mutated (no `push()`, `pop()`, etc.). ``` // @flow const readonlyArray: $ReadOnlyArray<number> = [1, 2, 3] const first = readonlyArray[0] // OK to read readonlyArray[1] = 20 // Error! readonlyArray.push(4) // Error! ``` Note that an array of type `$ReadOnlyArray<T>` can still have mutable *elements*: ``` // @flow const readonlyArray: $ReadOnlyArray<{x: number}> = [{x: 1}]; readonlyArray[0] = {x: 42}; // Error! readonlyArray[0].x = 42; // OK ``` The main advantage to using `$ReadOnlyArray` instead of `Array` is that `$ReadOnlyArray`’s type parameter is *covariant* while `Array`’s type parameter is *invariant*. That means that `$ReadOnlyArray<number>` is a subtype of `$ReadOnlyArray<number | string>` while `Array<number>` is NOT a subtype of `Array<number | string>`. So it’s often useful to use `$ReadOnlyArray` in type annotations for arrays of various types of elements. Take, for instance, the following scenario: ``` // @flow const someOperation = (arr: Array<number | string>) => { // Here we could do `arr.push('a string')` } const array: Array<number> = [1] someOperation(array) // Error! ``` Since the parameter `arr` of the `someOperation` function is typed as a mutable `Array`, pushing a string into it would be possible inside that scope, which would then break the type contract of the outside `array` variable. By annotating the parameter as `$ReadOnlyArray` instead in this case, Flow can be sure this won’t happen and no errors will occur: ``` // @flow const someOperation = (arr: $ReadOnlyArray<number | string>) => { // Nothing can be added to `arr` } const array: Array<number> = [1] someOperation(array) // Works! ```
programming_docs
flow Primitive Types Primitive Types =============== JavaScript has a number of different primitive types ([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures)): * Booleans * Strings * Numbers * `null` * `undefined` (`void` in Flow types) * Symbols (new in ECMAScript 2015) The primitive types appear in the language as either literal values. ``` true; "hello"; 3.14; null; undefined; ``` Or as constructed wrapper objects. ``` new Boolean(false); new String("world"); new Number(42); ``` Types for literal values are lowercase. ``` // @flow function method(x: number, y: string, z: boolean) { // ... } method(3.14, "hello", true); ``` Types for the wrapper objects are capitalized (the same as their constructor). ``` // @flow function method(x: Number, y: String, z: Boolean) { // ... } method(new Number(42), new String("world"), new Boolean(false)); ``` These wrapper objects are rarely used. Booleans -------- Booleans are `true` and `false` values in JavaScript. The `boolean` type in Flow accepts these values. ``` // @flow function acceptsBoolean(value: boolean) { // ... } acceptsBoolean(true); // Works! acceptsBoolean(false); // Works! acceptsBoolean("foo"); // Error! ``` JavaScript can also implicitly convert other types of values into booleans. ``` if (42) {} // 42 => true if ("") {} // "" => false ``` Flow understands these conversions and will allow any of them as part of an `if` statement and other types of expressions. Boolean types need you to be explicit by converting non-booleans. You can do that with `Boolean(x)` or `!!x`. ``` // @flow function acceptsBoolean(value: boolean) { // ... } acceptsBoolean(0); // Error! acceptsBoolean(Boolean(0)); // Works! acceptsBoolean(!!0); // Works! ``` Remember that `boolean` and `Boolean` are different types. * A `boolean` is a literal value like `true` or `false` or the result of an expression like `a === b`. * A `Boolean` is a wrapper object created by the global `new Boolean(x)` constructor. Numbers ------- Unlike many other languages, JavaScript only has one type of number. These values may appear as `42` or `3.14`. JavaScript also considers `Infinity` and `NaN` to be numbers. The `number` type captures everything JavaScript considers a number. ``` // @flow function acceptsNumber(value: number) { // ... } acceptsNumber(42); // Works! acceptsNumber(3.14); // Works! acceptsNumber(NaN); // Works! acceptsNumber(Infinity); // Works! acceptsNumber("foo"); // Error! ``` Remember that `number` and `Number` are different types. * A `number` is a literal value like `42` or `3.14` or the result of an expression like `parseFloat(x)`. * A `Number` is a wrapper object created by the global `new Number(x)` constructor. Strings ------- Strings are `"foo"` values in JavaScript. The `string` type in Flow accepts these values. ``` // @flow function acceptsString(value: string) { // ... } acceptsString("foo"); // Works! acceptsString(false); // Error! ``` JavaScript implicitly converts other types of values into strings by concatenating them. ``` "foo" + 42; // "foo42" "foo" + {}; // "foo[object Object]" ``` Flow will only accept strings and number when concatenating them to strings. ``` // @flow "foo" + "foo"; // Works! "foo" + 42; // Works! "foo" + {}; // Error! "foo" + []; // Error! ``` You must be explicit and convert other types into strings. You can do this by using the String method or using another method for stringifying values. ``` // @flow "foo" + String({}); // Works! "foo" + [].toString(); // Works! "" + JSON.stringify({}) // Works! ``` Remember that `string` and `String` are different types. * A `string` is a literal value like `"foo"` or the result of an expression like `"" + 42`. * A `String` is a wrapper object created by the global `new String(x)` constructor. `null` and `void` ------------------ JavaScript has both `null` and `undefined`. Flow treats these as separate types: `null` and `void` (for `undefined`). ``` // @flow function acceptsNull(value: null) { /* ... */ } function acceptsUndefined(value: void) { /* ... */ } acceptsNull(null); // Works! acceptsNull(undefined); // Error! acceptsUndefined(null); // Error! acceptsUndefined(undefined); // Works! ``` `null` and `void` also appear in other types. ### Maybe types Maybe types are for places where a value is optional and you can create them by adding a question mark in front of the type such as `?string` or `?number`. In addition to the `type` in `?type`, maybe types can also be `null` or `void`. ``` // @flow function acceptsMaybeString(value: ?string) { // ... } acceptsMaybeString("bar"); // Works! acceptsMaybeString(undefined); // Works! acceptsMaybeString(null); // Works! acceptsMaybeString(); // Works! ``` ### Optional object properties Object types can have optional properties where a question mark `?` comes after the property name. ``` { propertyName?: string } ``` In addition to their set value type, these optional properties can either be `void` or omitted altogether. However, they cannot be `null`. ``` // @flow function acceptsObject(value: { foo?: string }) { // ... } acceptsObject({ foo: "bar" }); // Works! acceptsObject({ foo: undefined }); // Works! acceptsObject({ foo: null }); // Error! acceptsObject({}); // Works! ``` ### Optional function parameters Functions can have optional parameters where a question mark `?` comes after the parameter name. ``` function method(param?: string) { /* ... */ } ``` In addition to their set type, these optional parameters can either be `void` or omitted altogether. However, they cannot be `null`. ``` // @flow function acceptsOptionalString(value?: string) { // ... } acceptsOptionalString("bar"); // Works! acceptsOptionalString(undefined); // Works! acceptsOptionalString(null); // Error! acceptsOptionalString(); // Works! ``` ### Function parameters with defaults Function parameters can also have defaults. This is a feature of ECMAScript 2015. ``` function method(value: string = "default") { /* ... */ } ``` In addition to their set type, default parameters can also be `void` or omitted altogether. However, they cannot be `null`. ``` // @flow function acceptsOptionalString(value: string = "foo") { // ... } acceptsOptionalString("bar"); // Works! acceptsOptionalString(undefined); // Works! acceptsOptionalString(null); // Error! acceptsOptionalString(); // Works! ``` Symbols ------- Symbols are created with `Symbol()` in JavaScript. Flow has basic support for symbols, using the `symbol` type. ``` // @flow function acceptsSymbol(value: symbol) { // ... } acceptsSymbol(Symbol()); // Works! acceptsSymbol(Symbol.isConcatSpreadable); // Works! acceptsSymbol(false); // Error! ``` You can use `typeof x === "symbol"` to refine to a symbol. ``` const x: symbol | number = Symbol(); if (typeof x === "symbol") { const y: symbol = x; } else { const z: number = x; } ``` flow Type Casting Expressions Type Casting Expressions ======================== Sometimes it is useful to assert a type without using something like a function or a variable to do so. For this Flow supports an inline type cast expression syntax which can be used in a number of different ways. Type Cast Expression Syntax --------------------------- In order to create a type cast expression around a `value`, add a colon `:` with the `Type` and wrap the expression with parentheses `(` `)`. ``` (value: Type) ``` > **Note:** The parentheses are necessary to avoid ambiguity with other syntax. > > Type cast expressions can appear anywhere an expression can appear. ``` let val = (value: Type); let obj = { prop: (value: Type) }; let arr = ([(value: Type), (value: Type)]: Array<Type>); ``` The value itself can also be an expression: ``` (2 + 2: number); ``` When you strip the types all that is left is the value. ``` (value: Type); ``` ``` value; ``` Type Assertions --------------- Using type cast expressions you can assert that values are certain types. ``` // @flow let value = 42; (value: 42); // Works! (value: number); // Works! (value: string); // Error! ``` Asserting types in this way works the same as types do anywhere else. Type Casting ------------ When you write a type cast expression, the result of that expression is the value with the provided type. If you hold onto the resulting value, it will have the new type. ``` // @flow let value = 42; (value: 42); // Works! (value: number); // Works! let newValue = (value: number); // $ExpectError (newValue: 42); // Error! (newValue: number); // Works! ``` Using type cast expressions --------------------------- > **Note:** We’re going to go through a stripped down example for demonstrating how to make use of type cast expressions. This example is not solved well in practice. > > ### Type Casting through any Because type casts work the same as all other type annotations, you can only cast values to less specific types. You cannot change the type or make it something more specific. But you can use any to cast to whatever type you want. ``` let value = 42; (value: number); // Works! // $ExpectError (value: string); // Error! let newValue = ((value: any): string); // $ExpectError (newValue: number); // Error! (newValue: string); // Works! ``` By casting the value to any, you can then cast to whatever you want. This is unsafe and not recommended. But it’s sometimes useful when you are doing something with a value which is very difficult or impossible to type and want to make sure that the result has the desired type. For example, the following function for cloning an object. ``` function cloneObject(obj) { const clone = {}; Object.keys(obj).forEach(key => { clone[key] = obj[key]; }); return clone; } ``` It would be hard to create a type for this because we’re creating a new object based on another object. If we cast through any, we can return a type which is more useful. ``` // @flow function cloneObject(obj) { const clone = {}; Object.keys(obj).forEach(key => { clone[key] = obj[key]; }); return ((clone: any): typeof obj); // << } const clone = cloneObject({ foo: 1, bar: true, baz: 'three' }); (clone.foo: 1); // Works! (clone.bar: true); // Works! (clone.baz: 'three'); // Works! ``` ### Type checking through type assertions If we want to validate what kinds of types are coming into our `cloneObject` method from before, we could write the following annotation: ``` function cloneObject(obj: { [key: string]: mixed }) { // ... } ``` But now we have a problem. Our `typeof obj` annotation also gets this new annotation which defeats the entire purpose. ``` // @flow function cloneObject(obj: { [key: string]: mixed }) { const clone = {}; // ... return ((clone: any): typeof obj); } const clone = cloneObject({ foo: 1, bar: true, baz: 'three' }); // $ExpectError (clone.foo: 1); // Error! // $ExpectError (clone.bar: true); // Error! // $ExpectError (clone.baz: 'three'); // Error! ``` Instead we can assert the type within the function using a type assertion and now we’re validating our inputs. ``` // @flow function cloneObject(obj) { (obj: { [key: string]: mixed }); // ... } cloneObject({ foo: 1 }); // Works! // $ExpectError cloneObject([1, 2, 3]); // Error! ``` Now type inference can keep working for `typeof obj` which returns the expected shape of the object. ``` // @flow function cloneObject(obj) { (obj: { [key: string]: mixed }); // << const clone = {}; // ... return ((clone: any): typeof obj); } const clone = cloneObject({ foo: 1, bar: true, baz: 'three' }); (clone.foo: 1); // Works! (clone.bar: true); // Works! (clone.baz: 'three'); // Works! ``` > **Note:** This is not the proper solution to the above problem, it was being used for demonstration only. The correct solution is annotating the function like this: > > ``` function cloneObject<T: { [key: string]: mixed }>(obj: T): $Shape<T> { // ... } ``` flow .flowconfig [untyped] .flowconfig [untyped] ===================== Flow needs to know which files to parse and of those how to handle any Flow types within them. For third party libraries you may wish to not parse, parse but not preserve types, or parse but not raise errors, depending on the quality and compatibility of their Flow implementation. Different sections are available to specify different behaviours, and by combining them most use cases are expected to be met. `[untyped]` ------------ The `[untyped]` section in a `.flowconfig` file tells Flow to not typecheck files matching the specified regular expressions and instead throw away types and treat modules as `any`. This is different from the `[ignore]` config section that causes matching files to be ignored by the module resolver, which inherently makes them un-typechecked, and also unresolvable by `import` or `require`. When ignored `[libs]` must then be specified for each `import` using `flow-typed`, which may not always be desired. It is also different from the `[declarations]` section. This also does not typecheck the file contents, but `[declarations]` does extract and use the signatures of functions, classes, etc, when checking other code. `[untyped]` instead causes a file to be ignored by the typechecker as if it had `noflow` in it, resolve modules as `any` type, but allow them to NOT be ignored by the module resolver. Any matching file is skipped by Flow (not even parsed, like other `noflow` files!), but can still be `require()`‘d. Things to keep in mind: 1. These are [OCaml regular expressions](http://caml.inria.fr/pub/docs/manual-ocaml/libref/Str.html#TYPEregexp). 2. These regular expressions match against absolute paths. They probably should start with `.*` An example `[untyped]` section might look like: ``` [untyped] .*/third_party/.* .*/src/\(foo\|bar\)/.* .*\.untype\.js ``` This `[untyped]` section will parse: 1. Any file or directory under a directory named `third_party` 2. Any file or directory under `.*/src/foo` or under `.*/src/bar` 3. Any file that ends with the extension `.untype.js` Starting with Flow v0.23.0, you may use the `<PROJECT_ROOT>` placeholder in your regular expressions. At runtime, Flow will treat the placeholder as if it were the absolute path to the project’s root directory. This is useful for writing regular expressions that are relative rather than absolute. For example, you can write: ``` [untyped] <PROJECT_ROOT>/third_party/.* ``` Which would parse in declaration mode any file or directory under the directory named `third_party/` within the project root. However, unlike the previous example’s `.*/third_party/.*`, it would NOT parse files or directories under directories named `third_party/`, like `src/third_party/`. flow .flowconfig [declarations] .flowconfig [declarations] ========================== Often third-party libraries have broken type definitions or have type definitions only compatible with a certain version of Flow. In those cases it may be useful to use type information from the third-party libraries without typechecking their contents. `[declarations]` ----------------- The `[declarations]` section in a `.flowconfig` file tells Flow to parse files matching the specified regular expressions in *declaration mode*. In declaration mode the code is not typechecked. However, the signatures of functions, classes, etc are extracted and used by the typechecker when checking other code. Conceptually one can think of declaration mode as if Flow still typechecks the files but acts as if there is a comment that matches [`suppress_comment`](../options#toc-suppress-comment-regex) on every line. See also `[untyped]`(untyped) for not typechecking files, and instead using `any` for all contents. Things to keep in mind: 1. Declaration mode should only be used for existing third-party code. You should never use this for code under your control. 2. These are [OCaml regular expressions](http://caml.inria.fr/pub/docs/manual-ocaml/libref/Str.html#TYPEregexp). 3. These regular expressions match against absolute paths. They probably should start with `.*` An example `[declarations]` section might look like: ``` [declarations] .*/third_party/.* .*/src/\(foo\|bar\)/.* .*\.decl\.js ``` This `[declarations]` section will parse in declaration mode: 1. Any file or directory under a directory named `third_party` 2. Any file or directory under `.*/src/foo` or under `.*/src/bar` 3. Any file that ends with the extension `.decl.js` Starting with Flow v0.23.0, you may use the `<PROJECT_ROOT>` placeholder in your regular expressions. At runtime, Flow will treat the placeholder as if it were the absolute path to the project’s root directory. This is useful for writing regular expressions that are relative rather than absolute. For example, you can write: ``` [declarations] <PROJECT_ROOT>/third_party/.* ``` Which would parse in declaration mode any file or directory under the directory named `third_party/` within the project root. However, unlike the previous example’s `.*/third_party/.*`, it would NOT parse files or directories under directories named `third_party/`, like `src/third_party/`. flow .flowconfig [include] .flowconfig [include] ===================== Flow needs to know which files to read and watch for changes. This set of files is determined by taking all included files and excluding all the ignored files. The `[include]` section in a `.flowconfig` file tells Flow to include the specified files or directories. Including a directory recursively includes all the files under that directory. Symlinks are followed as long as they lead to a file or directory that is also included. Each line in the include section is a path to include. These paths can be relative to the root directory or absolute, and support both single and double star wildcards. The project root directory (where your `.flowconfig` lives) is automatically included. For example, if `/path/to/root/.flowconfig` contains the following `[include]` section: ``` [include] ../externalFile.js ../externalDir/ ../otherProject/*.js ../otherProject/**/coolStuff/ ``` Then when Flow checks the project in `/path/to/root`, it will read and watch 1. `/path/to/root/` (automatically included) 2. `/path/to/externalFile.js` 3. `/path/to/externalDir/` 4. Any file in `/path/to/otherProject/` that ends in `.js` 5. Any directory under `/path/to/otherProject` named `coolStuff/` flow .flowconfig [ignore] .flowconfig [ignore] ==================== Flow needs to know which files to read and watch for changes. This set of files is determined by taking all included files and excluding all the ignored files. `[ignore]` ----------- The `[ignore]` section in a `.flowconfig` file tells Flow to ignore files matching the specified regular expressions when type checking your code. By default, nothing is ignored. Things to keep in mind: 1. These are [OCaml regular expressions](http://caml.inria.fr/pub/docs/manual-ocaml/libref/Str.html#TYPEregexp). 2. These regular expressions match against absolute paths. They probably should start with `.*` 3. Ignores are processed AFTER includes. If you both include and ignore a file it will be ignored. An example `[ignore]` section might look like: ``` [ignore] .*/__tests__/.* .*/src/\(foo\|bar\)/.* .*\.ignore\.js ``` This `[ignore]` section will ignore: 1. Any file or directory under a directory named `__tests__` 2. Any file or directory under `.*/src/foo` or under `.*/src/bar` 3. Any file that ends with the extension `.ignore.js` Starting with Flow v0.23.0, you may use the `<PROJECT_ROOT>` placeholder in your regular expressions. At runtime, Flow will treat the placeholder as if it were the absolute path to the project’s root directory. This is useful for writing regular expressions that are relative rather than absolute. For example, you can write: ``` [ignore] <PROJECT_ROOT>/__tests__/.* ``` Which would ignore any file or directory under the directory named `__tests__/` within the project root. However, unlike the previous example’s `.*/__tests__/.*`, it would NOT ignore files or directories under other directories named `__tests__/`, like `src/__tests__/`. Exclusions ---------- Sometimes you may want to ignore all files inside a directory with the exception of a few. An optional prefix “!” which negates the pattern may help. With this, any matching file excluded by a previous pattern will become included again. ``` [ignore] <PROJECT_ROOT>/node_modules/.* !<PROJECT_ROOT>/node_modules/not-ignored-package-A/.* !<PROJECT_ROOT>/node_modules/not-ignored-package-B/.* ```
programming_docs
flow .flowconfig [lints] .flowconfig [lints] =================== The `[lints]` section in a `.flowconfig` file can contain several key-value pairs of the form: ``` [lints] ruleA=severityA ruleB=severityB ``` Check out the [linting docs](https://flow.org/en/linting) for more information. flow .flowconfig [options] .flowconfig [options] ===================== The `[options]` section in a `.flowconfig` file can contain several key-value pairs of the form: ``` [options] keyA=valueA keyB=valueB ``` Any options that are omitted will use their default values. Some options can be overridden with command line flags. Available options ----------------- * [`all`](#toc-all-boolean) * [`autoimports`](#toc-autoimports-boolean) * [`babel_loose_array_spread`](#toc-babel-loose-array-spread-boolean) * [`emoji`](#toc-emoji-boolean) * [`exact_by_default`](#toc-exact-by-default-boolean) * [`experimental.const_params`](#toc-experimental-const-params-boolean) * [`include_warnings`](#toc-include-warnings-boolean) * [`inference_mode`](#toc-inference-mode-classic-constrain-writes) * [`lazy_mode`](#toc-lazy-mode-boolean) * [`log.file`](#toc-log-file-string) * [`max_header_tokens`](#toc-max-header-tokens-integer) * [`module.file_ext`](#toc-module-file-ext-string) * [`module.ignore_non_literal_requires`](#toc-module-ignore-non-literal-requires-boolean) * [`module.name_mapper`](#toc-module-name-mapper-regex-string) * [`module.name_mapper.extension`](#toc-module-name-mapper-extension-string-string) * [`module.system`](#toc-module-system-node-haste) * [`module.system.node.main_field`](#toc-module-system-node-main-field-string) * [`module.system.node.resolve_dirname`](#toc-module-system-node-resolve-dirname-string) * [`module.use_strict`](#toc-module-use-strict-boolean) * [`munge_underscores`](#toc-munge-underscores-boolean) * [`no_flowlib`](#toc-no-flowlib-boolean) * [`react.runtime`](#toc-react-runtime-automatic-classic) * [`server.max_workers`](#toc-server-max-workers-integer) * [`sharedmemory.dirs`](#toc-sharedmemory-dirs-string) * [`sharedmemory.minimum_available`](#toc-sharedmemory-minimum-available-unsigned-integer) * [`sharedmemory.hash_table_pow`](#toc-sharedmemory-hash-table-pow-unsigned-integer) * [`sharedmemory.heap_size`](#toc-sharedmemory-heap-size-unsigned-integer) * [`sharedmemory.log_level`](#toc-sharedmemory-log-level-unsigned-integer) * [`suppress_type`](#toc-suppress-type-string) * [`temp_dir`](#toc-temp-dir-string) * [`traces`](#toc-traces-integer) The following options are deprecated and have been removed in the latest version of Flow: * [`strip_root`](#toc-strip-root-boolean) * [`suppress_comment`](#toc-suppress-comment-regex) * [`types_first`](#toc-types-first-boolean) * [`well_formed_exports`](#toc-well-formed-exports-boolean) * [`esproposal.class_instance_fields`](#toc-esproposal-class-instance-fields-enable-ignore-warn) * [`esproposal.class_static_fields`](#toc-esproposal-class-static-fields-enable-ignore-warn) * [`esproposal.decorators`](#toc-esproposal-decorators-ignore-warn) * [`esproposal.export_star_as`](#toc-esproposal-export-star-as-enable-ignore-warn) * [`esproposal.optional_chaining`](#toc-esproposal-optional-chaining-enable-ignore-warn) * [`esproposal.nullish_coalescing`](#toc-esproposal-nullish-coalescing-enable-ignore-warn) ### `all` *`(boolean)`* Set this to `true` to check all files, not just those with `@flow`. The default value for `all` is `false`. ### `autoimports` *`(boolean)`* ≥0.143.0 When enabled, IDE autocomplete suggests the exports of other files, and the necessary `import` statements are automatically inserted. A “quick fix” code action is also provided on undefined variables that suggests matching imports. The default value for `autoimports` is `true` as of Flow v0.155.0. ### `babel_loose_array_spread` *`(boolean)`* Set this to `true` to check that array spread syntax is only used with arrays, not arbitrary iterables (such as `Map` or `Set`). This is useful if you transform your code with Babel in [loose mode](https://babeljs.io/docs/en/babel-plugin-transform-spread#loose) which makes this non-spec-compliant assumption at runtime. For example: ``` const set = new Set(); const values = [...set]; // Valid ES2015, but Set is not compatible with $ReadOnlyArray in Babel loose mode ``` The default value for `babel_loose_array_spread` is `false`. ### `emoji` *`(boolean)`* Set this to `true` to add emoji to the status messages that Flow outputs when it’s busy checking your project. The default value for `emoji` is `false`. ### `exact_by_default` *`(boolean)`* Set this to `true` to indicate that Flow should interpret object types as exact by default. When this flag is `false`, Flow has the following behavior: ``` {foo: number} // inexact {| foo: number |} // exact {foo: number, ...} // inexact ``` When this flag is `true`, Flow has the following behavior: ``` {foo: number} // exact {| foo: number |} // exact {foo: number, ...} // inexact ``` The default value is `false`. ### `experimental.const_params` *`(boolean)`* Setting this to `true` makes Flow treat all function parameters as const bindings. Reassigning a param is an error which lets Flow be less conservative with refinements. The default value is `false`. ### `inference_mode` *`(classic | constrain_writes)`* ≥0.184.0 Setting this to `constrain_writes` will enable the constrained-writes inference mode. For more info, see the [constrained-writes docs](../lang/constrained-writes). The default value is `classic` ### `include_warnings` *`(boolean)`* Setting this to `true` makes Flow commands include warnings in the error output. Warnings are hidden by default in the CLI to avoid console spew. (An IDE is a much better interface to show warnings.) The default value is `false`. ### `lazy_mode` *`(boolean)`* For more on lazy modes, see the [lazy modes docs](../lang/lazy-modes). Setting `lazy_mode` in the `.flowconfig` will cause new Flow servers for that root to use lazy mode (or no lazy mode if set to `false`). This option can be overridden from the CLI using the `--lazy-mode` flag. The default value is `false`. ### `log.file` *`(string)`* The path to the log file (defaults to `/tmp/flow/<escaped root path>.log`). ### `max_header_tokens` *`(integer)`* Flow tries to avoid parsing non-flow files. This means Flow needs to start lexing a file to see if it has `@flow` or `@noflow` in it. This option lets you configure how much of the file Flow lexes before it decides there is no relevant docblock. * Neither `@flow` nor `@noflow` - Parse this file with Flow syntax disallowed and do not typecheck it. * @flow - Parse this file with Flow syntax allowed and typecheck it. * @noflow - Parse this file with Flow syntax allowed and do not typecheck it. This is meant as an escape hatch to suppress Flow in a file without having to delete all the Flow-specific syntax. The default value of `max_header_tokens` is 10. ### `module.file_ext` *`(string)`* By default, Flow will look for files with the extensions `.js`, `.jsx`, `.mjs`, `.cjs` and `.json`. You can override this behavior with this option. For example, if you do: ``` [options] module.file_ext=.foo module.file_ext=.bar ``` Then Flow will instead look for the file extensions `.foo` and `.bar`. > **Note:** you can specify `module.file_ext` multiple times > > ### `module.ignore_non_literal_requires` *`(boolean)`* Set this to `true` and Flow will no longer complain when you use `require()` with something other than a string literal. The default value is `false`. ### `module.name_mapper` *`(regex -> string)`* Specify a regular expression to match against module names, and a replacement pattern, separated by a `->`. For example: ``` module.name_mapper='^image![a-zA-Z0-9$_]+$' -> 'ImageStub' ``` This makes Flow treat `require('image!foo.jpg')` as if it were `require('ImageStub')`. These are [OCaml regular expressions](http://caml.inria.fr/pub/docs/manual-ocaml/libref/Str.html#TYPEregexp). Use `\(` and `\)` (slashes required!) to create a capturing group, which you can refer to in the replacement pattern as `\1` (up to `\9`). > **Note:** you can specify `module.name_mapper` multiple times > > ### `module.name_mapper.extension` *`(string -> string)`* Specify a file extension to match, and a replacement module name, separated by a `->`. > **Note:** This is just shorthand for `module.name_mapper='^\(.*\)\.EXTENSION$' -> 'TEMPLATE'`) > > For example: ``` module.name_mapper.extension='css' -> '<PROJECT_ROOT>/CSSFlowStub.js.flow' ``` Makes Flow treat `require('foo.css')` as if it were `require(PROJECT_ROOT + '/CSSFlowStub')`. > **Note:** You can specify `module.name_mapper.extension` multiple times for different extensions. > > ### `module.system` *`(node|haste)`* The module system to use to resolve `import` and `require`. [Haste](https://github.com/facebook/node-haste) is used in React Native. The default is `node`. ### `module.system.node.main_field` *`(string)`* Flow reads `package.json` files for the `"name"` and `"main"` fields to figure out the name of the module and which file should be used to provide that module. So if Flow sees this in the `.flowconfig`: ``` [options] module.system.node.main_field=foo module.system.node.main_field=bar module.system.node.main_field=baz ``` and then it comes across a `package.json` with ``` { "name": "kittens", "main": "main.js", "bar": "bar.js", "baz": "baz.js" } ``` Flow will use `bar.js` to provide the `"kittens"` module. If this option is unspecified, Flow will always use the `"main"` field. See [this GitHub issue for the original motivation](https://github.com/facebook/flow/issues/5725) ### `module.system.node.resolve_dirname` *`(string)`* By default, Flow will look in directories named `node_modules` for node modules. You can configure this behavior with this option. For example, if you do: ``` [options] module.system.node.resolve_dirname=node_modules module.system.node.resolve_dirname=custom_node_modules ``` Then Flow will look in directories named `node_modules` or `custom_node_modules`. > **Note:** you can specify `module.system.node.resolve_dirname` multiple times > > ### `module.use_strict` *`(boolean)`* Set this to `true` if you use a transpiler that adds `"use strict";` to the top of every module. The default value is `false`. ### `munge_underscores` *`(boolean)`* Set this to `true` to have Flow treat underscore-prefixed class properties and methods as private. This should be used in conjunction with [`jstransform`’s ES6 class transform](https://github.com/facebook/jstransform/blob/master/visitors/es6-class-visitors.js), which enforces the same privacy at runtime. The default value is `false`. ### `no_flowlib` *`(boolean)`* Flow has builtin library definitions. Setting this to `true` will tell Flow to ignore the builtin library definitions. The default value is `false`. ### `react.runtime` *`(automatic|classic)`* ≥0.123.0 Set this to `automatic` if you are using React’s automatic runtime in `@babel/plugin-transform-react-jsx`. Otherwise, use `classic`. [See the babel documentation](https://babeljs.io/docs/en/babel-plugin-transform-react-jsx) for details about the transform. The default value is `automatic`. ### `server.max_workers` *`(integer)`* The maximum number of workers the Flow server can start. By default, the server will use all available cores. ### `sharedmemory.dirs` *`(string)`* This affects Linux only. Flow’s shared memory lives in a memory mapped file. On more modern versions of Linux (3.17+), there is a system call `memfd_create` which allows Flow to create the file anonymously and only in memory. However, in older kernels, Flow needs to create a file on the file system. Ideally this file lives on a memory-backed tmpfs. This option lets you decide where that file is created. By default this option is set to `/dev/shm` and `/tmp` > **Note:** You can specify `sharedmemory.dirs` multiple times. > > ### `sharedmemory.minimum_available` *`(unsigned integer)`* This affects Linux only. As explained in the [`sharedmemory.dirs`](options) option’s description, Flow needs to create a file on a filesystem for older kernels. `sharedmemory.dirs` specifies a list of locations where the shared memory file can be created. For each location, Flow will check to make sure the filesystem has enough space for the shared memory file. If Flow will likely run out of space, it skips that location and tries the next. This option lets you configure the minimum amount of space needed on a filesystem for shared memory. By default it is 536870912 (2^29 bytes, which is half a gigabyte). ### `sharedmemory.hash_table_pow` *`(unsigned integer)`* The 3 largest parts of the shared memory are a dependency table, a hash table, and a heap. While the heap grows and shrinks, the two tables are allocated in full. This option lets you change the size of the hash table. Setting this option to X means the table will support up to 2^X elements, which is 16\*2^X bytes. By default, this is set to 19 (Table size is 2^19, which is 8 megabytes) ### `sharedmemory.heap_size` *`(unsigned integer)`* This option configures the maximum possible size for the shared heap. You should most likely not need to configure this, as it doesn’t really affect how much RSS Flow uses. However, if you are working on a massive codebase you might see the following error after init: “Heap init size is too close to max heap size; GC will never get triggered!” In this case, you may need to increase the size of the heap. By default, this is set to 26843545600 (25 \* 2^30 bytes, which is 25GiB) ### `sharedmemory.log_level` *`(unsigned integer)`* Setting this to 1 will cause Flow to output some stats about the data that is serialized into and deserialized out of shared memory. By default this is 0. ### `suppress_type` *`(string)`* This option lets you alias `any` with a given string. This is useful for explaining why you’re using `any`. For example, let’s say you sometimes want to sometimes use `any` to suppress an error and sometimes to mark a TODO. Your code might look like ``` var myString: any = 1 + 1; var myBoolean: any = 1 + 1; ``` If you add the following to your configuration: ``` [options] suppress_type=$FlowFixMe suppress_type=$FlowTODO ``` You can update your code to the more readable: ``` var myString: $FlowFixMe = 1 + 1; var myBoolean: $FlowTODO = 1 + 1; ``` > **Note:** You can specify `suppress_type` multiple times. > > ### `temp_dir` *`(string)`* Tell Flow which directory to use as a temp directory. Can be overridden with the command line flag `--temp-dir`. The default value is `/tmp/flow`. ### `traces` *`(integer)`* Enables traces on all error output (showing additional details about the flow of types through the system), to the depth specified. This can be very expensive, so is disabled by default. ### `strip_root` *`(boolean)`* ≤0.48 Obsolete. Set this to `true` to always strip the root directory from file paths in error messages when using `--json`, `--from emacs`, and `--from vim`. Do not use this option. Instead, pass the command line flag `--strip-root`. By default this is `false`. ### `suppress_comment` *`(regex)`* ≤0.126 Defines a magical comment that suppresses any Flow errors on the following line. For example: ``` suppress_comment= \\(.\\|\n\\)*\\$FlowFixMe ``` will match a comment like this: ``` // $FlowFixMe: suppressing this error until we can refactor var x : string = 123; ``` and suppress the error. If there is no error on the next line (the suppression is unnecessary), an “Unused suppression” warning will be shown instead. If no suppression comments are specified in your config, Flow will apply one default: `// $FlowFixMe`. > **Note:** You can specify `suppress_comment` multiple times. If you do define any `suppress_comment`s, the built-in `$FlowFixMe` suppression will be erased in favor of the regexps you specify. If you wish to use `$FlowFixMe` with some additional custom suppression comments, you must manually specify `\\(.\\|\n\\)*\\$FlowFixMe` in your custom list of suppressions. > > > **Note:** In version v0.127.0, the option to specify the suppression comment syntax was removed. `$FlowFixMe`, `$FlowIssue`, `$FlowExpectedError`, and `$FlowIgnore` became the only standard suppressions. > > ### `types_first` *`(boolean)`* ≥0.125.0 ≤0.142 For more on types-first mode, see the [types-first docs](../lang/types-first). Flow builds intermediate artifacts to represent signatures of modules as they are checked. If this option is set to `false`, then these artifacts are built using inferred type information. If this option is set to `true`, then they are built using type annotations at module boundaries. The default value for `types_first` is `true` (as of version 0.134). ### `well_formed_exports` *`(boolean)`* ≥0.125.0 ≤0.142 Enforce the following restrictions on file exports: * Statements manipulating `module.exports` and the `exports` alias may only appear as top-level statements. * Parts of the source that are visible from a file’s exports need to be annotated unless their type can be trivially inferred (e.g. the exported expression is a numeric literal). This is a requirement for types-first mode to function properly. Failure to properly annotate exports raise `signature-verification-failure`s. This option is set to `true` by default, since it is implied by [`types_first`](#toc-types-first-boolean), but the option is useful on its own when upgrading a project from classic mode to types-first mode. ### `well_formed_exports.includes` *`(string)`* ≥0.128.0 ≤0.142 Limit the scope of the `well_formed_exports` requirement to a specific directory of this project. For example ``` well_formed_exports=true well_formed_exports.includes=<PROJECT_ROOT>/dirA well_formed_exports.includes=<PROJECT_ROOT>/dirB ``` will only report export related errors in files under `dirA` and `dirB`. This option requires `well_formed_exports` to be set to `true`. The purpose of this option is to help prepare a codebase for Flow types-first mode. See [this section](#toc-seal-your-intermediate-results) for more. Between versions v0.125.0 and v0.127.0, this option was named `well_formed_exports.whitelist`. ### `esproposal.class_instance_fields` *`(enable|ignore|warn)`* ≤0.148 Set this to `warn` to indicate that Flow should give a warning on use of instance [class fields](https://github.com/tc39/proposal-class-public-fields) per the pending spec. You may also set this to `ignore` to indicate that Flow should simply ignore the syntax (i.e. Flow will not use this syntax to indicate the presence of a property on instances of the class). The default value of this option is `enable`, which allows use of this proposed syntax. ### `esproposal.class_static_fields` *`(enable|ignore|warn)`* ≤0.148 Set this to `warn` to indicate that Flow should give a warning on use of static [class fields](https://github.com/tc39/proposal-class-public-fields) per the pending spec. You may also set this to `ignore` to indicate that Flow should simply ignore the syntax (i.e. Flow will not use this syntax to indicate the presence of a static property on the class). The default value of this option is `enable`, which allows use of this proposed syntax. ### `esproposal.decorators` *`(ignore|warn)`* ≤0.148 Set this to `ignore` to indicate that Flow should ignore decorators. The default value of this option is `warn`, which gives a warning on use since this proposal is still very early-stage. ### `esproposal.export_star_as` *`(enable|ignore|warn)`* ≤0.148 Set this to `enable` to indicate that Flow should support the `export * as` syntax from [leebyron’s proposal](https://github.com/leebyron/ecmascript-more-export-from). You may also set this to `ignore` to indicate that Flow should simply ignore the syntax. The default value of this option is `warn`, which gives a warning on use since this proposal is still very early-stage. ### `esproposal.optional_chaining` *`(enable|ignore|warn)`* ≤0.148 Set this to `enable` to indicate that Flow should support the use of [optional chaining](https://github.com/tc39/proposal-optional-chaining) per the pending spec. You may also set this to `ignore` to indicate that Flow should simply ignore the syntax. The default value of this option is `warn`, which gives a warning on use since this proposal is still very early-stage. ### `esproposal.nullish_coalescing` *`(enable|ignore|warn)`* ≤0.148 Set this to `enable` to indicate that Flow should support the use of [nullish coalescing](https://github.com/tc39/proposal-nullish-coalescing) per the pending spec. You may also set this to `ignore` to indicate that Flow should simply ignore the syntax. The default value of this option is `warn`, which gives a warning on use since this proposal is still very early-stage.
programming_docs
flow .flowconfig [version] .flowconfig [version] ===================== You can specify in the `.flowconfig` which version of Flow you expect to use. You do this with the `[version]` section. If this section is omitted or left blank, then any version is allowed. If a version is specified and not matched, then Flow will immediately error and exit. So if you have the following in your `.flowconfig`: ``` [version] 0.22.0 ``` and you try to use Flow v0.21.0, then Flow will immediately error with the message `"Wrong version of Flow. The config specifies version 0.22.0 but this is version 0.21.0"` So far, we support the following ways to specify supported versions * Explicit versions, (e.g. `0.22.0`, which only matches `0.22.0`). * Intersection ranges, which are ANDed together, (e.g. `>=0.13.0 <0.14.0`, which matches `0.13.0` and `0.13.5` but not `0.14.0`). * Caret ranges, which allow changes that do not modify the left-most non-zero digit (e.g. `^0.13.0` expands into `>=0.13.0 <0.14.0`, and `^0.13.1` expands into `>=0.13.1 <0.14.0`, whereas `^1.2.3` expands into `>=1.2.3 <2.0.0`). flow .flowconfig [libs] .flowconfig [libs] ================== The `[libs]` section in a `.flowconfig` file tells Flow to include the specified [library definitions](https://flow.org/en/libdefs/) when type checking your code. Multiple libraries can be specified. By default, the `flow-typed` folder in your project root directory is included as a library directory. This default allows you to use [`flow-typed`](https://github.com/flowtype/flow-typed) to install library definitions without additional configuration. Each line in the `[libs]` section is a path to the library file or directory which you would like to include. These paths can be relative to the project root directory or absolute. Including a directory recursively includes all the files under that directory as library files. flow Atom Atom ==== If you’re using [Atom](https://atom.io) you have a bunch of options to integrate Flow into your code base. Flow for Atom IDE ----------------- ``` apm install atom-ide-ui && apm install ide-flowtype ``` [Flow for Atom IDE](https://atom.io/packages/ide-flowtype) is extracted from [Nuclide](https://nuclide.io), and works with the [Atom IDE](https://ide.atom.io/) UI. It brings the core features you expect in a full-featured IDE into Atom, such as language-aware autocomplete, diagnostics, go-to-definition, type hints, and symbol outlines. Flow-IDE -------- ``` apm install flow-ide ``` [Flow-IDE](https://atom.io/packages/flow-ide) is a smaller package that only provides you with a linter and autocomplete functionality. It, too, currently lacks support for on-the-fly linting. Linter-Flow ----------- ``` apm install linter-flow ``` In case you’re looking for something even more minimal, [linter-flow](https://atom.io/packages/linter-flow) may be worth your attention. It only lints your code and provides no other features, but it does support on-the-fly linting. Autocomplete-Flow ----------------- ``` apm install autocomplete-flow ``` [autocomplete-flow](https://atom.io/packages/autocomplete-flow) is another purpose-built tool that only does one thing. This package, as the name suggests, will give your flow enabled code autocomplete suggestions and nothing else. flow Visual Studio Code Visual Studio Code ================== ![Screenshot of Flow Language Support](https://flow.org/static/flow_for_vscode.gif) Support for Flow in [Visual Studio Code](https://code.visualstudio.com/) is provided by the [Flow Language Support](https://marketplace.visualstudio.com/items?itemName=flowtype.flow-for-vscode) extension. It provides all the functionality you would expect: * IntelliSense (Autocomplete) * Go to Definition / Peek Definition * Diagnostics (Errors, Warnings) * Hover type information * Toggleable code coverage reports Installation ------------ Search for “Flow Language Support” in the VS Code extensions panel or install through the [Marketplace](https://marketplace.visualstudio.com/items?itemName=flowtype.flow-for-vscode). flow Emacs Emacs ===== flow-for-emacs -------------- You can add support for Flow in Emacs by using [flow-for-emacs](https://github.com/flowtype/flow-for-emacs) Requirements ------------ * Requires Flow to be installed and available on your path. * Requires projects containing JavaScript files to be initialised with flow init. * Requires JavaScript files to be marked with /\* @flow \*/ at the top. Installation ------------ ``` cd ~/.emacs.d/ git clone https://github.com/flowtype/flow-for-emacs.git echo -e "\n(load-file \"~/.emacs.d/flow-for-emacs/flow.el\")" >> ~/.emacs ``` flow WebStorm WebStorm ======== Webstorm installation instructions can be found here: * [WebStorm 2016.3](https://www.jetbrains.com/help/webstorm/2016.3/using-the-flow-type-checker.html) * [WebStorm 2017.1](https://www.jetbrains.com/help/webstorm/2017.1/flow-type-checker.html) flow Sublime Text Sublime Text ============ Flow For Sublime Text 2 and 3 ----------------------------- [Sublime Text](https://www.sublimetext.com/) can be integrated with Flow by using [Package Control](https://packagecontrol.io) * Install the Package Control plugin if you don’t have it * Press Ctrl+Shift+P to bring up the Command Palette (or use Tools > Command Palette menu) * Select Package Control: Install Package * Type ‘Flow’ to find ‘Flow for Sublime Text 2 and 3’ * Select ‘Flow for Sublime Text 2 and 3’ to install SublimeLinter-flow ------------------ You may also wish to install a popular SublimeLinter plugin for Flow like [SublimeLinter-flow](https://packagecontrol.io/packages/SublimeLinter-flow). flow Vim Vim === Flow’s editor integration is primarily via the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/). There are [many vim LSP clients](https://microsoft.github.io/language-server-protocol/implementors/tools/) to choose from, such as [ALE](#toc-ale). ALE --- The Asynchronous Lint Engine (ALE) plugin for Vim 8+ and NeoVim, [vim-ale](https://github.com/w0rp/ale), is a generalized linting engine with support for Flow and many other tools. ### Installation Follow the [instructions](https://github.com/w0rp/ale#3-installation) in the ALE README. Configure ALE to use the `flow-language-server` linter for JavaScript files: ``` " In ~/.vim/ftplugin/javascript.vim, or somewhere similar. " Enables only Flow for JavaScript. See :ALEInfo for a list of other available " linters. NOTE: the `flow` linter uses an old API; prefer `flow-language-server`. let b:ale_linters = ['flow-language-server'] " Or in ~/.vim/vimrc: let g:ale_linters = { \ 'javascript': ['flow-language-server'], \} ``` coc.nvim-neovim --------------- [Coc](https://github.com/neoclide/coc.nvim) is an intellisense engine for vim8 & neovim. ### Setup ``` set nocompatible filetype off " install coc.nvim using Plug or preffered plugin manager call plug#begin('~/.vim/plugged') Plug 'neoclide/coc.nvim', {'branch': 'release'} call plug#end() filetype plugin indent on " ======= coc settings set updatetime=300 set shortmess+=c " Use leader T to show documentation in preview window nnoremap <leader>t :call <SID>show_documentation()<CR> function! s:show_documentation() if (index(['vim','help'], &filetype) >= 0) execute 'h '.expand('&lt;cword&gt;') else call CocAction('doHover') endif endfunction " instead of having ~/.vim/coc-settings.json let s:LSP_CONFIG = { \ 'flow': { \ 'command': exepath('flow'), \ 'args': ['lsp'], \ 'filetypes': ['javascript', 'javascriptreact'], \ 'initializationOptions': {}, \ 'requireRootPattern': 1, \ 'settings': {}, \ 'rootPatterns': ['.flowconfig'] \ } \} let s:languageservers = {} for [lsp, config] in items(s:LSP_CONFIG) let s:not_empty_cmd = !empty(get(config, 'command')) if s:not_empty_cmd | let s:languageservers[lsp] = config | endif endfor if !empty(s:languageservers) call coc#config('languageserver', s:languageservers) endif ``` LanguageClient-neovim --------------------- Another way to add support for Flow in Vim is to use [LanguageClient-neovim](https://github.com/autozimu/LanguageClient-neovim). * Suports vim 8 and neovim * Adds completions to omnifunc * Checks JavaScript files for type errors on save * Look up types under cursor ### Requirements * Requires Flow to be installed and available on your path. * Requires projects containing JavaScript files to be initialised with flow init. * Requires JavaScript files to be marked with /\* @flow \*/ at the top. ### Pathogen ``` cd ~/.vim/bundle git clone git://github.com/autozimu/LanguageClient-neovim.git ``` ### NeoBundle Add this to your ~/.vimrc ``` NeoBundleLazy 'autozimu/LanguageClient-neovim', { \ 'autoload': { \ 'filetypes': 'javascript' \ }} ``` With Flow build step, using flow-bin ``` NeoBundleLazy 'autozimu/LanguageClient-neovim', { \ 'autoload': { \ 'filetypes': 'javascript' \ }, \ 'build': { \ 'mac': 'npm install -g flow-bin', \ 'unix': 'npm install -g flow-bin' \ }} ``` ### VimPlug ``` Plug 'autozimu/LanguageClient-neovim', { \ 'branch': 'next', \ 'do': 'bash install.sh && npm install -g flow-bin', \ } ``` ### Setup ``` let g:LanguageClient_rootMarkers = { \ 'javascript': ['.flowconfig', 'package.json'] \ } let g:LanguageClient_serverCommands={ \ 'javascript': ['flow', 'lsp'], \ 'javascript.jsx': ['flow', 'lsp'] \} " check the type under cursor w/ leader T nnoremap <leader>t :call LanguageClient_textDocument_hover()<CR> nnoremap <leader>y :call LanguageClient_textDocument_definition()<CR> ``` flow Defining enums Defining enums ============== Learn how to define a Flow Enum. Looking for a quick overview? Check out the [Quickstart Guide](../index#toc-quickstart). An enum declaration is a statement. Its name defines both a value (from which to [access its members](../using-enums#toc-accessing-enum-members), and call its [methods](../using-enums#toc-methods)), and a type (which can be [used as an annotation](../using-enums#toc-using-as-a-type-annotation) for the type of its members). Enum members must all be of the same type, and those members can be one of four types: [string](#toc-string-enums), [number](#toc-number-enums), [boolean](#toc-boolean-enums), and [symbol](#toc-symbol-enums). Every enum has some common properties: ### Consistent member type The type of the enum members must be consistent. For example, you can’t mix `string` and `number` members in one enum. They must all be strings, numbers, or booleans (you do not provide values for `symbol` based enums). ### Member name starting character Member names must be valid identifiers (e.g. not start with numbers), and must not start with lowercase `a` through `z`. Names starting with those letters are reserved for enum [methods](../using-enums#toc-methods) (e.g. `Status.cast(...)`). This is not allowed: ``` // @flow enum Status { active, // Error: names can't start with lowercase 'a' through 'z' } ``` ### Unique member names Member names must be unique. This is not allowed: ``` // @flow enum Status { Active, Active, // Error: the name 'Active` was already used above } ``` ### Literal member values If you specify a value for an enum member, it must be a literal (string, number, or boolean), not a computed value. This is not allowed: ``` // @flow enum Status { Active = 1 + 2, // Error: the value must be a literal } ``` ### Unique member values Member values must be unique. This is not allowed: ``` enum Status { Active = 1, Paused = 1, // Error: the value has already been used above } ``` ### Fixed at declaration An enum is not extendable, so you can’t add new members after the fact while your code is running. At runtime, enum member values can’t change and the members can’t be deleted. In this way they act like a frozen object. String enums ------------ String enums are the default. If you don’t specify an `of` clause (e.g. `enum Status of number {}`, `enum Status of symbol {}`, etc.), and do not specify any values (e.g. `enum Status {Active = 1}`) then the definition will default to be a string enum. Unlike the other types of enums (e.g. number enums), you can either specify values for the enum members, or not specify values and allow them to be defaulted. If you don’t specify values for your enum members, they default to strings which are the same as the name of your members. ``` enum Status { Active, Paused, Off, } ``` Is the same as: ``` enum Status { Active = 'Active', Paused = 'Paused', Off = 'Off', } ``` You must consistently either specify the value for all members, or none of the members. This is not allowed: ``` // @flow enum Status { Active = 'active', Paused = 'paused', Off, // Error: you must specify a value for all members (or none of the members) } ``` Optionally, you can use an `of` clause: ``` enum Status of string { Active, Paused, Off, } ``` We infer the type of the enum based on its values if there is no `of` clause. Using an `of` clause will ensure that if you use incorrect values, the error message will always interpret it as an enum of that type. Number enums ------------ Number enums must have their values specified. You can specify a number enum like this: ``` enum Status { Active = 1, Paused = 2, Off = 3, } ``` Optionally, you can use an `of` clause: ``` enum Status of number { Active = 1, Paused = 2, Off = 3, } ``` We do not allow defaulting of number enums (unlike some other languages), because if a member from the middle of such an enum is added or removed, all subsequent member values would be changed. This can be unsafe (e.g. push safety, serialization, logging). Requiring the user to be explicit about the renumbering makes them think about the consequences of doing so. The value provided must be a number literal. (Note: there is no literal for negative numbers in JavaScript, they are the application of a unary `-` operation on a number literal.) We could expand allowed values in the future to include certain non-literals, if requests to do so arise. Boolean enums ------------- Boolean enums must have their values specified. Boolean enums can only have two members. You can specify a boolean enum like this: ``` enum Status { Active = true, Off = false, } ``` Optionally, you can use an `of` clause: ``` enum Status of boolean { Active = true, Off = false, } ``` Symbol enums ------------ Symbol enums can’t have their values specified. Each member is a new symbol, with the symbol description set to the name of the member. You must use the `of` clause with symbol enums, to distinguish them from string enums, which are the default when omitting values. You can specify a symbol enum like this: ``` enum Status of symbol { Active, Paused, Off, } ``` Flow Enums with Unknown Members ------------------------------- You can specify that your enum contains “unknown members” by adding a `...` to the end of the declaration: ``` enum Status { Active, Paused, Off, ... } ``` When this is used, Flow will always require a `default` when [switching over the enum](../using-enums#toc-exhaustive-checking-with-unknown-members), even if all known enum members are checked. The `default` checks for “unknown” members you haven’t explicitly listed. This feature is useful when an enum value crosses some boundary and the enum declaration on each side may have different memebers. For example, an enum definition which is used on both the client and the server: an enum member could be added, which would be immediately seen by the server, but could be sent to an outdated client which isn’t yet aware of the new member. One use case for this would be the JS output of [GraphQL Enums](https://graphql.org/learn/schema/#enumeration-types): Flow Enums with unknown members could be used instead of the added `'%future added value'` member. Enums at runtime ---------------- Enums exist as values at runtime. We use a [Babel transform](https://www.npmjs.com/package/babel-plugin-transform-flow-enums) to transform Flow Enum declarations into calls to the [enums runtime](https://www.npmjs.com/package/flow-enums-runtime) (read more in the [enabling enums documentation](../enabling-enums)). We use a runtime so all enums can share an implementation of the enum [methods](../using-enums#toc-methods). We use `Object.create(null)` for enums’ prototype (which has the enum methods), so properties in `Object.prototype` will not pollute enums. The only own properties of the enum object are the enum members. The members are non-enumerable (use the [`.members()` method](../using-enums#toc-members) for that). The entire enum object is frozen, so it cannot be modified. Style guide ----------- ### Naming enums We encourage you to define enum names in `PascalCase`, following the naming conventions of other types. All caps names (e.g. `STATUS`) are harder to read and discouraged. We encourage you to name enums in the singular. E.g. `Status`, not `Statuses`. Just like the type of `true` and `false` is `boolean`, not `booleans`. Don’t append `Enum` to the name (e.g. don’t name your enum `StatusEnum`). This is unnecessary, just like we don’t append `Class` to every class name, and `Type` to every type alias. ### Naming enum members We encourage you to define enum member names in `PascalCase`. All caps names (e.g. `ACTIVE`) are harder to read and discouraged. Additionally, since Flow enforces that these are constants, you don’t need to use the name to signal that intent to the programmer. See also: the rule about [enum member name starting characters](#toc-member-name-starting-character). ### Don’t create a separate type A Flow Enum, like a class, is both a type and a value. You don’t need to create a separate type alias, you can use the enum name. ### Use dot access for accessing members Prefer `Status.Active` vs. `const {Active} = Status; Active`. This makes it easier find uses of the enum with text search, and makes it clearer to the reader what enum is involved. Additionally, this is required for [switch statements involving enums](../using-enums#toc-exhaustively-checking-enums-with-a-switch). flow Using enums Using enums =========== * [Accessing enum members](#toc-accessing-enum-members) * [Using as a type annotation](#toc-using-as-a-type-annotation) * [Casting to representation type](#toc-casting-to-representation-type) * [Methods](#toc-methods) + [.cast](#toc-cast) + [.isValid](#toc-isvalid) + [.members](#toc-members) + [.getName](#toc-getname) * [Exhaustively checking enums with a `switch`](#toc-exhaustively-checking-enums-with-a-switch) * [Exhaustive checking with unknown members](#toc-exhaustive-checking-with-unknown-members) * [Mapping enums to other values](#toc-mapping-enums-to-other-values) * [Enums in a union](#toc-enums-in-a-union) * [Exporting enums](#toc-exporting-enums) * [Importing enums](#toc-importing-enums) * [Generic enums](#toc-generic-enums) * [When to not use enums](#toc-when-to-not-use-enums) Flow Enums are not a syntax for [union types](https://flow.org/en/types/unions/). They are their own type, and each member of a Flow Enum has the same type. Large union types can cause performance issues, as Flow has to consider each member as a separate type. With Flow Enums, no matter how large your enum is, Flow will always exhibit good performance as it only has one type to keep track of. We use the following enum in the examples below: ``` enum Status { Active, Paused, Off, } ``` Accessing enum members ---------------------- Access members with the dot syntax: ``` const status = Status.Active; ``` You can’t use computed access: ``` const x = "Active"; Status[x]; // Error: computed access on enums is not allowed ``` Using as a type annotation -------------------------- The enum declaration defines both a value (from which you can access the enum members and methods) and a type of the same name, which is the type of the enum members. ``` function calculateStatus(): Status { ... } const status: Status = calculateStatus(); ``` Casting to representation type ------------------------------ Enums do not implicitly coerce to their representation type or vice-versa. If you want to convert from the enum type to the representation type, you can use an explicit cast `(x: string)`: ``` const s: string = Status.Active; // Error: 'Status' is not compatible with 'string' const statusString: string = (Status.Active: string); ``` To convert from a nullable enum type to nullable string, you can do: ``` const maybeStatus: ?Status = ....; const maybeStatusString: ?string = maybeStatus && (maybeStatus: string); ``` If you want to convert from the representation type (e.g. `string`) to an enum type (if valid), check out the [cast method](#toc-cast). Methods ------- Enum declarations also define some helpful methods. Below, `TEnum` is the type of the enum (e.g. `Status`), and `TRepresentationType` is the type of the representation type for that enum (e.g. `string`). ### .cast Type: `cast(input: ?TRepresentationType): TEnum | void` The `cast` method allows you to safely convert a primitive value, like a `string`, to the enum type (if it is a valid value of the enum), and `undefined` otherwise. ``` const data: string = getData(); const maybeStatus: Status | void = Status.cast(data); if (maybeStatus != null) { const status: Status = maybeStatus; // do stuff with status } ``` Set a default value in one line with the `??` operator: ``` const status: Status = Status.cast(data) ?? Status.Off; ``` The type of the argument of `cast` depends on the type of enum. If it is a [string enum](../defining-enums#toc-string-enums), the type of the argument will be `string`. If it is a [number enum](../defining-enums#toc-number-enums), the type of the argument will be `number`, and so on. If you wish to cast a `mixed` value, first use a `typeof` refinement: ``` const data: mixed = ...; if (typeof data === 'string') { const maybeStatus: Status | void = Status.cast(data); } ``` `cast` uses `this` (representing the object of enum members), so if you want to pass the function itself as a value, you should use an arrow function. For example: ``` const strings: Array<string> = ...; // WRONG: const statuses: Array<?Status> = strings.map(Status.cast); const statuses: Array<?Status> = strings.map((input) => Status.cast(input)); // Correct ``` Runtime cost: For [mirrored string enums](../defining-enums#toc-string-enums) (e.g `enum E {A, B}`), as the member names are the same as the values, the runtime cost is constant - equivalent to calling `.hasOwnProperty`. For other enums, a `Map` is created on the first call, and subsequent calls simply call `.has` on the cached map. Thus the cost is amoritzed constant. ### .isValid Type: `isValid(input: ?TRepresentationType): boolean` The `isValid` method is like `cast`, but simply returns a boolean: `true` if the input supplied is a valid enum value, and `false` if it is not. ``` const data: string = getData(); const isStatus: boolean = Status.isValid(data); ``` `isValid` uses `this` (representing the object of enum members), so if you want to pass the function itself as a value, you should use an arrow function. For example: ``` const strings: Array<string> = ...; // WRONG: const statusStrings = strings.filter(Status.isValid); const statusStrings = strings.filter((input) => Status.isValid(input)); // Correct ``` Runtime cost: The same as described under `.cast` above. ### .members Type: `members(): Iterator<TEnum>` The `members` method returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#iterators) (that is iterable) of all the enum members. ``` const buttons = []; function getButtonForStatus(status: Status) { ... } for (const status of Status.members()) { buttons.push(getButtonForStatus(status)); } ``` The iteration order is guaranteed to be the same as the order of the members in the declaration. The enum is not enumerable or iterable itself (e.g. a for-in/for-of loop over the enum will not iterate over its members), you have to use the `.members()` method for that purpose. You can convert the iterable into an `Array` using: `Array.from(Status.members())`. You can make use of [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)’s second argument to map over the values at the same time you construct the array: e.g. `const buttonArray = Array.from(Status.members(), status => getButtonForStatus(status));`. ### .getName Type: `getName(value: TEnum): string` The `getName` method maps enum values to the string name of that value’s enum member. When using `number`/`boolean`/`symbol` enums, this can be useful for debugging and for generating internal CRUD UIs. For example: ``` enum Status { Active = 1, Paused = 2, Off = 3, } const status: Status = ...; console.log(Status.getName(status)); // Will print a string, either "Active", "Paused", or "Off" depending on the value. ``` Runtime cost: The same as described under `.cast` above. A single cached reverse map from enum value to enum name is used for `.cast`, `.isValid`, and `.getName`. The first call of any of those methods will create this cached map. Exhaustively checking enums with a `switch` ------------------------------------------- When checking an enum value in a `switch` statement, we enforce that you check against all possible enum members, and don’t include redundant cases. This helps ensure you consider all possibilities when writing code that uses enums. It especially helps with refactoring when adding or removing members, by pointing out the different places you need to update. ``` const status: Status = ...; switch (status) { // Good, all members checked case Status.Active: break; case Status.Paused: break; case Status.Off: break; } ``` You can use `default` to match all members not checked so far: ``` switch (status) { case Status.Active: break; default: // When `Status.Paused` or `Status.Off` break; } ``` You can check multiple enum members in one switch case: ``` switch (status) { case Status.Active: case Status.Paused: break; case Status.Off: break; } ``` You must match against all of the members of the enum (or supply a `default` case): ``` // Error: you haven't checked 'Status.Off' in the switch switch (status) { case Status.Active: break; case Status.Paused: break; } ``` You can’t repeat cases (as this would be dead code!): ``` switch (status) { case Status.Active: break; case Status.Paused: break; case Status.Off: break; case Status.Paused: // Error: you already checked for 'Status.Paused' break; } ``` A `default` case is redundant if you’ve already matched all cases: ``` switch (status) { case Status.Active: break; case Status.Paused: break; case Status.Off: break; default: // Error: you've already checked all cases, the 'default' is redundant break; } // The following is OK because the `default` covers the `Status.Off` case: switch (status) { case Status.Active: break; case Status.Paused: break; default: break; } ``` Except if you are switching over an enum with [unknown members](../defining-enums#toc-flow-enums-with-unknown-members). If you nest exhaustively checked switches inside exhaustively checked switches, and are returning from each branch, you must add a `break;` after the nested switch: ``` switch (status) { case Status.Active: return 1; case Status.Paused: return 2; case Status.Off: switch (otherStatus) { case Status.Active: return 1; case Status.Paused: return 2; case Status.Off: return 3; } break; } ``` Remember, you can add blocks to your switch cases. They are useful if you want to use local variables: ``` switch (status) { case Status.Active: { const x = f(); ... break; } case Status.Paused: { const x = g(); ... break; } case Status.Off: { const y = ...; ... break; } } ``` If you didn’t add blocks in this example, the two declarations of `const x` would conflict and result in an error. Enums are not checked exhaustively in `if` statements or other contexts other than `switch` statements. Exhaustive checking with unknown members ---------------------------------------- If your enum has [unknown members](../defining-enums#toc-flow-enums-with-unknown-members) (specified with the `...`), e.g. ``` enum Status { Active, Paused, Off, ... } ``` Then a `default` is always required when switching over the enum. The `default` checks for “unknown” members you haven’t explicitly listed. ``` switch (status) { case Status.Active: break; case Status.Paused: break; case Status.Off: break; default: // Checks for members not explicitly listed } ``` You can use the `require-explicit-enum-switch-cases` [Flow Lint](https://flow.org/en/linting/flowlint-comments/) to require that all known members are explicitly listed as cases. For example: ``` // flowlint-next-line require-explicit-enum-switch-cases:error switch (status) { case Status.Active: break; case Status.Paused: break; default: break; } ``` Will trigger an error (without the lint there would be no error): ``` Incomplete exhaustive check: the member `Off` of enum `Status` has not been considered in check of `status`. The default case does not check for the missing members as the `require-explicit-enum-switch-cases` lint has been enabled. ``` You can fix if by doing: ``` // flowlint-next-line require-explicit-enum-switch-cases:error switch (status) { case Status.Active: break; case Status.Paused: break; case Status.Off: // Added the missing `Status.Off` case break; default: break; } ``` The `require-explicit-enum-switch-cases` lint is not one to enable globally, but rather on a per-`switch` basis when you want the behavior. With normal enums, for each `switch` statement on it, you can either provide a `default` or not, and thus decide if you want to require each case explicitly listed or not. Similarly for Flow Enums with unknown members, you can also enable this lint on a per-switch basis. The lint works for switches of regular Flow Enum types as well. It in effect bans the usage of `default` in that `switch` statement, by requiring the explicit listing of all enum members as cases. Mapping enums to other values ----------------------------- There are a variety of reasons you may want to map an enum value to another value, e.g. a label, icon, element, and so on. With previous patterns, it was common to use object literals for this purpose, however with Flow Enums we prefer functions which contain a switch, which we can exhaustively check. Instead of: ``` const STATUS_ICON: {[Status]: string} = { [Status.Active]: 'green-checkmark', [Status.Paused]: 'grey-pause', [Status.Off]: 'red-x', }; const icon = STATUS_ICON[status]; ``` Which doesn’t actually guarantee that we are mapping each `Status` to some value, use: ``` function getStatusIcon(status: Status): string { switch (status) { case Status.Active: return 'green-checkmark'; case Status.Paused: return 'grey-pause'; case Status.Off: return 'red-x'; } } const icon = getStatusIcon(status); ``` In the future if you add or remove an enum member, Flow will tell you to update the switch as well so it’s always accurate. If you actually want a dictionary which is not exhaustive, you can use a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map): ``` const counts = new Map<Status, number>([ [Status.Active, 2], [Status.Off, 5], ]); const activeCount: Status | void = counts.get(Status.Active); ``` Flow Enums cannot be used as keys in object literals, as [explained later on this page](#toc-distinct-object-keys). Enums in a union ---------------- If your enum value is in a union (e.g. `?Status`), first refine to only the enum type: ``` const status: ?Status = ...; if (status != null) { (status: Status); // 'status' is refined to 'Status' at this point switch (status) { case Status.Active: break; case Status.Paused: break; case Status.Off: break; } } ``` If you want to refine *to* the enum value, you can use `typeof` with the representation type, for example: ``` const val: Status | number = ...; // 'Status' is a string enum if (typeof val === 'string') { (val: Status); // 'val' is refined to 'Status' at this point switch (val) { case Status.Active: break; case Status.Paused: break; case Status.Off: break; } } ``` Exporting enums --------------- An enum is a type and a value (like a class is). To export both the type and the value, export it like a you would a value: ``` export enum Status {} ``` Or, as the default export (note: you must always specify an enum name, `export default enum {}` is not allowed): ``` export default enum Status {} ``` Using CommonJS: ``` enum Status {} module.exports = Status; ``` To export **only** its type, but not the value, you can do: ``` enum Status_ {} export type Status = Status_; ``` Since `export type` introduces a new binding with that name, the enum and the exported type must have different names. Other functions within the file will still have access to the enum implementation. Importing enums --------------- If you have exported an enum like this: ``` // status.js export default enum Status { Active, Paused, Off, } ``` You can import it as both a value and a type like this: ``` import Status from 'status'; const x: Status /* used as type */ = Status.Active /* used as value */; ``` If you only need to use the type, you can import it as a type: ``` import type Status from 'status'; function printStatus(status: Status) { ... } ``` Using CommonJS: ``` const Status = require('status'); ``` Generic enums ------------- There is currently no way to specify a generic enum type, but there have been enough requests that it is something we will look into in the future. For some use cases of generic enums, you can currently ask users to supply functions which call the enum [methods](#toc-methods) instead (rather than passing in the enum itself), for example: ``` function castToEnumArray<TRepresentationType, TEnum>( f: TRepresentationType => TEnum, xs: Array<TRepresentationType>, ): Array<TEnum | void> { return xs.map(f); } castToEnumArray((input) => Status.cast(input), ["Active", "Paused", "Invalid"]); ``` When to not use enums --------------------- Enums are designed to cover many use cases and exhibit certain benefits. The design makes a variety of trade-offs to make this happen, and in certain situations, these trade-offs might not be right for you. In these cases, you can continue to use existing patterns to satisfy your use cases. ### Distinct object keys You can’t use enum members as distinct object keys. The following pattern works because the types of `LegacyStatus.Active` and `LegacyStatus.Off` are different. One has the type `'Active'` and one has the type `'Off'`. ``` const LegacyStatus = Object.freeze({ Active: 'Active', Paused: 'Paused', Off: 'Off', }); const o = { [LegacyStatus.Active]: "hi", [LegacyStatus.Off]: 1, }; const x: string = o[LegacyStatus.Active]; // OK const y: number = o[LegacyStatus.Off]; // OK const z: boolean = o[LegacyStatus.Active]; // Error - as expected ``` We can’t use the same pattern with enums. All enum members have the same type, the enum type, so Flow can’t track the relationship between keys and values. If you wish to map from an enum value to another value, you should use a [function with an exhaustively-checked switch instead](#toc-mapping-enums-to-other-values). ### Disjoint object unions A defining feature of enums is that unlike unions, each enum member does not form its own separate type. Every member has the same type, the enum type. This allows enum usage to be analyzed by Flow in a consistently fast way, however it means that in certain situations which require separate types, we can’t use enums. Consider the following union, following the [disjoint object union](https://flow.org/en/types/unions/#toc-disjoint-unions) pattern: ``` type Action = | {type: 'Upload', data: string} | {type: 'Delete', id: number}; ``` Each object type in the union has a single common field (`type`) which is used to distinguish which object type we are dealing with. We can’t use enum types for this field, because for this mechanism to work, the type of that field must be different in each member of the union, but enum members all have the same type. In the future, we might add the ability for enums to encapsulate additional data besides a key and a primitive value - this would allow us to replace disjoint object unions. ### Guaranteed inlining Flow Enums are designed to allow for inlining (e.g. [member values must be literals](../defining-enums#toc-literal-member-values), [enums are frozen](../defining-enums#toc-fixed-at-declaration)), however the inlining itself needs to be part of the build system (whatever you use) rather than Flow itself. While enum member access (e.g. `Status.Active`) can be inlined (other than [symbol enums](../defining-enums#toc-symbol-enums) which cannot be inlined due to the nature of symbols), usage of its methods (e.g. `Status.cast(x)`) cannot be inlined.
programming_docs
flow Migrating from legacy patterns Migrating from legacy patterns ============================== Learn how to migrate to Flow Enums from legacy JavaScript enum patterns like `Object.freeze`. First, learn how to [update the enum definition site](#toc-updating-definitions), and next learn how to [update files that import and use the enum](#toc-updating-usage). Updating definitions -------------------- ### Object.freeze If you are using `Object.freeze`, you can migrate to an enum if the values of the object are: * All the same primitive type, and that type is `boolean`, `string`, `number`, or `symbol`. * All literals. * Contain no duplicate values. Replace ``` const Status = Object.freeze({ Active: 1, Paused: 2, Off: 3, }); export type StatusType = $Values<typeof Status>; export default Status; ``` with ``` export default enum Status { Active = 1, Paused = 2, Off = 3, } ``` * Check to ensure that the key names do not start with lowercase ‘a’-‘z’ (disallowed in enums). If they do, you’ll need to rename the member names. * Remove any usage of `$Keys<...>` or `$Values<...>` on the enum type, these are no longer needed as a Flow Enum defines a type itself (its name). * Delete any type exports based on the enum, as you just need to export the Flow Enum. A Flow Enum acts as both a type and a value (like a class). Then, take a look at [how to update files that import and use the enum](#toc-updating-usage). ### keyMirror The `keyMirror` utility creates an object whose values are mirrors of its key names. You can replace `keyMirror` usage with a string based enum. Replace ``` import keyMirror from 'keyMirror'; const Status = keyMirror({ Active: null, Paused: null, Off: null, }); export type StatusType = $Keys<typeof Status>; export default Status; ``` with ``` export default enum Status { Active, Paused, Off, } ``` * Check to ensure that the key names do not start with lowercase ‘a’-‘z’ (disallowed in enums). If they do, you’ll need to rename the member names. * Remove any usage of `$Keys<...>` on the enum type, it’s no longer needed as a Flow Enum defines a type itself (its name). * Delete any type exports based on the enum, you just need to export the Flow Enum. A Flow Enum acts as both a type and a value (like a class). Then, take a look at [how to update files that import and use the enum](#toc-updating-usage). Updating usage -------------- ### Fix type imports Previous patterns required you to export (and then import) a type separate from the enum itself. Flow Enums are both types and values (like a class), so you just need to export the Flow Enum itself. Since there is now one export, you only need one import. Read more about [exporting enums](../using-enums#toc-exporting-enums) and [importing enums](../using-enums#toc-importing-enums). If you previously had: ``` const Status = Object.freeze({ Active: 1, Paused: 2, Off: 3, }); export type StatusType = $Values<typeof Status>; export default Status; ``` And you’ve replaced it with: ``` export default enum Status { Active = 1, Paused = 2, Off = 3, } ``` Then you need to fix the imports as well: #### If both type and value were imported For a user of the enum, if you previously imported both the type and the value, you can delete the type import and update annotations used. Change ``` import type {StatusType} from 'status'; import Status from 'status'; const myStatus: StatusType = Status.Active; ``` to ``` // Type import is deleted import Status from 'status'; const myStatus: Status = Status.Active; // Changed type annotation to just `Status` ``` #### If only the type was imported For a user of the enum, if you previously imported just the type, change the type import to a default import rather than a named import. Change ``` import type {StatusType} from 'status'; function isActive(status: StatusType) { ... } ``` to ``` // Remove the braces `{` `}` and changed the name - this is a default import now import type Status from 'status'; function isActive(status: Status) { ... } // Changed type annotation to just `Status` ``` ### Mapping enums to other values Sometimes you want to map from an enum value to some other value. Previously, we sometimes used object literals for this. With Flow Enums, use a function with a `switch` instead. The switch is [exhaustively checked](../using-enums#toc-exhaustively-checking-enums-with-a-switch), so Flow will ensure you update your mapping when you add or remove Flow Enum members. Replace this pattern ``` const STATUS_ICON: {[Status]: string} = { [Status.Active]: 'green-checkmark', [Status.Paused]: 'grey-pause', [Status.Off]: 'red-x', }; const icon = STATUS_ICON[status]; ``` with ``` function statusIcon(status: Status): string { switch (status) { case Status.Active: return 'green-checkmark'; case Status.Paused: return 'grey-pause'; case Status.Off: return 'red-x'; } } const icon = statusIcon(status); ``` Read more about [mapping enums to other values](../using-enums#toc-mapping-enums-to-other-values). ### Usage as the representation type (e.g. a string) You can’t use a Flow Enum directly as its representation type (e.g. a `string`). If you get Flow errors about using an enum as its representation type, first try to refactor your code so that it expects the enum type instead of the representation type (e.g. change annotations from `string` to `Status`). If you really want to use the enum as its representation type, you can add in explicit casts. See [casting to represetation type](../using-enums#toc-casting-to-representation-type). ### Casting to the enum type If before you cast from an enum’s representation type (e.g. `string`) to the enum type with something like this: ``` function castToStatus(input: number): StatusType | void { switch(input) { case 1: return Status.Active; case 2: return Status.Paused; case 3: return Status.Off; default: return undefined; } } castToStatus(x); ``` You can now just use the [cast](../using-enums#toc-cast) method: ``` Status.cast(x); ``` ### Update switch statements Flow Enums are exhaustively checked in `switch` statements. You might need to update your code when you are switching over an enum value. Read more at [exhaustively checking enums in switch statements](../using-enums#toc-exhaustively-checking-enums-with-a-switch). ### Operations over enum members If previously you used functionality like `Object.values`, `Object.keys`, or `for-in` loops to get and operate on the enum members, you can use the [members method](../using-enums#toc-members) instead. flow Enabling enums in your project Enabling enums in your project ============================== Upgrade tooling --------------- To enable Flow Enums in your repo, you must first update the following packages: * Upgrade to at least Flow 0.159 + Flow needs to have some configuration set to enable enums - see below. * Upgrade [Prettier](https://prettier.io/) to at least version 2.2 + As of that version, Prettier can handle parsing and pretty printing Flow Enums out of the box. + You must use the `flow` [parser option](https://prettier.io/docs/en/options.html#parser) for JavaScript files to be able to format Flow Enums. * Upgrade [Babel](https://babeljs.io/) to at least version 7.13.0 + As of that version, Babel can parse Flow Enums. However, to enable this parsing some configuration needs to be supplied, and additionally it does not include the transform required - see below. * Upgrade [jscodeshift](https://github.com/facebook/jscodeshift) to at least version 0.11.0 * Upgrade [hermes-parser](https://www.npmjs.com/package/hermes-parser) to at least version 0.4.8 * For ESLint, either: + Use [hermes-eslint](https://www.npmjs.com/package/hermes-eslint) as your ESLint parser, at least version 0.4.8 + Or upgrade [babel-eslint](https://github.com/babel/babel-eslint) to version 10.1.0 - As of that version, `babel-eslint` can handle Flow Enums out of the box. - Do not upgrade to 11.x, this branch does not support Flow Enums. + Or use another solution using Babel 7.13.0 or later, with Flow enabled - this may also work If you have any other tool which examines your code, you need to update it as well. If it uses [flow-parser](https://www.npmjs.com/package/flow-parser), [hermes-parser](https://www.npmjs.com/package/hermes-parser) or `@babel/parser`, upgrade those as per the instructions above. If it uses some other parser, you will need to implement parsing Flow Enums in that parser. You can look at the existing code in Babel, Flow, and Hermes parsers to guide your work. Enable enums ------------ * In your `.flowconfig`, under the `[options]` heading, add `enums=true` * Add the Flow Enums Babel transform. It turns enum declaration AST nodes into calls to the runtime: [babel-plugin-transform-flow-enums](https://www.npmjs.com/package/babel-plugin-transform-flow-enums). Add it to your development dependencies and adjust your Babel configuration to use the transform. The transform by default requires the runtime package directly (below), but you can configure this. * Add the Flow Enum runtime package to your production dependencies. This will be required and used at runtime to create Flow Enums: [flow-enums-runtime](https://www.npmjs.com/package/flow-enums-runtime) Enable suggested ESLint rules ----------------------------- Enums can be exhaustively checked in `switch` statements, so may increase the use of `switch` statements compared to before. To prevent common issues with `switch` statements, we suggest you enable these ESLint rules (at least as warnings): * [no-fallthrough](https://eslint.org/docs/rules/no-fallthrough): This prevents the user from accidentally forgetting a `break` statement at the end of their switch case, while supporting common use-cases. * [no-case-declarations](https://eslint.org/docs/rules/no-case-declarations): This prevents lexicaly scoped declarations (`let`, `const`) from being introduced in a switch case, without wrapping that case in a new block. Otherwise, declarations in different cases could conflict. We also have some Flow Enums specific rules as part of [eslint-plugin-fb-flow](https://www.npmjs.com/package/eslint-plugin-fb-flow): * [use-flow-enums](https://www.npmjs.com/package/eslint-plugin-fb-flow#use-flow-enums): Suggests that enum-like `Object.freeze` and `keyMirror` usage be turned into Flow Enums instead. * [flow-enums-default-if-possible](https://www.npmjs.com/package/eslint-plugin-fb-flow#flow-enums-default-if-possible): Auto-fixes string enums with specified values identical to the member names to defaulted enums. * [no-flow-enums-object-mapping](https://www.npmjs.com/package/eslint-plugin-fb-flow#no-flow-enums-object-mapping): Suggests using a function with a switch to map enum values to other values, instead of an object literal. flow Flow Coverage Flow Coverage ============= The coverage command provides a metric of the amount of checking that Flow has performed on each part of your code. A program with high Flow coverage should increase your confidence that Flow has detected any potential runtime errors. The determining factor for this is the presence of [`any`](../types/any) in the inferred type of each expression. An expression whose inferred type is `any` is considered *uncovered*, otherwise it is considered *covered*. To see why this metric was chosen for determining Flow’s effectiveness, consider the example ``` const one: any = 1; one(); ``` This code leads to a runtime type error, since we are attempting to perform a call on a number. Flow, however, does not flag an error here, because we have annotated variable `one` as `any`. Flow’s checking is effectively turned off whenever `any` is involved, so it will silently allow the call. The use of this *unsafe* type has rendered the type checker ineffective, and the coverage metric is here to surface this, by reporting all instances of `one` as uncovered. Design Space ------------ **Which types should be “covered”?** What was described above is a rather coarse grained way to determine coverage. One could imagine a criterion that flags expressions as uncovered if *any* part of their type includes `any`, for example `Array<any>`. While there is value in a metric like this, the “uncovered” part of the type will typically be uncovered through various operations on values of this type. For example, in the code ``` declare var arr: Array<any>; arr.forEach(x => {}); ``` the parameter `x` will be flagged as uncovered. Also, in practice, a strict criterion like this would be too noisy and rather expensive to compute on the fly. **Union types** An exception to this principle are union types: the type `number | any` is considered *uncovered*, even though technically `any` is not the top-level constructor. Unions merely encode an option among *a set of* other types. In that sense we are conservatively viewing an expression as uncovered, when at least one possible type of that expression causes limited checking. For example, in the code ``` let x: number | any = 1; x = "a"; ``` Flow will let you assign anything to `x`, which reduces confidence in the use of `x` as a number. Thus `x` is considered uncovered. **The empty type** An interesting type from a coverage perspective is the `empty` type. This type roughly corresponds to *dead code*. As such checking around expressions with type `empty` is more relaxed, but for a good reason: this code will not be executed at runtime. Since it is a common practice to clean up such code, Flow coverage will also report code whose type is inferred to be `empty`, but distinguishes it from the case of `any`. Command Line Use ---------------- To find out the coverage of a file foo.js with the following contents ``` // @flow function add(one: any, two: any): number { return one + two; } add(1, 2); ``` you can issue the following command ``` $ flow coverage file.js Covered: 50.00% (5 of 10 expressions) ``` This output means that 5 out of the 10 nodes of this program were inferred to have type `any`. To see exactly which parts are uncovered you can also pass one of the following flags: * `--color`: This will print foo.js on the terminal with the uncovered locations in red color. * `--json`: This will list out all location spans that are uncovered under the tag `"uncovered_locs"`. Finally, as an example of dead code, consider the code ``` function untypedAdd(one, two) { return one + two; } ``` Note that function `untypedAdd` is never called, so `one` and `two` will be inferred to have type `empty`. In the colored version of this command these parts appear in blue color, and in the JSON version they are under the tag `"empty_locs"`. **Use on multiple files** If you want to check coverage of multiple files at once, Flow offers the `batch-coverage` command: ``` $ flow batch-coverage dir/ ``` will report coverage statistics for each file under `dir/`, as well as aggregate results. Note that `batch-coverage` requires a non-lazy Flow server. flow Flow Annotate-Exports Flow Annotate-Exports ===================== Upgrading to [Types-First](https://flow.org/en/lang/types-first) mode may require a substantial number of type annotations at module boundaries. To help with the process of upgrading large codebases, we are providing a codemod command, whose goal is to fill in these missing annotations. This command is included in the Flow binary in versions `>= 0.125`. > Note: As of version 0.134, types-first is the default mode. If you are using a version `>=0.134`, make sure you set `types_first=false` in your .flowconfig while running this codemod. > > This command uses types that Flow infers, to fill in positions that would otherwise raise *signature-verification* failures. It will include the necessary type import statements, as long as the respective types are exported from their defining modules. It is designed for use on multiple files at once, rather than one file at a time. For this reason it doesn’t connect to an existing Flow server, but rather starts a checking process of its own. As is typical with such mechanized approaches, it comes with a few caveats: 1. It won’t be able to fill in every required type annotation. Some cases will require manual effort. 2. Inserted annotations may cause new flow errors, since it’s not always possible to match inferred type with types that can be written as annotations. 3. File formatting may be affected. If a code formatter (e.g. prettier) is used, it is recommended that you run it after the codemod has finished running. How to apply the codemod ------------------------ A typical way to invoke this command is ``` flow codemod annotate-exports \ --write \ --repeat \ --log-level info \ /path/to/folder \ 2> out.log ``` This command will transform files under `/path/to/folder`. This does not need to be the root directory (the one containing `.flowconfig`). It uses the following flags: * `--write` will update files that require annotations under `/path/to/folder` in-place. Without this flag the resulting files will be printed on the command line. * `--repeat` ensures that the transformation will be applied until no more files change. This mode is necessary here, because each new type the codemod adds may require new locations to be annotated. * `--log-level info` outputs useful debugging information in the standard error stream. This option might lead to verbose output, so we’re redirecting the error output to a log file `out.log`. Another convenient way to provide the input is by passing the flag ``` --input-file file.txt ``` where `file.txt` contains a specific list of files to be transformed. Codemod output -------------- After each iteration of the codemod, a summary will be printed on the CLI. This summary includes statistical information about the number of annotations that were added, and how many locations were skipped. It also prints counts for various kinds of errors that were encountered. These can be matched to the errors printed in the logs. A common error case is when a type `A`, defined in a file `a.js`, but not exported, is inferred in file `b.js`. The codemod will skip adding this annotation and report an error in the logs. The fix this case, you can export `A` in `a.js`. Note that it is not necessary to manually import `A` in `b.js`. The codemod will do this automatically. flow Lazy Modes Lazy Modes ========== By default, the Flow server will typecheck all your code. This way it can answer questions like “are there any Flow errors anywhere in my code”. This is very useful for tooling, like a continuous integration hook which prevents code changes which introduce Flow errors. However, sometimes a Flow user might not care about all the code. If they are editing a file `foo.js`, they might only want Flow to typecheck the subset of the repository needed to answer questions about `foo.js`. Since Flow would only check a smaller number of files, this would be faster. This is the motivation behind Flow’s lazy mode. Classifying Files ----------------- Lazy mode classifes your code into four categories: 1. **Focused files**. These are the files which the user cares about. 2. **Dependent files**. These are the files which depend on the focused files. Changes to the focused files might cause type errors in the dependent files. 3. **Dependency files**. These are the files which are needed in order to typecheck the focused or dependent files. 4. **Unchecked files**. All other files. Lazy mode will still find all the JavaScript files and parse them. But it won’t typecheck the unchecked files. Choosing Focused Files ---------------------- Focused files are all of the files that have changed in one of the following ways. Flow will focus files when they change on disk, using Flow’s built-in file watcher (“dfind”) or Watchman. So, all files that change while Flow is running will be focused. But what about files that change when Flow is not running? If you’re using Git or Mercurial, Flow will ask it for all of the files that have changed since the mergebase with “master” (the common ancestor of the current commit and the master branch). If you’re not using “master” (e.g. “main” instead), you can change this with the `file_watcher.mergebase_with` config. If you’re working from a clone, you might want to set this to “origin/master” (for Git), which will focus all files that have changed locally, even if you commit to your local “master” branch. The net result is that Flow will find the same errors in lazy mode as in a full check, so long as there are no errors upstream. For example, if your CI ensures that there are no errors in “master,” then it’s redundant for Flow to check all of the unchanged files for errors that can’t exist. Using Lazy Mode --------------- To enable lazy mode, set `lazy_mode=true` in the `.flowconfig`. To start a Flow server in lazy mode manually, run ``` flow server --lazy-mode true ``` Forcing Flow to Treat a File as Focused --------------------------------------- You can force Flow to treat one or more files as focused from the CLI. ``` flow force-recheck --focus ./path/to/A.js /path/to/B.js ```
programming_docs
flow Nominal & Structural Typing Nominal & Structural Typing =========================== An important attribute of every type system is whether they are structural or nominal, they can even be mixed within a single type system. So it’s important to know the difference. A type is something like a string, a boolean, an object, or a class. They have names and they have structures. Primitives like strings or booleans have a very simple structure and only go by one name. More complex types like object or classes have more complex structures. They each get their own name even if they sometimes have the same structure overall. A static type checker uses either the names or the structure of the types in order to compare them against other types. Checking against the name is nominal typing and checking against the structure is structural typing. ### Nominal typing Languages like C++, Java, and Swift have primarily nominal type systems. ``` class Foo { method(input: string) { /* ... */ } } class Bar { method(input: string) { /* ... */ } } let foo: Foo = new Bar(); // Error! ``` Here you can see a pseudo-example of a nominal type system erroring out when you’re trying to put a `Bar` where a `Foo` is required because they have different names. ### Structural typing Languages like OCaml, Haskell, and Elm have primarily structural type systems. ``` class Foo { method(input: string) { /* ... */ } } class Bar { method(input: string) { /* ... */ } } let foo: Foo = new Bar(); // Works! ``` Here you can see a pseudo-example of a structural type system passing when you’re trying to put a Bar where a `Foo` is required because their structure is exactly the same. But as soon as you change the shape it will start to cause errors. ``` class Foo { method(input: string) { /* ... */ } } class Bar { method(input: number) { /* ... */ } } let foo: Foo = new Bar(); // Error! ``` It can get a little bit more complicated than this. We’ve demonstrated both nominal and structure typing of classes, but there are also other complex types like objects and functions which can also be either nominal or structural. Even further, they can be different within the same type system (most of the languages listed before has features of both). For example, Flow uses structural typing for objects and functions, but nominal typing for classes. #### Functions are structurally typed When comparing a function type with a function it must have the same structure in order to be considered valid. ``` // @flow type FuncType = (input: string) => void; function func(input: string) { /* ... */ } let test: FuncType = func; // Works! ``` #### Objects are structurally typed When comparing an object type with an object it must have the same structure in order to be considered valid. ``` type ObjType = { property: string }; let obj = { property: "value" }; let test: ObjType = obj; ``` #### Classes are nominally typed When you have two classes with the same structure, they still are not considered equivalent because Flow uses nominal typing for classes. ``` // @flow class Foo { method(input: string) { /* ... */ } } class Bar { method(input: string) { /* ... */ } } let test: Foo = new Bar(); // Error! ``` If you wanted to use a class structurally you could do that using an interface: ``` interface Interface { method(value: string): void; }; class Foo { method(input: string) { /* ... */ } } class Bar { method(input: string) { /* ... */ } } let test1: Interface = new Foo(); // Okay. let test2: Interface = new Bar(); // Okay. ``` ### Mixing nominal and structural typing The design decision in Flow around mixing nominal and structural typing was chosen based on how objects, functions, and classes are already used in JavaScript. The JavaScript language is a bunch of object-oriented ideas and functional ideas mixed together. Developer’s usage of JavaScript tends to be mixed as well. Classes (or constructor functions) being the more object-oriented side and functions (as lambdas) and objects tend to be more on the functional side, developers use both simultaneously. When someone writes a class, they are declaring a *thing*. This thing might have the same structure as something else but they still serve different purposes. Imagine two component classes that both have `render()` methods, these components could still have totally different purposes, but in a structural type system they’d be considered exactly the same. Flow chooses what is natural for JavaScript, and should behave the way you expect it to. flow Width Subtyping Width Subtyping =============== It’s safe to use an object with “extra” properties in a position that is annotated with a specific set of properties. ``` // @flow function method(obj: { foo: string }) { // ... } method({ foo: "test", // Works! bar: 42 // Works! }); ``` Within `method`, we know that `obj` has at least a property `foo` and the property access expression `obj.foo` will have type `string`. This is a kind of subtyping commonly referred to as “width subtyping” because a type that is “wider” (i.e., has more properties) is a subtype of a narrower type. So in the following example, `obj2` is a *subtype* of `obj1`. ``` let obj1 = { foo: 'test' }; let obj2 = { foo: 'test', bar: 42 }; ``` However, it’s often useful to know that a property is definitely absent. ``` // @flow function method(obj: { foo: string } | { bar: number }) { if (obj.foo) { (obj.foo: string); // Error! } } ``` The above code has a type error because Flow would also allow the call expression `method({ foo: 1, bar: 2 })`, because `{ foo: number, bar: number }` is a subtype of `{ bar: number }`, one of the members of the parameter’s union type. For cases like this where it’s useful to assert the absence of a property, Flow provides a special syntax for [“exact” object types](https://flow.org/en/types/objects/#toc-exact-object-types). ``` // @flow function method(obj: {| foo: string |} | {| bar: number |}) { if (obj.foo) { (obj.foo: string); // Works! } } ``` [Exact object types](https://flow.org/en/types/objects/#toc-exact-object-types) disable width subtyping, and do not allow additional properties to exist. Using exact object types lets Flow know that no extra properties will exist at runtime, which allows [refinements](../refinements) to get more specific. ``` // @flow function method(obj: {| foo: string |} | {| bar: number |}) { if (obj.foo) { (obj.foo: string); // Works! } } ``` flow Type Variance Type Variance ============= Variance is a topic that comes up fairly often in type systems and can be a bit confusing the first time you hear it. Let’s walk through each form of variance. First we’ll setup a couple of classes that extend one another. ``` class Noun {} class City extends Noun {} class SanFrancisco extends City {} ``` We’ll use these classes to write a method that has each kind of variance. > **Note:** The `*variantOf` types below are not a part of Flow, they are being used to explain variance. > > ### Invariance ``` function method(value: InvariantOf<City>) {...} method(new Noun()); // error... method(new City()); // okay method(new SanFrancisco()); // error... ``` * Invariance *does not* accept **supertypes**. * Invariance *does not* accept **subtypes**. ### Covariance ``` function method(value: CovariantOf<City>) {...} method(new Noun()); // error... method(new City()); // okay method(new SanFrancisco()); // okay ``` * Covariance *does not* accept **supertypes**. * Covariance *does* accept **subtypes**. ### Contravariance ``` function method(value: ContravariantOf<City>) {...} method(new Noun()); // okay method(new City()); // okay method(new SanFrancisco()); // error... ``` * Contravariance *does* accept **supertypes**. * Contravariance *does not* accept **subtypes**. ### Bivariance ``` function method(value: BivariantOf<City>) {...} method(new Noun()); // okay method(new City()); // okay method(new SanFrancisco()); // okay ``` * Bivariance *does* accept **supertypes**. * Bivariance *does* accept **subtypes**. As a result of having weak dynamic typing, JavaScript doesn’t have any of these, you can use any type at any time. Variance in Classes ------------------- To get a sense of when and why the different kinds of variance matters, let’s talk about methods of subclasses and how they get type checked. We’ll quickly set up our `BaseClass` which will define just one method that accepts an input value with the type `City` and a returned output also with the type `City`. ``` class BaseClass { method(value: City): City { ... } } ``` Now, let’s walk through different definitions of `method()` in a couple different *subclasses*. ### Equally specific inputs and outputs — Good To start, we can define a SubClass that extends our BaseClass. Here you can see that the value and the return type are both City just like in BaseClass: ``` class SubClass extends BaseClass { method(value: City): City { ... } } ``` This is okay because if something else in your program is using `SubClass` as if it were a `BaseClass`, it would still be using a `City` and wouldn’t cause any issues. ### More specific outputs — Good Next, we’ll have a different `SubClass` that returns a more specific type: ``` class SubClass extends BaseClass { method(value: City): SanFrancisco { ... } } ``` This is also okay because if something is using `SubClass` as if it were a `BaseClass` they would still have access to the same interface as before because `SanFrancisco` is just a `City` with a little more information. ### Less specific outputs — Bad Next, we’ll have a different `SubClass` that returns a less specific type: ``` class SubClass extends BaseClass { method(value: City): Noun { ... } // ERROR!! } ``` In Flow this will cause an error because if you are expecting to get a return value of a `City`, you may be using something that doesn’t exist on `Noun`, which could easily cause an error at runtime. ### Less specific inputs — Good Next, we’ll have another SubClass that accepts a value of a less specific type. ``` class SubClass extends BaseClass { method(value: Noun): City { ... } } ``` This is perfectly fine because if we pass in a more specific type we’ll still have all the information we need to be compatible with `Noun`. ### More specific inputs — Bad Finally, we’ll have yet another `SubClass` that accepts a value of a more specific type. ``` class SubClass extends BaseClass { method(value: SanFrancisco): City { ... } // ERROR!! } ``` This is an error in Flow because if you are expecting a `SanFrancisco` and you get a `City` you could be using something that only exists on `SanFrancisco` which would cause an error at runtime. All of this is why Flow has contravariant inputs (accepts less specific types to be passed in), and covariant outputs (allows more specific types to be returned). flow Types-First Types-First =========== Flow checks codebases by processing each file separately in dependency order. After a file has been checked, a signature is extracted and stored in main memory, to be used for files that depend on it. Currently, the default mode (we’ll also refer to it as *classic* mode) builds these signatures by using the types inferred for the file’s exports. In the new *types-first* architecture, Flow relies on annotations available at the boundaries of files to build these signatures. The benefit of this new architecture is dual: 1. It dramatically improves *performance*, in particular when it comes to rechecks. Suppose we want Flow to check a file `foo.js`, for which it hasn’t checked its dependencies yet. Classic mode would need to check all dependencies and generate signatures from them first, before it could check `foo.js`. In types-first, Flow extracts the dependency signatures just by looking at the annotations around the exports. This process is mostly syntactic, and therefore much faster than full type inference. 2. It improves error *reliability*. Inferred types often become complicated, and may lead to errors being reported in downstream files, far away from their actual source. Type annotations at file boundaries of files can help localize such errors, and address them in the file that introduced them. The caveat of this new version is that it requires exported parts of the code to be annotated with types, or to be expressions whose type can be trivially inferred (for example numbers and strings). How to upgrade your codebase to Types-First ------------------------------------------- ### Upgrade Flow version Types-first mode is officially released with version 0.125, but has been available in *experimental* status as of version 0.102. If you are currently on an older Flow version, you’d have to first upgrade Flow. Using the latest Flow version is the best way to benefit from the performance benefits outlined above. ### Prepare your codebase for Types-First Types-first requires annotations at module boundaries in order to build type signature for files. If these annotations are missing, then a `signature-verification-failure` is raised, and the exported type for the respective part of the code will be `any`. To see what types are missing to make your codebase types-first ready, add the following line to the `[options]` section of the `.flowconfig` file: ``` well_formed_exports=true ``` Consider for example a file `foo.js` that exports a function call to `foo` ``` declare function foo<T>(x: T): T; module.exports = foo(1); ``` The return type of function calls is currently not trivially inferable (due to features like polymorphism, overloading etc.). Their result needs to be annotated and so you’d see the following error: ``` Cannot build a typed interface for this module. You should annotate the exports of this module with types. Cannot determine the type of this call expression. Please provide an annotation, e.g., by adding a type cast around this expression. (`signature-verification-failure`) 4│ module.exports = foo(1); ^^^^^^ ``` To resolve this, you can add an annotation like the following: ``` declare function foo<T>(x: T): T; module.exports = (foo(1): number); ``` > Note: As of version 0.134, types-first is the default mode. This mode automatically enables `well_formed_exports`, so you would see these errors without explicitly setting this flag. It is advisable to set `types_first=false` during this part of the upgrade. > > #### Seal your intermediate results As you make progress adding types to your codebase, you can include directories so that they don’t regress as new code gets committed, and until the entire project has well-formed exports. You can do this by adding lines like the following to your .flowconfig: ``` well_formed_exports.includes=<PROJECT_ROOT>/path/to/directory ``` > Warning: That this is a *substring* check, not a regular expression (for performance reasons). > > #### A codemod for large codebases Adding the necessary annotations to large codebases can be quite tedious. To ease this burden, we are providing a codemod based on Flow’s inference, that can be used to annotate multiple files in bulk. See [this tutorial](https://flow.org/en/cli/annotate-exports/) for more. ### Enable the types-first flag Once you have eliminated signature verification errors, you can turn on the types-first mode, by adding the following line to the `[options]` section of the `.flowconfig` file: ``` types_first=true ``` You can also pass `--types-first` to the `flow check` or `flow start` commands. The `well_formed_exports` flag from before is implied by `types_first`. Once this process is completed and types-first has been enabled, you can remove `well_formed_exports`. Unfortunately, it is not possible to enable types-first mode for part of your repo; this switch affects all files managed by the current `.flowconfig`. > Note: The above flags are available in versions of Flow `>=0.102` with the `experimental.` prefix (and prior to v0.128, it used `whitelist` in place of `includes`): > > > ``` > experimental.well_formed_exports=true > experimental.well_formed_exports.whitelist=<PROJECT_ROOT>/path/to/directory > experimental.types_first=true > ``` > > Note: If you are using a version where types-first is enabled by default (ie. `>=0.134`), make sure you set `types_first=false` in your .flowconfig while running the codemods. > > ### Deal with newly introduced errors Switching between classic and types-first mode may cause some new Flow errors, besides signature-verification failures that we mentioned earlier. These errors are due differences in the way types based on annotations are interpreted, compared to their respective inferred types. Below are some common error patterns and how to overcome them. #### Array tuples treated as regular arrays in exports In types-first, an array literal in an *export position* ``` module.exports = [e1, e2]; ``` is treated as having type `Array<t1 | t2>`, where `e1` and `e2` have types `t1` and `t2`, instead of the tuple type `[t1, t2]`. In classic mode, the inferred type encompassed both types at the same time. This might cause errors in importing files that expect for example to find type `t1` in the first position of the import. **Fix:** If a tuple type is expected, then the annotation `[t1, t2]` needs to be explicitly added on the export side. #### Indirect object assignments in exports Flow allows the code ``` function foo(): void {} foo.x = () => {}; foo.x.y = 2; module.exports = foo; ``` but in types-first the exported type will be ``` { (): void; x: () => void; } ``` In other words it won’t take into account the update on `y`. **Fix:** To include the update on `y` in the exported type, the export will need to be annotated with the type ``` { (): void; x: { (): void; y: number; }; }; ``` The same holds for more complex assignment patterns like ``` function foo(): void {} Object.assign(foo, { x: 1}); module.exports = foo; ``` where you’ll need to manually annotate the export with `{ (): void; x: number }`, or assignments preceding the function definition ``` foo.x = 1; function foo(): void {} module.exports = foo; ``` Note that in the last example, Flow types-first will pick up the static update if it was after the definition: ``` function foo(): void {} foo.x = 1; module.exports = foo; ``` ### Exported variables with updates The types-first signature extractor will not pick up subsequent update of an exported let-bound variables. Consider the example ``` let foo: number | string = 1; foo = "blah"; module.exports = foo; ``` In classic mode the exported type would be `string`. In types-first it will be `number | string`, so if downstream typing depends on the more precise type, then you might get some errors. **Fix:** Introduce a new variable on the update and export that one. For example ``` const foo1: number | string = 1; const foo2 = "blah"; module.exports = foo2; ``` flow Constrained Writes Constrained Writes ================== As of Flow v0.186.0, unannotated variables will be inferred to have a precise type by their initializer or initial assignment, and all subsequent assignments to that variable will be constrained by this type. This page shows some examples of how Flow determines what type an unannotated variable is inferred to have. **If you want a variable to have a different type than what Flow infers for it, you can always add a type annotation to the variable’s declaration. That will override everything discussed in this page!** Variables initialized at their declarations ------------------------------------------- The common case for unannotated variables is very straightforward: when a variable is declared with an initializer that is not the literal `null`, that variable will from then on have the type of the initializer, and future writes to the variable will be constrained by that type [(try flow)](https://flow.org/try/#0JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwBQdMAnmFnAArFjoC8cA3gB84YLgC44IYAA8sAEziCAvvTpysuADbJKcAG4640iQDsAriABGWKPXVadbA1DhNTF67bUbtu5yK5UCU4IblVNLHhRCDkzfDg+AFlkGAALADpUAEdYAAppAEo4AGpXegB6crgAA2jY-Gq4VLQ4ZlYa8ysbaroI+ABhEkgTLBN4Plz+aLAlYMCingA+AThKGDMoEzgAHkWpriVt8uWlOkqawfAIEbHG5vQ2rGrsPBh0y+HRmAAVFixtkLcRY9PpwLAREBfBI7D7XKH8dKI6aoJRwY5wM5VargrCQ25NFqPGovfDpACiEK+2xJb1hNx+fwBgUWwKAA): ``` let product = Math.sqrt(x) * y; // `product` has type `number` let Component = ({prop}: Props) => { return <>{prop}</> } // `Component` has type`React.ComponentType<Props>` let element = <Component {...props} /> // `element` has type `React.Element<React.ComponentType<Props>>` ``` Any subsequent assignments to `product`, `Component`, or `element` will be checked against the types that Flow infers for the initializers, and if conflicting types are assigned, Flow will signal an error [(try flow)](https://flow.org/try/#0JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwBQdMAnmFnAArFjoC8cA3gB84YLgC44IYAA8sAEziCAvvTpysuADbJKcAG4640iQDsAriABGWKPXVadbA1DhNTF67bUbtu5yK5UCU4IblVNLHhRCDkzfDg+AFlkGAALADpUAEdYAAppAEo4AGpXegB6crgAA2jY-Gq4VLQ4ZlYa8ysbaroI+ABhEkgTLBN4Plz+aLAlYMCingA+AThKGDMoEzgAHkWpriVt8uWlOkqawfAIEbHG5vQ2rGrsPBh0y+HRmAAVFixtkLcRY9PpwLAREBfBI7D7XKH8dKI6aoJRwY5wM5VargrCQ25NFqPGovfDpACiEK+2xJb1hNx+fwBgUWwIYRIA8mkbIDeAJhBAuVAAPrTCRSWQKZR2HyOfSGTmpGx0r4SXIK7nzBLLGnpAByMSw0ocfkMAsVwuREnVUB5DHO+pgbDSKTguVwG0oY00TCKMCgTAAtARNBAAO5wOQQLCoExkeDNPROxVwEbh6wJ4DQOAQAhwMwmZAmEwClLyOVQYDISwRVCYsEF6vyAA0cFQEDgwHgkejsfgqCwSejbBaNmIUFQ6TodTi4zgACJ2RsU1hw9P4sAJ4i5zQ0VUyVAx3RlWNoZMzTYRQcrYKeQtlvxVpENltdvxzxaDkcTjvzvvDzi8VnbZrWPeAEURd9L1CFE0UWH89wPaAgA): ``` product = "Our new product is..."; // Error Component = ({other_prop}: OtherProps) => { return <>{other_prop}</> }; // Error element = <OtherComponent {...other_props} />; // Error ``` If you want these examples to typecheck, and for Flow to realize that different kinds of values can be written to these variables, you must add a type annotation reflecting this more general type to their declarations [(try flow)](https://flow.org/try/#0JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwBQdMAnmFnAArFjoC8cA3gB84YLgC44IYAA8sAEziCAvvTpysuADbJKcAG4640iQDsAriABGWKPXVadbA1DhNTF67bUbtu5yK5UCU4IblVNLHhRCDkzfHcrG0U4VBgoYBMAczg+AFlkGAALADpUAEdYAAppAEo4AGpXcMi4AGESSBMsExgJKVkFPkr+aLAlYMC6ngA+AThKGDMoEzgAHmmRriVVgHpZpTodnbgAOQg4TIgYuGZWG-PKUSxUbvgi4FQAQkxntLjF3S4GJsDKpHByBgReBYCIgV4SbB4GDFM7qHJraa7WYMRgsNgAeSKNhC3HRQjgECJUAA+qM+jJ5IoVN4HH5DITCjZ2uAIF0ehJKhziZMcrNEfgUcC7D5HPpDJTOTTRkE4EKoCTUAxorF8OiAET4pZwLoAdwCMX+cA+xRtevo3M6r3RwwVNlpWwkao1U1m-HmkSWK3W-FdSq2WLgKjgdBhWDhPXRqzVDt5Tv4NuKofdoVQSjgexocCAA): ``` let product: number | string = ... let Component: mixed = ... // No good type to represent this! Consider restructuring let element: React.Node = ... ``` Variables declared without initializers --------------------------------------- Often variables are declared without initializers. In such cases, Flow will try to choose the “first” assignment or assignments to the variable to define its type. “First” here means both top-to-bottom and nearer-scope to deeper-scope—we’ll try to choose an assignment that happens in the same function scope as the variable’s declaration, and only look inside nested functions if we don’t find any assignments locally [(try flow)](https://flow.org/try/#0DYUwLgBGD2AOAyIBuJgEEDOGCWBzAdiACYDcAUGQGYCu+AxmNtPhABaqwgBOAFAJQQA3mQhQ4iFOix5CRCAF4IAFgBMJCAHoNEAKJcu0LhGwtqsOtAC2J3BBRcczCNEoQAYsGgB3AFwQABjAIyKiYOATE-mwAhhhQAJ6cARhgXDb+ZAC+FEESodIRcooARAASqJ4QXobARMXqWhAAKqzYcV5pYCAQRODc1oRxYOx20VwA5EOJIGS5IVLhsgpQXNQgDdp6BkYmEGYWA7b2jiwu7p6+AXOSYTKRMVNJ-ilp+Lj+QA). ``` let topLevelAssigned; function helper() { topLevelAssigned = 42; // Error: `topLevelAssigned` has type `string` } topLevelAssigned = "Hello world"; // This write determines the var's type topLevelAssigned = true; // Error: `topLevelAssigned` has type `string` ``` If there are two or more possible “first assignments,” due to an if or switch statement, they’ll both count—this is one of the few ways that Flow will still infer unions for variable types [(try flow)](https://flow.org/try/#0CYUwxgNghgTiAEA3W8wHsB2wCWAXbmAXPAEZpoQhQYDcAUHZbvALYCeAcgK4skgwB5GAGVcMbBgDm9OtgBm8ABToseAhgCU8AN514rTjz6CRYiZPgBeeABYATPQC+8EBADOCXfvbde-IaLiUlbwAEQAEq4QaPAA7mgwEMChTgw+Rv6mQRbWdgCMNPAA9EXwchIgdOl+JoHmIaEA4uTAJGwgKcWl5RiV1cYBZsHWclDuIIUl8ACiMDAJ8BLwXAAO6Cz1iPxu6vBoCgBi0bHEAAb9mXVSp-AAFlBu8LhsKwinGBkw8AA+8G5DklOQA): ``` let myNumberOrString; if (condition) { myNumberOrString = 42; // Determines type } else { myNumberOrString = "Hello world"; // Determines type } myNumberOrString = 21; // fine, compatible with type myNumberOrString = "Goodbye"; // fine, compatible with type myNumberOrString = false; // Error: `myNumberOrString` has type `number | string` ``` This only applies when the variable is written to in both branches, however. If only one branch contains a write, that write becomes the type of the variable afterwards (though Flow will still check to make sure that the variable is definitely initialized) [(try flow)](https://flow.org/try/#0CYUwxgNghgTiAEA3W8wHsB2wCWAXbmAXPAEZpoQhQYDcAUHZbvJiAEIzVgAWAggM79sAcwwhg9OtgBm8ABToseAhgCU8AN514LMRy59BIscHgBeeACIAEiAgQ08AO5oYEYAEJL9AL4NW+hg8AkKi4gB0uGgAqgAOsSAwAMJQ-CByqjTwAPTZ8ACiMDCuxAAGAZxBhqEmpfAAtlAAnqQIAK4Y2J34UBDYAF7idBUGIcbi5vAALABMWbkFRa7wXfBtsej1XcJIiUKYLLIAYg5OZSNVY2HAddyp8LhNCfCl-Lgw26VAA): ``` let oneBranchAssigned; if (condition) { oneBranchAssigned = "Hello world!"; } oneBranchAssigned.toUpperCase(); // Error: `oneBranchAssigned` may be uninitialized oneBranchAssigned = 42; // Error: `oneBranchAssigned` has type `string` ``` Variables initialized to `null` ------------------------------- Finally, the one exception to the general principle that variable’s types are determined by their first assignment(s) is when a variable is initialized as (or whose first assignment is) the literal value `null`. In such cases, the *next* non-null assignment (using the same rules as above) determines the rest of the variable’s type, and the overall type of the variable becomes a union of `null` and the type of the subsequent assignment. This supports the common pattern where a variable starts off as `null` before getting assigned by a value of some other type [(try flow)](https://flow.org/try/#0GYVwdgxgLglg9mABMGYAmBJAIgNQIYA2IApgDwAqAfABRozQBciA3gNoDWxAnkwM5QAnVAHMAuk3IBfAJQSWAKESICxKIhhp8BRAF5EYEAQIBuRAHoz6sDFiEYAL2JpEeXogAGBo+8XI4AxGoIBH5ETi4rRDpoaQUlJRhgQPDdHT0Acmx02OZfePVNQl0o+igOblFTC0QMMGBiAKgACzw1dw0td0QWtyguAAdiDy9tAB9Ech98yV8ZhKTqDqK0vRGcvMRmgTgAd31iPYBRAW2BagAiADk4RGIwQQjgfxqsAEJz6WNZ3wFVEAEkEsTPJJEA). ``` function findIDValue<T>(dict: {[key: string]: T}): T { let idVal = null; // initialized as `null` for (const key in dict) { if (key === 'ID') { idVal = dict[key]; // Infer that `idVal` has type `null | T` } } if (idVal === null) { throw new Error("No entry for ID!"); } return idVal; } ```
programming_docs
flow Subsets & Subtypes Subsets & Subtypes ================== What is a subtype? ------------------ A type like `number`, `boolean`, or `string` describes a set of possible values. A `number` describes every possible number, so a single number (such as `42`) would be a *subtype* of the `number` type. Conversely, `number` would be a *supertype* of the type `42`. If we want to know whether one type is the subtype of another, we need to look at all the possible values for both types and figure out if the other has a *subset* of the values. For example, if we had a `TypeA` which described the numbers 1 through 3, and a `TypeB` which described the numbers 1 through 5: `TypeA` would be considered a *subtype* of `TypeB`, because `TypeA` is a subset of `TypeB`. ``` type TypeA = 1 | 2 | 3; type TypeB = 1 | 2 | 3 | 4 | 5; ``` Consider a `TypeLetters` which described the strings: “A”, “B”, “C”, and a `TypeNumbers` which described the numbers: 1, 2, 3. Neither of them would be a subtype of the other, as they each contain a completely different set of values. ``` type TypeLetters = "A" | "B" | "C"; type TypeNumbers = 1 | 2 | 3; ``` Finally, if we had a `TypeA` which described the numbers 1 through 3, and a `TypeB` which described the numbers 3 through 5. Neither of them would be a subtype of the other. Even though they both have 3 and describe numbers, they each have some unique items. ``` type TypeA = 1 | 2 | 3; type TypeB = 3 | 4 | 5; ``` When are subtypes used? ----------------------- Most of the work that Flow does is comparing types against one another. For example, in order to know if you are calling a function correctly, Flow needs to compare the arguments you are passing with the parameters the function expects. This often means figuring out if the value you are passing in is a subtype of the value you are expecting. So if I write a function that expects the numbers 1 through 5, any subtype of that set will be acceptable. ``` // @flow function f(param: 1 | 2 | 3 | 4 | 5) { // ... } declare var oneOrTwo: 1 | 2; // Subset of the input parameters type. declare var fiveOrSix: 5 | 6; // Not a subset of the input parameters type. f(oneOrTwo); // Works! // $ExpectError f(fiveOrSix); // Error! ``` Subtypes of complex types ------------------------- Flow needs to compare more than just sets of primitive values, it also needs to be able to compare objects, functions, and every other type that appears in the language. ### Subtypes of objects You can start to compare two objects by their keys. If one object contains all the keys of another object, then it may be a subtype. For example, if we had an `ObjectA` which contained the key `foo`, and an `ObjectB` which contained the keys `foo` and `bar`. Then it’s possible that `ObjectB` is a subtype of `ObjectA`. ``` // @flow type ObjectA = { foo: string }; type ObjectB = { foo: string, bar: number }; let objectB: ObjectB = { foo: 'test', bar: 42 }; let objectA: ObjectA = objectB; // Works! ``` But we also need to compare the types of the values. If both objects had a key `foo` but one was a `number` and the other was a `string`, then one would not be the subtype of the other. ``` // @flow type ObjectA = { foo: string }; type ObjectB = { foo: number, bar: number }; let objectB: ObjectB = { foo: 1, bar: 2 }; // $ExpectError let objectA: ObjectA = objectB; // Error! ``` If these values on the object happen to be other objects, we would have to compare those against one another. We need to compare every value recursively until we can decide if we have a subtype or not. ### Subtypes of functions Subtyping rules for functions are more complicated. So far, we’ve seen that `A` is a subtype of `B` if `B` contains all possible values for `A`. For functions, it’s not clear how this relationship would apply. To simplify things, you can think of a function type `A` as being a subtype of a function type `B` if functions of type `A` can be used wherever a function of type `B` is expected. Let’s say we have a function type and a few functions. Which of the functions can be used safely in code that expects the given function type? ``` type FuncType = (1 | 2) => "A" | "B"; let f1: (1 | 2) => "A" | "B" | "C" = (x) => /* ... */ let f2: (1 | null) => "A" | "B" = (x) => /* ... */ let f3: (1 | 2 | 3) => "A" = (x) => /* ... */ ``` * `f1` can return a value that `FuncType` never does, so code that relies on `FuncType` might not be safe if `f1` is used. Its type is not a subtype of `FuncType`. * `f2` can’t handle all the argument values that `FuncType` does, so code that relies on `FuncType` can’t safely use `f2`. Its type is also not a subtype of `FuncType`. * `f3` can accept all the argument values that `FuncType` does, and only returns values that `FuncType` does, so its type is a subtype of `FuncType`. In general, the function subtyping rule is this: A function type `B` is a subtype of a function type `A` if and only if `B`’s inputs are a superset of `A`’s, and `B`’s outputs are a subset of `A`’s. The subtype must accept *at least* the same inputs as its parent, and must return *at most* the same outputs. The decision of which direction to apply the subtyping rule on inputs and outputs is governed by variance, which is the topic of the next section. flow Depth Subtyping Depth Subtyping =============== Assume we have two classes, which have a subtype relationship: ``` class Person { name: string } class Employee extends Person { department: string } ``` It’s valid to use an `Employee` instance where a `Person` instance is expected. ``` // @flow class Person { name: string } class Employee extends Person { department: string } var employee: Employee = new Employee; var person: Person = employee; // OK ``` However, it is not valid to use an object containing an `Employee` instance where an object containing a `Person` instance is expected. ``` // @flow class Person { name: string } class Employee extends Person { department: string } var employee: { who: Employee } = { who: new Employee }; // $ExpectError var person: { who: Person } = employee; // Error ``` This is an error because objects are mutable. The value referenced by the `employee` variable is the same as the value referenced by the `person` variable. ``` person.who = new Person; ``` If we write into the `who` property of the `person` object, we’ve also changed the value of `employee.who`, which is explicitly annotated to be an `Employee` instance. If we prevented any code from ever writing a new value to the object through the `person` variable, it would be safe to use the `employee` variable. Flow provides a syntax for this: ``` // @flow class Person { name: string } class Employee extends Person { department: string } var employee: { who: Employee } = { who: new Employee }; var person: { +who: Person } = employee; // OK // $ExpectError person.who = new Person; // Error! ``` The plus sign indicates that the `who` property is “covariant.” Using a covariant property allows us to use objects which have subtype-compatible values for that property. By default, object properties are invariant, which allow both reads and writes, but are more restrictive in the values they accept. Read more about [property variance](variance). flow Type Refinements Type Refinements ================ Refinements are a frequently used aspect of many type systems. They are so ingrained in the way that we program and even the way that we think you might not even notice them. In the code below, value can either be `"A"` or `"B"`. ``` // @flow function method(value: "A" | "B") { if (value === "A") { // value is "A" } } ``` Inside of the if block we know that value must be `"A"` because that’s the only time the if-statement will be truthy. The ability for a static type checker to be able to tell that the value inside the if statement must be `"A"` is known as a refinement. Next we’ll add an else block to our if statement. ``` // @flow function method(value: "A" | "B") { if (value === "A") { // value is "A" } else { // value is "B" } } ``` Inside of the else block we know that value must be `"B"` because it can only be `"A"` or `"B"` and we’ve removed `"A"` from the possibilities. You can expand this even further and keep refining possibilities away: ``` // @flow function method(value: "A" | "B" | "C" | "D") { if (value === "A") { // value is "A" } else if (value === "B") { // value is "B" } else if (value === "C") { // value is "C" } else { // value is "D" } } ``` Refinements can also come in other forms other than testing for equality: ``` // @flow function method(value: boolean | Array<string> | Event) { if (typeof value === "boolean") { // value is a boolean } else if (Array.isArray(value)) { // value is an Array } else if (value instanceof Event) { // value is an Event } } ``` Or you could refine on the shape of objects. ``` // @flow type A = { type: "A" }; type B = { type: "B" }; function method(value: A | B) { if (value.type === "A") { // value is A } else { // value is B } } ``` Which also applies to nested types within objects. ``` // @flow function method(value: { prop?: string }) { if (value.prop) { value.prop.charAt(0); } } ``` Refinement Invalidations ------------------------ It is also possible to invalidate refinements, for example: ``` // @flow function otherMethod() { /* ... */ } function method(value: { prop?: string }) { if (value.prop) { otherMethod(); // $ExpectError value.prop.charAt(0); } } ``` The reason for this is that we don’t know that `otherMethod()` hasn’t done something to our value. Imagine the following scenario: ``` // @flow var obj = { prop: "test" }; function otherMethod() { if (Math.random() > 0.5) { delete obj.prop; } } function method(value: { prop?: string }) { if (value.prop) { otherMethod(); // $ExpectError value.prop.charAt(0); } } method(obj); ``` Inside of `otherMethod()` we sometimes remove `prop`. Flow doesn’t know if the `if (value.prop)` check is still true, so it invalidates the refinement. There’s a straightforward way to get around this. Store the value before calling another method and use the stored value instead. This way you can prevent the refinement from invalidating. ``` // @flow function otherMethod() { /* ... */ } function method(value: { prop?: string }) { if (value.prop) { var prop = value.prop; otherMethod(); prop.charAt(0); } } ``` flow Types & Expressions Types & Expressions =================== In JavaScript there are many types of values: numbers, strings, booleans, functions, objects, and more. ``` (1234: number); ("hi": string); (true: boolean); ([1, 2]: Array<number>); ({ prop: "value" }: Object); (function method() {}: Function); ``` These values can be used in many different ways: ``` 1 + 2; "foo" + "bar"; !true; [1, 2].push(3); let value = obj.prop; obj.prop = "value"; method("value"); ``` All of these different expressions create a new type which is a result of the types of values and the operations run on them. ``` let num: number = 1 + 2; let str: string = "foo" + "bar"; ``` In Flow every value and expression has a type. Figuring out types statically ----------------------------- Flow needs a way to be able to figure out the type of every expression. But it can’t just run your code to figure it out, if it did it would be affected by any issues that your code has. For example, if you created an infinite loop Flow would wait for it to finish forever. Instead, Flow needs to be able to figure out the type of a value by analyzing it without running it (static analysis). It works its way through every known type and starts to figure out what all the expressions around them result in. For example, to figure out the result of the following expression, Flow needs to figure out what its values are first. ``` val1 + val2; ``` If the values are numbers, then the expression results in a number. If the values are strings, then the expression results in a string. There are a number of different possibilities here, so Flow must look up what the values are. If Flow is unable to figure out what the exact type is for each value, Flow must figure out what every possible value is and check to make sure that the code around it will still work with all of the possible types. Soundness and Completeness -------------------------- When you run your code, a single expression will only be run with a limited set of values. But still Flow checks *every* possible value. In this way Flow is checking too many things or *over-approximating* what will be valid code. By checking every possible value, Flow might catch errors that will not actually occur when the code is run. Flow does this in order to be *“sound”*. In type systems, ***soundness*** is the ability for a type checker to catch every single error that *might* happen at runtime. This comes at the cost of sometimes catching errors that will not actually happen at runtime. On the flip-side, ***completeness*** is the ability for a type checker to only ever catch errors that *would* happen at runtime. This comes at the cost of sometimes missing errors that will happen at runtime. In an ideal world, every type checker would be both sound *and* complete so that it catches *every* error that *will* happen at runtime. Flow tries to be as sound and complete as possible. But because JavaScript was not designed around a type system, Flow sometimes has to make a tradeoff. When this happens Flow tends to favor soundness over completeness, ensuring that code doesn’t have any bugs. Soundness is fine as long as Flow isn’t being too noisy and preventing you from being productive. Sometimes when soundness would get in your way too much, Flow will favor completeness instead. There’s only a handful of cases where Flow does this. Other type systems will favor completeness instead, only reporting real errors in favor of possibly missing errors. Unit/Integration testing is an extreme form of this approach. Often this comes at the cost of missing the errors that are the most complicated to find, leaving that part up to the developer. flow Children Children ======== React elements can have zero, one, or many children. Being able to type these children with Flow allows you to build expressive APIs with React children. Generally, the type you should first try when adding a type for the children of your React component is [`React.Node`](../types#toc-react-node). Like this: ``` import * as React from 'react'; type Props = { children?: React.Node, }; function MyComponent(props: Props) { return <div>{props.children}</div>; } ``` > **Note:** You need to use `import * as React from 'react'` here instead of `import React from 'react'` to get access to the [`React.Node`](../types#toc-react-node) type. We explain why that is in the [React Type Reference](../types). > > However, if you want to do anything more powerful with the React children API then you will need a strong intuition of how React handles children. Let us look at a couple of cases before continuing to help build that intuition. If you already have a strong intuition about how React children work then feel free to [skip to our examples demonstrating how to type various children patterns that commonly show up in React components](#examples). Our first case is an element with no children: ``` <MyComponent />; // which is the same as... React.createElement(MyComponent, {}); ``` If you pass in no children when creating an element of `MyComponent` then `props.children` will not be set. If you try to access `props.children`, it will be undefined. What happens when you have a single child? ``` <MyComponent>{42}</MyComponent>; // which is the same as... React.createElement(MyComponent, {}, 42); ``` If you pass in a single value then `props.children` will be *exactly* that single value. Here `props.children` will be the number 42. Importantly, `props.children` will not be an array! It will be *exactly* the number 42. What happens when you have multiple children? ``` <MyComponent>{1}{2}</MyComponent>; // which is the same as... React.createElement(MyComponent, {}, 1, 2); ``` Now, if you pass two values then `props.children` will be an array. Specifically in this case `props.children` will be `[1, 2]`. Multiple children may also look like: ``` <MyComponent>{'hello'} world</MyComponent>; // which is the same as... React.createElement(MyComponent, {}, 'hello', ' world'); ``` In which `props.children` would be the array `['hello', ' world']`. or: ``` <MyComponent>{'hello'} <strong>world</strong></MyComponent>; // which is the same as... React.createElement( MyComponent, {}, 'hello', ' ', React.createElement('strong', {}, 'world'), ); ``` In which `props.children` would be the array `['hello', ' ', <strong>world</strong>]`. Moving on to the next case. What happens if we have a single child, but that child is an array? ``` <MyComponent>{[1, 2]}</MyComponent>; // which is the same as... React.createElement(MyComponent, {}, [1, 2]); ``` This follows the same rule that when you pass in a single child then `props.children` will be *exactly* that value. Even though `[1, 2]` is an array it is a single value and so `props.children` will be *exactly* that value. That is to say `props.children` will be the array `[1, 2]` and not an array of arrays. This case happens often when you use `array.map()` such as in: ``` <MyComponent> {messages.map(message => <strong>{message}</strong>)} </MyComponent> // which is the same as... React.createElement( MyComponent, {}, messages.map(message => React.createElement('strong', {}, message)), ); ``` So a single array child is left alone, but what happens if we have multiple children that are arrays? ``` <MyComponent>{[1, 2]}{[3, 4]}</MyComponent>; // which is the same as... React.createElement(MyComponent, {}, [1, 2], [3, 4]); ``` Here `props.children` will be an array of arrays. Specifically `props.children` will be `[[1, 2], [3, 4]]`. The rule to remember with React children is that if you have no children then `props.children` will not be set, if you have one single child then `props.children` will be set to exactly that value, and if you have two or more children then `props.children` will be a new array of those values. > **Note:** Watch out for whitespace! Take the following: > > > ``` > <MyComponent>{42} </MyComponent> > ``` > This compiles to: `React.createElement(MyComponent, {}, 42, ' ')`. (With the spaces!) See how the spaces show up as part of the children? In this case `props.children` would be `[42, ' ']` and *not* the number 42. However, the following is fine: > > > ``` > <MyComponent> > {42} > </MyComponent> > ``` > It will compile to what you would expect: `React.createElement(MyComponent, {}, 42)`. > > Newlines and indentation after newlines are stripped, but watch out for whitespace when using a component with strict types around what children may be. > > > **Note:** Watch out for comments! Take the following: > > > ``` > <MyComponent> > // some comment... > {42} > </MyComponent> > ``` > This compiles to: `React.createElement(MyComponent, {}, '// some comment...', 42)`. See how the comment is included in the element’s children? In this case `props.children` would be `['// some comment...', 42]` which includes the comment. To write comments in JSX use the following syntax: > > > ``` > <MyComponent> > {/* some comment... */} > {42} > </MyComponent> > ``` > Now let's see how you would take this intuition and type the children of various React components. Only allowing a specific element type as children. -------------------------------------------------- Sometimes you only want a specific component as the children to your React component. This often happens when you are building a table component which needs specific column children components, or a tab bar which needs specific configuration for each tab. One such tab bar component that uses this pattern is React Native’s `<TabBarIOS>` component. [React Native’s `<TabBarIOS>` component](http://facebook.github.io/react-native/docs/tabbarios.html) only allows React element children and those elements *must* have a component type of `<TabBarIOS.Item>`. You are expected to use `<TabBarIOS>` like: ``` <TabBarIOS> <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item> <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item> <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item> </TabBarIOS> ``` You are not allowed to do the following when using `<TabBarIOS>`: ``` <TabBarIOS> <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item> <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item> <View>{/* ... */}</View> <SomeOtherComponent>{/* ... */}</SomeOtherComponent> <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item> </TabBarIOS> ``` See how we added `<View>` and `<SomeOtherComponent>` as children to `<TabBarIOS>`? This is not allowed and `<TabBarIOS>` will throw an error. How do we make sure Flow does not allow this pattern? ``` import * as React from 'react'; class TabBarIOSItem extends React.Component<{}> { // implementation... } type Props = { children: React.ChildrenArray<React.Element<typeof TabBarIOSItem>>, }; class TabBarIOS extends React.Component<Props> { static Item = TabBarIOSItem; // implementation... } <TabBarIOS> <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item> <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item> <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item> </TabBarIOS>; ``` We set the type of props to `React.ChildrenArray<React.Element<typeof TabBarIOSItem>>` which will guarantee that `<TabBarIOS>` must only have children that are `TabBarIOS.Item` React elements. Our [types reference](../types) has more information about both [`React.ChildrenArray<T>`](../types#toc-react-childrenarray) and [`React.Element<typeof Component>`](../types#toc-react-element). > **Note:** If you want methods like `map()` and `forEach()` or to handle a [`React.ChildrenArray<T>`](../types#toc-react-childrenarray) as a normal JavaScript array then React provides the [`React.Children` API](https://facebook.github.io/react/docs/react-api.html#react.children) to do just this. It has functions like `React.Children.toArray(props.children)` that you can use to treat your [`React.ChildrenArray<T>`](../types#toc-react-childrenarray) as a flat array. > > Enforcing that a component only gets a single child. ---------------------------------------------------- Sometimes you want to enforce that your component will *only* receive a single child. You could use [`React.Children.only()` function](https://facebook.github.io/react/docs/react-api.html#react.children.only) to enforce this constraint, but you could also enforce this in Flow. To do this, instead of wrapping the type for your children in [`React.ChildrenArray<T>`](../types#toc-react-childrenarray), specify a single element argument, like so: ``` import * as React from 'react'; type Props = { children: React.Element<any>, }; function MyComponent(props: Props) { // implementation... } // Not allowed! You must have children. <MyComponent />; // Not ok! We have multiple element children. <MyComponent> <div /> <div /> <div /> </MyComponent>; // This is ok. We have a single element child. <MyComponent> <div /> </MyComponent>; ``` Typing function children or other exotic children types. -------------------------------------------------------- React allows you to pass *any* value as the children of a React component. There are some creative uses of this capability such as using a function for children which could look like this: ``` <MyComponent> {data => ( <div>{data.foo}</div> )} </MyComponent> ``` `react-router` version 4 asks for a [function as the children to its `<Route>` component](https://reacttraining.com/react-router/core/api/Route/children-func). You would provide a function as the children to `react-router` like this: ``` <Route path={to}> {({ match }) => ( <li className={match ? 'active' : ''}> <Link to={to} {...rest}/> </li> )} </Route> ``` (Example adapted from the [`react-router` documentation](https://reacttraining.com/react-router/core/api/Route/children-func).) Here is how you would type the `<Route>` component in Flow: ``` import * as React from 'react'; type Props = { children: (data: { match: boolean }) => React.Node, path: string, // other props... }; class Route extends React.Component<Props> { // implementation... } <Route path={to}> {({ match }) => ( <li className={match ? 'active' : ''}> <Link to={to} {...rest}/> </li> )} </Route>; ``` The type for `children` is a function that takes in some object type and returns a [`React.Node`](../types#toc-react-node) which is the type for any value that can be rendered by React. A `children` function does not need to return [`React.Node`](../types#toc-react-node). It could return any type, but in this case `react-router` wants to render the result returned by the `children` function. This pattern is also not limited to function children. You could also pass in arbitrary object or class types. Using `React.Node` but without some primitive types like strings. ================================================================= [`React.Node`](../types#toc-react-node) is the general type for children, but sometimes you might want to use [`React.Node`](../types#toc-react-node) while excluding some primitives like strings and numbers. [The React Native `<View>` component](http://facebook.github.io/react-native/docs/view.html) does this, for example. [The React Native `<View>` component](http://facebook.github.io/react-native/docs/view.html) will allow any primitive value or any React element as its children. However, `<View>` does not allow strings or numbers as children! You could use [`React.Node`](../types#toc-react-node) as the children type for `<View>`, however [`React.Node`](../types#toc-react-node) includes strings which we don’t want for `<View>`. So we need to create our own type. ``` import * as React from 'react'; type ReactNodeWithoutStrings = React.ChildrenArray< | void | null | boolean | React.Element<any> >; type Props = { children?: ReactNodeWithoutStrings, // other props... }; class View extends React.Component<Props> { // implementation... } ``` [`React.ChildrenArray<T>`](../types#toc-react-childrenarray) is a type that models React nested array data structure for children. `ReactNodeWithoutStrings` uses [`React.ChildrenArray<T>`](../types#toc-react-childrenarray) to be an arbitrarily nested array of null, boolean, or React elements. [`React.Element<typeof Component>`](../types#toc-react-element) is the type of a React element like `<div/>` or `<MyComponent/>`. Notably elements are not the same as components! > **Note:** If you want methods like `map()` and `forEach()` or to handle a [`React.ChildrenArray<T>`](../types#toc-react-childrenarray) as a normal JavaScript array then React provides the [`React.Children` API](https://facebook.github.io/react/docs/react-api.html#react.children) to do just this. It has functions like `React.Children.toArray(props.children)` that you can use to treat your [`React.ChildrenArray<T>`](../types#toc-react-childrenarray) as a flat array. > >
programming_docs
flow Redux Redux ===== [Redux](http://redux.js.org) has three major parts that should be typed: * State * Actions * Reducers Typing Redux state ------------------ Typing your [state](http://redux.js.org/docs/introduction/ThreePrinciples.html#single-source-of-truth) object, works the same as typing any other object in Flow. ``` type State = { users: Array<{ id: string, name: string, age: number, phoneNumber: string, }>, activeUserID: string, // ... }; ``` We can use this type alias to make sure reducers work correctly. ### Typing Redux state immutability Redux state [is meant to be immutable](http://redux.js.org/docs/introduction/ThreePrinciples.html#state-is-read-only): creating a new state object instead of changing properties on a single object. You can enforce this in Flow by making every property effectively “read-only” using “covariant” properties throughout your state object. ``` type State = { +users: Array<{ +id: string, +name: string, +age: number, +phoneNumber: string, }>, +activeUserID: string, // ... }; ``` Now Flow will complain when you try to write to any of these properties. ``` // @flow type State = { +foo: string }; let state: State = { foo: "foo" }; state.foo = "bar"; // Error! ``` Typing Redux actions -------------------- The base type for Redux [actions](http://redux.js.org/docs/basics/Actions.html) is an object with a `type` property. ``` type Action = { +type: string, }; ``` But you’ll want to use more specific types for your actions using disjoint unions and each individual type of action. ``` type Action = | { type: "FOO", foo: number } | { type: "BAR", bar: boolean } | { type: "BAZ", baz: string }; ``` Using disjoint unions, Flow will be able to understand your reducers much better. ### Typing Redux action creators In order to type your Redux [action creators](http://redux.js.org/docs/basics/Actions.html#action-creators), you’ll want to split up your `Action` disjoint union into separate action types. ``` type FooAction = { type: "FOO", foo: number }; type BarAction = { type: "BAR", bar: boolean }; type Action = | FooAction | BarAction; ``` Then to type the action creator, just add a return type of the appropriate action. ``` // @flow type FooAction = { type: "FOO", foo: number }; type BarAction = { type: "BAR", bar: boolean }; type Action = | FooAction | BarAction; function foo(value: number): FooAction { return { type: "FOO", foo: value }; } function bar(value: boolean): BarAction { return { type: "BAR", bar: value }; } ``` ### Typing Redux thunk actions In order to type your Redux [thunk actions](http://redux.js.org/docs/advanced/AsyncActions.html#async-action-creators), you’ll add types for `ThunkAction` as a function `Dispatch`, and `GetState`. `GetState` is a function that returns an `Object`. `Dispatch` accepts a disjoint union of `Action`, `ThunkAction`, `PromiseAction` and `Array<Action>` and can return `any`. ``` type Dispatch = (action: Action | ThunkAction | PromiseAction) => any; type GetState = () => State; type ThunkAction = (dispatch: Dispatch, getState: GetState) => any; type PromiseAction = Promise<Action>; ``` Then to type a thunk action creator, add a return type of a `ThunkAction` to your action creator. ``` type Action = | { type: "FOO", foo: number } | { type: "BAR", bar: boolean }; type GetState = () => State; type PromiseAction = Promise<Action>; type ThunkAction = (dispatch: Dispatch, getState: GetState) => any; type Dispatch = (action: Action | ThunkAction | PromiseAction | Array<Action>) => any; function foo(): ThunkAction { return (dispatch, getState) => { const baz = getState().baz dispatch({ type: "BAR", bar: true }) doSomethingAsync(baz) .then(value => { dispatch({ type: "FOO", foo: value }) }) } } ``` Typing Redux reducers --------------------- [Reducers](http://redux.js.org/docs/basics/Reducers.html) take the state and actions that we’ve typed and pulls them together for one method. ``` function reducer(state: State, action: Action): State { // ... } ``` You can also validate that you have handled every single type of action by using the `empty` type in your `default` case. ``` // @flow type State = { +value: boolean }; type FooAction = { type: "FOO", foo: boolean }; type BarAction = { type: "BAR", bar: boolean }; type Action = FooAction | BarAction; function reducer(state: State, action: Action): State { switch (action.type) { case "FOO": return { ...state, value: action.foo }; case "BAR": return { ...state, value: action.bar }; default: (action: empty); return state; } } ``` Flow + Redux resources ---------------------- * [Using Redux with Flow](http://frantic.im/using-redux-with-flow) - Alex Kotliarskyi * [Redux and Flowtype](https://medium.com/@cdebotton/redux-and-flowtype-69ff1dd09036#.fsrm1amlk) - Christian de Botton flow Components Components ========== Adding Flow types to your React components is incredibly powerful. After typing your component, Flow will statically ensure that you are using the component in the way it was designed to be used. Early in React’s history the library provided [`PropTypes`](https://facebook.github.io/react/docs/typechecking-with-proptypes.html) which performed basic runtime checks. Flow is much more powerful as it can tell you when you are misusing a component without running your code. There are some Babel plugins which will generate `PropTypes` from Flow types such as [`babel-plugin-react-flow-props-to-prop-types`](https://github.com/thejameskyle/babel-plugin-react-flow-props-to-prop-types) if you want both static and runtime checks. Class Components ---------------- Before we show how to type a React class component with Flow, let us first show how you would write a React class component *without* Flow but with React’s prop types. You would extend `React.Component` and add a static `propTypes` property. ``` import React from 'react'; import PropTypes from 'prop-types'; class MyComponent extends React.Component { static propTypes = { foo: PropTypes.number.isRequired, bar: PropTypes.string, }; render() { return <div>{this.props.bar}</div>; } } ``` Now, let’s Flowify the component we just wrote: ``` import * as React from 'react'; type Props = { foo: number, bar?: string, }; class MyComponent extends React.Component<Props> { render() { this.props.doesNotExist; // Error! You did not define a `doesNotExist` prop. return <div>{this.props.bar}</div>; } } <MyComponent foo={42} />; ``` We removed our dependency on `prop-types` and added a Flow object type named `Props` with the same shape as the prop types but using Flow’s static type syntax. Then we passed our new `Props` type into `React.Component` as a type argument. Now if you try to use `<MyComponent>` with a string for `foo` instead of a number you will get an error. Now wherever we use `this.props` in our React component Flow will treat it as the `Props` type we defined. > **Note:** If you don’t need to use the `Props` type again you could also define it inline: `extends React.Component<{ foo: number, bar?: string }>`. > > > **Note:** We import `React` as a namespace here with `import * as React from 'react'` instead of as a default with `import React from 'react'`. When importing React as an ES module you may use either style, but importing as a namespace gives you access to React’s [utility types](../types). > > `React.Component<Props, State>` is a [generic type](https://flow.org/en/types/generics/) that takes two type arguments. Props and state. The second type argument, `State`, is optional. By default it is undefined so you can see in the example above we did not include `State`. We will learn more about state in the next section… ### Adding State To add a type for state to your React class component then create a new object type, in the example below we name it `State`, and pass it as the second type argument to `React.Component`. ``` import * as React from 'react'; type Props = { /* ... */ }; type State = { count: number, }; class MyComponent extends React.Component<Props, State> { state = { count: 0, }; componentDidMount() { setInterval(() => { this.setState(prevState => ({ count: prevState.count + 1, })); }, 1000); } render() { return <div>Count: {this.state.count}</div>; } } <MyComponent />; ``` In the example above we are using a [React `setState()` updater function](https://facebook.github.io/react/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous) but you could also pass a partial state object to `setState()`. > **Note:** If you don’t need to use the `State` type again you could also define it inline: `extends React.Component<{}, { count: number }>`. > > ### Using Default Props React supports the notion of `defaultProps` which you can think of as default function arguments. When you create an element and you did not include a prop with a default then React will substitute that prop with its corresponding value from `defaultProps`. Flow supports this notion as well. To type default props add a `static defaultProps` property to your class. ``` import * as React from 'react'; type Props = { foo: number, // foo is required. bar: string, // bar is required. }; class MyComponent extends React.Component<Props> { static defaultProps = { foo: 42, // ...but we have a default prop for foo. }; } // So we don't need to include foo. <MyComponent bar={"abc"} /> ``` Flow will infer the type of your default props from `static defaultProps` so you don’t have to add any type annotations to use default props. > **Note:** You don’t need to make `foo` nullable in your `Props` type. Flow will make sure that `foo` is optional if you have a default prop for `foo`. > > If you would like to add a type annotation to `defaultProps` you can define the type as ``` type DefaultProps = {| foo: number, |} ``` and spread that into the `Props` type: ``` type Props = { ...DefaultProps, bar: string, } ``` This way you avoid duplicating the properties that happen to have a default value. Stateless Functional Components ------------------------------- In addition to classes, React also supports stateless functional components. You type these components like you would type a function: ``` import * as React from 'react'; type Props = { foo: number, bar?: string, }; function MyComponent(props: Props) { props.doesNotExist; // Error! You did not define a `doesNotExist` prop. return <div>{props.bar}</div>; } <MyComponent foo={42} /> ``` ### Using Default Props for Functional Components React also supports default props on stateless functional components. Similarly to class components, default props for stateless functional components will work without any extra type annotations. ``` import * as React from 'react'; type Props = { foo: number, // foo is required. }; function MyComponent(props: Props) {} MyComponent.defaultProps = { foo: 42, // ...but we have a default prop for foo. }; // So we don't need to include foo. <MyComponent />; ``` > **Note:** You don’t need to make `foo` nullable in your `Props` type. Flow will make sure that `foo` is optional if you have a default prop for `foo`. > > flow Context Context ======= Flow can typecheck your React components that use the [context API](https://reactjs.org/docs/context.html) introduced in React 16.3. > **Note:** Typing context values requires Flow 0.70 or later. > > Flow will infer types from the way you use a context’s `{ Provider, Consumer }` pair: ``` import React from "react"; const Theme = React.createContext(); <Theme.Provider value="light" />; <Theme.Consumer>{value => value.toUpperCase()}</Theme.Consumer>; // Error! `value` is nullable. <Theme.Consumer> {value => value ? value.toUpperCase() // Valid: `value` is a string. : null } </Theme.Consumer>; ``` If your context has a default value, Flow will type your consumer component accordingly: ``` import React from "react"; const Theme = React.createContext("light"); <Theme.Consumer>{value => value.toUpperCase()}</Theme.Consumer>; // Valid: `value` is a non-nullable string. ``` To explicitly specify the type of a context value, pass a type parameter to `createContext`: ``` import React from "react"; const Theme = React.createContext<"light" | "dark">("light"); <Theme.Provider value="blue" />; // Error! "blue" is not one of the allowed values. ``` flow Higher-order Components Higher-order Components ======================= A popular pattern in React is the [higher-order component pattern](https://facebook.github.io/react/docs/higher-order-components.html), so it’s important that we can provide effective types for higher-order components in Flow. If you don’t already know what a higher-order component is then make sure to read the [React documentation on higher-order components](https://facebook.github.io/react/docs/higher-order-components.html) before continuing. In 0.89.0, we introduced [`React.AbstractComponent`](../types#toc-react-abstractcomponent), which gives you more expressive power when writing HOCs and library definitions. Let’s take a look at how you can type some example HOCs. The Trivial HOC --------------- Let’s start with the simplest HOC: ``` //@flow import * as React from 'react'; function trivialHOC<Config: {}>( Component: React.AbstractComponent<Config> ): React.AbstractComponent<Config> { return Component; } ``` This is a basic template for what your HOCs might look like. At runtime, this HOC doesn’t do anything at all. Let’s take a look at some more complex examples. Injecting Props --------------- A common use case for higher-order components is to inject a prop. The HOC automatically sets a prop and returns a component which no longer requires that prop. For example, consider a navigation prop, or in the case of [`react-redux` a `store` prop](https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options). How would one type this? To remove a prop from the config, we can take a component that includes the prop and return a component that does not. It’s best to construct these types using object type spread. ``` //@flow import * as React from 'react'; type InjectedProps = {| foo: number |} function injectProp<Config>( Component: React.AbstractComponent<{| ...Config, ...InjectedProps |}> ): React.AbstractComponent<Config> { return function WrapperComponent( props: Config, ) { return <Component {...props} foo={42} />; }; } class MyComponent extends React.Component<{| a: number, b: number, ...InjectedProps, |}> {} const MyEnhancedComponent = injectProp(MyComponent); // We don't need to pass in `foo` even though `MyComponent` requires it. <MyEnhancedComponent a={1} b={2} />; ``` Preserving the Instance Type of a Component ------------------------------------------- Recall that the instance type of a function component is `void`. Our example above wraps a component in a function, so the returned component has the instance type `void`. ``` //@flow import * as React from 'react'; type InjectedProps = {| foo: number |} function injectProp<Config>( Component: React.AbstractComponent<{| ...Config, ...InjectedProps |}> ): React.AbstractComponent<Config> { return function WrapperComponent( props: Config, ) { return <Component {...props} foo={42} />; }; } class MyComponent extends React.Component<{| a: number, b: number, ...InjectedProps, |}> {} const MyEnhancedComponent = injectProp(MyComponent); // If we create a ref object for the component, it will never be assigned // an instance of MyComponent! const ref = React.createRef<MyComponent>(); // Error, mixed is incompatible with MyComponent. <MyEnhancedComponent ref={ref} a={1} b={2} />; ``` We get this error message because `React.AbstractComponent<Config>` doesn’t set the `Instance` type parameter, so it is automatically set to `mixed`. If we wanted to preserve the instance type of the component, we can use [`React.forwardRef`](https://reactjs.org/docs/forwarding-refs.html): ``` //@flow import * as React from 'react'; type InjectedProps = {| foo: number |} function injectAndPreserveInstance<Config, Instance>( Component: React.AbstractComponent<{| ...Config, ...InjectedProps |}, Instance> ): React.AbstractComponent<Config, Instance> { return React.forwardRef<Config, Instance>((props, ref) => <Component ref={ref} foo={3} {...props} /> ); } class MyComponent extends React.Component<{ a: number, b: number, ...InjectedProps, }> {} const MyEnhancedComponent = injectAndPreserveInstance(MyComponent); const ref = React.createRef<MyComponent>(); // All good! The ref is forwarded. <MyEnhancedComponent ref={ref} a={1} b={2} />; ``` Exporting Wrapped Components ---------------------------- If you try to export a wrapped component, chances are that you’ll run into a missing annotation error: ``` //@flow import * as React from 'react'; function trivialHOC<Config: {}>( Component: React.AbstractComponent<Config>, ): React.AbstractComponent<Config> { return Component; } type DefaultProps = {| foo: number |}; type Props = {...DefaultProps, bar: number}; class MyComponent extends React.Component<Props> { static defaultProps: DefaultProps = {foo: 3}; } // Error, missing annotation for Config. const MyEnhancedComponent = trivialHOC(MyComponent); module.exports = MyEnhancedComponent; ``` If your component has no `defaultProps`, you can use `Props` as a type argument for `Config`. If your component does have `defaultProps`, you don’t want to just add `Props` as a type argument to `trivialHOC` because that will get rid of the `defaultProps` information that flow has about your component. This is where [`React.Config<Props, DefaultProps>`](../types#toc-react-config) comes in handy! We can use the type for Props and DefaultProps to calculate the `Config` type for our component. ``` //@flow import * as React from 'react'; function trivialHOC<Config: {}>( Component: React.AbstractComponent<Config>, ): React.AbstractComponent<Config> { return Component; } type DefaultProps = {| foo: number |}; type Props = {...DefaultProps, bar: number}; class MyComponent extends React.Component<Props> { static defaultProps: DefaultProps = {foo: 3}; } const MyEnhancedComponent = trivialHOC<React.Config<Props, DefaultProps>>(MyComponent); // Ok! module.exports = MyEnhancedComponent; ``` flow ref functions ref functions ============= React allows you to grab the instance of an element or component with [`ref` functions](https://facebook.github.io/react/docs/refs-and-the-dom.html). To use a ref function add a [maybe instance type](https://flow.org/en/types/maybe/) to your class and assign your instance to that property in your ref function. ``` import * as React from 'react'; class MyComponent extends React.Component<{}> { // The `?` here is important because you may not always have the instance. button: ?HTMLButtonElement; render() { return <button ref={button => (this.button = button)}>Toggle</button>; } } ``` The `?` in `?HTMLButtonElement` is important. In the example above the first argument to `ref` will be `HTMLButtonElement | null` as React will [call your `ref` callback with null](https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element) when the component unmounts. Also, the `button` property on `MyComponent` will not be set until React has finished rendering. Until then your `button` ref will be undefined. Protect yourself against these cases and use a `?` (like in `?HTMLButtonElement`) to protect yourself from bugs.
programming_docs
flow Type Reference Type Reference ============== React exports a handful of utility types that may be useful to you when typing advanced React patterns. In previous sections we have seen a few of them. The following is a complete reference for each of these types along with some examples for how/where to use them. Table of contents: * [`React.Node`](#toc-react-node) * [`React.Element<typeof Component>`](#toc-react-element) * [`React.ChildrenArray<T>`](#toc-react-childrenarray) * [`React.AbstractComponent<Config, Instance>`](#toc-react-abstractcomponent) * [`React.ComponentType<Props>`](#toc-react-componenttype) * [`React.StatelessFunctionalComponent<Props>`](#toc-react-statelessfunctionalcomponent) * [`React.ElementType`](#toc-react-elementtype) * [`React.Key`](#toc-react-key) * [`React.Ref<typeof Component>`](#toc-react-ref) * [`React.ElementProps<typeof Component>`](#toc-react-elementprops) * [`React.ElementConfig<typeof Component>`](#toc-react-elementconfig) * [`React.ElementRef<typeof Component>`](#toc-react-elementref) * [`React.Config<Props, DefaultProps>`](#toc-react-config) These types are all exported as named type exports from the `react` module. If you want to access them as members on the `React` object (e.g. [`React.Node`](#toc-react-node) or [`React.StatelessFunctionalComponent`](#toc-react-statelessfunctionalcomponent)) and you are importing React as an ES module then you should import `React` as a namespace: ``` import * as React from 'react'; ``` If you are using CommonJS you can also require React: ``` const React = require('react'); ``` You can also use named type imports in either an ES module environment or a CommonJS environment: ``` import type {Node} from 'react'; ``` We will refer to all the types in the following reference as if we imported them with: ``` import * as React from 'react'; ``` > **Note:** While importing React with a default import works: > > > ``` > import React from 'react'; > ``` > You will have access to all of the values that React exports, but you will **not** have access to the types documented below! This is because Flow will not add types to a default export since the default export could be any value (like a number). Flow will add exported named types to an ES namespace object which you can get with `import * as React from 'react'` since Flow knows if you export a value with the same name as an exported type. > > Again, if you import React with: `import React from 'react'` you will be able to access `React.Component`, `React.createElement()`, `React.Children`, and other JavaScript *values*. However, you will not be able to access [`React.Node`](#toc-react-node), [`React.ChildrenArray`](#toc-react-childrenarray) or other Flow *types*. You will need to use a named type import like: `import type {Node} from 'react'` in addition to your default import. > > `React.Node` ------------- This represents any node that can be rendered in a React application. `React.Node` can be null, a boolean, a number, a string, a React element, or an array of any of those types recursively. If you need a return type for your component `render()` methods then you should use `React.Node`. However, if you need a generic type for a children prop, use `?React.Node`; children can be undefined, when `render()` can’t return `undefined`. Here is an example of `React.Node` being used as the return type to `render()`: ``` class MyComponent extends React.Component<{}> { render(): React.Node { // ... } } ``` It may also be used as the return type of a stateless functional component: ``` function MyComponent(props: {}): React.Node { // ... } ``` You don’t need to annotate the return type of either your `render()` method or a stateless functional component. However, if you want to annotate the return type then `React.Node` is the generic to use. Here is an example of `React.Node` as the prop type for children: ``` function MyComponent({ children }: { children: React.Node }) { return <div>{children}</div>; } ``` All `react-dom` JSX intrinsics have `React.Node` as their children type. `<div>`, `<span>`, and all the rest. The definition of `React.Node` can be roughly approximated with a [`React.ChildrenArray<T>`](#toc-react-childrenarray): ``` type Node = React.ChildrenArray<void | null | boolean | string | number | React.Element<any>>; ``` `React.Element<typeof Component>` ---------------------------------- A React element is the type for the value of a JSX element: ``` const element: React.Element<'div'> = <div />; ``` `React.Element<typeof Component>` is also the return type of `React.createElement()`. A `React.Element<typeof Component>` takes a single type argument, `typeof Component`. `typeof Component` is the component type of the React element. For an intrinsic element, `typeof Component` will be the string literal for the intrinsic you used. Here are a few examples with DOM intrinsics: ``` (<div />: React.Element<'div'>); // OK (<span />: React.Element<'span'>); // OK (<div />: React.Element<'span'>); // Error: div is not a span. ``` `typeof Component` can also be your React class component or stateless functional component. ``` class Foo extends React.Component<{}> {} function Bar(props: {}) {} (<Foo />: React.Element<typeof Foo>); // OK (<Bar />: React.Element<typeof Bar>); // OK (<Foo />: React.Element<typeof Bar>); // Error: Foo is not Bar ``` Take note of the `typeof`, it is required! `Foo` without `typeof` would be the type of an instance of `Foo`. So: `(new Foo(): Foo)`. We want the type *of* `Foo` not the type of an instance of `Foo`. So: `(Foo: typeof Foo)`. `Class<Foo>` would also work here, but we prefer `typeof` for consistency with stateless functional components. We also need `typeof` for `Bar` because `Bar` is a value. So we want to get the type *of* the value `Bar`. `(Bar: Bar)` is an error because `Bar` cannot be used as a type, so the following is correct: `(Bar: typeof Bar)`. `React.ChildrenArray<T>` ------------------------- A React children array can be a single value or an array nested to any level. It is designed to be used with the [`React.Children` API](https://reactjs.org/docs/react-api.html#reactchildren). For example if you want to get a normal JavaScript array from a `React.ChildrenArray<T>` see the following example: ``` import * as React from 'react'; // A children array can be a single value... const children: React.ChildrenArray<number> = 42; // ...or an arbitrarily nested array. const children: React.ChildrenArray<number> = [[1, 2], 3, [4, 5]]; // Using the `React.Children` API can flatten the array. const array: Array<number> = React.Children.toArray(children); ``` `React.AbstractComponent<Config, Instance>` -------------------------------------------- `React.AbstractComponent<Config, Instance>` (v0.89.0+) represents a component with a config of type Config and instance of type Instance. Instance is optional and is mixed by default. A class or function component with config `Config` may be used in places that expect `React.AbstractComponent<Config>`. This is Flow’s most abstract representation of a React component, and is most useful for writing HOCs and library definitions. `React.ComponentType<Props>` ----------------------------- This is a union of a class component or a stateless functional component. This is the type you want to use for functions that receive or return React components such as higher-order components or other utilities. Here is how you may use `React.ComponentType<Props>` with [`React.Element<typeof Component>`](#toc-react-element) to construct a component with a specific set of props: ``` type Props = { foo: number, bar: number, }; function createMyElement<C: React.ComponentType<Props>>( Component: C, ): React.Element<C> { return <Component foo={1} bar={2} />; } ``` `React.ComponentType<Props>` does not include intrinsic JSX element types like `div` or `span`. See [`React.ElementType`](#toc-react-elementtype) if you also want to include JSX intrinsics. The definition for `React.ComponentType<Props>` is roughly: ``` type ComponentType<Props> = | React.StatelessFunctionalComponent<Props> | Class<React.Component<Props, any>>; ``` > **Note:** In 0.89.0+, React.ComponentType is an alias for React.AbstractComponent<Config, any>, which represents a component with config type Config and any instance type. > > `React.StatelessFunctionalComponent<Props>` -------------------------------------------- This is the type of a React stateless functional component. The definition for `React.StatelessFunctionalComponent<Props>` is roughly: ``` type StatelessFunctionalComponent<Props> = (props: Props) => React.Node; ``` There is a little bit more to the definition of `React.StatelessFunctionalComponent<Props>` for context and props. `React.ElementType` -------------------- Similar to [`React.ComponentType<Props>`](#toc-react-componenttype) except it also includes JSX intrinsics (strings). The definition for `React.ElementType` is roughly: ``` type ElementType = | string | React.ComponentType<any>; ``` `React.MixedElement` --------------------- The most general type of all React elements (similar to `mixed` for all values). `React.MixedElement` is defined as `React.Element<React.ElementType>`. A common use case of this type is when we want to annotate an element with a type that hides the element details. For example ``` const element: React.MixedElement = <div />; ``` `React.Key` ------------ The type of the key prop on React elements. It is a union of strings and numbers defined as: ``` type Key = string | number; ``` `React.Ref<typeof Component>` ------------------------------ The type of the [ref prop on React elements](https://facebook.github.io/react/docs/refs-and-the-dom.html). `React.Ref<typeof Component>` could be a string or a ref function. The ref function will take one and only argument which will be the element instance which is retrieved using [`React.ElementRef<typeof Component>`](#toc-react-elementref) or null since [React will pass null into a ref function when unmounting](https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element). Like [`React.Element<typeof Component>`](#toc-react-element), `typeof Component` must be the type *of* a React component so you need to use `typeof` as in `React.Ref<typeof MyComponent>`. The definition for `React.Ref<typeof Component>` is roughly: ``` type Ref<C> = | string | (instance: React.ElementRef<C> | null) => mixed; ``` `React.ElementProps<typeof Component>` --------------------------------------- Gets the props for a React element type, *without* preserving the optionality of `defaultProps`. `typeof Component` could be the type of a React class component, a stateless functional component, or a JSX intrinsic string. This type is used for the `props` property on [`React.Element<typeof Component>`](#toc-react-element). Like [`React.Element<typeof Component>`](#toc-react-element), `typeof Component` must be the type *of* a React component so you need to use `typeof` as in `React.ElementProps<typeof MyComponent>`. > **Note:** Because [`React.ElementProps`](#toc-react-elementprops) does not preserve the optionality of `defaultProps`, [`React.ElementConfig`](#toc-react-elementconfig) (which does) is more often the right choice, especially for simple props pass-through as with [higher-order components](../hoc#toc-supporting-defaultprops-with-react-elementconfig). > > `React.ElementConfig<typeof Component>` ---------------------------------------- Like `React.ElementProps<typeof Component>` this utility gets the type of a component’s props but *preserves* the optionality of `defaultProps`! For example, ``` import * as React from 'react'; class MyComponent extends React.Component<{foo: number}> { static defaultProps = {foo: 42}; render() { return this.props.foo; } } // `React.ElementProps<>` requires `foo` even though it has a `defaultProp`. ({foo: 42}: React.ElementProps<typeof MyComponent>); // `React.ElementConfig<>` does not require `foo` since it has a `defaultProp`. ({}: React.ElementConfig<typeof MyComponent>); ``` Like [`React.Element<typeof Component>`](#toc-react-element), `typeof Component` must be the type *of* a React component so you need to use `typeof` as in `React.ElementProps<typeof MyComponent>`. `React.ElementRef<typeof Component>` ------------------------------------- Gets the instance type for a React element. The instance will be different for various component types: * React class components will be the class instance. So if you had `class Foo extends React.Component<{}> {}` and used `React.ElementRef<typeof Foo>` then the type would be the instance of `Foo`. * React stateless functional components do not have a backing instance and so `React.ElementRef<typeof Bar>` (when `Bar` is `function Bar() {}`) will give you the undefined type. * JSX intrinsics like `div` will give you their DOM instance. For `React.ElementRef<'div'>` that would be `HTMLDivElement`. For `React.ElementRef<'input'>` that would be `HTMLInputElement`. Like [`React.Element<typeof Component>`](#toc-react-element), `typeof Component` must be the type *of* a React component so you need to use `typeof` as in `React.ElementRef<typeof MyComponent>`. `React.Config<Props, DefaultProps>` ------------------------------------ Calculates a config object from props and default props. This is most useful for annotating HOCs that are abstracted over configs. See our [docs on writing HOCs](../hoc) for more information. flow Event Handling Event Handling ============== In the [React docs “Handling Events” section](https://facebook.github.io/react/docs/handling-events.html) a few different recommendations are provided on how to define event handlers. If you are using Flow we recommend that you use [property initializer syntax](https://babeljs.io/docs/plugins/transform-class-properties/) as it is the easiest to statically type. Property initializer syntax looks like this: ``` class MyComponent extends React.Component<{}> { handleClick = event => { /* ... */ }; } ``` To type event handlers you may use the `SyntheticEvent<T>` types like this: ``` import * as React from 'react'; class MyComponent extends React.Component<{}, { count: number }> { handleClick = (event: SyntheticEvent<HTMLButtonElement>) => { // To access your button instance use `event.currentTarget`. (event.currentTarget: HTMLButtonElement); this.setState(prevState => ({ count: prevState.count + 1, })); }; render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={this.handleClick}> Increment </button> </div> ); } } ``` There are also more specific synthetic event types like `SyntheticKeyboardEvent<T>`, `SyntheticMouseEvent<T>`, or `SyntheticTouchEvent<T>`. The `SyntheticEvent<T>` types all take a single type argument. The type of the HTML element the event handler was placed on. If you don’t want to add the type of your element instance you can also use `SyntheticEvent` with *no* type arguments like so: `SyntheticEvent<>`. > **Note:** To get the element instance, like `HTMLButtonElement` in the example above, it is a common mistake to use `event.target` instead of `event.currentTarget`. The reason why you want to use `event.currentTarget` is that `event.target` may be the wrong element due to [event propagation](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Examples#Example_5:_Event_Propagation). > > > **Note:** React uses its own event system so it is important to use the `SyntheticEvent` types instead of the DOM types such as `Event`, `KeyboardEvent`, and `MouseEvent`. > > The `SyntheticEvent<T>` types that React provides and the DOM events they are related to are: * `SyntheticEvent<T>` for [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event) * `SyntheticAnimationEvent<T>` for [AnimationEvent](https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent) * `SyntheticCompositionEvent<T>` for [CompositionEvent](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent) * `SyntheticInputEvent<T>` for [InputEvent](https://developer.mozilla.org/en-US/docs/Web/API/InputEvent) * `SyntheticUIEvent<T>` for [UIEvent](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent) * `SyntheticFocusEvent<T>` for [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent) * `SyntheticKeyboardEvent<T>` for [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent) * `SyntheticMouseEvent<T>` for [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent) * `SyntheticDragEvent<T>` for [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent) * `SyntheticWheelEvent<T>` for [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent) * `SyntheticTouchEvent<T>` for [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent) * `SyntheticTransitionEvent<T>` for [TransitionEvent](https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent) lua Lua 5.4 Reference Manual Lua 5.4 Reference Manual ========================= by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes 1 – Introduction ================ Lua is a powerful, efficient, lightweight, embeddable scripting language. It supports procedural programming, object-oriented programming, functional programming, data-driven programming, and data description. Lua combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is dynamically typed, runs by interpreting bytecode with a register-based virtual machine, and has automatic memory management with a generational garbage collection, making it ideal for configuration, scripting, and rapid prototyping. Lua is implemented as a library, written in *clean C*, the common subset of Standard C and C++. The Lua distribution includes a host program called `lua`, which uses the Lua library to offer a complete, standalone Lua interpreter, for interactive or batch use. Lua is intended to be used both as a powerful, lightweight, embeddable scripting language for any program that needs one, and as a powerful but lightweight and efficient stand-alone language. As an extension language, Lua has no notion of a "main" program: it works *embedded* in a host client, called the *embedding program* or simply the *host*. (Frequently, this host is the stand-alone `lua` program.) The host program can invoke functions to execute a piece of Lua code, can write and read Lua variables, and can register C functions to be called by Lua code. Through the use of C functions, Lua can be augmented to cope with a wide range of different domains, thus creating customized programming languages sharing a syntactical framework. Lua is free software, and is provided as usual with no guarantees, as stated in its license. The implementation described in this manual is available at Lua's official web site, `www.lua.org`. Like any other reference manual, this document is dry in places. For a discussion of the decisions behind the design of Lua, see the technical papers available at Lua's web site. For a detailed introduction to programming in Lua, see Roberto's book, *Programming in Lua*. 2 – Basic Concepts ================== This section describes the basic concepts of the language. 2.1 – Values and Types ---------------------- Lua is a dynamically typed language. This means that variables do not have types; only values do. There are no type definitions in the language. All values carry their own type. All values in Lua are first-class values. This means that all values can be stored in variables, passed as arguments to other functions, and returned as results. There are eight basic types in Lua: *nil*, *boolean*, *number*, *string*, *function*, *userdata*, *thread*, and *table*. The type *nil* has one single value, **nil**, whose main property is to be different from any other value; it often represents the absence of a useful value. The type *boolean* has two values, **false** and **true**. Both **nil** and **false** make a condition false; they are collectively called *false values*. Any other value makes a condition true. The type *number* represents both integer numbers and real (floating-point) numbers, using two subtypes: *integer* and *float*. Standard Lua uses 64-bit integers and double-precision (64-bit) floats, but you can also compile Lua so that it uses 32-bit integers and/or single-precision (32-bit) floats. The option with 32 bits for both integers and floats is particularly attractive for small machines and embedded systems. (See macro `LUA_32BITS` in file `luaconf.h`.) Unless stated otherwise, any overflow when manipulating integer values *wrap around*, according to the usual rules of two-complement arithmetic. (In other words, the actual result is the unique representable integer that is equal modulo *2n* to the mathematical result, where *n* is the number of bits of the integer type.) Lua has explicit rules about when each subtype is used, but it also converts between them automatically as needed (see [§3.4.3](#3.4.3)). Therefore, the programmer may choose to mostly ignore the difference between integers and floats or to assume complete control over the representation of each number. The type *string* represents immutable sequences of bytes. Lua is 8-bit clean: strings can contain any 8-bit value, including embedded zeros ('`\0`'). Lua is also encoding-agnostic; it makes no assumptions about the contents of a string. The length of any string in Lua must fit in a Lua integer. Lua can call (and manipulate) functions written in Lua and functions written in C (see [§3.4.10](#3.4.10)). Both are represented by the type *function*. The type *userdata* is provided to allow arbitrary C data to be stored in Lua variables. A userdata value represents a block of raw memory. There are two kinds of userdata: *full userdata*, which is an object with a block of memory managed by Lua, and *light userdata*, which is simply a C pointer value. Userdata has no predefined operations in Lua, except assignment and identity test. By using *metatables*, the programmer can define operations for full userdata values (see [§2.4](#2.4)). Userdata values cannot be created or modified in Lua, only through the C API. This guarantees the integrity of data owned by the host program and C libraries. The type *thread* represents independent threads of execution and it is used to implement coroutines (see [§2.6](#2.6)). Lua threads are not related to operating-system threads. Lua supports coroutines on all systems, even those that do not support threads natively. The type *table* implements associative arrays, that is, arrays that can have as indices not only numbers, but any Lua value except **nil** and NaN. (*Not a Number* is a special floating-point value used by the IEEE 754 standard to represent undefined numerical results, such as `0/0`.) Tables can be *heterogeneous*; that is, they can contain values of all types (except **nil**). Any key associated to the value **nil** is not considered part of the table. Conversely, any key that is not part of a table has an associated value **nil**. Tables are the sole data-structuring mechanism in Lua; they can be used to represent ordinary arrays, lists, symbol tables, sets, records, graphs, trees, etc. To represent records, Lua uses the field name as an index. The language supports this representation by providing `a.name` as syntactic sugar for `a["name"]`. There are several convenient ways to create tables in Lua (see [§3.4.9](#3.4.9)). Like indices, the values of table fields can be of any type. In particular, because functions are first-class values, table fields can contain functions. Thus tables can also carry *methods* (see [§3.4.11](#3.4.11)). The indexing of tables follows the definition of raw equality in the language. The expressions `a[i]` and `a[j]` denote the same table element if and only if `i` and `j` are raw equal (that is, equal without metamethods). In particular, floats with integral values are equal to their respective integers (e.g., `1.0 == 1`). To avoid ambiguities, any float used as a key that is equal to an integer is converted to that integer. For instance, if you write `a[2.0] = true`, the actual key inserted into the table will be the integer `2`. Tables, functions, threads, and (full) userdata values are *objects*: variables do not actually *contain* these values, only *references* to them. Assignment, parameter passing, and function returns always manipulate references to such values; these operations do not imply any kind of copy. The library function [`type`](#pdf-type) returns a string describing the type of a given value (see [`type`](#pdf-type)). 2.2 – Environments and the Global Environment --------------------------------------------- As we will discuss further in [§3.2](#3.2) and [§3.3.3](#3.3.3), any reference to a free name (that is, a name not bound to any declaration) `var` is syntactically translated to `_ENV.var`. Moreover, every chunk is compiled in the scope of an external local variable named `_ENV` (see [§3.3.2](#3.3.2)), so `_ENV` itself is never a free name in a chunk. Despite the existence of this external `_ENV` variable and the translation of free names, `_ENV` is a completely regular name. In particular, you can define new variables and parameters with that name. Each reference to a free name uses the `_ENV` that is visible at that point in the program, following the usual visibility rules of Lua (see [§3.5](#3.5)). Any table used as the value of `_ENV` is called an *environment*. Lua keeps a distinguished environment called the *global environment*. This value is kept at a special index in the C registry (see [§4.3](#4.3)). In Lua, the global variable [`_G`](#pdf-_G) is initialized with this same value. ([`_G`](#pdf-_G) is never used internally, so changing its value will affect only your own code.) When Lua loads a chunk, the default value for its `_ENV` variable is the global environment (see [`load`](#pdf-load)). Therefore, by default, free names in Lua code refer to entries in the global environment and, therefore, they are also called *global variables*. Moreover, all standard libraries are loaded in the global environment and some functions there operate on that environment. You can use [`load`](#pdf-load) (or [`loadfile`](#pdf-loadfile)) to load a chunk with a different environment. (In C, you have to load the chunk and then change the value of its first upvalue; see [`lua_setupvalue`](#lua_setupvalue).) 2.3 – Error Handling -------------------- Several operations in Lua can *raise* an error. An error interrupts the normal flow of the program, which can continue by *catching* the error. Lua code can explicitly raise an error by calling the [`error`](#pdf-error) function. (This function never returns.) To catch errors in Lua, you can do a *protected call*, using [`pcall`](#pdf-pcall) (or [`xpcall`](#pdf-xpcall)). The function [`pcall`](#pdf-pcall) calls a given function in *protected mode*. Any error while running the function stops its execution, and control returns immediately to `pcall`, which returns a status code. Because Lua is an embedded extension language, Lua code starts running by a call from C code in the host program. (When you use Lua standalone, the `lua` application is the host program.) Usually, this call is protected; so, when an otherwise unprotected error occurs during the compilation or execution of a Lua chunk, control returns to the host, which can take appropriate measures, such as printing an error message. Whenever there is an error, an *error object* is propagated with information about the error. Lua itself only generates errors whose error object is a string, but programs may generate errors with any value as the error object. It is up to the Lua program or its host to handle such error objects. For historical reasons, an error object is often called an *error message*, even though it does not have to be a string. When you use [`xpcall`](#pdf-xpcall) (or [`lua_pcall`](#lua_pcall), in C) you may give a *message handler* to be called in case of errors. This function is called with the original error object and returns a new error object. It is called before the error unwinds the stack, so that it can gather more information about the error, for instance by inspecting the stack and creating a stack traceback. This message handler is still protected by the protected call; so, an error inside the message handler will call the message handler again. If this loop goes on for too long, Lua breaks it and returns an appropriate message. The message handler is called only for regular runtime errors. It is not called for memory-allocation errors nor for errors while running finalizers or other message handlers. Lua also offers a system of *warnings* (see [`warn`](#pdf-warn)). Unlike errors, warnings do not interfere in any way with program execution. They typically only generate a message to the user, although this behavior can be adapted from C (see [`lua_setwarnf`](#lua_setwarnf)). 2.4 – Metatables and Metamethods -------------------------------- Every value in Lua can have a *metatable*. This *metatable* is an ordinary Lua table that defines the behavior of the original value under certain events. You can change several aspects of the behavior of a value by setting specific fields in its metatable. For instance, when a non-numeric value is the operand of an addition, Lua checks for a function in the field "`__add`" of the value's metatable. If it finds one, Lua calls this function to perform the addition. The key for each event in a metatable is a string with the event name prefixed by two underscores; the corresponding value is called a *metavalue*. For most events, the metavalue must be a function, which is then called a *metamethod*. In the previous example, the key is the string "`__add`" and the metamethod is the function that performs the addition. Unless stated otherwise, a metamethod may in fact be any callable value, which is either a function or a value with a `__call` metamethod. You can query the metatable of any value using the [`getmetatable`](#pdf-getmetatable) function. Lua queries metamethods in metatables using a raw access (see [`rawget`](#pdf-rawget)). You can replace the metatable of tables using the [`setmetatable`](#pdf-setmetatable) function. You cannot change the metatable of other types from Lua code, except by using the debug library ([§6.10](#6.10)). Tables and full userdata have individual metatables, although multiple tables and userdata can share their metatables. Values of all other types share one single metatable per type; that is, there is one single metatable for all numbers, one for all strings, etc. By default, a value has no metatable, but the string library sets a metatable for the string type (see [§6.4](#6.4)). A detailed list of operations controlled by metatables is given next. Each event is identified by its corresponding key. By convention, all metatable keys used by Lua are composed by two underscores followed by lowercase Latin letters. * `__add`: the addition (`+`) operation. If any operand for an addition is not a number, Lua will try to call a metamethod. It starts by checking the first operand (even if it is a number); if that operand does not define a metamethod for `__add`, then Lua will check the second operand. If Lua can find a metamethod, it calls the metamethod with the two operands as arguments, and the result of the call (adjusted to one value) is the result of the operation. Otherwise, if no metamethod is found, Lua raises an error. * `__sub`: the subtraction (`-`) operation. Behavior similar to the addition operation. * `__mul`: the multiplication (`*`) operation. Behavior similar to the addition operation. * `__div`: the division (`/`) operation. Behavior similar to the addition operation. * `__mod`: the modulo (`%`) operation. Behavior similar to the addition operation. * `__pow`: the exponentiation (`^`) operation. Behavior similar to the addition operation. * `__unm`: the negation (unary `-`) operation. Behavior similar to the addition operation. * `__idiv`: the floor division (`//`) operation. Behavior similar to the addition operation. * `__band`: the bitwise AND (`&`) operation. Behavior similar to the addition operation, except that Lua will try a metamethod if any operand is neither an integer nor a float coercible to an integer (see [§3.4.3](#3.4.3)). * `__bor`: the bitwise OR (`|`) operation. Behavior similar to the bitwise AND operation. * `__bxor`: the bitwise exclusive OR (binary `~`) operation. Behavior similar to the bitwise AND operation. * `__bnot`: the bitwise NOT (unary `~`) operation. Behavior similar to the bitwise AND operation. * `__shl`: the bitwise left shift (`<<`) operation. Behavior similar to the bitwise AND operation. * `__shr`: the bitwise right shift (`>>`) operation. Behavior similar to the bitwise AND operation. * `__concat`: the concatenation (`..`) operation. Behavior similar to the addition operation, except that Lua will try a metamethod if any operand is neither a string nor a number (which is always coercible to a string). * `__len`: the length (`#`) operation. If the object is not a string, Lua will try its metamethod. If there is a metamethod, Lua calls it with the object as argument, and the result of the call (always adjusted to one value) is the result of the operation. If there is no metamethod but the object is a table, then Lua uses the table length operation (see [§3.4.7](#3.4.7)). Otherwise, Lua raises an error. * `__eq`: the equal (`==`) operation. Behavior similar to the addition operation, except that Lua will try a metamethod only when the values being compared are either both tables or both full userdata and they are not primitively equal. The result of the call is always converted to a boolean. * `__lt`: the less than (`<`) operation. Behavior similar to the addition operation, except that Lua will try a metamethod only when the values being compared are neither both numbers nor both strings. Moreover, the result of the call is always converted to a boolean. * `__le`: the less equal (`<=`) operation. Behavior similar to the less than operation. * `__index`: The indexing access operation `table[key]`. This event happens when `table` is not a table or when `key` is not present in `table`. The metavalue is looked up in the metatable of `table`. The metavalue for this event can be either a function, a table, or any value with an `__index` metavalue. If it is a function, it is called with `table` and `key` as arguments, and the result of the call (adjusted to one value) is the result of the operation. Otherwise, the final result is the result of indexing this metavalue with `key`. This indexing is regular, not raw, and therefore can trigger another `__index` metavalue. * `__newindex`: The indexing assignment `table[key] = value`. Like the index event, this event happens when `table` is not a table or when `key` is not present in `table`. The metavalue is looked up in the metatable of `table`. Like with indexing, the metavalue for this event can be either a function, a table, or any value with an `__newindex` metavalue. If it is a function, it is called with `table`, `key`, and `value` as arguments. Otherwise, Lua repeats the indexing assignment over this metavalue with the same key and value. This assignment is regular, not raw, and therefore can trigger another `__newindex` metavalue. Whenever a `__newindex` metavalue is invoked, Lua does not perform the primitive assignment. If needed, the metamethod itself can call [`rawset`](#pdf-rawset) to do the assignment. * `__call`: The call operation `func(args)`. This event happens when Lua tries to call a non-function value (that is, `func` is not a function). The metamethod is looked up in `func`. If present, the metamethod is called with `func` as its first argument, followed by the arguments of the original call (`args`). All results of the call are the results of the operation. This is the only metamethod that allows multiple results. In addition to the previous list, the interpreter also respects the following keys in metatables: `__gc` (see [§2.5.3](#2.5.3)), `__close` (see [§3.3.8](#3.3.8)), `__mode` (see [§2.5.4](#2.5.4)), and `__name`. (The entry `__name`, when it contains a string, may be used by [`tostring`](#pdf-tostring) and in error messages.) For the unary operators (negation, length, and bitwise NOT), the metamethod is computed and called with a dummy second operand, equal to the first one. This extra operand is only to simplify Lua's internals (by making these operators behave like a binary operation) and may be removed in future versions. For most uses this extra operand is irrelevant. Because metatables are regular tables, they can contain arbitrary fields, not only the event names defined above. Some functions in the standard library (e.g., [`tostring`](#pdf-tostring)) use other fields in metatables for their own purposes. It is a good practice to add all needed metamethods to a table before setting it as a metatable of some object. In particular, the `__gc` metamethod works only when this order is followed (see [§2.5.3](#2.5.3)). It is also a good practice to set the metatable of an object right after its creation. 2.5 – Garbage Collection ------------------------ Lua performs automatic memory management. This means that you do not have to worry about allocating memory for new objects or freeing it when the objects are no longer needed. Lua manages memory automatically by running a *garbage collector* to collect all *dead* objects. All memory used by Lua is subject to automatic management: strings, tables, userdata, functions, threads, internal structures, etc. An object is considered *dead* as soon as the collector can be sure the object will not be accessed again in the normal execution of the program. ("Normal execution" here excludes finalizers, which can resurrect dead objects (see [§2.5.3](#2.5.3)), and excludes also operations using the debug library.) Note that the time when the collector can be sure that an object is dead may not coincide with the programmer's expectations. The only guarantees are that Lua will not collect an object that may still be accessed in the normal execution of the program, and it will eventually collect an object that is inaccessible from Lua. (Here, *inaccessible from Lua* means that neither a variable nor another live object refer to the object.) Because Lua has no knowledge about C code, it never collects objects accessible through the registry (see [§4.3](#4.3)), which includes the global environment (see [§2.2](#2.2)). The garbage collector (GC) in Lua can work in two modes: incremental and generational. The default GC mode with the default parameters are adequate for most uses. However, programs that waste a large proportion of their time allocating and freeing memory can benefit from other settings. Keep in mind that the GC behavior is non-portable both across platforms and across different Lua releases; therefore, optimal settings are also non-portable. You can change the GC mode and parameters by calling [`lua_gc`](#lua_gc) in C or [`collectgarbage`](#pdf-collectgarbage) in Lua. You can also use these functions to control the collector directly (e.g., to stop and restart it). ### 2.5.1 – Incremental Garbage Collection In incremental mode, each GC cycle performs a mark-and-sweep collection in small steps interleaved with the program's execution. In this mode, the collector uses three numbers to control its garbage-collection cycles: the *garbage-collector pause*, the *garbage-collector step multiplier*, and the *garbage-collector step size*. The garbage-collector pause controls how long the collector waits before starting a new cycle. The collector starts a new cycle when the use of memory hits *n%* of the use after the previous collection. Larger values make the collector less aggressive. Values equal to or less than 100 mean the collector will not wait to start a new cycle. A value of 200 means that the collector waits for the total memory in use to double before starting a new cycle. The default value is 200; the maximum value is 1000. The garbage-collector step multiplier controls the speed of the collector relative to memory allocation, that is, how many elements it marks or sweeps for each kilobyte of memory allocated. Larger values make the collector more aggressive but also increase the size of each incremental step. You should not use values less than 100, because they make the collector too slow and can result in the collector never finishing a cycle. The default value is 100; the maximum value is 1000. The garbage-collector step size controls the size of each incremental step, specifically how many bytes the interpreter allocates before performing a step. This parameter is logarithmic: A value of *n* means the interpreter will allocate *2n* bytes between steps and perform equivalent work during the step. A large value (e.g., 60) makes the collector a stop-the-world (non-incremental) collector. The default value is 13, which means steps of approximately 8 Kbytes. ### 2.5.2 – Generational Garbage Collection In generational mode, the collector does frequent *minor* collections, which traverses only objects recently created. If after a minor collection the use of memory is still above a limit, the collector does a stop-the-world *major* collection, which traverses all objects. The generational mode uses two parameters: the *minor multiplier* and the *the major multiplier*. The minor multiplier controls the frequency of minor collections. For a minor multiplier *x*, a new minor collection will be done when memory grows *x%* larger than the memory in use after the previous major collection. For instance, for a multiplier of 20, the collector will do a minor collection when the use of memory gets 20% larger than the use after the previous major collection. The default value is 20; the maximum value is 200. The major multiplier controls the frequency of major collections. For a major multiplier *x*, a new major collection will be done when memory grows *x%* larger than the memory in use after the previous major collection. For instance, for a multiplier of 100, the collector will do a major collection when the use of memory gets larger than twice the use after the previous collection. The default value is 100; the maximum value is 1000. ### 2.5.3 – Garbage-Collection Metamethods You can set garbage-collector metamethods for tables and, using the C API, for full userdata (see [§2.4](#2.4)). These metamethods, called *finalizers*, are called when the garbage collector detects that the corresponding table or userdata is dead. Finalizers allow you to coordinate Lua's garbage collection with external resource management such as closing files, network or database connections, or freeing your own memory. For an object (table or userdata) to be finalized when collected, you must *mark* it for finalization. You mark an object for finalization when you set its metatable and the metatable has a field indexed by the string "`__gc`". Note that if you set a metatable without a `__gc` field and later create that field in the metatable, the object will not be marked for finalization. When a marked object becomes dead, it is not collected immediately by the garbage collector. Instead, Lua puts it in a list. After the collection, Lua goes through that list. For each object in the list, it checks the object's `__gc` metamethod: If it is present, Lua calls it with the object as its single argument. At the end of each garbage-collection cycle, the finalizers are called in the reverse order that the objects were marked for finalization, among those collected in that cycle; that is, the first finalizer to be called is the one associated with the object marked last in the program. The execution of each finalizer may occur at any point during the execution of the regular code. Because the object being collected must still be used by the finalizer, that object (and other objects accessible only through it) must be *resurrected* by Lua. Usually, this resurrection is transient, and the object memory is freed in the next garbage-collection cycle. However, if the finalizer stores the object in some global place (e.g., a global variable), then the resurrection is permanent. Moreover, if the finalizer marks a finalizing object for finalization again, its finalizer will be called again in the next cycle where the object is dead. In any case, the object memory is freed only in a GC cycle where the object is dead and not marked for finalization. When you close a state (see [`lua_close`](#lua_close)), Lua calls the finalizers of all objects marked for finalization, following the reverse order that they were marked. If any finalizer marks objects for collection during that phase, these marks have no effect. Finalizers cannot yield. Except for that, they can do anything, such as raise errors, create new objects, or even run the garbage collector. However, because they can run in unpredictable times, it is good practice to restrict each finalizer to the minimum necessary to properly release its associated resource. Any error while running a finalizer generates a warning; the error is not propagated. ### 2.5.4 – Weak Tables A *weak table* is a table whose elements are *weak references*. A weak reference is ignored by the garbage collector. In other words, if the only references to an object are weak references, then the garbage collector will collect that object. A weak table can have weak keys, weak values, or both. A table with weak values allows the collection of its values, but prevents the collection of its keys. A table with both weak keys and weak values allows the collection of both keys and values. In any case, if either the key or the value is collected, the whole pair is removed from the table. The weakness of a table is controlled by the `__mode` field of its metatable. This metavalue, if present, must be one of the following strings: "`k`", for a table with weak keys; "`v`", for a table with weak values; or "`kv`", for a table with both weak keys and values. A table with weak keys and strong values is also called an *ephemeron table*. In an ephemeron table, a value is considered reachable only if its key is reachable. In particular, if the only reference to a key comes through its value, the pair is removed. Any change in the weakness of a table may take effect only at the next collect cycle. In particular, if you change the weakness to a stronger mode, Lua may still collect some items from that table before the change takes effect. Only objects that have an explicit construction are removed from weak tables. Values, such as numbers and light C functions, are not subject to garbage collection, and therefore are not removed from weak tables (unless their associated values are collected). Although strings are subject to garbage collection, they do not have an explicit construction and their equality is by value; they behave more like values than like objects. Therefore, they are not removed from weak tables. Resurrected objects (that is, objects being finalized and objects accessible only through objects being finalized) have a special behavior in weak tables. They are removed from weak values before running their finalizers, but are removed from weak keys only in the next collection after running their finalizers, when such objects are actually freed. This behavior allows the finalizer to access properties associated with the object through weak tables. If a weak table is among the resurrected objects in a collection cycle, it may not be properly cleared until the next cycle. 2.6 – Coroutines ---------------- Lua supports coroutines, also called *collaborative multithreading*. A coroutine in Lua represents an independent thread of execution. Unlike threads in multithread systems, however, a coroutine only suspends its execution by explicitly calling a yield function. You create a coroutine by calling [`coroutine.create`](#pdf-coroutine.create). Its sole argument is a function that is the main function of the coroutine. The `create` function only creates a new coroutine and returns a handle to it (an object of type *thread*); it does not start the coroutine. You execute a coroutine by calling [`coroutine.resume`](#pdf-coroutine.resume). When you first call [`coroutine.resume`](#pdf-coroutine.resume), passing as its first argument a thread returned by [`coroutine.create`](#pdf-coroutine.create), the coroutine starts its execution by calling its main function. Extra arguments passed to [`coroutine.resume`](#pdf-coroutine.resume) are passed as arguments to that function. After the coroutine starts running, it runs until it terminates or *yields*. A coroutine can terminate its execution in two ways: normally, when its main function returns (explicitly or implicitly, after the last instruction); and abnormally, if there is an unprotected error. In case of normal termination, [`coroutine.resume`](#pdf-coroutine.resume) returns **true**, plus any values returned by the coroutine main function. In case of errors, [`coroutine.resume`](#pdf-coroutine.resume) returns **false** plus the error object. In this case, the coroutine does not unwind its stack, so that it is possible to inspect it after the error with the debug API. A coroutine yields by calling [`coroutine.yield`](#pdf-coroutine.yield). When a coroutine yields, the corresponding [`coroutine.resume`](#pdf-coroutine.resume) returns immediately, even if the yield happens inside nested function calls (that is, not in the main function, but in a function directly or indirectly called by the main function). In the case of a yield, [`coroutine.resume`](#pdf-coroutine.resume) also returns **true**, plus any values passed to [`coroutine.yield`](#pdf-coroutine.yield). The next time you resume the same coroutine, it continues its execution from the point where it yielded, with the call to [`coroutine.yield`](#pdf-coroutine.yield) returning any extra arguments passed to [`coroutine.resume`](#pdf-coroutine.resume). Like [`coroutine.create`](#pdf-coroutine.create), the [`coroutine.wrap`](#pdf-coroutine.wrap) function also creates a coroutine, but instead of returning the coroutine itself, it returns a function that, when called, resumes the coroutine. Any arguments passed to this function go as extra arguments to [`coroutine.resume`](#pdf-coroutine.resume). [`coroutine.wrap`](#pdf-coroutine.wrap) returns all the values returned by [`coroutine.resume`](#pdf-coroutine.resume), except the first one (the boolean error code). Unlike [`coroutine.resume`](#pdf-coroutine.resume), the function created by [`coroutine.wrap`](#pdf-coroutine.wrap) propagates any error to the caller. In this case, the function also closes the coroutine (see [`coroutine.close`](#pdf-coroutine.close)). As an example of how coroutines work, consider the following code: ``` function foo (a) print("foo", a) return coroutine.yield(2*a) end co = coroutine.create(function (a,b) print("co-body", a, b) local r = foo(a+1) print("co-body", r) local r, s = coroutine.yield(a+b, a-b) print("co-body", r, s) return b, "end" end) print("main", coroutine.resume(co, 1, 10)) print("main", coroutine.resume(co, "r")) print("main", coroutine.resume(co, "x", "y")) print("main", coroutine.resume(co, "x", "y")) ``` When you run it, it produces the following output: ``` co-body 1 10 foo 2 main true 4 co-body r main true 11 -9 co-body x y main true 10 end main false cannot resume dead coroutine ``` You can also create and manipulate coroutines through the C API: see functions [`lua_newthread`](#lua_newthread), [`lua_resume`](#lua_resume), and [`lua_yield`](#lua_yield). 3 – The Language ================ This section describes the lexis, the syntax, and the semantics of Lua. In other words, this section describes which tokens are valid, how they can be combined, and what their combinations mean. Language constructs will be explained using the usual extended BNF notation, in which {*a*} means 0 or more *a*'s, and [*a*] means an optional *a*. Non-terminals are shown like non-terminal, keywords are shown like **kword**, and other terminal symbols are shown like ‘**=**’. The complete syntax of Lua can be found in [§9](#9) at the end of this manual. 3.1 – Lexical Conventions ------------------------- Lua is a free-form language. It ignores spaces and comments between lexical elements (tokens), except as delimiters between two tokens. In source code, Lua recognizes as spaces the standard ASCII whitespace characters space, form feed, newline, carriage return, horizontal tab, and vertical tab. *Names* (also called *identifiers*) in Lua can be any string of Latin letters, Arabic-Indic digits, and underscores, not beginning with a digit and not being a reserved word. Identifiers are used to name variables, table fields, and labels. The following *keywords* are reserved and cannot be used as names: ``` and break do else elseif end false for function goto if in local nil not or repeat return then true until while ``` Lua is a case-sensitive language: `and` is a reserved word, but `And` and `AND` are two different, valid names. As a convention, programs should avoid creating names that start with an underscore followed by one or more uppercase letters (such as [`_VERSION`](#pdf-_VERSION)). The following strings denote other tokens: ``` + - * / % ^ # & ~ | << >> // == ~= <= >= < > = ( ) { } [ ] :: ; : , . .. ... ``` A *short literal string* can be delimited by matching single or double quotes, and can contain the following C-like escape sequences: '`\a`' (bell), '`\b`' (backspace), '`\f`' (form feed), '`\n`' (newline), '`\r`' (carriage return), '`\t`' (horizontal tab), '`\v`' (vertical tab), '`\\`' (backslash), '`\"`' (quotation mark [double quote]), and '`\'`' (apostrophe [single quote]). A backslash followed by a line break results in a newline in the string. The escape sequence '`\z`' skips the following span of whitespace characters, including line breaks; it is particularly useful to break and indent a long literal string into multiple lines without adding the newlines and spaces into the string contents. A short literal string cannot contain unescaped line breaks nor escapes not forming a valid escape sequence. We can specify any byte in a short literal string, including embedded zeros, by its numeric value. This can be done with the escape sequence `\x*XX*`, where *XX* is a sequence of exactly two hexadecimal digits, or with the escape sequence `\*ddd*`, where *ddd* is a sequence of up to three decimal digits. (Note that if a decimal escape sequence is to be followed by a digit, it must be expressed using exactly three digits.) The UTF-8 encoding of a Unicode character can be inserted in a literal string with the escape sequence `\u{*XXX*}` (with mandatory enclosing braces), where *XXX* is a sequence of one or more hexadecimal digits representing the character code point. This code point can be any value less than *231*. (Lua uses the original UTF-8 specification here, which is not restricted to valid Unicode code points.) Literal strings can also be defined using a long format enclosed by *long brackets*. We define an *opening long bracket of level *n** as an opening square bracket followed by *n* equal signs followed by another opening square bracket. So, an opening long bracket of level 0 is written as `[[`, an opening long bracket of level 1 is written as `[=[`, and so on. A *closing long bracket* is defined similarly; for instance, a closing long bracket of level 4 is written as `]====]`. A *long literal* starts with an opening long bracket of any level and ends at the first closing long bracket of the same level. It can contain any text except a closing bracket of the same level. Literals in this bracketed form can run for several lines, do not interpret any escape sequences, and ignore long brackets of any other level. Any kind of end-of-line sequence (carriage return, newline, carriage return followed by newline, or newline followed by carriage return) is converted to a simple newline. When the opening long bracket is immediately followed by a newline, the newline is not included in the string. As an example, in a system using ASCII (in which '`a`' is coded as 97, newline is coded as 10, and '`1`' is coded as 49), the five literal strings below denote the same string: ``` a = 'alo\n123"' a = "alo\n123\"" a = '\97lo\10\04923"' a = [[alo 123"]] a = [==[ alo 123"]==] ``` Any byte in a literal string not explicitly affected by the previous rules represents itself. However, Lua opens files for parsing in text mode, and the system's file functions may have problems with some control characters. So, it is safer to represent binary data as a quoted literal with explicit escape sequences for the non-text characters. A *numeric constant* (or *numeral*) can be written with an optional fractional part and an optional decimal exponent, marked by a letter '`e`' or '`E`'. Lua also accepts hexadecimal constants, which start with `0x` or `0X`. Hexadecimal constants also accept an optional fractional part plus an optional binary exponent, marked by a letter '`p`' or '`P`'. A numeric constant with a radix point or an exponent denotes a float; otherwise, if its value fits in an integer or it is a hexadecimal constant, it denotes an integer; otherwise (that is, a decimal integer numeral that overflows), it denotes a float. Hexadecimal numerals with neither a radix point nor an exponent always denote an integer value; if the value overflows, it *wraps around* to fit into a valid integer. Examples of valid integer constants are ``` 3 345 0xff 0xBEBADA ``` Examples of valid float constants are ``` 3.0 3.1416 314.16e-2 0.31416E1 34e1 0x0.1E 0xA23p-4 0X1.921FB54442D18P+1 ``` A *comment* starts with a double hyphen (`--`) anywhere outside a string. If the text immediately after `--` is not an opening long bracket, the comment is a *short comment*, which runs until the end of the line. Otherwise, it is a *long comment*, which runs until the corresponding closing long bracket. 3.2 – Variables --------------- Variables are places that store values. There are three kinds of variables in Lua: global variables, local variables, and table fields. A single name can denote a global variable or a local variable (or a function's formal parameter, which is a particular kind of local variable): ``` var ::= Name ``` Name denotes identifiers (see [§3.1](#3.1)). Any variable name is assumed to be global unless explicitly declared as a local (see [§3.3.7](#3.3.7)). Local variables are *lexically scoped*: local variables can be freely accessed by functions defined inside their scope (see [§3.5](#3.5)). Before the first assignment to a variable, its value is **nil**. Square brackets are used to index a table: ``` var ::= prefixexp ‘[’ exp ‘]’ ``` The meaning of accesses to table fields can be changed via metatables (see [§2.4](#2.4)). The syntax `var.Name` is just syntactic sugar for `var["Name"]`: ``` var ::= prefixexp ‘.’ Name ``` An access to a global variable `x` is equivalent to `_ENV.x`. Due to the way that chunks are compiled, the variable `_ENV` itself is never global (see [§2.2](#2.2)). 3.3 – Statements ---------------- Lua supports an almost conventional set of statements, similar to those in other conventional languages. This set includes blocks, assignments, control structures, function calls, and variable declarations. ### 3.3.1 – Blocks A block is a list of statements, which are executed sequentially: ``` block ::= {stat} ``` Lua has *empty statements* that allow you to separate statements with semicolons, start a block with a semicolon or write two semicolons in sequence: ``` stat ::= ‘;’ ``` Both function calls and assignments can start with an open parenthesis. This possibility leads to an ambiguity in Lua's grammar. Consider the following fragment: ``` a = b + c (print or io.write)('done') ``` The grammar could see this fragment in two ways: ``` a = b + c(print or io.write)('done') a = b + c; (print or io.write)('done') ``` The current parser always sees such constructions in the first way, interpreting the open parenthesis as the start of the arguments to a call. To avoid this ambiguity, it is a good practice to always precede with a semicolon statements that start with a parenthesis: ``` ;(print or io.write)('done') ``` A block can be explicitly delimited to produce a single statement: ``` stat ::= do block end ``` Explicit blocks are useful to control the scope of variable declarations. Explicit blocks are also sometimes used to add a **return** statement in the middle of another block (see [§3.3.4](#3.3.4)). ### 3.3.2 – Chunks The unit of compilation of Lua is called a *chunk*. Syntactically, a chunk is simply a block: ``` chunk ::= block ``` Lua handles a chunk as the body of an anonymous function with a variable number of arguments (see [§3.4.11](#3.4.11)). As such, chunks can define local variables, receive arguments, and return values. Moreover, such anonymous function is compiled as in the scope of an external local variable called `_ENV` (see [§2.2](#2.2)). The resulting function always has `_ENV` as its only external variable, even if it does not use that variable. A chunk can be stored in a file or in a string inside the host program. To execute a chunk, Lua first *loads* it, precompiling the chunk's code into instructions for a virtual machine, and then Lua executes the compiled code with an interpreter for the virtual machine. Chunks can also be precompiled into binary form; see the program `luac` and the function [`string.dump`](#pdf-string.dump) for details. Programs in source and compiled forms are interchangeable; Lua automatically detects the file type and acts accordingly (see [`load`](#pdf-load)). ### 3.3.3 – Assignment Lua allows multiple assignments. Therefore, the syntax for assignment defines a list of variables on the left side and a list of expressions on the right side. The elements in both lists are separated by commas: ``` stat ::= varlist ‘=’ explist varlist ::= var {‘,’ var} explist ::= exp {‘,’ exp} ``` Expressions are discussed in [§3.4](#3.4). Before the assignment, the list of values is *adjusted* to the length of the list of variables. If there are more values than needed, the excess values are thrown away. If there are fewer values than needed, the list is extended with **nil**'s. If the list of expressions ends with a function call, then all values returned by that call enter the list of values, before the adjustment (except when the call is enclosed in parentheses; see [§3.4](#3.4)). The assignment statement first evaluates all its expressions and only then the assignments are performed. Thus the code ``` i = 3 i, a[i] = i+1, 20 ``` sets `a[3]` to 20, without affecting `a[4]` because the `i` in `a[i]` is evaluated (to 3) before it is assigned 4. Similarly, the line ``` x, y = y, x ``` exchanges the values of `x` and `y`, and ``` x, y, z = y, z, x ``` cyclically permutes the values of `x`, `y`, and `z`. An assignment to a global name `x = val` is equivalent to the assignment `_ENV.x = val` (see [§2.2](#2.2)). The meaning of assignments to table fields and global variables (which are actually table fields, too) can be changed via metatables (see [§2.4](#2.4)). ### 3.3.4 – Control Structures The control structures **if**, **while**, and **repeat** have the usual meaning and familiar syntax: ``` stat ::= while exp do block end stat ::= repeat block until exp stat ::= if exp then block {elseif exp then block} [else block] end ``` Lua also has a **for** statement, in two flavors (see [§3.3.5](#3.3.5)). The condition expression of a control structure can return any value. Both **false** and **nil** test false. All values different from **nil** and **false** test true. In particular, the number 0 and the empty string also test true. In the **repeat**–**until** loop, the inner block does not end at the **until** keyword, but only after the condition. So, the condition can refer to local variables declared inside the loop block. The **goto** statement transfers the program control to a label. For syntactical reasons, labels in Lua are considered statements too: ``` stat ::= goto Name stat ::= label label ::= ‘::’ Name ‘::’ ``` A label is visible in the entire block where it is defined, except inside nested functions. A goto may jump to any visible label as long as it does not enter into the scope of a local variable. A label should not be declared where a label with the same name is visible, even if this other label has been declared in an enclosing block. Labels and empty statements are called *void statements*, as they perform no actions. The **break** statement terminates the execution of a **while**, **repeat**, or **for** loop, skipping to the next statement after the loop: ``` stat ::= break ``` A **break** ends the innermost enclosing loop. The **return** statement is used to return values from a function or a chunk (which is handled as an anonymous function). Functions can return more than one value, so the syntax for the **return** statement is ``` stat ::= return [explist] [‘;’] ``` The **return** statement can only be written as the last statement of a block. If it is necessary to **return** in the middle of a block, then an explicit inner block can be used, as in the idiom `do return end`, because now **return** is the last statement in its (inner) block. ### 3.3.5 – For Statement The **for** statement has two forms: one numerical and one generic. #### The numerical **for** loop The numerical **for** loop repeats a block of code while a control variable goes through an arithmetic progression. It has the following syntax: ``` stat ::= for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end ``` The given identifier (Name) defines the control variable, which is a new variable local to the loop body (*block*). The loop starts by evaluating once the three control expressions. Their values are called respectively the *initial value*, the *limit*, and the *step*. If the step is absent, it defaults to 1. If both the initial value and the step are integers, the loop is done with integers; note that the limit may not be an integer. Otherwise, the three values are converted to floats and the loop is done with floats. Beware of floating-point accuracy in this case. After that initialization, the loop body is repeated with the value of the control variable going through an arithmetic progression, starting at the initial value, with a common difference given by the step. A negative step makes a decreasing sequence; a step equal to zero raises an error. The loop continues while the value is less than or equal to the limit (greater than or equal to for a negative step). If the initial value is already greater than the limit (or less than, if the step is negative), the body is not executed. For integer loops, the control variable never wraps around; instead, the loop ends in case of an overflow. You should not change the value of the control variable during the loop. If you need its value after the loop, assign it to another variable before exiting the loop. #### The generic **for** loop The generic **for** statement works over functions, called *iterators*. On each iteration, the iterator function is called to produce a new value, stopping when this new value is **nil**. The generic **for** loop has the following syntax: ``` stat ::= for namelist in explist do block end namelist ::= Name {‘,’ Name} ``` A **for** statement like ``` for var_1, ···, var_n in explist do body end ``` works as follows. The names *var\_i* declare loop variables local to the loop body. The first of these variables is the *control variable*. The loop starts by evaluating *explist* to produce four values: an *iterator function*, a *state*, an initial value for the control variable, and a *closing value*. Then, at each iteration, Lua calls the iterator function with two arguments: the state and the control variable. The results from this call are then assigned to the loop variables, following the rules of multiple assignments (see [§3.3.3](#3.3.3)). If the control variable becomes **nil**, the loop terminates. Otherwise, the body is executed and the loop goes to the next iteration. The closing value behaves like a to-be-closed variable (see [§3.3.8](#3.3.8)), which can be used to release resources when the loop ends. Otherwise, it does not interfere with the loop. You should not change the value of the control variable during the loop. ### 3.3.6 – Function Calls as Statements To allow possible side-effects, function calls can be executed as statements: ``` stat ::= functioncall ``` In this case, all returned values are thrown away. Function calls are explained in [§3.4.10](#3.4.10). ### 3.3.7 – Local Declarations Local variables can be declared anywhere inside a block. The declaration can include an initialization: ``` stat ::= local attnamelist [‘=’ explist] attnamelist ::= Name attrib {‘,’ Name attrib} ``` If present, an initial assignment has the same semantics of a multiple assignment (see [§3.3.3](#3.3.3)). Otherwise, all variables are initialized with **nil**. Each variable name may be postfixed by an attribute (a name between angle brackets): ``` attrib ::= [‘<’ Name ‘>’] ``` There are two possible attributes: `const`, which declares a constant variable, that is, a variable that cannot be assigned to after its initialization; and `close`, which declares a to-be-closed variable (see [§3.3.8](#3.3.8)). A list of variables can contain at most one to-be-closed variable. A chunk is also a block (see [§3.3.2](#3.3.2)), and so local variables can be declared in a chunk outside any explicit block. The visibility rules for local variables are explained in [§3.5](#3.5). ### 3.3.8 – To-be-closed Variables A to-be-closed variable behaves like a constant local variable, except that its value is *closed* whenever the variable goes out of scope, including normal block termination, exiting its block by **break**/**goto**/**return**, or exiting by an error. Here, to *close* a value means to call its `__close` metamethod. When calling the metamethod, the value itself is passed as the first argument and the error object that caused the exit (if any) is passed as a second argument; if there was no error, the second argument is **nil**. The value assigned to a to-be-closed variable must have a `__close` metamethod or be a false value. (**nil** and **false** are ignored as to-be-closed values.) If several to-be-closed variables go out of scope at the same event, they are closed in the reverse order that they were declared. If there is any error while running a closing method, that error is handled like an error in the regular code where the variable was defined. However, Lua may call the method one more time. After an error, the other pending closing methods will still be called. Errors in these methods interrupt the respective method and generate a warning, but are otherwise ignored; the error reported is only the original one. If a coroutine yields and is never resumed again, some variables may never go out of scope, and therefore they will never be closed. (These variables are the ones created inside the coroutine and in scope at the point where the coroutine yielded.) Similarly, if a coroutine ends with an error, it does not unwind its stack, so it does not close any variable. In both cases, you can either use finalizers or call [`coroutine.close`](#pdf-coroutine.close) to close the variables. However, if the coroutine was created through [`coroutine.wrap`](#pdf-coroutine.wrap), then its corresponding function will close the coroutine in case of errors. 3.4 – Expressions ----------------- The basic expressions in Lua are the following: ``` exp ::= prefixexp exp ::= nil | false | true exp ::= Numeral exp ::= LiteralString exp ::= functiondef exp ::= tableconstructor exp ::= ‘...’ exp ::= exp binop exp exp ::= unop exp prefixexp ::= var | functioncall | ‘(’ exp ‘)’ ``` Numerals and literal strings are explained in [§3.1](#3.1); variables are explained in [§3.2](#3.2); function definitions are explained in [§3.4.11](#3.4.11); function calls are explained in [§3.4.10](#3.4.10); table constructors are explained in [§3.4.9](#3.4.9). Vararg expressions, denoted by three dots ('`...`'), can only be used when directly inside a vararg function; they are explained in [§3.4.11](#3.4.11). Binary operators comprise arithmetic operators (see [§3.4.1](#3.4.1)), bitwise operators (see [§3.4.2](#3.4.2)), relational operators (see [§3.4.4](#3.4.4)), logical operators (see [§3.4.5](#3.4.5)), and the concatenation operator (see [§3.4.6](#3.4.6)). Unary operators comprise the unary minus (see [§3.4.1](#3.4.1)), the unary bitwise NOT (see [§3.4.2](#3.4.2)), the unary logical **not** (see [§3.4.5](#3.4.5)), and the unary *length operator* (see [§3.4.7](#3.4.7)). Both function calls and vararg expressions can result in multiple values. If a function call is used as a statement (see [§3.3.6](#3.3.6)), then its return list is adjusted to zero elements, thus discarding all returned values. If an expression is used as the last (or the only) element of a list of expressions, then no adjustment is made (unless the expression is enclosed in parentheses). In all other contexts, Lua adjusts the result list to one element, either discarding all values except the first one or adding a single **nil** if there are no values. Here are some examples: ``` f() -- adjusted to 0 results g(f(), x) -- f() is adjusted to 1 result g(x, f()) -- g gets x plus all results from f() a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil) a,b = ... -- a gets the first vararg argument, b gets -- the second (both a and b can get nil if there -- is no corresponding vararg argument) a,b,c = x, f() -- f() is adjusted to 2 results a,b,c = f() -- f() is adjusted to 3 results return f() -- returns all results from f() return ... -- returns all received vararg arguments return x,y,f() -- returns x, y, and all results from f() {f()} -- creates a list with all results from f() {...} -- creates a list with all vararg arguments {f(), nil} -- f() is adjusted to 1 result ``` Any expression enclosed in parentheses always results in only one value. Thus, `(f(x,y,z))` is always a single value, even if `f` returns several values. (The value of `(f(x,y,z))` is the first value returned by `f` or **nil** if `f` does not return any values.) ### 3.4.1 – Arithmetic Operators Lua supports the following arithmetic operators: * `+`: addition * `-`: subtraction * `*`: multiplication * `/`: float division * `//`: floor division * `%`: modulo * `^`: exponentiation * `-`: unary minus With the exception of exponentiation and float division, the arithmetic operators work as follows: If both operands are integers, the operation is performed over integers and the result is an integer. Otherwise, if both operands are numbers, then they are converted to floats, the operation is performed following the machine's rules for floating-point arithmetic (usually the IEEE 754 standard), and the result is a float. (The string library coerces strings to numbers in arithmetic operations; see [§3.4.3](#3.4.3) for details.) Exponentiation and float division (`/`) always convert their operands to floats and the result is always a float. Exponentiation uses the ISO C function `pow`, so that it works for non-integer exponents too. Floor division (`//`) is a division that rounds the quotient towards minus infinity, resulting in the floor of the division of its operands. Modulo is defined as the remainder of a division that rounds the quotient towards minus infinity (floor division). In case of overflows in integer arithmetic, all operations *wrap around*. ### 3.4.2 – Bitwise Operators Lua supports the following bitwise operators: * `&`: bitwise AND * `|`: bitwise OR * `~`: bitwise exclusive OR * `>>`: right shift * `<<`: left shift * `~`: unary bitwise NOT All bitwise operations convert its operands to integers (see [§3.4.3](#3.4.3)), operate on all bits of those integers, and result in an integer. Both right and left shifts fill the vacant bits with zeros. Negative displacements shift to the other direction; displacements with absolute values equal to or higher than the number of bits in an integer result in zero (as all bits are shifted out). ### 3.4.3 – Coercions and Conversions Lua provides some automatic conversions between some types and representations at run time. Bitwise operators always convert float operands to integers. Exponentiation and float division always convert integer operands to floats. All other arithmetic operations applied to mixed numbers (integers and floats) convert the integer operand to a float. The C API also converts both integers to floats and floats to integers, as needed. Moreover, string concatenation accepts numbers as arguments, besides strings. In a conversion from integer to float, if the integer value has an exact representation as a float, that is the result. Otherwise, the conversion gets the nearest higher or the nearest lower representable value. This kind of conversion never fails. The conversion from float to integer checks whether the float has an exact representation as an integer (that is, the float has an integral value and it is in the range of integer representation). If it does, that representation is the result. Otherwise, the conversion fails. Several places in Lua coerce strings to numbers when necessary. In particular, the string library sets metamethods that try to coerce strings to numbers in all arithmetic operations. If the conversion fails, the library calls the metamethod of the other operand (if present) or it raises an error. Note that bitwise operators do not do this coercion. Nonetheless, it is always a good practice not to rely on these implicit coercions, as they are not always applied; in particular, `"1"==1` is false and `"1"<1` raises an error (see [§3.4.4](#3.4.4)). These coercions exist mainly for compatibility and may be removed in future versions of the language. A string is converted to an integer or a float following its syntax and the rules of the Lua lexer. The string may have also leading and trailing whitespaces and a sign. All conversions from strings to numbers accept both a dot and the current locale mark as the radix character. (The Lua lexer, however, accepts only a dot.) If the string is not a valid numeral, the conversion fails. If necessary, the result of this first step is then converted to a specific number subtype following the previous rules for conversions between floats and integers. The conversion from numbers to strings uses a non-specified human-readable format. To convert numbers to strings in any specific way, use the function [`string.format`](#pdf-string.format). ### 3.4.4 – Relational Operators Lua supports the following relational operators: * `==`: equality * `~=`: inequality * `<`: less than * `>`: greater than * `<=`: less or equal * `>=`: greater or equal These operators always result in **false** or **true**. Equality (`==`) first compares the type of its operands. If the types are different, then the result is **false**. Otherwise, the values of the operands are compared. Strings are equal if they have the same byte content. Numbers are equal if they denote the same mathematical value. Tables, userdata, and threads are compared by reference: two objects are considered equal only if they are the same object. Every time you create a new object (a table, a userdata, or a thread), this new object is different from any previously existing object. A function is always equal to itself. Functions with any detectable difference (different behavior, different definition) are always different. Functions created at different times but with no detectable differences may be classified as equal or not (depending on internal caching details). You can change the way that Lua compares tables and userdata by using the `__eq` metamethod (see [§2.4](#2.4)). Equality comparisons do not convert strings to numbers or vice versa. Thus, `"0"==0` evaluates to **false**, and `t[0]` and `t["0"]` denote different entries in a table. The operator `~=` is exactly the negation of equality (`==`). The order operators work as follows. If both arguments are numbers, then they are compared according to their mathematical values, regardless of their subtypes. Otherwise, if both arguments are strings, then their values are compared according to the current locale. Otherwise, Lua tries to call the `__lt` or the `__le` metamethod (see [§2.4](#2.4)). A comparison `a > b` is translated to `b < a` and `a >= b` is translated to `b <= a`. Following the IEEE 754 standard, the special value NaN is considered neither less than, nor equal to, nor greater than any value, including itself. ### 3.4.5 – Logical Operators The logical operators in Lua are **and**, **or**, and **not**. Like the control structures (see [§3.3.4](#3.3.4)), all logical operators consider both **false** and **nil** as false and anything else as true. The negation operator **not** always returns **false** or **true**. The conjunction operator **and** returns its first argument if this value is **false** or **nil**; otherwise, **and** returns its second argument. The disjunction operator **or** returns its first argument if this value is different from **nil** and **false**; otherwise, **or** returns its second argument. Both **and** and **or** use short-circuit evaluation; that is, the second operand is evaluated only if necessary. Here are some examples: ``` 10 or 20 --> 10 10 or error() --> 10 nil or "a" --> "a" nil and 10 --> nil false and error() --> false false and nil --> false false or nil --> nil 10 and 20 --> 20 ``` ### 3.4.6 – Concatenation The string concatenation operator in Lua is denoted by two dots ('`..`'). If both operands are strings or numbers, then the numbers are converted to strings in a non-specified format (see [§3.4.3](#3.4.3)). Otherwise, the `__concat` metamethod is called (see [§2.4](#2.4)). ### 3.4.7 – The Length Operator The length operator is denoted by the unary prefix operator `#`. The length of a string is its number of bytes. (That is the usual meaning of string length when each character is one byte.) The length operator applied on a table returns a border in that table. A *border* in a table `t` is any natural number that satisfies the following condition: ``` (border == 0 or t[border] ~= nil) and t[border + 1] == nil ``` In words, a border is any (natural) index present in the table that is followed by an absent index (or zero, when index 1 is absent). A table with exactly one border is called a *sequence*. For instance, the table `{10, 20, 30, 40, 50}` is a sequence, as it has only one border (5). The table `{10, 20, 30, nil, 50}` has two borders (3 and 5), and therefore it is not a sequence. (The **nil** at index 4 is called a *hole*.) The table `{nil, 20, 30, nil, nil, 60, nil}` has three borders (0, 3, and 6) and three holes (at indices 1, 4, and 5), so it is not a sequence, too. The table `{}` is a sequence with border 0. Note that non-natural keys do not interfere with whether a table is a sequence. When `t` is a sequence, `#t` returns its only border, which corresponds to the intuitive notion of the length of the sequence. When `t` is not a sequence, `#t` can return any of its borders. (The exact one depends on details of the internal representation of the table, which in turn can depend on how the table was populated and the memory addresses of its non-numeric keys.) The computation of the length of a table has a guaranteed worst time of *O(log n)*, where *n* is the largest natural key in the table. A program can modify the behavior of the length operator for any value but strings through the `__len` metamethod (see [§2.4](#2.4)). ### 3.4.8 – Precedence Operator precedence in Lua follows the table below, from lower to higher priority: ``` or and < > <= >= ~= == | ~ & << >> .. + - * / // % unary operators (not # - ~) ^ ``` As usual, you can use parentheses to change the precedences of an expression. The concatenation ('`..`') and exponentiation ('`^`') operators are right associative. All other binary operators are left associative. ### 3.4.9 – Table Constructors Table constructors are expressions that create tables. Every time a constructor is evaluated, a new table is created. A constructor can be used to create an empty table or to create a table and initialize some of its fields. The general syntax for constructors is ``` tableconstructor ::= ‘{’ [fieldlist] ‘}’ fieldlist ::= field {fieldsep field} [fieldsep] field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp fieldsep ::= ‘,’ | ‘;’ ``` Each field of the form `[exp1] = exp2` adds to the new table an entry with key `exp1` and value `exp2`. A field of the form `name = exp` is equivalent to `["name"] = exp`. Fields of the form `exp` are equivalent to `[i] = exp`, where `i` are consecutive integers starting with 1; fields in the other formats do not affect this counting. For example, ``` a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } ``` is equivalent to ``` do local t = {} t[f(1)] = g t[1] = "x" -- 1st exp t[2] = "y" -- 2nd exp t.x = 1 -- t["x"] = 1 t[3] = f(x) -- 3rd exp t[30] = 23 t[4] = 45 -- 4th exp a = t end ``` The order of the assignments in a constructor is undefined. (This order would be relevant only when there are repeated keys.) If the last field in the list has the form `exp` and the expression is a function call or a vararg expression, then all values returned by this expression enter the list consecutively (see [§3.4.10](#3.4.10)). The field list can have an optional trailing separator, as a convenience for machine-generated code. ### 3.4.10 – Function Calls A function call in Lua has the following syntax: ``` functioncall ::= prefixexp args ``` In a function call, first prefixexp and args are evaluated. If the value of prefixexp has type *function*, then this function is called with the given arguments. Otherwise, if present, the prefixexp `__call` metamethod is called: its first argument is the value of prefixexp, followed by the original call arguments (see [§2.4](#2.4)). The form ``` functioncall ::= prefixexp ‘:’ Name args ``` can be used to emulate methods. A call `v:name(*args*)` is syntactic sugar for `v.name(v,*args*)`, except that `v` is evaluated only once. Arguments have the following syntax: ``` args ::= ‘(’ [explist] ‘)’ args ::= tableconstructor args ::= LiteralString ``` All argument expressions are evaluated before the call. A call of the form `f{*fields*}` is syntactic sugar for `f({*fields*})`; that is, the argument list is a single new table. A call of the form `f'*string*'` (or `f"*string*"` or `f[[*string*]]`) is syntactic sugar for `f('*string*')`; that is, the argument list is a single literal string. A call of the form `return *functioncall*` not in the scope of a to-be-closed variable is called a *tail call*. Lua implements *proper tail calls* (or *proper tail recursion*): in a tail call, the called function reuses the stack entry of the calling function. Therefore, there is no limit on the number of nested tail calls that a program can execute. However, a tail call erases any debug information about the calling function. Note that a tail call only happens with a particular syntax, where the **return** has one single function call as argument, and it is outside the scope of any to-be-closed variable. This syntax makes the calling function return exactly the returns of the called function, without any intervening action. So, none of the following examples are tail calls: ``` return (f(x)) -- results adjusted to 1 return 2 * f(x) -- result multiplied by 2 return x, f(x) -- additional results f(x); return -- results discarded return x or f(x) -- results adjusted to 1 ``` ### 3.4.11 – Function Definitions The syntax for function definition is ``` functiondef ::= function funcbody funcbody ::= ‘(’ [parlist] ‘)’ block end ``` The following syntactic sugar simplifies function definitions: ``` stat ::= function funcname funcbody stat ::= local function Name funcbody funcname ::= Name {‘.’ Name} [‘:’ Name] ``` The statement ``` function f () body end ``` translates to ``` f = function () body end ``` The statement ``` function t.a.b.c.f () body end ``` translates to ``` t.a.b.c.f = function () body end ``` The statement ``` local function f () body end ``` translates to ``` local f; f = function () body end ``` not to ``` local f = function () body end ``` (This only makes a difference when the body of the function contains references to `f`.) A function definition is an executable expression, whose value has type *function*. When Lua precompiles a chunk, all its function bodies are precompiled too, but they are not created yet. Then, whenever Lua executes the function definition, the function is *instantiated* (or *closed*). This function instance, or *closure*, is the final value of the expression. Parameters act as local variables that are initialized with the argument values: ``` parlist ::= namelist [‘,’ ‘...’] | ‘...’ ``` When a Lua function is called, it adjusts its list of arguments to the length of its list of parameters, unless the function is a *vararg function*, which is indicated by three dots ('`...`') at the end of its parameter list. A vararg function does not adjust its argument list; instead, it collects all extra arguments and supplies them to the function through a *vararg expression*, which is also written as three dots. The value of this expression is a list of all actual extra arguments, similar to a function with multiple results. If a vararg expression is used inside another expression or in the middle of a list of expressions, then its return list is adjusted to one element. If the expression is used as the last element of a list of expressions, then no adjustment is made (unless that last expression is enclosed in parentheses). As an example, consider the following definitions: ``` function f(a, b) end function g(a, b, ...) end function r() return 1,2,3 end ``` Then, we have the following mapping from arguments to parameters and to the vararg expression: ``` CALL PARAMETERS f(3) a=3, b=nil f(3, 4) a=3, b=4 f(3, 4, 5) a=3, b=4 f(r(), 10) a=1, b=10 f(r()) a=1, b=2 g(3) a=3, b=nil, ... --> (nothing) g(3, 4) a=3, b=4, ... --> (nothing) g(3, 4, 5, 8) a=3, b=4, ... --> 5 8 g(5, r()) a=5, b=1, ... --> 2 3 ``` Results are returned using the **return** statement (see [§3.3.4](#3.3.4)). If control reaches the end of a function without encountering a **return** statement, then the function returns with no results. There is a system-dependent limit on the number of values that a function may return. This limit is guaranteed to be greater than 1000. The *colon* syntax is used to emulate *methods*, adding an implicit extra parameter `self` to the function. Thus, the statement ``` function t.a.b.c:f (params) body end ``` is syntactic sugar for ``` t.a.b.c.f = function (self, params) body end ``` 3.5 – Visibility Rules ---------------------- Lua is a lexically scoped language. The scope of a local variable begins at the first statement after its declaration and lasts until the last non-void statement of the innermost block that includes the declaration. Consider the following example: ``` x = 10 -- global variable do -- new block local x = x -- new 'x', with value 10 print(x) --> 10 x = x+1 do -- another block local x = x+1 -- another 'x' print(x) --> 12 end print(x) --> 11 end print(x) --> 10 (the global one) ``` Notice that, in a declaration like `local x = x`, the new `x` being declared is not in scope yet, and so the second `x` refers to the outside variable. Because of the lexical scoping rules, local variables can be freely accessed by functions defined inside their scope. A local variable used by an inner function is called an *upvalue* (or *external local variable*, or simply *external variable*) inside the inner function. Notice that each execution of a **local** statement defines new local variables. Consider the following example: ``` a = {} local x = 20 for i = 1, 10 do local y = 0 a[i] = function () y = y + 1; return x + y end end ``` The loop creates ten closures (that is, ten instances of the anonymous function). Each of these closures uses a different `y` variable, while all of them share the same `x`. 4 – The Application Program Interface ===================================== This section describes the C API for Lua, that is, the set of C functions available to the host program to communicate with Lua. All API functions and related types and constants are declared in the header file `lua.h`. Even when we use the term "function", any facility in the API may be provided as a macro instead. Except where stated otherwise, all such macros use each of their arguments exactly once (except for the first argument, which is always a Lua state), and so do not generate any hidden side-effects. As in most C libraries, the Lua API functions do not check their arguments for validity or consistency. However, you can change this behavior by compiling Lua with the macro `LUA_USE_APICHECK` defined. The Lua library is fully reentrant: it has no global variables. It keeps all information it needs in a dynamic structure, called the *Lua state*. Each Lua state has one or more threads, which correspond to independent, cooperative lines of execution. The type [`lua_State`](#lua_State) (despite its name) refers to a thread. (Indirectly, through the thread, it also refers to the Lua state associated to the thread.) A pointer to a thread must be passed as the first argument to every function in the library, except to [`lua_newstate`](#lua_newstate), which creates a Lua state from scratch and returns a pointer to the *main thread* in the new state. 4.1 – The Stack --------------- Lua uses a *virtual stack* to pass values to and from C. Each element in this stack represents a Lua value (**nil**, number, string, etc.). Functions in the API can access this stack through the Lua state parameter that they receive. Whenever Lua calls C, the called function gets a new stack, which is independent of previous stacks and of stacks of C functions that are still active. This stack initially contains any arguments to the C function and it is where the C function can store temporary Lua values and must push its results to be returned to the caller (see [`lua_CFunction`](#lua_CFunction)). For convenience, most query operations in the API do not follow a strict stack discipline. Instead, they can refer to any element in the stack by using an *index*: A positive index represents an absolute stack position, starting at 1 as the bottom of the stack; a negative index represents an offset relative to the top of the stack. More specifically, if the stack has *n* elements, then index 1 represents the first element (that is, the element that was pushed onto the stack first) and index *n* represents the last element; index -1 also represents the last element (that is, the element at the top) and index *-n* represents the first element. ### 4.1.1 – Stack Size When you interact with the Lua API, you are responsible for ensuring consistency. In particular, *you are responsible for controlling stack overflow*. You can use the function [`lua_checkstack`](#lua_checkstack) to ensure that the stack has enough space for pushing new elements. Whenever Lua calls C, it ensures that the stack has space for at least `LUA_MINSTACK` extra elements; that is, you can safely push up to `LUA_MINSTACK` values into it. `LUA_MINSTACK` is defined as 20, so that usually you do not have to worry about stack space unless your code has loops pushing elements onto the stack. When you call a Lua function without a fixed number of results (see [`lua_call`](#lua_call)), Lua ensures that the stack has enough space for all results, but it does not ensure any extra space. So, before pushing anything on the stack after such a call you should use [`lua_checkstack`](#lua_checkstack). ### 4.1.2 – Valid and Acceptable Indices Any function in the API that receives stack indices works only with *valid indices* or *acceptable indices*. A *valid index* is an index that refers to a position that stores a modifiable Lua value. It comprises stack indices between 1 and the stack top (`1 ≤ abs(index) ≤ top`) plus *pseudo-indices*, which represent some positions that are accessible to C code but that are not in the stack. Pseudo-indices are used to access the registry (see [§4.3](#4.3)) and the upvalues of a C function (see [§4.2](#4.2)). Functions that do not need a specific mutable position, but only a value (e.g., query functions), can be called with acceptable indices. An *acceptable index* can be any valid index, but it also can be any positive index after the stack top within the space allocated for the stack, that is, indices up to the stack size. (Note that 0 is never an acceptable index.) Indices to upvalues (see [§4.2](#4.2)) greater than the real number of upvalues in the current C function are also acceptable (but invalid). Except when noted otherwise, functions in the API work with acceptable indices. Acceptable indices serve to avoid extra tests against the stack top when querying the stack. For instance, a C function can query its third argument without the need to check whether there is a third argument, that is, without the need to check whether 3 is a valid index. For functions that can be called with acceptable indices, any non-valid index is treated as if it contains a value of a virtual type `LUA_TNONE`, which behaves like a nil value. ### 4.1.3 – Pointers to strings Several functions in the API return pointers (`const char*`) to Lua strings in the stack. (See [`lua_pushfstring`](#lua_pushfstring), [`lua_pushlstring`](#lua_pushlstring), [`lua_pushstring`](#lua_pushstring), and [`lua_tolstring`](#lua_tolstring). See also [`luaL_checklstring`](#luaL_checklstring), [`luaL_checkstring`](#luaL_checkstring), and [`luaL_tolstring`](#luaL_tolstring) in the auxiliary library.) In general, Lua's garbage collection can free or move internal memory and then invalidate pointers to internal strings. To allow a safe use of these pointers, The API guarantees that any pointer to a string in a stack index is valid while the value at that index is neither modified nor popped. When the index is a pseudo-index (referring to an upvalue), the pointer is valid while the corresponding call is active and the corresponding upvalue is not modified. Some functions in the debug interface also return pointers to strings, namely [`lua_getlocal`](#lua_getlocal), [`lua_getupvalue`](#lua_getupvalue), [`lua_setlocal`](#lua_setlocal), and [`lua_setupvalue`](#lua_setupvalue). For these functions, the pointer is guaranteed to be valid while the caller function is active and the given closure (if one was given) is in the stack. Except for these guarantees, the garbage collector is free to invalidate any pointer to internal strings. 4.2 – C Closures ---------------- When a C function is created, it is possible to associate some values with it, thus creating a *C closure* (see [`lua_pushcclosure`](#lua_pushcclosure)); these values are called *upvalues* and are accessible to the function whenever it is called. Whenever a C function is called, its upvalues are located at specific pseudo-indices. These pseudo-indices are produced by the macro [`lua_upvalueindex`](#lua_upvalueindex). The first upvalue associated with a function is at index `lua_upvalueindex(1)`, and so on. Any access to `lua_upvalueindex(*n*)`, where *n* is greater than the number of upvalues of the current function (but not greater than 256, which is one plus the maximum number of upvalues in a closure), produces an acceptable but invalid index. A C closure can also change the values of its corresponding upvalues. 4.3 – Registry -------------- Lua provides a *registry*, a predefined table that can be used by any C code to store whatever Lua values it needs to store. The registry table is always accessible at pseudo-index `LUA_REGISTRYINDEX`. Any C library can store data into this table, but it must take care to choose keys that are different from those used by other libraries, to avoid collisions. Typically, you should use as key a string containing your library name, or a light userdata with the address of a C object in your code, or any Lua object created by your code. As with variable names, string keys starting with an underscore followed by uppercase letters are reserved for Lua. The integer keys in the registry are used by the reference mechanism (see [`luaL_ref`](#luaL_ref)) and by some predefined values. Therefore, integer keys in the registry must not be used for other purposes. When you create a new Lua state, its registry comes with some predefined values. These predefined values are indexed with integer keys defined as constants in `lua.h`. The following constants are defined: * **`LUA_RIDX_MAINTHREAD`:** At this index the registry has the main thread of the state. (The main thread is the one created together with the state.) * **`LUA_RIDX_GLOBALS`:** At this index the registry has the global environment. 4.4 – Error Handling in C ------------------------- Internally, Lua uses the C `longjmp` facility to handle errors. (Lua will use exceptions if you compile it as C++; search for `LUAI_THROW` in the source code for details.) When Lua faces any error, such as a memory allocation error or a type error, it *raises* an error; that is, it does a long jump. A *protected environment* uses `setjmp` to set a recovery point; any error jumps to the most recent active recovery point. Inside a C function you can raise an error explicitly by calling [`lua_error`](#lua_error). Most functions in the API can raise an error, for instance due to a memory allocation error. The documentation for each function indicates whether it can raise errors. If an error happens outside any protected environment, Lua calls a *panic function* (see [`lua_atpanic`](#lua_atpanic)) and then calls `abort`, thus exiting the host application. Your panic function can avoid this exit by never returning (e.g., doing a long jump to your own recovery point outside Lua). The panic function, as its name implies, is a mechanism of last resort. Programs should avoid it. As a general rule, when a C function is called by Lua with a Lua state, it can do whatever it wants on that Lua state, as it should be already protected. However, when C code operates on other Lua states (e.g., a Lua-state argument to the function, a Lua state stored in the registry, or the result of [`lua_newthread`](#lua_newthread)), it should use them only in API calls that cannot raise errors. The panic function runs as if it were a message handler (see [§2.3](#2.3)); in particular, the error object is on the top of the stack. However, there is no guarantee about stack space. To push anything on the stack, the panic function must first check the available space (see [§4.1.1](#4.1.1)). ### 4.4.1 – Status Codes Several functions that report errors in the API use the following status codes to indicate different kinds of errors or other conditions: * **`LUA_OK` (0):** no errors. * **`LUA_ERRRUN`:** a runtime error. * **`LUA_ERRMEM`:** memory allocation error. For such errors, Lua does not call the message handler. * **`LUA_ERRERR`:** error while running the message handler. * **`LUA_ERRSYNTAX`:** syntax error during precompilation. * **`LUA_YIELD`:** the thread (coroutine) yields. * **`LUA_ERRFILE`:** a file-related error; e.g., it cannot open or read the file. These constants are defined in the header file `lua.h`. 4.5 – Handling Yields in C -------------------------- Internally, Lua uses the C `longjmp` facility to yield a coroutine. Therefore, if a C function `foo` calls an API function and this API function yields (directly or indirectly by calling another function that yields), Lua cannot return to `foo` any more, because the `longjmp` removes its frame from the C stack. To avoid this kind of problem, Lua raises an error whenever it tries to yield across an API call, except for three functions: [`lua_yieldk`](#lua_yieldk), [`lua_callk`](#lua_callk), and [`lua_pcallk`](#lua_pcallk). All those functions receive a *continuation function* (as a parameter named `k`) to continue execution after a yield. We need to set some terminology to explain continuations. We have a C function called from Lua which we will call the *original function*. This original function then calls one of those three functions in the C API, which we will call the *callee function*, that then yields the current thread. This can happen when the callee function is [`lua_yieldk`](#lua_yieldk), or when the callee function is either [`lua_callk`](#lua_callk) or [`lua_pcallk`](#lua_pcallk) and the function called by them yields. Suppose the running thread yields while executing the callee function. After the thread resumes, it eventually will finish running the callee function. However, the callee function cannot return to the original function, because its frame in the C stack was destroyed by the yield. Instead, Lua calls a *continuation function*, which was given as an argument to the callee function. As the name implies, the continuation function should continue the task of the original function. As an illustration, consider the following function: ``` int original_function (lua_State *L) { ... /* code 1 */ status = lua_pcall(L, n, m, h); /* calls Lua */ ... /* code 2 */ } ``` Now we want to allow the Lua code being run by [`lua_pcall`](#lua_pcall) to yield. First, we can rewrite our function like here: ``` int k (lua_State *L, int status, lua_KContext ctx) { ... /* code 2 */ } int original_function (lua_State *L) { ... /* code 1 */ return k(L, lua_pcall(L, n, m, h), ctx); } ``` In the above code, the new function `k` is a *continuation function* (with type [`lua_KFunction`](#lua_KFunction)), which should do all the work that the original function was doing after calling [`lua_pcall`](#lua_pcall). Now, we must inform Lua that it must call `k` if the Lua code being executed by [`lua_pcall`](#lua_pcall) gets interrupted in some way (errors or yielding), so we rewrite the code as here, replacing [`lua_pcall`](#lua_pcall) by [`lua_pcallk`](#lua_pcallk): ``` int original_function (lua_State *L) { ... /* code 1 */ return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1); } ``` Note the external, explicit call to the continuation: Lua will call the continuation only if needed, that is, in case of errors or resuming after a yield. If the called function returns normally without ever yielding, [`lua_pcallk`](#lua_pcallk) (and [`lua_callk`](#lua_callk)) will also return normally. (Of course, instead of calling the continuation in that case, you can do the equivalent work directly inside the original function.) Besides the Lua state, the continuation function has two other parameters: the final status of the call and the context value (`ctx`) that was passed originally to [`lua_pcallk`](#lua_pcallk). Lua does not use this context value; it only passes this value from the original function to the continuation function. For [`lua_pcallk`](#lua_pcallk), the status is the same value that would be returned by [`lua_pcallk`](#lua_pcallk), except that it is [`LUA_YIELD`](#pdf-LUA_YIELD) when being executed after a yield (instead of [`LUA_OK`](#pdf-LUA_OK)). For [`lua_yieldk`](#lua_yieldk) and [`lua_callk`](#lua_callk), the status is always [`LUA_YIELD`](#pdf-LUA_YIELD) when Lua calls the continuation. (For these two functions, Lua will not call the continuation in case of errors, because they do not handle errors.) Similarly, when using [`lua_callk`](#lua_callk), you should call the continuation function with [`LUA_OK`](#pdf-LUA_OK) as the status. (For [`lua_yieldk`](#lua_yieldk), there is not much point in calling directly the continuation function, because [`lua_yieldk`](#lua_yieldk) usually does not return.) Lua treats the continuation function as if it were the original function. The continuation function receives the same Lua stack from the original function, in the same state it would be if the callee function had returned. (For instance, after a [`lua_callk`](#lua_callk) the function and its arguments are removed from the stack and replaced by the results from the call.) It also has the same upvalues. Whatever it returns is handled by Lua as if it were the return of the original function. 4.6 – Functions and Types[-o, +p, *x*] -------------------------------------- Here we list all functions and types from the C API in alphabetical order. Each function has an indicator like this: The first field, `o`, is how many elements the function pops from the stack. The second field, `p`, is how many elements the function pushes onto the stack. (Any function always pushes its results after popping its arguments.) A field in the form `x|y` means the function can push (or pop) `x` or `y` elements, depending on the situation; an interrogation mark '`?`' means that we cannot know how many elements the function pops/pushes by looking only at its arguments. (For instance, they may depend on what is in the stack.) The third field, `x`, tells whether the function may raise errors: '`-`' means the function never raises any error; '`m`' means the function may raise only out-of-memory errors; '`v`' means the function may raise the errors explained in the text; '`e`' means the function can run arbitrary Lua code, either directly or through metamethods, and therefore may raise any errors. ### `lua_absindex`[-0, +0, –] ``` int lua_absindex (lua_State *L, int idx); ``` Converts the acceptable index `idx` into an equivalent absolute index (that is, one that does not depend on the stack top). ### `lua_Alloc` ``` typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); ``` The type of the memory-allocation function used by Lua states. The allocator function must provide a functionality similar to `realloc`, but not exactly the same. Its arguments are `ud`, an opaque pointer passed to [`lua_newstate`](#lua_newstate); `ptr`, a pointer to the block being allocated/reallocated/freed; `osize`, the original size of the block or some code about what is being allocated; and `nsize`, the new size of the block. When `ptr` is not `NULL`, `osize` is the size of the block pointed by `ptr`, that is, the size given when it was allocated or reallocated. When `ptr` is `NULL`, `osize` encodes the kind of object that Lua is allocating. `osize` is any of [`LUA_TSTRING`](#pdf-LUA_TSTRING), [`LUA_TTABLE`](#pdf-LUA_TTABLE), [`LUA_TFUNCTION`](#pdf-LUA_TFUNCTION), [`LUA_TUSERDATA`](#pdf-LUA_TUSERDATA), or [`LUA_TTHREAD`](#pdf-LUA_TTHREAD) when (and only when) Lua is creating a new object of that type. When `osize` is some other value, Lua is allocating memory for something else. Lua assumes the following behavior from the allocator function: When `nsize` is zero, the allocator must behave like `free` and then return `NULL`. When `nsize` is not zero, the allocator must behave like `realloc`. In particular, the allocator returns `NULL` if and only if it cannot fulfill the request. Here is a simple implementation for the allocator function. It is used in the auxiliary library by [`luaL_newstate`](#luaL_newstate). ``` static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; /* not used */ if (nsize == 0) { free(ptr); return NULL; } else return realloc(ptr, nsize); } ``` Note that Standard C ensures that `free(NULL)` has no effect and that `realloc(NULL,size)` is equivalent to `malloc(size)`. ### `lua_arith`[-(2|1), +1, *e*] ``` void lua_arith (lua_State *L, int op); ``` Performs an arithmetic or bitwise operation over the two values (or one, in the case of negations) at the top of the stack, with the value on the top being the second operand, pops these values, and pushes the result of the operation. The function follows the semantics of the corresponding Lua operator (that is, it may call metamethods). The value of `op` must be one of the following constants: * **`LUA_OPADD`:** performs addition (`+`) * **`LUA_OPSUB`:** performs subtraction (`-`) * **`LUA_OPMUL`:** performs multiplication (`*`) * **`LUA_OPDIV`:** performs float division (`/`) * **`LUA_OPIDIV`:** performs floor division (`//`) * **`LUA_OPMOD`:** performs modulo (`%`) * **`LUA_OPPOW`:** performs exponentiation (`^`) * **`LUA_OPUNM`:** performs mathematical negation (unary `-`) * **`LUA_OPBNOT`:** performs bitwise NOT (`~`) * **`LUA_OPBAND`:** performs bitwise AND (`&`) * **`LUA_OPBOR`:** performs bitwise OR (`|`) * **`LUA_OPBXOR`:** performs bitwise exclusive OR (`~`) * **`LUA_OPSHL`:** performs left shift (`<<`) * **`LUA_OPSHR`:** performs right shift (`>>`) ### `lua_atpanic`[-0, +0, –] ``` lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf); ``` Sets a new panic function and returns the old one (see [§4.4](#4.4)). ### `lua_call`[-(nargs+1), +nresults, *e*] ``` void lua_call (lua_State *L, int nargs, int nresults); ``` Calls a function. Like regular Lua calls, `lua_call` respects the `__call` metamethod. So, here the word "function" means any callable value. To do a call you must use the following protocol: first, the function to be called is pushed onto the stack; then, the arguments to the call are pushed in direct order; that is, the first argument is pushed first. Finally you call [`lua_call`](#lua_call); `nargs` is the number of arguments that you pushed onto the stack. When the function returns, all arguments and the function value are popped and the call results are pushed onto the stack. The number of results is adjusted to `nresults`, unless `nresults` is `LUA_MULTRET`. In this case, all results from the function are pushed; Lua takes care that the returned values fit into the stack space, but it does not ensure any extra space in the stack. The function results are pushed onto the stack in direct order (the first result is pushed first), so that after the call the last result is on the top of the stack. Any error while calling and running the function is propagated upwards (with a `longjmp`). The following example shows how the host program can do the equivalent to this Lua code: ``` a = f("how", t.x, 14) ``` Here it is in C: ``` lua_getglobal(L, "f"); /* function to be called */ lua_pushliteral(L, "how"); /* 1st argument */ lua_getglobal(L, "t"); /* table to be indexed */ lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */ lua_remove(L, -2); /* remove 't' from the stack */ lua_pushinteger(L, 14); /* 3rd argument */ lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */ lua_setglobal(L, "a"); /* set global 'a' */ ``` Note that the code above is *balanced*: at its end, the stack is back to its original configuration. This is considered good programming practice. ### `lua_callk`[-(nargs + 1), +nresults, *e*] ``` void lua_callk (lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k); ``` This function behaves exactly like [`lua_call`](#lua_call), but allows the called function to yield (see [§4.5](#4.5)). ### `lua_CFunction` ``` typedef int (*lua_CFunction) (lua_State *L); ``` Type for C functions. In order to communicate properly with Lua, a C function must use the following protocol, which defines the way parameters and results are passed: a C function receives its arguments from Lua in its stack in direct order (the first argument is pushed first). So, when the function starts, `lua_gettop(L)` returns the number of arguments received by the function. The first argument (if any) is at index 1 and its last argument is at index `lua_gettop(L)`. To return values to Lua, a C function just pushes them onto the stack, in direct order (the first result is pushed first), and returns in C the number of results. Any other value in the stack below the results will be properly discarded by Lua. Like a Lua function, a C function called by Lua can also return many results. As an example, the following function receives a variable number of numeric arguments and returns their average and their sum: ``` static int foo (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ lua_Number sum = 0.0; int i; for (i = 1; i <= n; i++) { if (!lua_isnumber(L, i)) { lua_pushliteral(L, "incorrect argument"); lua_error(L); } sum += lua_tonumber(L, i); } lua_pushnumber(L, sum/n); /* first result */ lua_pushnumber(L, sum); /* second result */ return 2; /* number of results */ } ``` ### `lua_checkstack`[-0, +0, –] ``` int lua_checkstack (lua_State *L, int n); ``` Ensures that the stack has space for at least `n` extra elements, that is, that you can safely push up to `n` values into it. It returns false if it cannot fulfill the request, either because it would cause the stack to be greater than a fixed maximum size (typically at least several thousand elements) or because it cannot allocate memory for the extra space. This function never shrinks the stack; if the stack already has space for the extra elements, it is left unchanged. ### `lua_close`[-0, +0, –] ``` void lua_close (lua_State *L); ``` Close all active to-be-closed variables in the main thread, release all objects in the given Lua state (calling the corresponding garbage-collection metamethods, if any), and frees all dynamic memory used by this state. On several platforms, you may not need to call this function, because all resources are naturally released when the host program ends. On the other hand, long-running programs that create multiple states, such as daemons or web servers, will probably need to close states as soon as they are not needed. ### `lua_compare`[-0, +0, *e*] ``` int lua_compare (lua_State *L, int index1, int index2, int op); ``` Compares two Lua values. Returns 1 if the value at index `index1` satisfies `op` when compared with the value at index `index2`, following the semantics of the corresponding Lua operator (that is, it may call metamethods). Otherwise returns 0. Also returns 0 if any of the indices is not valid. The value of `op` must be one of the following constants: * **`LUA_OPEQ`:** compares for equality (`==`) * **`LUA_OPLT`:** compares for less than (`<`) * **`LUA_OPLE`:** compares for less or equal (`<=`) ### `lua_concat`[-n, +1, *e*] ``` void lua_concat (lua_State *L, int n); ``` Concatenates the `n` values at the top of the stack, pops them, and leaves the result on the top. If `n` is 1, the result is the single value on the stack (that is, the function does nothing); if `n` is 0, the result is the empty string. Concatenation is performed following the usual semantics of Lua (see [§3.4.6](#3.4.6)). ### `lua_copy`[-0, +0, –] ``` void lua_copy (lua_State *L, int fromidx, int toidx); ``` Copies the element at index `fromidx` into the valid index `toidx`, replacing the value at that position. Values at other positions are not affected. ### `lua_createtable`[-0, +1, *m*] ``` void lua_createtable (lua_State *L, int narr, int nrec); ``` Creates a new empty table and pushes it onto the stack. Parameter `narr` is a hint for how many elements the table will have as a sequence; parameter `nrec` is a hint for how many other elements the table will have. Lua may use these hints to preallocate memory for the new table. This preallocation may help performance when you know in advance how many elements the table will have. Otherwise you can use the function [`lua_newtable`](#lua_newtable). ### `lua_dump`[-0, +0, –] ``` int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip); ``` Dumps a function as a binary chunk. Receives a Lua function on the top of the stack and produces a binary chunk that, if loaded again, results in a function equivalent to the one dumped. As it produces parts of the chunk, [`lua_dump`](#lua_dump) calls function `writer` (see [`lua_Writer`](#lua_Writer)) with the given `data` to write them. If `strip` is true, the binary representation may not include all debug information about the function, to save space. The value returned is the error code returned by the last call to the writer; 0 means no errors. This function does not pop the Lua function from the stack. ### `lua_error`[-1, +0, *v*] ``` int lua_error (lua_State *L); ``` Raises a Lua error, using the value on the top of the stack as the error object. This function does a long jump, and therefore never returns (see [`luaL_error`](#luaL_error)). ### `lua_gc`[-0, +0, –] ``` int lua_gc (lua_State *L, int what, ...); ``` Controls the garbage collector. This function performs several tasks, according to the value of the parameter `what`. For options that need extra arguments, they are listed after the option. * `LUA_GCCOLLECT`: Performs a full garbage-collection cycle. * `LUA_GCSTOP`: Stops the garbage collector. * `LUA_GCRESTART`: Restarts the garbage collector. * `LUA_GCCOUNT`: Returns the current amount of memory (in Kbytes) in use by Lua. * `LUA_GCCOUNTB`: Returns the remainder of dividing the current amount of bytes of memory in use by Lua by 1024. `LUA_GCSTEP` `(int stepsize)`: Performs an incremental step of garbage collection, corresponding to the allocation of `stepsize` Kbytes. * `LUA_GCISRUNNING`: Returns a boolean that tells whether the collector is running (i.e., not stopped). * `LUA_GCINC` (int pause, int stepmul, stepsize): Changes the collector to incremental mode with the given parameters (see [§2.5.1](#2.5.1)). Returns the previous mode (`LUA_GCGEN` or `LUA_GCINC`). * `LUA_GCGEN` (int minormul, int majormul): Changes the collector to generational mode with the given parameters (see [§2.5.2](#2.5.2)). Returns the previous mode (`LUA_GCGEN` or `LUA_GCINC`). For more details about these options, see [`collectgarbage`](#pdf-collectgarbage). ### `lua_getallocf`[-0, +0, –] ``` lua_Alloc lua_getallocf (lua_State *L, void **ud); ``` Returns the memory-allocation function of a given state. If `ud` is not `NULL`, Lua stores in `*ud` the opaque pointer given when the memory-allocator function was set. ### `lua_getfield`[-0, +1, *e*] ``` int lua_getfield (lua_State *L, int index, const char *k); ``` Pushes onto the stack the value `t[k]`, where `t` is the value at the given index. As in Lua, this function may trigger a metamethod for the "index" event (see [§2.4](#2.4)). Returns the type of the pushed value. ### `lua_getextraspace`[-0, +0, –] ``` void *lua_getextraspace (lua_State *L); ``` Returns a pointer to a raw memory area associated with the given Lua state. The application can use this area for any purpose; Lua does not use it for anything. Each new thread has this area initialized with a copy of the area of the main thread. By default, this area has the size of a pointer to void, but you can recompile Lua with a different size for this area. (See `LUA_EXTRASPACE` in `luaconf.h`.) ### `lua_getglobal`[-0, +1, *e*] ``` int lua_getglobal (lua_State *L, const char *name); ``` Pushes onto the stack the value of the global `name`. Returns the type of that value. ### `lua_geti`[-0, +1, *e*] ``` int lua_geti (lua_State *L, int index, lua_Integer i); ``` Pushes onto the stack the value `t[i]`, where `t` is the value at the given index. As in Lua, this function may trigger a metamethod for the "index" event (see [§2.4](#2.4)). Returns the type of the pushed value. ### `lua_getmetatable`[-0, +(0|1), –] ``` int lua_getmetatable (lua_State *L, int index); ``` If the value at the given index has a metatable, the function pushes that metatable onto the stack and returns 1. Otherwise, the function returns 0 and pushes nothing on the stack. ### `lua_gettable`[-1, +1, *e*] ``` int lua_gettable (lua_State *L, int index); ``` Pushes onto the stack the value `t[k]`, where `t` is the value at the given index and `k` is the value on the top of the stack. This function pops the key from the stack, pushing the resulting value in its place. As in Lua, this function may trigger a metamethod for the "index" event (see [§2.4](#2.4)). Returns the type of the pushed value. ### `lua_gettop`[-0, +0, –] ``` int lua_gettop (lua_State *L); ``` Returns the index of the top element in the stack. Because indices start at 1, this result is equal to the number of elements in the stack; in particular, 0 means an empty stack. ### `lua_getiuservalue`[-0, +1, –] ``` int lua_getiuservalue (lua_State *L, int index, int n); ``` Pushes onto the stack the `n`-th user value associated with the full userdata at the given index and returns the type of the pushed value. If the userdata does not have that value, pushes **nil** and returns [`LUA_TNONE`](#pdf-LUA_TNONE). ### `lua_insert`[-1, +1, –] ``` void lua_insert (lua_State *L, int index); ``` Moves the top element into the given valid index, shifting up the elements above this index to open space. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position. ### `lua_Integer` ``` typedef ... lua_Integer; ``` The type of integers in Lua. By default this type is `long long`, (usually a 64-bit two-complement integer), but that can be changed to `long` or `int` (usually a 32-bit two-complement integer). (See `LUA_INT_TYPE` in `luaconf.h`.) Lua also defines the constants `LUA_MININTEGER` and `LUA_MAXINTEGER`, with the minimum and the maximum values that fit in this type. ### `lua_isboolean`[-0, +0, –] ``` int lua_isboolean (lua_State *L, int index); ``` Returns 1 if the value at the given index is a boolean, and 0 otherwise. ### `lua_iscfunction`[-0, +0, –] ``` int lua_iscfunction (lua_State *L, int index); ``` Returns 1 if the value at the given index is a C function, and 0 otherwise. ### `lua_isfunction`[-0, +0, –] ``` int lua_isfunction (lua_State *L, int index); ``` Returns 1 if the value at the given index is a function (either C or Lua), and 0 otherwise. ### `lua_isinteger`[-0, +0, –] ``` int lua_isinteger (lua_State *L, int index); ``` Returns 1 if the value at the given index is an integer (that is, the value is a number and is represented as an integer), and 0 otherwise. ### `lua_islightuserdata`[-0, +0, –] ``` int lua_islightuserdata (lua_State *L, int index); ``` Returns 1 if the value at the given index is a light userdata, and 0 otherwise. ### `lua_isnil`[-0, +0, –] ``` int lua_isnil (lua_State *L, int index); ``` Returns 1 if the value at the given index is **nil**, and 0 otherwise. ### `lua_isnone`[-0, +0, –] ``` int lua_isnone (lua_State *L, int index); ``` Returns 1 if the given index is not valid, and 0 otherwise. ### `lua_isnoneornil`[-0, +0, –] ``` int lua_isnoneornil (lua_State *L, int index); ``` Returns 1 if the given index is not valid or if the value at this index is **nil**, and 0 otherwise. ### `lua_isnumber`[-0, +0, –] ``` int lua_isnumber (lua_State *L, int index); ``` Returns 1 if the value at the given index is a number or a string convertible to a number, and 0 otherwise. ### `lua_isstring`[-0, +0, –] ``` int lua_isstring (lua_State *L, int index); ``` Returns 1 if the value at the given index is a string or a number (which is always convertible to a string), and 0 otherwise. ### `lua_istable`[-0, +0, –] ``` int lua_istable (lua_State *L, int index); ``` Returns 1 if the value at the given index is a table, and 0 otherwise. ### `lua_isthread`[-0, +0, –] ``` int lua_isthread (lua_State *L, int index); ``` Returns 1 if the value at the given index is a thread, and 0 otherwise. ### `lua_isuserdata`[-0, +0, –] ``` int lua_isuserdata (lua_State *L, int index); ``` Returns 1 if the value at the given index is a userdata (either full or light), and 0 otherwise. ### `lua_isyieldable`[-0, +0, –] ``` int lua_isyieldable (lua_State *L); ``` Returns 1 if the given coroutine can yield, and 0 otherwise. ### `lua_KContext` ``` typedef ... lua_KContext; ``` The type for continuation-function contexts. It must be a numeric type. This type is defined as `intptr_t` when `intptr_t` is available, so that it can store pointers too. Otherwise, it is defined as `ptrdiff_t`. ### `lua_KFunction` ``` typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx); ``` Type for continuation functions (see [§4.5](#4.5)). ### `lua_len`[-0, +1, *e*] ``` void lua_len (lua_State *L, int index); ``` Returns the length of the value at the given index. It is equivalent to the '`#`' operator in Lua (see [§3.4.7](#3.4.7)) and may trigger a metamethod for the "length" event (see [§2.4](#2.4)). The result is pushed on the stack. ### `lua_load`[-0, +1, –] ``` int lua_load (lua_State *L, lua_Reader reader, void *data, const char *chunkname, const char *mode); ``` Loads a Lua chunk without running it. If there are no errors, `lua_load` pushes the compiled chunk as a Lua function on top of the stack. Otherwise, it pushes an error message. The `lua_load` function uses a user-supplied `reader` function to read the chunk (see [`lua_Reader`](#lua_Reader)). The `data` argument is an opaque value passed to the reader function. The `chunkname` argument gives a name to the chunk, which is used for error messages and in debug information (see [§4.7](#4.7)). `lua_load` automatically detects whether the chunk is text or binary and loads it accordingly (see program `luac`). The string `mode` works as in function [`load`](#pdf-load), with the addition that a `NULL` value is equivalent to the string "`bt`". `lua_load` uses the stack internally, so the reader function must always leave the stack unmodified when returning. `lua_load` can return [`LUA_OK`](#pdf-LUA_OK), [`LUA_ERRSYNTAX`](#pdf-LUA_ERRSYNTAX), or [`LUA_ERRMEM`](#pdf-LUA_ERRMEM). The function may also return other values corresponding to errors raised by the read function (see [§4.4.1](#4.4.1)). If the resulting function has upvalues, its first upvalue is set to the value of the global environment stored at index `LUA_RIDX_GLOBALS` in the registry (see [§4.3](#4.3)). When loading main chunks, this upvalue will be the `_ENV` variable (see [§2.2](#2.2)). Other upvalues are initialized with **nil**. ### `lua_newstate`[-0, +0, –] ``` lua_State *lua_newstate (lua_Alloc f, void *ud); ``` Creates a new independent state and returns its main thread. Returns `NULL` if it cannot create the state (due to lack of memory). The argument `f` is the allocator function; Lua will do all memory allocation for this state through this function (see [`lua_Alloc`](#lua_Alloc)). The second argument, `ud`, is an opaque pointer that Lua passes to the allocator in every call. ### `lua_newtable`[-0, +1, *m*] ``` void lua_newtable (lua_State *L); ``` Creates a new empty table and pushes it onto the stack. It is equivalent to `lua_createtable(L, 0, 0)`. ### `lua_newthread`[-0, +1, *m*] ``` lua_State *lua_newthread (lua_State *L); ``` Creates a new thread, pushes it on the stack, and returns a pointer to a [`lua_State`](#lua_State) that represents this new thread. The new thread returned by this function shares with the original thread its global environment, but has an independent execution stack. Threads are subject to garbage collection, like any Lua object. ### `lua_newuserdatauv`[-0, +1, *m*] ``` void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue); ``` This function creates and pushes on the stack a new full userdata, with `nuvalue` associated Lua values, called `user values`, plus an associated block of raw memory with `size` bytes. (The user values can be set and read with the functions [`lua_setiuservalue`](#lua_setiuservalue) and [`lua_getiuservalue`](#lua_getiuservalue).) The function returns the address of the block of memory. Lua ensures that this address is valid as long as the corresponding userdata is alive (see [§2.5](#2.5)). Moreover, if the userdata is marked for finalization (see [§2.5.3](#2.5.3)), its address is valid at least until the call to its finalizer. ### `lua_next`[-1, +(2|0), *v*] ``` int lua_next (lua_State *L, int index); ``` Pops a key from the stack, and pushes a key–value pair from the table at the given index, the "next" pair after the given key. If there are no more elements in the table, then [`lua_next`](#lua_next) returns 0 and pushes nothing. A typical table traversal looks like this: ``` /* table is in the stack at index 't' */ lua_pushnil(L); /* first key */ while (lua_next(L, t) != 0) { /* uses 'key' (at index -2) and 'value' (at index -1) */ printf("%s - %s\n", lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1))); /* removes 'value'; keeps 'key' for next iteration */ lua_pop(L, 1); } ``` While traversing a table, avoid calling [`lua_tolstring`](#lua_tolstring) directly on a key, unless you know that the key is actually a string. Recall that [`lua_tolstring`](#lua_tolstring) may change the value at the given index; this confuses the next call to [`lua_next`](#lua_next). This function may raise an error if the given key is neither **nil** nor present in the table. See function [`next`](#pdf-next) for the caveats of modifying the table during its traversal. ### `lua_Number` ``` typedef ... lua_Number; ``` The type of floats in Lua. By default this type is double, but that can be changed to a single float or a long double. (See `LUA_FLOAT_TYPE` in `luaconf.h`.) ### `lua_numbertointeger` ``` int lua_numbertointeger (lua_Number n, lua_Integer *p); ``` Tries to convert a Lua float to a Lua integer; the float `n` must have an integral value. If that value is within the range of Lua integers, it is converted to an integer and assigned to `*p`. The macro results in a boolean indicating whether the conversion was successful. (Note that this range test can be tricky to do correctly without this macro, due to rounding.) This macro may evaluate its arguments more than once. ### `lua_pcall`[-(nargs + 1), +(nresults|1), –] ``` int lua_pcall (lua_State *L, int nargs, int nresults, int msgh); ``` Calls a function (or a callable object) in protected mode. Both `nargs` and `nresults` have the same meaning as in [`lua_call`](#lua_call). If there are no errors during the call, [`lua_pcall`](#lua_pcall) behaves exactly like [`lua_call`](#lua_call). However, if there is any error, [`lua_pcall`](#lua_pcall) catches it, pushes a single value on the stack (the error object), and returns an error code. Like [`lua_call`](#lua_call), [`lua_pcall`](#lua_pcall) always removes the function and its arguments from the stack. If `msgh` is 0, then the error object returned on the stack is exactly the original error object. Otherwise, `msgh` is the stack index of a *message handler*. (This index cannot be a pseudo-index.) In case of runtime errors, this handler will be called with the error object and its return value will be the object returned on the stack by [`lua_pcall`](#lua_pcall). Typically, the message handler is used to add more debug information to the error object, such as a stack traceback. Such information cannot be gathered after the return of [`lua_pcall`](#lua_pcall), since by then the stack has unwound. The [`lua_pcall`](#lua_pcall) function returns one of the following status codes: [`LUA_OK`](#pdf-LUA_OK), [`LUA_ERRRUN`](#pdf-LUA_ERRRUN), [`LUA_ERRMEM`](#pdf-LUA_ERRMEM), or [`LUA_ERRERR`](#pdf-LUA_ERRERR). ### `lua_pcallk`[-(nargs + 1), +(nresults|1), –] ``` int lua_pcallk (lua_State *L, int nargs, int nresults, int msgh, lua_KContext ctx, lua_KFunction k); ``` This function behaves exactly like [`lua_pcall`](#lua_pcall), except that it allows the called function to yield (see [§4.5](#4.5)). ### `lua_pop`[-n, +0, –] ``` void lua_pop (lua_State *L, int n); ``` Pops `n` elements from the stack. ### `lua_pushboolean`[-0, +1, –] ``` void lua_pushboolean (lua_State *L, int b); ``` Pushes a boolean value with value `b` onto the stack. ### `lua_pushcclosure`[-n, +1, *m*] ``` void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n); ``` Pushes a new C closure onto the stack. This function receives a pointer to a C function and pushes onto the stack a Lua value of type `function` that, when called, invokes the corresponding C function. The parameter `n` tells how many upvalues this function will have (see [§4.2](#4.2)). Any function to be callable by Lua must follow the correct protocol to receive its parameters and return its results (see [`lua_CFunction`](#lua_CFunction)). When a C function is created, it is possible to associate some values with it, the so called upvalues; these upvalues are then accessible to the function whenever it is called. This association is called a C closure (see [§4.2](#4.2)). To create a C closure, first the initial values for its upvalues must be pushed onto the stack. (When there are multiple upvalues, the first value is pushed first.) Then [`lua_pushcclosure`](#lua_pushcclosure) is called to create and push the C function onto the stack, with the argument `n` telling how many values will be associated with the function. [`lua_pushcclosure`](#lua_pushcclosure) also pops these values from the stack. The maximum value for `n` is 255. When `n` is zero, this function creates a *light C function*, which is just a pointer to the C function. In that case, it never raises a memory error. ### `lua_pushcfunction`[-0, +1, –] ``` void lua_pushcfunction (lua_State *L, lua_CFunction f); ``` Pushes a C function onto the stack. This function is equivalent to [`lua_pushcclosure`](#lua_pushcclosure) with no upvalues. ### `lua_pushfstring`[-0, +1, *v*] ``` const char *lua_pushfstring (lua_State *L, const char *fmt, ...); ``` Pushes onto the stack a formatted string and returns a pointer to this string (see [§4.1.3](#4.1.3)). It is similar to the ISO C function `sprintf`, but has two important differences. First, you do not have to allocate space for the result; the result is a Lua string and Lua takes care of memory allocation (and deallocation, through garbage collection). Second, the conversion specifiers are quite restricted. There are no flags, widths, or precisions. The conversion specifiers can only be '`%%`' (inserts the character '`%`'), '`%s`' (inserts a zero-terminated string, with no size restrictions), '`%f`' (inserts a [`lua_Number`](#lua_Number)), '`%I`' (inserts a [`lua_Integer`](#lua_Integer)), '`%p`' (inserts a pointer), '`%d`' (inserts an `int`), '`%c`' (inserts an `int` as a one-byte character), and '`%U`' (inserts a `long int` as a UTF-8 byte sequence). This function may raise errors due to memory overflow or an invalid conversion specifier. ### `lua_pushglobaltable`[-0, +1, –] ``` void lua_pushglobaltable (lua_State *L); ``` Pushes the global environment onto the stack. ### `lua_pushinteger`[-0, +1, –] ``` void lua_pushinteger (lua_State *L, lua_Integer n); ``` Pushes an integer with value `n` onto the stack. ### `lua_pushlightuserdata`[-0, +1, –] ``` void lua_pushlightuserdata (lua_State *L, void *p); ``` Pushes a light userdata onto the stack. Userdata represent C values in Lua. A *light userdata* represents a pointer, a `void*`. It is a value (like a number): you do not create it, it has no individual metatable, and it is not collected (as it was never created). A light userdata is equal to "any" light userdata with the same C address. ### `lua_pushliteral`[-0, +1, *m*] ``` const char *lua_pushliteral (lua_State *L, const char *s); ``` This macro is equivalent to [`lua_pushstring`](#lua_pushstring), but should be used only when `s` is a literal string. (Lua may optimize this case.) ### `lua_pushlstring`[-0, +1, *m*] ``` const char *lua_pushlstring (lua_State *L, const char *s, size_t len); ``` Pushes the string pointed to by `s` with size `len` onto the stack. Lua will make or reuse an internal copy of the given string, so the memory at `s` can be freed or reused immediately after the function returns. The string can contain any binary data, including embedded zeros. Returns a pointer to the internal copy of the string (see [§4.1.3](#4.1.3)). ### `lua_pushnil`[-0, +1, –] ``` void lua_pushnil (lua_State *L); ``` Pushes a nil value onto the stack. ### `lua_pushnumber`[-0, +1, –] ``` void lua_pushnumber (lua_State *L, lua_Number n); ``` Pushes a float with value `n` onto the stack. ### `lua_pushstring`[-0, +1, *m*] ``` const char *lua_pushstring (lua_State *L, const char *s); ``` Pushes the zero-terminated string pointed to by `s` onto the stack. Lua will make or reuse an internal copy of the given string, so the memory at `s` can be freed or reused immediately after the function returns. Returns a pointer to the internal copy of the string (see [§4.1.3](#4.1.3)). If `s` is `NULL`, pushes **nil** and returns `NULL`. ### `lua_pushthread`[-0, +1, –] ``` int lua_pushthread (lua_State *L); ``` Pushes the thread represented by `L` onto the stack. Returns 1 if this thread is the main thread of its state. ### `lua_pushvalue`[-0, +1, –] ``` void lua_pushvalue (lua_State *L, int index); ``` Pushes a copy of the element at the given index onto the stack. ### `lua_pushvfstring`[-0, +1, *v*] ``` const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp); ``` Equivalent to [`lua_pushfstring`](#lua_pushfstring), except that it receives a `va_list` instead of a variable number of arguments. ### `lua_rawequal`[-0, +0, –] ``` int lua_rawequal (lua_State *L, int index1, int index2); ``` Returns 1 if the two values in indices `index1` and `index2` are primitively equal (that is, equal without calling the `__eq` metamethod). Otherwise returns 0. Also returns 0 if any of the indices are not valid. ### `lua_rawget`[-1, +1, –] ``` int lua_rawget (lua_State *L, int index); ``` Similar to [`lua_gettable`](#lua_gettable), but does a raw access (i.e., without metamethods). ### `lua_rawgeti`[-0, +1, –] ``` int lua_rawgeti (lua_State *L, int index, lua_Integer n); ``` Pushes onto the stack the value `t[n]`, where `t` is the table at the given index. The access is raw, that is, it does not use the `__index` metavalue. Returns the type of the pushed value. ### `lua_rawgetp`[-0, +1, –] ``` int lua_rawgetp (lua_State *L, int index, const void *p); ``` Pushes onto the stack the value `t[k]`, where `t` is the table at the given index and `k` is the pointer `p` represented as a light userdata. The access is raw; that is, it does not use the `__index` metavalue. Returns the type of the pushed value. ### `lua_rawlen`[-0, +0, –] ``` lua_Unsigned lua_rawlen (lua_State *L, int index); ``` Returns the raw "length" of the value at the given index: for strings, this is the string length; for tables, this is the result of the length operator ('`#`') with no metamethods; for userdata, this is the size of the block of memory allocated for the userdata. For other values, this call returns 0. ### `lua_rawset`[-2, +0, *m*] ``` void lua_rawset (lua_State *L, int index); ``` Similar to [`lua_settable`](#lua_settable), but does a raw assignment (i.e., without metamethods). ### `lua_rawseti`[-1, +0, *m*] ``` void lua_rawseti (lua_State *L, int index, lua_Integer i); ``` Does the equivalent of `t[i] = v`, where `t` is the table at the given index and `v` is the value on the top of the stack. This function pops the value from the stack. The assignment is raw, that is, it does not use the `__newindex` metavalue. ### `lua_rawsetp`[-1, +0, *m*] ``` void lua_rawsetp (lua_State *L, int index, const void *p); ``` Does the equivalent of `t[p] = v`, where `t` is the table at the given index, `p` is encoded as a light userdata, and `v` is the value on the top of the stack. This function pops the value from the stack. The assignment is raw, that is, it does not use the `__newindex` metavalue. ### `lua_Reader` ``` typedef const char * (*lua_Reader) (lua_State *L, void *data, size_t *size); ``` The reader function used by [`lua_load`](#lua_load). Every time [`lua_load`](#lua_load) needs another piece of the chunk, it calls the reader, passing along its `data` parameter. The reader must return a pointer to a block of memory with a new piece of the chunk and set `size` to the block size. The block must exist until the reader function is called again. To signal the end of the chunk, the reader must return `NULL` or set `size` to zero. The reader function may return pieces of any size greater than zero. ### `lua_register`[-0, +0, *e*] ``` void lua_register (lua_State *L, const char *name, lua_CFunction f); ``` Sets the C function `f` as the new value of global `name`. It is defined as a macro: ``` #define lua_register(L,n,f) \ (lua_pushcfunction(L, f), lua_setglobal(L, n)) ``` ### `lua_remove`[-1, +0, –] ``` void lua_remove (lua_State *L, int index); ``` Removes the element at the given valid index, shifting down the elements above this index to fill the gap. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position. ### `lua_replace`[-1, +0, –] ``` void lua_replace (lua_State *L, int index); ``` Moves the top element into the given valid index without shifting any element (therefore replacing the value at that given index), and then pops the top element. ### `lua_resetthread`[-0, +?, –] ``` int lua_resetthread (lua_State *L); ``` Resets a thread, cleaning its call stack and closing all pending to-be-closed variables. Returns a status code: [`LUA_OK`](#pdf-LUA_OK) for no errors in closing methods, or an error status otherwise. In case of error, leaves the error object on the top of the stack, ### `lua_resume`[-?, +?, –] ``` int lua_resume (lua_State *L, lua_State *from, int nargs, int *nresults); ``` Starts and resumes a coroutine in the given thread `L`. To start a coroutine, you push the main function plus any arguments onto the empty stack of the thread. then you call [`lua_resume`](#lua_resume), with `nargs` being the number of arguments. This call returns when the coroutine suspends or finishes its execution. When it returns, `*nresults` is updated and the top of the stack contains the `*nresults` values passed to [`lua_yield`](#lua_yield) or returned by the body function. [`lua_resume`](#lua_resume) returns [`LUA_YIELD`](#pdf-LUA_YIELD) if the coroutine yields, [`LUA_OK`](#pdf-LUA_OK) if the coroutine finishes its execution without errors, or an error code in case of errors (see [§4.4.1](#4.4.1)). In case of errors, the error object is on the top of the stack. To resume a coroutine, you remove the `*nresults` yielded values from its stack, push the values to be passed as results from `yield`, and then call [`lua_resume`](#lua_resume). The parameter `from` represents the coroutine that is resuming `L`. If there is no such coroutine, this parameter can be `NULL`. ### `lua_rotate`[-0, +0, –] ``` void lua_rotate (lua_State *L, int idx, int n); ``` Rotates the stack elements between the valid index `idx` and the top of the stack. The elements are rotated `n` positions in the direction of the top, for a positive `n`, or `-n` positions in the direction of the bottom, for a negative `n`. The absolute value of `n` must not be greater than the size of the slice being rotated. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position. ### `lua_setallocf`[-0, +0, –] ``` void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); ``` Changes the allocator function of a given state to `f` with user data `ud`. ### `lua_setfield`[-1, +0, *e*] ``` void lua_setfield (lua_State *L, int index, const char *k); ``` Does the equivalent to `t[k] = v`, where `t` is the value at the given index and `v` is the value on the top of the stack. This function pops the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event (see [§2.4](#2.4)). ### `lua_setglobal`[-1, +0, *e*] ``` void lua_setglobal (lua_State *L, const char *name); ``` Pops a value from the stack and sets it as the new value of global `name`. ### `lua_seti`[-1, +0, *e*] ``` void lua_seti (lua_State *L, int index, lua_Integer n); ``` Does the equivalent to `t[n] = v`, where `t` is the value at the given index and `v` is the value on the top of the stack. This function pops the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event (see [§2.4](#2.4)). ### `lua_setiuservalue`[-1, +0, –] ``` int lua_setiuservalue (lua_State *L, int index, int n); ``` Pops a value from the stack and sets it as the new `n`-th user value associated to the full userdata at the given index. Returns 0 if the userdata does not have that value. ### `lua_setmetatable`[-1, +0, –] ``` int lua_setmetatable (lua_State *L, int index); ``` Pops a table or **nil** from the stack and sets that value as the new metatable for the value at the given index. (**nil** means no metatable.) (For historical reasons, this function returns an `int`, which now is always 1.) ### `lua_settable`[-2, +0, *e*] ``` void lua_settable (lua_State *L, int index); ``` Does the equivalent to `t[k] = v`, where `t` is the value at the given index, `v` is the value on the top of the stack, and `k` is the value just below the top. This function pops both the key and the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event (see [§2.4](#2.4)). ### `lua_settop`[-?, +?, –] ``` void lua_settop (lua_State *L, int index); ``` Accepts any index, or 0, and sets the stack top to this index. If the new top is greater than the old one, then the new elements are filled with **nil**. If `index` is 0, then all stack elements are removed. ### `lua_setwarnf`[-0, +0, –] ``` void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud); ``` Sets the warning function to be used by Lua to emit warnings (see [`lua_WarnFunction`](#lua_WarnFunction)). The `ud` parameter sets the value `ud` passed to the warning function. ### `lua_State` ``` typedef struct lua_State lua_State; ``` An opaque structure that points to a thread and indirectly (through the thread) to the whole state of a Lua interpreter. The Lua library is fully reentrant: it has no global variables. All information about a state is accessible through this structure. A pointer to this structure must be passed as the first argument to every function in the library, except to [`lua_newstate`](#lua_newstate), which creates a Lua state from scratch. ### `lua_status`[-0, +0, –] ``` int lua_status (lua_State *L); ``` Returns the status of the thread `L`. The status can be [`LUA_OK`](#pdf-LUA_OK) for a normal thread, an error code if the thread finished the execution of a [`lua_resume`](#lua_resume) with an error, or [`LUA_YIELD`](#pdf-LUA_YIELD) if the thread is suspended. You can call functions only in threads with status [`LUA_OK`](#pdf-LUA_OK). You can resume threads with status [`LUA_OK`](#pdf-LUA_OK) (to start a new coroutine) or [`LUA_YIELD`](#pdf-LUA_YIELD) (to resume a coroutine). ### `lua_stringtonumber`[-0, +1, –] ``` size_t lua_stringtonumber (lua_State *L, const char *s); ``` Converts the zero-terminated string `s` to a number, pushes that number into the stack, and returns the total size of the string, that is, its length plus one. The conversion can result in an integer or a float, according to the lexical conventions of Lua (see [§3.1](#3.1)). The string may have leading and trailing whitespaces and a sign. If the string is not a valid numeral, returns 0 and pushes nothing. (Note that the result can be used as a boolean, true if the conversion succeeds.) ### `lua_toboolean`[-0, +0, –] ``` int lua_toboolean (lua_State *L, int index); ``` Converts the Lua value at the given index to a C boolean value (0 or 1). Like all tests in Lua, [`lua_toboolean`](#lua_toboolean) returns true for any Lua value different from **false** and **nil**; otherwise it returns false. (If you want to accept only actual boolean values, use [`lua_isboolean`](#lua_isboolean) to test the value's type.) ### `lua_tocfunction`[-0, +0, –] ``` lua_CFunction lua_tocfunction (lua_State *L, int index); ``` Converts a value at the given index to a C function. That value must be a C function; otherwise, returns `NULL`. ### `lua_toclose`[-0, +0, *m*] ``` void lua_toclose (lua_State *L, int index); ``` Marks the given index in the stack as a to-be-closed "variable" (see [§3.3.8](#3.3.8)). Like a to-be-closed variable in Lua, the value at that index in the stack will be closed when it goes out of scope. Here, in the context of a C function, to go out of scope means that the running function returns to Lua, there is an error, or the index is removed from the stack through [`lua_settop`](#lua_settop) or [`lua_pop`](#lua_pop). An index marked as to-be-closed should not be removed from the stack by any other function in the API except [`lua_settop`](#lua_settop) or [`lua_pop`](#lua_pop). This function should not be called for an index that is equal to or below an active to-be-closed index. In the case of an out-of-memory error, the value in the given index is immediately closed, as if it was already marked. Note that, both in case of errors and of a regular return, by the time the `__close` metamethod runs, the C stack was already unwound, so that any automatic C variable declared in the calling function will be out of scope. ### `lua_tointeger`[-0, +0, –] ``` lua_Integer lua_tointeger (lua_State *L, int index); ``` Equivalent to [`lua_tointegerx`](#lua_tointegerx) with `isnum` equal to `NULL`. ### `lua_tointegerx`[-0, +0, –] ``` lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum); ``` Converts the Lua value at the given index to the signed integral type [`lua_Integer`](#lua_Integer). The Lua value must be an integer, or a number or string convertible to an integer (see [§3.4.3](#3.4.3)); otherwise, `lua_tointegerx` returns 0. If `isnum` is not `NULL`, its referent is assigned a boolean value that indicates whether the operation succeeded. ### `lua_tolstring`[-0, +0, *m*] ``` const char *lua_tolstring (lua_State *L, int index, size_t *len); ``` Converts the Lua value at the given index to a C string. If `len` is not `NULL`, it sets `*len` with the string length. The Lua value must be a string or a number; otherwise, the function returns `NULL`. If the value is a number, then `lua_tolstring` also *changes the actual value in the stack to a string*. (This change confuses [`lua_next`](#lua_next) when `lua_tolstring` is applied to keys during a table traversal.) `lua_tolstring` returns a pointer to a string inside the Lua state (see [§4.1.3](#4.1.3)). This string always has a zero ('`\0`') after its last character (as in C), but can contain other zeros in its body. ### `lua_tonumber`[-0, +0, –] ``` lua_Number lua_tonumber (lua_State *L, int index); ``` Equivalent to [`lua_tonumberx`](#lua_tonumberx) with `isnum` equal to `NULL`. ### `lua_tonumberx`[-0, +0, –] ``` lua_Number lua_tonumberx (lua_State *L, int index, int *isnum); ``` Converts the Lua value at the given index to the C type [`lua_Number`](#lua_Number) (see [`lua_Number`](#lua_Number)). The Lua value must be a number or a string convertible to a number (see [§3.4.3](#3.4.3)); otherwise, [`lua_tonumberx`](#lua_tonumberx) returns 0. If `isnum` is not `NULL`, its referent is assigned a boolean value that indicates whether the operation succeeded. ### `lua_topointer`[-0, +0, –] ``` const void *lua_topointer (lua_State *L, int index); ``` Converts the value at the given index to a generic C pointer (`void*`). The value can be a userdata, a table, a thread, a string, or a function; otherwise, `lua_topointer` returns `NULL`. Different objects will give different pointers. There is no way to convert the pointer back to its original value. Typically this function is used only for hashing and debug information. ### `lua_tostring`[-0, +0, *m*] ``` const char *lua_tostring (lua_State *L, int index); ``` Equivalent to [`lua_tolstring`](#lua_tolstring) with `len` equal to `NULL`. ### `lua_tothread`[-0, +0, –] ``` lua_State *lua_tothread (lua_State *L, int index); ``` Converts the value at the given index to a Lua thread (represented as `lua_State*`). This value must be a thread; otherwise, the function returns `NULL`. ### `lua_touserdata`[-0, +0, –] ``` void *lua_touserdata (lua_State *L, int index); ``` If the value at the given index is a full userdata, returns its memory-block address. If the value is a light userdata, returns its value (a pointer). Otherwise, returns `NULL`. ### `lua_type`[-0, +0, –] ``` int lua_type (lua_State *L, int index); ``` Returns the type of the value in the given valid index, or `LUA_TNONE` for a non-valid but acceptable index. The types returned by [`lua_type`](#lua_type) are coded by the following constants defined in `lua.h`: `LUA_TNIL`, `LUA_TNUMBER`, `LUA_TBOOLEAN`, `LUA_TSTRING`, `LUA_TTABLE`, `LUA_TFUNCTION`, `LUA_TUSERDATA`, `LUA_TTHREAD`, and `LUA_TLIGHTUSERDATA`. ### `lua_typename`[-0, +0, –] ``` const char *lua_typename (lua_State *L, int tp); ``` Returns the name of the type encoded by the value `tp`, which must be one the values returned by [`lua_type`](#lua_type). ### `lua_Unsigned` ``` typedef ... lua_Unsigned; ``` The unsigned version of [`lua_Integer`](#lua_Integer). ### `lua_upvalueindex`[-0, +0, –] ``` int lua_upvalueindex (int i); ``` Returns the pseudo-index that represents the `i`-th upvalue of the running function (see [§4.2](#4.2)). `i` must be in the range *[1,256]*. ### `lua_version`[-0, +0, –] ``` lua_Number lua_version (lua_State *L); ``` Returns the version number of this core. ### `lua_WarnFunction` ``` typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont); ``` The type of warning functions, called by Lua to emit warnings. The first parameter is an opaque pointer set by [`lua_setwarnf`](#lua_setwarnf). The second parameter is the warning message. The third parameter is a boolean that indicates whether the message is to be continued by the message in the next call. See [`warn`](#pdf-warn) for more details about warnings. ### `lua_warning`[-0, +0, –] ``` void lua_warning (lua_State *L, const char *msg, int tocont); ``` Emits a warning with the given message. A message in a call with `tocont` true should be continued in another call to this function. See [`warn`](#pdf-warn) for more details about warnings. ### `lua_Writer` ``` typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud); ``` The type of the writer function used by [`lua_dump`](#lua_dump). Every time [`lua_dump`](#lua_dump) produces another piece of chunk, it calls the writer, passing along the buffer to be written (`p`), its size (`sz`), and the `ud` parameter supplied to [`lua_dump`](#lua_dump). The writer returns an error code: 0 means no errors; any other value means an error and stops [`lua_dump`](#lua_dump) from calling the writer again. ### `lua_xmove`[-?, +?, –] ``` void lua_xmove (lua_State *from, lua_State *to, int n); ``` Exchange values between different threads of the same state. This function pops `n` values from the stack `from`, and pushes them onto the stack `to`. ### `lua_yield`[-?, +?, *v*] ``` int lua_yield (lua_State *L, int nresults); ``` This function is equivalent to [`lua_yieldk`](#lua_yieldk), but it has no continuation (see [§4.5](#4.5)). Therefore, when the thread resumes, it continues the function that called the function calling `lua_yield`. To avoid surprises, this function should be called only in a tail call. ### `lua_yieldk`[-?, +?, *v*] ``` int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx, lua_KFunction k); ``` Yields a coroutine (thread). When a C function calls [`lua_yieldk`](#lua_yieldk), the running coroutine suspends its execution, and the call to [`lua_resume`](#lua_resume) that started this coroutine returns. The parameter `nresults` is the number of values from the stack that will be passed as results to [`lua_resume`](#lua_resume). When the coroutine is resumed again, Lua calls the given continuation function `k` to continue the execution of the C function that yielded (see [§4.5](#4.5)). This continuation function receives the same stack from the previous function, with the `n` results removed and replaced by the arguments passed to [`lua_resume`](#lua_resume). Moreover, the continuation function receives the value `ctx` that was passed to [`lua_yieldk`](#lua_yieldk). Usually, this function does not return; when the coroutine eventually resumes, it continues executing the continuation function. However, there is one special case, which is when this function is called from inside a line or a count hook (see [§4.7](#4.7)). In that case, `lua_yieldk` should be called with no continuation (probably in the form of [`lua_yield`](#lua_yield)) and no results, and the hook should return immediately after the call. Lua will yield and, when the coroutine resumes again, it will continue the normal execution of the (Lua) function that triggered the hook. This function can raise an error if it is called from a thread with a pending C call with no continuation function (what is called a *C-call boundary*), or it is called from a thread that is not running inside a resume (typically the main thread). 4.7 – The Debug Interface ------------------------- Lua has no built-in debugging facilities. Instead, it offers a special interface by means of functions and *hooks*. This interface allows the construction of different kinds of debuggers, profilers, and other tools that need "inside information" from the interpreter. ### `lua_Debug` ``` typedef struct lua_Debug { int event; const char *name; /* (n) */ const char *namewhat; /* (n) */ const char *what; /* (S) */ const char *source; /* (S) */ size_t srclen; /* (S) */ int currentline; /* (l) */ int linedefined; /* (S) */ int lastlinedefined; /* (S) */ unsigned char nups; /* (u) number of upvalues */ unsigned char nparams; /* (u) number of parameters */ char isvararg; /* (u) */ char istailcall; /* (t) */ unsigned short ftransfer; /* (r) index of first value transferred */ unsigned short ntransfer; /* (r) number of transferred values */ char short_src[LUA_IDSIZE]; /* (S) */ /* private part */ other fields } lua_Debug; ``` A structure used to carry different pieces of information about a function or an activation record. [`lua_getstack`](#lua_getstack) fills only the private part of this structure, for later use. To fill the other fields of [`lua_Debug`](#lua_Debug) with useful information, you must call [`lua_getinfo`](#lua_getinfo). The fields of [`lua_Debug`](#lua_Debug) have the following meaning: * `source`: the source of the chunk that created the function. If `source` starts with a '`@`', it means that the function was defined in a file where the file name follows the '`@`'. If `source` starts with a '`=`', the remainder of its contents describes the source in a user-dependent manner. Otherwise, the function was defined in a string where `source` is that string. * `srclen`: The length of the string `source`. * `short_src`: a "printable" version of `source`, to be used in error messages. * `linedefined`: the line number where the definition of the function starts. * `lastlinedefined`: the line number where the definition of the function ends. * `what`: the string `"Lua"` if the function is a Lua function, `"C"` if it is a C function, `"main"` if it is the main part of a chunk. * `currentline`: the current line where the given function is executing. When no line information is available, `currentline` is set to -1. * `name`: a reasonable name for the given function. Because functions in Lua are first-class values, they do not have a fixed name: some functions can be the value of multiple global variables, while others can be stored only in a table field. The `lua_getinfo` function checks how the function was called to find a suitable name. If it cannot find a name, then `name` is set to `NULL`. * `namewhat`: explains the `name` field. The value of `namewhat` can be `"global"`, `"local"`, `"method"`, `"field"`, `"upvalue"`, or `""` (the empty string), according to how the function was called. (Lua uses the empty string when no other option seems to apply.) * `istailcall`: true if this function invocation was called by a tail call. In this case, the caller of this level is not in the stack. * `nups`: the number of upvalues of the function. * `nparams`: the number of parameters of the function (always 0 for C functions). * `isvararg`: true if the function is a vararg function (always true for C functions). * `ftransfer`: the index in the stack of the first value being "transferred", that is, parameters in a call or return values in a return. (The other values are in consecutive indices.) Using this index, you can access and modify these values through [`lua_getlocal`](#lua_getlocal) and [`lua_setlocal`](#lua_setlocal). This field is only meaningful during a call hook, denoting the first parameter, or a return hook, denoting the first value being returned. (For call hooks, this value is always 1.) * `ntransfer`: The number of values being transferred (see previous item). (For calls of Lua functions, this value is always equal to `nparams`.) ### `lua_gethook`[-0, +0, –] ``` lua_Hook lua_gethook (lua_State *L); ``` Returns the current hook function. ### `lua_gethookcount`[-0, +0, –] ``` int lua_gethookcount (lua_State *L); ``` Returns the current hook count. ### `lua_gethookmask`[-0, +0, –] ``` int lua_gethookmask (lua_State *L); ``` Returns the current hook mask. ### `lua_getinfo`[-(0|1), +(0|1|2), *m*] ``` int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); ``` Gets information about a specific function or function invocation. To get information about a function invocation, the parameter `ar` must be a valid activation record that was filled by a previous call to [`lua_getstack`](#lua_getstack) or given as argument to a hook (see [`lua_Hook`](#lua_Hook)). To get information about a function, you push it onto the stack and start the `what` string with the character '`>`'. (In that case, `lua_getinfo` pops the function from the top of the stack.) For instance, to know in which line a function `f` was defined, you can write the following code: ``` lua_Debug ar; lua_getglobal(L, "f"); /* get global 'f' */ lua_getinfo(L, ">S", &ar); printf("%d\n", ar.linedefined); ``` Each character in the string `what` selects some fields of the structure `ar` to be filled or a value to be pushed on the stack: * '`n`': fills in the field `name` and `namewhat`; * '`S`': fills in the fields `source`, `short_src`, `linedefined`, `lastlinedefined`, and `what`; * '`l`': fills in the field `currentline`; * '`t`': fills in the field `istailcall`; * '`u`': fills in the fields `nups`, `nparams`, and `isvararg`; * '`f`': pushes onto the stack the function that is running at the given level; * '`L`': pushes onto the stack a table whose indices are the numbers of the lines that are valid on the function. (A *valid line* is a line with some associated code, that is, a line where you can put a break point. Non-valid lines include empty lines and comments.) If this option is given together with option '`f`', its table is pushed after the function. This is the only option that can raise a memory error. This function returns 0 to signal an invalid option in `what`; even then the valid options are handled correctly. ### `lua_getlocal`[-0, +(0|1), –] ``` const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n); ``` Gets information about a local variable or a temporary value of a given activation record or a given function. In the first case, the parameter `ar` must be a valid activation record that was filled by a previous call to [`lua_getstack`](#lua_getstack) or given as argument to a hook (see [`lua_Hook`](#lua_Hook)). The index `n` selects which local variable to inspect; see [`debug.getlocal`](#pdf-debug.getlocal) for details about variable indices and names. [`lua_getlocal`](#lua_getlocal) pushes the variable's value onto the stack and returns its name. In the second case, `ar` must be `NULL` and the function to be inspected must be on the top of the stack. In this case, only parameters of Lua functions are visible (as there is no information about what variables are active) and no values are pushed onto the stack. Returns `NULL` (and pushes nothing) when the index is greater than the number of active local variables. ### `lua_getstack`[-0, +0, –] ``` int lua_getstack (lua_State *L, int level, lua_Debug *ar); ``` Gets information about the interpreter runtime stack. This function fills parts of a [`lua_Debug`](#lua_Debug) structure with an identification of the *activation record* of the function executing at a given level. Level 0 is the current running function, whereas level *n+1* is the function that has called level *n* (except for tail calls, which do not count in the stack). When called with a level greater than the stack depth, [`lua_getstack`](#lua_getstack) returns 0; otherwise it returns 1. ### `lua_getupvalue`[-0, +(0|1), –] ``` const char *lua_getupvalue (lua_State *L, int funcindex, int n); ``` Gets information about the `n`-th upvalue of the closure at index `funcindex`. It pushes the upvalue's value onto the stack and returns its name. Returns `NULL` (and pushes nothing) when the index `n` is greater than the number of upvalues. See [`debug.getupvalue`](#pdf-debug.getupvalue) for more information about upvalues. ### `lua_Hook` ``` typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); ``` Type for debugging hook functions. Whenever a hook is called, its `ar` argument has its field `event` set to the specific event that triggered the hook. Lua identifies these events with the following constants: `LUA_HOOKCALL`, `LUA_HOOKRET`, `LUA_HOOKTAILCALL`, `LUA_HOOKLINE`, and `LUA_HOOKCOUNT`. Moreover, for line events, the field `currentline` is also set. To get the value of any other field in `ar`, the hook must call [`lua_getinfo`](#lua_getinfo). For call events, `event` can be `LUA_HOOKCALL`, the normal value, or `LUA_HOOKTAILCALL`, for a tail call; in this case, there will be no corresponding return event. While Lua is running a hook, it disables other calls to hooks. Therefore, if a hook calls back Lua to execute a function or a chunk, this execution occurs without any calls to hooks. Hook functions cannot have continuations, that is, they cannot call [`lua_yieldk`](#lua_yieldk), [`lua_pcallk`](#lua_pcallk), or [`lua_callk`](#lua_callk) with a non-null `k`. Hook functions can yield under the following conditions: Only count and line events can yield; to yield, a hook function must finish its execution calling [`lua_yield`](#lua_yield) with `nresults` equal to zero (that is, with no values). ### `lua_setcstacklimit`[-0, +0, –] ``` int (lua_setcstacklimit) (lua_State *L, unsigned int limit); ``` Sets a new limit for the C stack. This limit controls how deeply nested calls can go in Lua, with the intent of avoiding a stack overflow. Returns the old limit in case of success, or zero in case of error. For more details about this function, see [`debug.setcstacklimit`](#pdf-debug.setcstacklimit), its equivalent in the standard library. ### `lua_sethook`[-0, +0, –] ``` void lua_sethook (lua_State *L, lua_Hook f, int mask, int count); ``` Sets the debugging hook function. Argument `f` is the hook function. `mask` specifies on which events the hook will be called: it is formed by a bitwise OR of the constants `LUA_MASKCALL`, `LUA_MASKRET`, `LUA_MASKLINE`, and `LUA_MASKCOUNT`. The `count` argument is only meaningful when the mask includes `LUA_MASKCOUNT`. For each event, the hook is called as explained below: * **The call hook:** is called when the interpreter calls a function. The hook is called just after Lua enters the new function. * **The return hook:** is called when the interpreter returns from a function. The hook is called just before Lua leaves the function. * **The line hook:** is called when the interpreter is about to start the execution of a new line of code, or when it jumps back in the code (even to the same line). This event only happens while Lua is executing a Lua function. * **The count hook:** is called after the interpreter executes every `count` instructions. This event only happens while Lua is executing a Lua function. Hooks are disabled by setting `mask` to zero. ### `lua_setlocal`[-(0|1), +0, –] ``` const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n); ``` Sets the value of a local variable of a given activation record. It assigns the value on the top of the stack to the variable and returns its name. It also pops the value from the stack. Returns `NULL` (and pops nothing) when the index is greater than the number of active local variables. Parameters `ar` and `n` are as in the function [`lua_getlocal`](#lua_getlocal). ### `lua_setupvalue`[-(0|1), +0, –] ``` const char *lua_setupvalue (lua_State *L, int funcindex, int n); ``` Sets the value of a closure's upvalue. It assigns the value on the top of the stack to the upvalue and returns its name. It also pops the value from the stack. Returns `NULL` (and pops nothing) when the index `n` is greater than the number of upvalues. Parameters `funcindex` and `n` are as in the function [`lua_getupvalue`](#lua_getupvalue). ### `lua_upvalueid`[-0, +0, –] ``` void *lua_upvalueid (lua_State *L, int funcindex, int n); ``` Returns a unique identifier for the upvalue numbered `n` from the closure at index `funcindex`. These unique identifiers allow a program to check whether different closures share upvalues. Lua closures that share an upvalue (that is, that access a same external local variable) will return identical ids for those upvalue indices. Parameters `funcindex` and `n` are as in the function [`lua_getupvalue`](#lua_getupvalue), but `n` cannot be greater than the number of upvalues. ### `lua_upvaluejoin`[-0, +0, –] ``` void lua_upvaluejoin (lua_State *L, int funcindex1, int n1, int funcindex2, int n2); ``` Make the `n1`-th upvalue of the Lua closure at index `funcindex1` refer to the `n2`-th upvalue of the Lua closure at index `funcindex2`. 5 – The Auxiliary Library ========================= The *auxiliary library* provides several convenient functions to interface C with Lua. While the basic API provides the primitive functions for all interactions between C and Lua, the auxiliary library provides higher-level functions for some common tasks. All functions and types from the auxiliary library are defined in header file `lauxlib.h` and have a prefix `luaL_`. All functions in the auxiliary library are built on top of the basic API, and so they provide nothing that cannot be done with that API. Nevertheless, the use of the auxiliary library ensures more consistency to your code. Several functions in the auxiliary library use internally some extra stack slots. When a function in the auxiliary library uses less than five slots, it does not check the stack size; it simply assumes that there are enough slots. Several functions in the auxiliary library are used to check C function arguments. Because the error message is formatted for arguments (e.g., "`bad argument #1`"), you should not use these functions for other stack values. Functions called `luaL_check*` always raise an error if the check is not satisfied. 5.1 – Functions and Types ------------------------- Here we list all functions and types from the auxiliary library in alphabetical order. ### `luaL_addchar`[-?, +?, *m*] ``` void luaL_addchar (luaL_Buffer *B, char c); ``` Adds the byte `c` to the buffer `B` (see [`luaL_Buffer`](#luaL_Buffer)). ### `luaL_addgsub`[-0, +0, *m*] ``` const void luaL_addgsub (luaL_Buffer *B, const char *s, const char *p, const char *r); ``` Adds a copy of the string `s` to the buffer `B` (see [`luaL_Buffer`](#luaL_Buffer)), replacing any occurrence of the string `p` with the string `r`. ### `luaL_addlstring`[-?, +?, *m*] ``` void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l); ``` Adds the string pointed to by `s` with length `l` to the buffer `B` (see [`luaL_Buffer`](#luaL_Buffer)). The string can contain embedded zeros. ### `luaL_addsize`[-?, +?, –] ``` void luaL_addsize (luaL_Buffer *B, size_t n); ``` Adds to the buffer `B` a string of length `n` previously copied to the buffer area (see [`luaL_prepbuffer`](#luaL_prepbuffer)). ### `luaL_addstring`[-?, +?, *m*] ``` void luaL_addstring (luaL_Buffer *B, const char *s); ``` Adds the zero-terminated string pointed to by `s` to the buffer `B` (see [`luaL_Buffer`](#luaL_Buffer)). ### `luaL_addvalue`[-1, +?, *m*] ``` void luaL_addvalue (luaL_Buffer *B); ``` Adds the value on the top of the stack to the buffer `B` (see [`luaL_Buffer`](#luaL_Buffer)). Pops the value. This is the only function on string buffers that can (and must) be called with an extra element on the stack, which is the value to be added to the buffer. ### `luaL_argcheck`[-0, +0, *v*] ``` void luaL_argcheck (lua_State *L, int cond, int arg, const char *extramsg); ``` Checks whether `cond` is true. If it is not, raises an error with a standard message (see [`luaL_argerror`](#luaL_argerror)). ### `luaL_argerror`[-0, +0, *v*] ``` int luaL_argerror (lua_State *L, int arg, const char *extramsg); ``` Raises an error reporting a problem with argument `arg` of the C function that called it, using a standard message that includes `extramsg` as a comment: ``` bad argument #arg to 'funcname' (extramsg) ``` This function never returns. ### `luaL_argexpected`[-0, +0, *v*] ``` void luaL_argexpected (lua_State *L, int cond, int arg, const char *tname); ``` Checks whether `cond` is true. If it is not, raises an error about the type of the argument `arg` with a standard message (see [`luaL_typeerror`](#luaL_typeerror)). ### `luaL_Buffer` ``` typedef struct luaL_Buffer luaL_Buffer; ``` Type for a *string buffer*. A string buffer allows C code to build Lua strings piecemeal. Its pattern of use is as follows: * First declare a variable `b` of type [`luaL_Buffer`](#luaL_Buffer). * Then initialize it with a call `luaL_buffinit(L, &b)`. * Then add string pieces to the buffer calling any of the `luaL_add*` functions. * Finish by calling `luaL_pushresult(&b)`. This call leaves the final string on the top of the stack. If you know beforehand the maximum size of the resulting string, you can use the buffer like this: * First declare a variable `b` of type [`luaL_Buffer`](#luaL_Buffer). * Then initialize it and preallocate a space of size `sz` with a call `luaL_buffinitsize(L, &b, sz)`. * Then produce the string into that space. * Finish by calling `luaL_pushresultsize(&b, sz)`, where `sz` is the total size of the resulting string copied into that space (which may be less than or equal to the preallocated size). During its normal operation, a string buffer uses a variable number of stack slots. So, while using a buffer, you cannot assume that you know where the top of the stack is. You can use the stack between successive calls to buffer operations as long as that use is balanced; that is, when you call a buffer operation, the stack is at the same level it was immediately after the previous buffer operation. (The only exception to this rule is [`luaL_addvalue`](#luaL_addvalue).) After calling [`luaL_pushresult`](#luaL_pushresult), the stack is back to its level when the buffer was initialized, plus the final string on its top. ### `luaL_buffaddr`[-0, +0, –] ``` char *luaL_buffaddr (luaL_Buffer *B); ``` Returns the address of the current content of buffer `B` (see [`luaL_Buffer`](#luaL_Buffer)). Note that any addition to the buffer may invalidate this address. ### `luaL_buffinit`[-0, +0, –] ``` void luaL_buffinit (lua_State *L, luaL_Buffer *B); ``` Initializes a buffer `B` (see [`luaL_Buffer`](#luaL_Buffer)). This function does not allocate any space; the buffer must be declared as a variable. ### `luaL_bufflen`[-0, +0, –] ``` size_t luaL_bufflen (luaL_Buffer *B); ``` Returns the length of the current content of buffer `B` (see [`luaL_Buffer`](#luaL_Buffer)). ### `luaL_buffinitsize`[-?, +?, *m*] ``` char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz); ``` Equivalent to the sequence [`luaL_buffinit`](#luaL_buffinit), [`luaL_prepbuffsize`](#luaL_prepbuffsize). ### `luaL_buffsub`[-0, +0, –] ``` void luaL_buffsub (luaL_Buffer *B, int n); ``` Removes `n` bytes from the the buffer `B` (see [`luaL_Buffer`](#luaL_Buffer)). The buffer must have at least that many bytes. ### `luaL_callmeta`[-0, +(0|1), *e*] ``` int luaL_callmeta (lua_State *L, int obj, const char *e); ``` Calls a metamethod. If the object at index `obj` has a metatable and this metatable has a field `e`, this function calls this field passing the object as its only argument. In this case this function returns true and pushes onto the stack the value returned by the call. If there is no metatable or no metamethod, this function returns false without pushing any value on the stack. ### `luaL_checkany`[-0, +0, *v*] ``` void luaL_checkany (lua_State *L, int arg); ``` Checks whether the function has an argument of any type (including **nil**) at position `arg`. ### `luaL_checkinteger`[-0, +0, *v*] ``` lua_Integer luaL_checkinteger (lua_State *L, int arg); ``` Checks whether the function argument `arg` is an integer (or can be converted to an integer) and returns this integer. ### `luaL_checklstring`[-0, +0, *v*] ``` const char *luaL_checklstring (lua_State *L, int arg, size_t *l); ``` Checks whether the function argument `arg` is a string and returns this string; if `l` is not `NULL` fills its referent with the string's length. This function uses [`lua_tolstring`](#lua_tolstring) to get its result, so all conversions and caveats of that function apply here. ### `luaL_checknumber`[-0, +0, *v*] ``` lua_Number luaL_checknumber (lua_State *L, int arg); ``` Checks whether the function argument `arg` is a number and returns this number converted to a `lua_Number`. ### `luaL_checkoption`[-0, +0, *v*] ``` int luaL_checkoption (lua_State *L, int arg, const char *def, const char *const lst[]); ``` Checks whether the function argument `arg` is a string and searches for this string in the array `lst` (which must be NULL-terminated). Returns the index in the array where the string was found. Raises an error if the argument is not a string or if the string cannot be found. If `def` is not `NULL`, the function uses `def` as a default value when there is no argument `arg` or when this argument is **nil**. This is a useful function for mapping strings to C enums. (The usual convention in Lua libraries is to use strings instead of numbers to select options.) ### `luaL_checkstack`[-0, +0, *v*] ``` void luaL_checkstack (lua_State *L, int sz, const char *msg); ``` Grows the stack size to `top + sz` elements, raising an error if the stack cannot grow to that size. `msg` is an additional text to go into the error message (or `NULL` for no additional text). ### `luaL_checkstring`[-0, +0, *v*] ``` const char *luaL_checkstring (lua_State *L, int arg); ``` Checks whether the function argument `arg` is a string and returns this string. This function uses [`lua_tolstring`](#lua_tolstring) to get its result, so all conversions and caveats of that function apply here. ### `luaL_checktype`[-0, +0, *v*] ``` void luaL_checktype (lua_State *L, int arg, int t); ``` Checks whether the function argument `arg` has type `t`. See [`lua_type`](#lua_type) for the encoding of types for `t`. ### `luaL_checkudata`[-0, +0, *v*] ``` void *luaL_checkudata (lua_State *L, int arg, const char *tname); ``` Checks whether the function argument `arg` is a userdata of the type `tname` (see [`luaL_newmetatable`](#luaL_newmetatable)) and returns the userdata's memory-block address (see [`lua_touserdata`](#lua_touserdata)). ### `luaL_checkversion`[-0, +0, *v*] ``` void luaL_checkversion (lua_State *L); ``` Checks whether the code making the call and the Lua library being called are using the same version of Lua and the same numeric types. ### `luaL_dofile`[-0, +?, *m*] ``` int luaL_dofile (lua_State *L, const char *filename); ``` Loads and runs the given file. It is defined as the following macro: ``` (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0)) ``` It returns [`LUA_OK`](#pdf-LUA_OK) if there are no errors, or an error code in case of errors (see [§4.4.1](#4.4.1)). ### `luaL_dostring`[-0, +?, –] ``` int luaL_dostring (lua_State *L, const char *str); ``` Loads and runs the given string. It is defined as the following macro: ``` (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0)) ``` It returns [`LUA_OK`](#pdf-LUA_OK) if there are no errors, or an error code in case of errors (see [§4.4.1](#4.4.1)). ### `luaL_error`[-0, +0, *v*] ``` int luaL_error (lua_State *L, const char *fmt, ...); ``` Raises an error. The error message format is given by `fmt` plus any extra arguments, following the same rules of [`lua_pushfstring`](#lua_pushfstring). It also adds at the beginning of the message the file name and the line number where the error occurred, if this information is available. This function never returns, but it is an idiom to use it in C functions as `return luaL_error(*args*)`. ### `luaL_execresult`[-0, +3, *m*] ``` int luaL_execresult (lua_State *L, int stat); ``` This function produces the return values for process-related functions in the standard library ([`os.execute`](#pdf-os.execute) and [`io.close`](#pdf-io.close)). ### `luaL_fileresult`[-0, +(1|3), *m*] ``` int luaL_fileresult (lua_State *L, int stat, const char *fname); ``` This function produces the return values for file-related functions in the standard library ([`io.open`](#pdf-io.open), [`os.rename`](#pdf-os.rename), [`file:seek`](#pdf-file:seek), etc.). ### `luaL_getmetafield`[-0, +(0|1), *m*] ``` int luaL_getmetafield (lua_State *L, int obj, const char *e); ``` Pushes onto the stack the field `e` from the metatable of the object at index `obj` and returns the type of the pushed value. If the object does not have a metatable, or if the metatable does not have this field, pushes nothing and returns `LUA_TNIL`. ### `luaL_getmetatable`[-0, +1, *m*] ``` int luaL_getmetatable (lua_State *L, const char *tname); ``` Pushes onto the stack the metatable associated with the name `tname` in the registry (see [`luaL_newmetatable`](#luaL_newmetatable)), or **nil** if there is no metatable associated with that name. Returns the type of the pushed value. ### `luaL_getsubtable`[-0, +1, *e*] ``` int luaL_getsubtable (lua_State *L, int idx, const char *fname); ``` Ensures that the value `t[fname]`, where `t` is the value at index `idx`, is a table, and pushes that table onto the stack. Returns true if it finds a previous table there and false if it creates a new table. ### `luaL_gsub`[-0, +1, *m*] ``` const char *luaL_gsub (lua_State *L, const char *s, const char *p, const char *r); ``` Creates a copy of string `s`, replacing any occurrence of the string `p` with the string `r`. Pushes the resulting string on the stack and returns it. ### `luaL_len`[-0, +0, *e*] ``` lua_Integer luaL_len (lua_State *L, int index); ``` Returns the "length" of the value at the given index as a number; it is equivalent to the '`#`' operator in Lua (see [§3.4.7](#3.4.7)). Raises an error if the result of the operation is not an integer. (This case can only happen through metamethods.) ### `luaL_loadbuffer`[-0, +1, –] ``` int luaL_loadbuffer (lua_State *L, const char *buff, size_t sz, const char *name); ``` Equivalent to [`luaL_loadbufferx`](#luaL_loadbufferx) with `mode` equal to `NULL`. ### `luaL_loadbufferx`[-0, +1, –] ``` int luaL_loadbufferx (lua_State *L, const char *buff, size_t sz, const char *name, const char *mode); ``` Loads a buffer as a Lua chunk. This function uses [`lua_load`](#lua_load) to load the chunk in the buffer pointed to by `buff` with size `sz`. This function returns the same results as [`lua_load`](#lua_load). `name` is the chunk name, used for debug information and error messages. The string `mode` works as in the function [`lua_load`](#lua_load). ### `luaL_loadfile`[-0, +1, *m*] ``` int luaL_loadfile (lua_State *L, const char *filename); ``` Equivalent to [`luaL_loadfilex`](#luaL_loadfilex) with `mode` equal to `NULL`. ### `luaL_loadfilex`[-0, +1, *m*] ``` int luaL_loadfilex (lua_State *L, const char *filename, const char *mode); ``` Loads a file as a Lua chunk. This function uses [`lua_load`](#lua_load) to load the chunk in the file named `filename`. If `filename` is `NULL`, then it loads from the standard input. The first line in the file is ignored if it starts with a `#`. The string `mode` works as in the function [`lua_load`](#lua_load). This function returns the same results as [`lua_load`](#lua_load) or [`LUA_ERRFILE`](#pdf-LUA_ERRFILE) for file-related errors. As [`lua_load`](#lua_load), this function only loads the chunk; it does not run it. ### `luaL_loadstring`[-0, +1, –] ``` int luaL_loadstring (lua_State *L, const char *s); ``` Loads a string as a Lua chunk. This function uses [`lua_load`](#lua_load) to load the chunk in the zero-terminated string `s`. This function returns the same results as [`lua_load`](#lua_load). Also as [`lua_load`](#lua_load), this function only loads the chunk; it does not run it. ### `luaL_newlib`[-0, +1, *m*] ``` void luaL_newlib (lua_State *L, const luaL_Reg l[]); ``` Creates a new table and registers there the functions in the list `l`. It is implemented as the following macro: ``` (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) ``` The array `l` must be the actual array, not a pointer to it. ### `luaL_newlibtable`[-0, +1, *m*] ``` void luaL_newlibtable (lua_State *L, const luaL_Reg l[]); ``` Creates a new table with a size optimized to store all entries in the array `l` (but does not actually store them). It is intended to be used in conjunction with [`luaL_setfuncs`](#luaL_setfuncs) (see [`luaL_newlib`](#luaL_newlib)). It is implemented as a macro. The array `l` must be the actual array, not a pointer to it. ### `luaL_newmetatable`[-0, +1, *m*] ``` int luaL_newmetatable (lua_State *L, const char *tname); ``` If the registry already has the key `tname`, returns 0. Otherwise, creates a new table to be used as a metatable for userdata, adds to this new table the pair `__name = tname`, adds to the registry the pair `[tname] = new table`, and returns 1. In both cases, the function pushes onto the stack the final value associated with `tname` in the registry. ### `luaL_newstate`[-0, +0, –] ``` lua_State *luaL_newstate (void); ``` Creates a new Lua state. It calls [`lua_newstate`](#lua_newstate) with an allocator based on the standard C allocation functions and then sets a warning function and a panic function (see [§4.4](#4.4)) that print messages to the standard error output. Returns the new state, or `NULL` if there is a memory allocation error. ### `luaL_openlibs`[-0, +0, *e*] ``` void luaL_openlibs (lua_State *L); ``` Opens all standard Lua libraries into the given state. ### `luaL_opt`[-0, +0, –] ``` T luaL_opt (L, func, arg, dflt); ``` This macro is defined as follows: ``` (lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg))) ``` In words, if the argument `arg` is nil or absent, the macro results in the default `dflt`. Otherwise, it results in the result of calling `func` with the state `L` and the argument index `arg` as arguments. Note that it evaluates the expression `dflt` only if needed. ### `luaL_optinteger`[-0, +0, *v*] ``` lua_Integer luaL_optinteger (lua_State *L, int arg, lua_Integer d); ``` If the function argument `arg` is an integer (or it is convertible to an integer), returns this integer. If this argument is absent or is **nil**, returns `d`. Otherwise, raises an error. ### `luaL_optlstring`[-0, +0, *v*] ``` const char *luaL_optlstring (lua_State *L, int arg, const char *d, size_t *l); ``` If the function argument `arg` is a string, returns this string. If this argument is absent or is **nil**, returns `d`. Otherwise, raises an error. If `l` is not `NULL`, fills its referent with the result's length. If the result is `NULL` (only possible when returning `d` and `d == NULL`), its length is considered zero. This function uses [`lua_tolstring`](#lua_tolstring) to get its result, so all conversions and caveats of that function apply here. ### `luaL_optnumber`[-0, +0, *v*] ``` lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d); ``` If the function argument `arg` is a number, returns this number as a `lua_Number`. If this argument is absent or is **nil**, returns `d`. Otherwise, raises an error. ### `luaL_optstring`[-0, +0, *v*] ``` const char *luaL_optstring (lua_State *L, int arg, const char *d); ``` If the function argument `arg` is a string, returns this string. If this argument is absent or is **nil**, returns `d`. Otherwise, raises an error. ### `luaL_prepbuffer`[-?, +?, *m*] ``` char *luaL_prepbuffer (luaL_Buffer *B); ``` Equivalent to [`luaL_prepbuffsize`](#luaL_prepbuffsize) with the predefined size `LUAL_BUFFERSIZE`. ### `luaL_prepbuffsize`[-?, +?, *m*] ``` char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz); ``` Returns an address to a space of size `sz` where you can copy a string to be added to buffer `B` (see [`luaL_Buffer`](#luaL_Buffer)). After copying the string into this space you must call [`luaL_addsize`](#luaL_addsize) with the size of the string to actually add it to the buffer. ### `luaL_pushfail`[-0, +1, –] ``` void luaL_pushfail (lua_State *L); ``` Pushes the **fail** value onto the stack (see [§6](#6)). ### `luaL_pushresult`[-?, +1, *m*] ``` void luaL_pushresult (luaL_Buffer *B); ``` Finishes the use of buffer `B` leaving the final string on the top of the stack. ### `luaL_pushresultsize`[-?, +1, *m*] ``` void luaL_pushresultsize (luaL_Buffer *B, size_t sz); ``` Equivalent to the sequence [`luaL_addsize`](#luaL_addsize), [`luaL_pushresult`](#luaL_pushresult). ### `luaL_ref`[-1, +0, *m*] ``` int luaL_ref (lua_State *L, int t); ``` Creates and returns a *reference*, in the table at index `t`, for the object on the top of the stack (and pops the object). A reference is a unique integer key. As long as you do not manually add integer keys into the table `t`, [`luaL_ref`](#luaL_ref) ensures the uniqueness of the key it returns. You can retrieve an object referred by the reference `r` by calling `lua_rawgeti(L, t, r)`. The function [`luaL_unref`](#luaL_unref) frees a reference. If the object on the top of the stack is **nil**, [`luaL_ref`](#luaL_ref) returns the constant `LUA_REFNIL`. The constant `LUA_NOREF` is guaranteed to be different from any reference returned by [`luaL_ref`](#luaL_ref). ### `luaL_Reg` ``` typedef struct luaL_Reg { const char *name; lua_CFunction func; } luaL_Reg; ``` Type for arrays of functions to be registered by [`luaL_setfuncs`](#luaL_setfuncs). `name` is the function name and `func` is a pointer to the function. Any array of [`luaL_Reg`](#luaL_Reg) must end with a sentinel entry in which both `name` and `func` are `NULL`. ### `luaL_requiref`[-0, +1, *e*] ``` void luaL_requiref (lua_State *L, const char *modname, lua_CFunction openf, int glb); ``` If `package.loaded[modname]` is not true, calls the function `openf` with the string `modname` as an argument and sets the call result to `package.loaded[modname]`, as if that function has been called through [`require`](#pdf-require). If `glb` is true, also stores the module into the global `modname`. Leaves a copy of the module on the stack. ### `luaL_setfuncs`[-nup, +0, *m*] ``` void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup); ``` Registers all functions in the array `l` (see [`luaL_Reg`](#luaL_Reg)) into the table on the top of the stack (below optional upvalues, see next). When `nup` is not zero, all functions are created with `nup` upvalues, initialized with copies of the `nup` values previously pushed on the stack on top of the library table. These values are popped from the stack after the registration. ### `luaL_setmetatable`[-0, +0, –] ``` void luaL_setmetatable (lua_State *L, const char *tname); ``` Sets the metatable of the object on the top of the stack as the metatable associated with name `tname` in the registry (see [`luaL_newmetatable`](#luaL_newmetatable)). ### `luaL_Stream` ``` typedef struct luaL_Stream { FILE *f; lua_CFunction closef; } luaL_Stream; ``` The standard representation for file handles used by the standard I/O library. A file handle is implemented as a full userdata, with a metatable called `LUA_FILEHANDLE` (where `LUA_FILEHANDLE` is a macro with the actual metatable's name). The metatable is created by the I/O library (see [`luaL_newmetatable`](#luaL_newmetatable)). This userdata must start with the structure `luaL_Stream`; it can contain other data after this initial structure. The field `f` points to the corresponding C stream (or it can be `NULL` to indicate an incompletely created handle). The field `closef` points to a Lua function that will be called to close the stream when the handle is closed or collected; this function receives the file handle as its sole argument and must return either a true value, in case of success, or a false value plus an error message, in case of error. Once Lua calls this field, it changes the field value to `NULL` to signal that the handle is closed. ### `luaL_testudata`[-0, +0, *m*] ``` void *luaL_testudata (lua_State *L, int arg, const char *tname); ``` This function works like [`luaL_checkudata`](#luaL_checkudata), except that, when the test fails, it returns `NULL` instead of raising an error. ### `luaL_tolstring`[-0, +1, *e*] ``` const char *luaL_tolstring (lua_State *L, int idx, size_t *len); ``` Converts any Lua value at the given index to a C string in a reasonable format. The resulting string is pushed onto the stack and also returned by the function (see [§4.1.3](#4.1.3)). If `len` is not `NULL`, the function also sets `*len` with the string length. If the value has a metatable with a `__tostring` field, then `luaL_tolstring` calls the corresponding metamethod with the value as argument, and uses the result of the call as its result. ### `luaL_traceback`[-0, +1, *m*] ``` void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, int level); ``` Creates and pushes a traceback of the stack `L1`. If `msg` is not `NULL`, it is appended at the beginning of the traceback. The `level` parameter tells at which level to start the traceback. ### `luaL_typeerror`[-0, +0, *v*] ``` const char *luaL_typeerror (lua_State *L, int arg, const char *tname); ``` Raises a type error for the argument `arg` of the C function that called it, using a standard message; `tname` is a "name" for the expected type. This function never returns. ### `luaL_typename`[-0, +0, –] ``` const char *luaL_typename (lua_State *L, int index); ``` Returns the name of the type of the value at the given index. ### `luaL_unref`[-0, +0, –] ``` void luaL_unref (lua_State *L, int t, int ref); ``` Releases the reference `ref` from the table at index `t` (see [`luaL_ref`](#luaL_ref)). The entry is removed from the table, so that the referred object can be collected. The reference `ref` is also freed to be used again. If `ref` is [`LUA_NOREF`](#pdf-LUA_NOREF) or [`LUA_REFNIL`](#pdf-LUA_REFNIL), [`luaL_unref`](#luaL_unref) does nothing. ### `luaL_where`[-0, +1, *m*] ``` void luaL_where (lua_State *L, int lvl); ``` Pushes onto the stack a string identifying the current position of the control at level `lvl` in the call stack. Typically this string has the following format: ``` chunkname:currentline: ``` Level 0 is the running function, level 1 is the function that called the running function, etc. This function is used to build a prefix for error messages. 6 – The Standard Libraries ========================== The standard Lua libraries provide useful functions that are implemented in C through the C API. Some of these functions provide essential services to the language (e.g., [`type`](#pdf-type) and [`getmetatable`](#pdf-getmetatable)); others provide access to outside services (e.g., I/O); and others could be implemented in Lua itself, but that for different reasons deserve an implementation in C (e.g., [`table.sort`](#pdf-table.sort)). All libraries are implemented through the official C API and are provided as separate C modules. Unless otherwise noted, these library functions do not adjust its number of arguments to its expected parameters. For instance, a function documented as `foo(arg)` should not be called without an argument. The notation **fail** means a false value representing some kind of failure. (Currently, **fail** is equal to **nil**, but that may change in future versions. The recommendation is to always test the success of these functions with `(not status)`, instead of `(status == nil)`.) Currently, Lua has the following standard libraries: * basic library ([§6.1](#6.1)); * coroutine library ([§6.2](#6.2)); * package library ([§6.3](#6.3)); * string manipulation ([§6.4](#6.4)); * basic UTF-8 support ([§6.5](#6.5)); * table manipulation ([§6.6](#6.6)); * mathematical functions ([§6.7](#6.7)) (sin, log, etc.); * input and output ([§6.8](#6.8)); * operating system facilities ([§6.9](#6.9)); * debug facilities ([§6.10](#6.10)). Except for the basic and the package libraries, each library provides all its functions as fields of a global table or as methods of its objects. To have access to these libraries, the C host program should call the [`luaL_openlibs`](#luaL_openlibs) function, which opens all standard libraries. Alternatively, the host program can open them individually by using [`luaL_requiref`](#luaL_requiref) to call `luaopen_base` (for the basic library), `luaopen_package` (for the package library), `luaopen_coroutine` (for the coroutine library), `luaopen_string` (for the string library), `luaopen_utf8` (for the UTF-8 library), `luaopen_table` (for the table library), `luaopen_math` (for the mathematical library), `luaopen_io` (for the I/O library), `luaopen_os` (for the operating system library), and `luaopen_debug` (for the debug library). These functions are declared in `lualib.h`. 6.1 – Basic Functions --------------------- The basic library provides core functions to Lua. If you do not include this library in your application, you should check carefully whether you need to provide implementations for some of its facilities. ### `assert (v [, message])` Raises an error if the value of its argument `v` is false (i.e., **nil** or **false**); otherwise, returns all its arguments. In case of error, `message` is the error object; when absent, it defaults to "`assertion failed!`" ### `collectgarbage ([opt [, arg]])` This function is a generic interface to the garbage collector. It performs different functions according to its first argument, `opt`: * "`collect`": Performs a full garbage-collection cycle. This is the default option. * "`stop`": Stops automatic execution of the garbage collector. The collector will run only when explicitly invoked, until a call to restart it. * "`restart`": Restarts automatic execution of the garbage collector. * "`count`": Returns the total memory in use by Lua in Kbytes. The value has a fractional part, so that it multiplied by 1024 gives the exact number of bytes in use by Lua. * "`step`": Performs a garbage-collection step. The step "size" is controlled by `arg`. With a zero value, the collector will perform one basic (indivisible) step. For non-zero values, the collector will perform as if that amount of memory (in Kbytes) had been allocated by Lua. Returns **true** if the step finished a collection cycle. * "`isrunning`": Returns a boolean that tells whether the collector is running (i.e., not stopped). * "`incremental`": Change the collector mode to incremental. This option can be followed by three numbers: the garbage-collector pause, the step multiplier, and the step size (see [§2.5.1](#2.5.1)). A zero means to not change that value. * "`generational`": Change the collector mode to generational. This option can be followed by two numbers: the garbage-collector minor multiplier and the major multiplier (see [§2.5.2](#2.5.2)). A zero means to not change that value. See [§2.5](#2.5) for more details about garbage collection and some of these options. ### `dofile ([filename])` Opens the named file and executes its content as a Lua chunk. When called without arguments, `dofile` executes the content of the standard input (`stdin`). Returns all values returned by the chunk. In case of errors, `dofile` propagates the error to its caller. (That is, `dofile` does not run in protected mode.) ### `error (message [, level])` Raises an error (see [§2.3](#2.3)) with @{message} as the error object. This function never returns. Usually, `error` adds some information about the error position at the beginning of the message, if the message is a string. The `level` argument specifies how to get the error position. With level 1 (the default), the error position is where the `error` function was called. Level 2 points the error to where the function that called `error` was called; and so on. Passing a level 0 avoids the addition of error position information to the message. ### `_G` A global variable (not a function) that holds the global environment (see [§2.2](#2.2)). Lua itself does not use this variable; changing its value does not affect any environment, nor vice versa. ### `getmetatable (object)` If `object` does not have a metatable, returns **nil**. Otherwise, if the object's metatable has a `__metatable` field, returns the associated value. Otherwise, returns the metatable of the given object. ### `ipairs (t)` Returns three values (an iterator function, the table `t`, and 0) so that the construction ``` for i,v in ipairs(t) do body end ``` will iterate over the key–value pairs (`1,t[1]`), (`2,t[2]`), ..., up to the first absent index. ### `load (chunk [, chunkname [, mode [, env]]])` Loads a chunk. If `chunk` is a string, the chunk is this string. If `chunk` is a function, `load` calls it repeatedly to get the chunk pieces. Each call to `chunk` must return a string that concatenates with previous results. A return of an empty string, **nil**, or no value signals the end of the chunk. If there are no syntactic errors, `load` returns the compiled chunk as a function; otherwise, it returns **fail** plus the error message. When you load a main chunk, the resulting function will always have exactly one upvalue, the `_ENV` variable (see [§2.2](#2.2)). However, when you load a binary chunk created from a function (see [`string.dump`](#pdf-string.dump)), the resulting function can have an arbitrary number of upvalues, and there is no guarantee that its first upvalue will be the `_ENV` variable. (A non-main function may not even have an `_ENV` upvalue.) Regardless, if the resulting function has any upvalues, its first upvalue is set to the value of `env`, if that parameter is given, or to the value of the global environment. Other upvalues are initialized with **nil**. All upvalues are fresh, that is, they are not shared with any other function. `chunkname` is used as the name of the chunk for error messages and debug information (see [§4.7](#4.7)). When absent, it defaults to `chunk`, if `chunk` is a string, or to "`=(load)`" otherwise. The string `mode` controls whether the chunk can be text or binary (that is, a precompiled chunk). It may be the string "`b`" (only binary chunks), "`t`" (only text chunks), or "`bt`" (both binary and text). The default is "`bt`". It is safe to load malformed binary chunks; `load` signals an appropriate error. However, Lua does not check the consistency of the code inside binary chunks; running maliciously crafted bytecode can crash the interpreter. ### `loadfile ([filename [, mode [, env]]])` Similar to [`load`](#pdf-load), but gets the chunk from file `filename` or from the standard input, if no file name is given. ### `next (table [, index])` Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. A call to `next` returns the next index of the table and its associated value. When called with **nil** as its second argument, `next` returns an initial index and its associated value. When called with the last index, or with **nil** in an empty table, `next` returns **nil**. If the second argument is absent, then it is interpreted as **nil**. In particular, you can use `next(t)` to check whether a table is empty. The order in which the indices are enumerated is not specified, *even for numeric indices*. (To traverse a table in numerical order, use a numerical **for**.) The behavior of `next` is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may set existing fields to nil. ### `pairs (t)` If `t` has a metamethod `__pairs`, calls it with `t` as argument and returns the first three results from the call. Otherwise, returns three values: the [`next`](#pdf-next) function, the table `t`, and **nil**, so that the construction ``` for k,v in pairs(t) do body end ``` will iterate over all key–value pairs of table `t`. See function [`next`](#pdf-next) for the caveats of modifying the table during its traversal. ### `pcall (f [, arg1, ···])` Calls the function `f` with the given arguments in *protected mode*. This means that any error inside `f` is not propagated; instead, `pcall` catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, `pcall` also returns all results from the call, after this first result. In case of any error, `pcall` returns **false** plus the error object. Note that errors caught by `pcall` do not call a message handler. ### `print (···)` Receives any number of arguments and prints their values to `stdout`, converting each argument to a string following the same rules of [`tostring`](#pdf-tostring). The function `print` is not intended for formatted output, but only as a quick way to show a value, for instance for debugging. For complete control over the output, use [`string.format`](#pdf-string.format) and [`io.write`](#pdf-io.write). ### `rawequal (v1, v2)` Checks whether `v1` is equal to `v2`, without invoking the `__eq` metamethod. Returns a boolean. ### `rawget (table, index)` Gets the real value of `table[index]`, without using the `__index` metavalue. `table` must be a table; `index` may be any value. ### `rawlen (v)` Returns the length of the object `v`, which must be a table or a string, without invoking the `__len` metamethod. Returns an integer. ### `rawset (table, index, value)` Sets the real value of `table[index]` to `value`, without using the `__newindex` metavalue. `table` must be a table, `index` any value different from **nil** and NaN, and `value` any Lua value. This function returns `table`. ### `select (index, ···)` If `index` is a number, returns all arguments after argument number `index`; a negative number indexes from the end (-1 is the last argument). Otherwise, `index` must be the string `"#"`, and `select` returns the total number of extra arguments it received. ### `setmetatable (table, metatable)` Sets the metatable for the given table. If `metatable` is **nil**, removes the metatable of the given table. If the original metatable has a `__metatable` field, raises an error. This function returns `table`. To change the metatable of other types from Lua code, you must use the debug library ([§6.10](#6.10)). ### `tonumber (e [, base])` When called with no `base`, `tonumber` tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then `tonumber` returns this number; otherwise, it returns **fail**. The conversion of strings can result in integers or floats, according to the lexical conventions of Lua (see [§3.1](#3.1)). The string may have leading and trailing spaces and a sign. When called with `base`, then `e` must be a string to be interpreted as an integer numeral in that base. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter '`A`' (in either upper or lower case) represents 10, '`B`' represents 11, and so forth, with '`Z`' representing 35. If the string `e` is not a valid numeral in the given base, the function returns **fail**. ### `tostring (v)` Receives a value of any type and converts it to a string in a human-readable format. If the metatable of `v` has a `__tostring` field, then `tostring` calls the corresponding value with `v` as argument, and uses the result of the call as its result. Otherwise, if the metatable of `v` has a `__name` field with a string value, `tostring` may use that string in its final result. For complete control of how numbers are converted, use [`string.format`](#pdf-string.format). ### `type (v)` Returns the type of its only argument, coded as a string. The possible results of this function are "`nil`" (a string, not the value **nil**), "`number`", "`string`", "`boolean`", "`table`", "`function`", "`thread`", and "`userdata`". ### `_VERSION` A global variable (not a function) that holds a string containing the running Lua version. The current value of this variable is "`Lua 5.4`". ### `warn (msg1, ···)` Emits a warning with a message composed by the concatenation of all its arguments (which should be strings). By convention, a one-piece message starting with '`@`' is intended to be a *control message*, which is a message to the warning system itself. In particular, the standard warning function in Lua recognizes the control messages "`@off`", to stop the emission of warnings, and "`@on`", to (re)start the emission; it ignores unknown control messages. ### `xpcall (f, msgh [, arg1, ···])` This function is similar to [`pcall`](#pdf-pcall), except that it sets a new message handler `msgh`. 6.2 – Coroutine Manipulation ---------------------------- This library comprises the operations to manipulate coroutines, which come inside the table `coroutine`. See [§2.6](#2.6) for a general description of coroutines. ### `coroutine.close (co)` Closes coroutine `co`, that is, closes all its pending to-be-closed variables and puts the coroutine in a dead state. The given coroutine must be dead or suspended. In case of error closing some variable, returns **false** plus the error object; otherwise returns **true**. ### `coroutine.create (f)` Creates a new coroutine, with body `f`. `f` must be a function. Returns this new coroutine, an object with type `"thread"`. ### `coroutine.isyieldable ([co])` Returns true when the coroutine `co` can yield. The default for `co` is the running coroutine. A coroutine is yieldable if it is not the main thread and it is not inside a non-yieldable C function. ### `coroutine.resume (co [, val1, ···])` Starts or continues the execution of coroutine `co`. The first time you resume a coroutine, it starts running its body. The values `val1`, ... are passed as the arguments to the body function. If the coroutine has yielded, `resume` restarts it; the values `val1`, ... are passed as the results from the yield. If the coroutine runs without any errors, `resume` returns **true** plus any values passed to `yield` (when the coroutine yields) or any values returned by the body function (when the coroutine terminates). If there is any error, `resume` returns **false** plus the error message. ### `coroutine.running ()` Returns the running coroutine plus a boolean, true when the running coroutine is the main one. ### `coroutine.status (co)` Returns the status of the coroutine `co`, as a string: `"running"`, if the coroutine is running (that is, it is the one that called `status`); `"suspended"`, if the coroutine is suspended in a call to `yield`, or if it has not started running yet; `"normal"` if the coroutine is active but not running (that is, it has resumed another coroutine); and `"dead"` if the coroutine has finished its body function, or if it has stopped with an error. ### `coroutine.wrap (f)` Creates a new coroutine, with body `f`; `f` must be a function. Returns a function that resumes the coroutine each time it is called. Any arguments passed to this function behave as the extra arguments to `resume`. The function returns the same values returned by `resume`, except the first boolean. In case of error, the function closes the coroutine and propagates the error. ### `coroutine.yield (···)` Suspends the execution of the calling coroutine. Any arguments to `yield` are passed as extra results to `resume`. 6.3 – Modules ------------- The package library provides basic facilities for loading modules in Lua. It exports one function directly in the global environment: [`require`](#pdf-require). Everything else is exported in the table `package`. ### `require (modname)` Loads the given module. The function starts by looking into the [`package.loaded`](#pdf-package.loaded) table to determine whether `modname` is already loaded. If it is, then `require` returns the value stored at `package.loaded[modname]`. (The absence of a second result in this case signals that this call did not have to load the module.) Otherwise, it tries to find a *loader* for the module. To find a loader, `require` is guided by the table [`package.searchers`](#pdf-package.searchers). Each item in this table is a search function, that searches for the module in a particular way. By changing this table, we can change how `require` looks for a module. The following explanation is based on the default configuration for [`package.searchers`](#pdf-package.searchers). First `require` queries `package.preload[modname]`. If it has a value, this value (which must be a function) is the loader. Otherwise `require` searches for a Lua loader using the path stored in [`package.path`](#pdf-package.path). If that also fails, it searches for a C loader using the path stored in [`package.cpath`](#pdf-package.cpath). If that also fails, it tries an *all-in-one* loader (see [`package.searchers`](#pdf-package.searchers)). Once a loader is found, `require` calls the loader with two arguments: `modname` and an extra value, a *loader data*, also returned by the searcher. The loader data can be any value useful to the module; for the default searchers, it indicates where the loader was found. (For instance, if the loader came from a file, this extra value is the file path.) If the loader returns any non-nil value, `require` assigns the returned value to `package.loaded[modname]`. If the loader does not return a non-nil value and has not assigned any value to `package.loaded[modname]`, then `require` assigns **true** to this entry. In any case, `require` returns the final value of `package.loaded[modname]`. Besides that value, `require` also returns as a second result the loader data returned by the searcher, which indicates how `require` found the module. If there is any error loading or running the module, or if it cannot find any loader for the module, then `require` raises an error. ### `package.config` A string describing some compile-time configurations for packages. This string is a sequence of lines: * The first line is the directory separator string. Default is '`\`' for Windows and '`/`' for all other systems. * The second line is the character that separates templates in a path. Default is '`;`'. * The third line is the string that marks the substitution points in a template. Default is '`?`'. * The fourth line is a string that, in a path in Windows, is replaced by the executable's directory. Default is '`!`'. * The fifth line is a mark to ignore all text after it when building the `luaopen_` function name. Default is '`-`'. ### `package.cpath` A string with the path used by [`require`](#pdf-require) to search for a C loader. Lua initializes the C path [`package.cpath`](#pdf-package.cpath) in the same way it initializes the Lua path [`package.path`](#pdf-package.path), using the environment variable `LUA_CPATH_5_4`, or the environment variable `LUA_CPATH`, or a default path defined in `luaconf.h`. ### `package.loaded` A table used by [`require`](#pdf-require) to control which modules are already loaded. When you require a module `modname` and `package.loaded[modname]` is not false, [`require`](#pdf-require) simply returns the value stored there. This variable is only a reference to the real table; assignments to this variable do not change the table used by [`require`](#pdf-require). ### `package.loadlib (libname, funcname)` Dynamically links the host program with the C library `libname`. If `funcname` is "`*`", then it only links with the library, making the symbols exported by the library available to other dynamically linked libraries. Otherwise, it looks for a function `funcname` inside the library and returns this function as a C function. So, `funcname` must follow the [`lua_CFunction`](#lua_CFunction) prototype (see [`lua_CFunction`](#lua_CFunction)). This is a low-level function. It completely bypasses the package and module system. Unlike [`require`](#pdf-require), it does not perform any path searching and does not automatically adds extensions. `libname` must be the complete file name of the C library, including if necessary a path and an extension. `funcname` must be the exact name exported by the C library (which may depend on the C compiler and linker used). This function is not supported by Standard C. As such, it is only available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, plus other Unix systems that support the `dlfcn` standard). This function is inherently insecure, as it allows Lua to call any function in any readable dynamic library in the system. (Lua calls any function assuming the function has a proper prototype and respects a proper protocol (see [`lua_CFunction`](#lua_CFunction)). Therefore, calling an arbitrary function in an arbitrary dynamic library more often than not results in an access violation.) ### `package.path` A string with the path used by [`require`](#pdf-require) to search for a Lua loader. At start-up, Lua initializes this variable with the value of the environment variable `LUA_PATH_5_4` or the environment variable `LUA_PATH` or with a default path defined in `luaconf.h`, if those environment variables are not defined. A "`;;`" in the value of the environment variable is replaced by the default path. ### `package.preload` A table to store loaders for specific modules (see [`require`](#pdf-require)). This variable is only a reference to the real table; assignments to this variable do not change the table used by [`require`](#pdf-require). ### `package.searchers` A table used by [`require`](#pdf-require) to control how to find modules. Each entry in this table is a *searcher function*. When looking for a module, [`require`](#pdf-require) calls each of these searchers in ascending order, with the module name (the argument given to [`require`](#pdf-require)) as its sole argument. If the searcher finds the module, it returns another function, the module *loader*, plus an extra value, a *loader data*, that will be passed to that loader and returned as a second result by [`require`](#pdf-require). If it cannot find the module, it returns a string explaining why (or **nil** if it has nothing to say). Lua initializes this table with four searcher functions. The first searcher simply looks for a loader in the [`package.preload`](#pdf-package.preload) table. The second searcher looks for a loader as a Lua library, using the path stored at [`package.path`](#pdf-package.path). The search is done as described in function [`package.searchpath`](#pdf-package.searchpath). The third searcher looks for a loader as a C library, using the path given by the variable [`package.cpath`](#pdf-package.cpath). Again, the search is done as described in function [`package.searchpath`](#pdf-package.searchpath). For instance, if the C path is the string ``` "./?.so;./?.dll;/usr/local/?/init.so" ``` the searcher for module `foo` will try to open the files `./foo.so`, `./foo.dll`, and `/usr/local/foo/init.so`, in that order. Once it finds a C library, this searcher first uses a dynamic link facility to link the application with the library. Then it tries to find a C function inside the library to be used as the loader. The name of this C function is the string "`luaopen_`" concatenated with a copy of the module name where each dot is replaced by an underscore. Moreover, if the module name has a hyphen, its suffix after (and including) the first hyphen is removed. For instance, if the module name is `a.b.c-v2.1`, the function name will be `luaopen_a_b_c`. The fourth searcher tries an *all-in-one loader*. It searches the C path for a library for the root name of the given module. For instance, when requiring `a.b.c`, it will search for a C library for `a`. If found, it looks into it for an open function for the submodule; in our example, that would be `luaopen_a_b_c`. With this facility, a package can pack several C submodules into one single library, with each submodule keeping its original open function. All searchers except the first one (preload) return as the extra value the file path where the module was found, as returned by [`package.searchpath`](#pdf-package.searchpath). The first searcher always returns the string "`:preload:`". Searchers should raise no errors and have no side effects in Lua. (They may have side effects in C, for instance by linking the application with a library.) ### `package.searchpath (name, path [, sep [, rep]])` Searches for the given `name` in the given `path`. A path is a string containing a sequence of *templates* separated by semicolons. For each template, the function replaces each interrogation mark (if any) in the template with a copy of `name` wherein all occurrences of `sep` (a dot, by default) were replaced by `rep` (the system's directory separator, by default), and then tries to open the resulting file name. For instance, if the path is the string ``` "./?.lua;./?.lc;/usr/local/?/init.lua" ``` the search for the name `foo.a` will try to open the files `./foo/a.lua`, `./foo/a.lc`, and `/usr/local/foo/a/init.lua`, in that order. Returns the resulting name of the first file that it can open in read mode (after closing the file), or **fail** plus an error message if none succeeds. (This error message lists all file names it tried to open.) 6.4 – String Manipulation ------------------------- This library provides generic functions for string manipulation, such as finding and extracting substrings, and pattern matching. When indexing a string in Lua, the first character is at position 1 (not at 0, as in C). Indices are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on. The string library provides all its functions inside the table `string`. It also sets a metatable for strings where the `__index` field points to the `string` table. Therefore, you can use the string functions in object-oriented style. For instance, `string.byte(s,i)` can be written as `s:byte(i)`. The string library assumes one-byte character encodings. ### `string.byte (s [, i [, j]])` Returns the internal numeric codes of the characters `s[i]`, `s[i+1]`, ..., `s[j]`. The default value for `i` is 1; the default value for `j` is `i`. These indices are corrected following the same rules of function [`string.sub`](#pdf-string.sub). Numeric codes are not necessarily portable across platforms. ### `string.char (···)` Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numeric code equal to its corresponding argument. Numeric codes are not necessarily portable across platforms. ### `string.dump (function [, strip])` Returns a string containing a binary representation (a *binary chunk*) of the given function, so that a later [`load`](#pdf-load) on this string returns a copy of the function (but with new upvalues). If `strip` is a true value, the binary representation may not include all debug information about the function, to save space. Functions with upvalues have only their number of upvalues saved. When (re)loaded, those upvalues receive fresh instances. (See the [`load`](#pdf-load) function for details about how these upvalues are initialized. You can use the debug library to serialize and reload the upvalues of a function in a way adequate to your needs.) ### `string.find (s, pattern [, init [, plain]])` Looks for the first match of `pattern` (see [§6.4.1](#6.4.1)) in the string `s`. If it finds a match, then `find` returns the indices of `s` where this occurrence starts and ends; otherwise, it returns **fail**. A third, optional numeric argument `init` specifies where to start the search; its default value is 1 and can be negative. A value of **true** as a fourth, optional argument `plain` turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in `pattern` being considered magic. If the pattern has captures, then in a successful match the captured values are also returned, after the two indices. ### `string.format (formatstring, ···)` Returns a formatted version of its variable number of arguments following the description given in its first argument, which must be a string. The format string follows the same rules as the ISO C function `sprintf`. The only differences are that the conversion specifiers and modifiers `*`, `h`, `L`, `l`, and `n` are not supported and that there is an extra specifier, `q`. The specifier `q` formats booleans, nil, numbers, and strings in a way that the result is a valid constant in Lua source code. Booleans and nil are written in the obvious way (`true`, `false`, `nil`). Floats are written in hexadecimal, to preserve full precision. A string is written between double quotes, using escape sequences when necessary to ensure that it can safely be read back by the Lua interpreter. For instance, the call ``` string.format('%q', 'a string with "quotes" and \n new line') ``` may produce the string: ``` "a string with \"quotes\" and \ new line" ``` This specifier does not support modifiers (flags, width, length). The conversion specifiers `A`, `a`, `E`, `e`, `f`, `G`, and `g` all expect a number as argument. The specifiers `c`, `d`, `i`, `o`, `u`, `X`, and `x` expect an integer. When Lua is compiled with a C89 compiler, the specifiers `A` and `a` (hexadecimal floats) do not support modifiers. The specifier `s` expects a string; if its argument is not a string, it is converted to one following the same rules of [`tostring`](#pdf-tostring). If the specifier has any modifier, the corresponding string argument should not contain embedded zeros. The specifier `p` formats the pointer returned by [`lua_topointer`](#lua_topointer). That gives a unique string identifier for tables, userdata, threads, strings, and functions. For other values (numbers, nil, booleans), this specifier results in a string representing the pointer `NULL`. ### `string.gmatch (s, pattern [, init])` Returns an iterator function that, each time it is called, returns the next captures from `pattern` (see [§6.4.1](#6.4.1)) over the string `s`. If `pattern` specifies no captures, then the whole match is produced in each call. A third, optional numeric argument `init` specifies where to start the search; its default value is 1 and can be negative. As an example, the following loop will iterate over all the words from string `s`, printing one per line: ``` s = "hello world from Lua" for w in string.gmatch(s, "%a+") do print(w) end ``` The next example collects all pairs `key=value` from the given string into a table: ``` t = {} s = "from=world, to=Lua" for k, v in string.gmatch(s, "(%w+)=(%w+)") do t[k] = v end ``` For this function, a caret '`^`' at the start of a pattern does not work as an anchor, as this would prevent the iteration. ### `string.gsub (s, pattern, repl [, n])` Returns a copy of `s` in which all (or the first `n`, if given) occurrences of the `pattern` (see [§6.4.1](#6.4.1)) have been replaced by a replacement string specified by `repl`, which can be a string, a table, or a function. `gsub` also returns, as its second value, the total number of matches that occurred. The name `gsub` comes from *Global SUBstitution*. If `repl` is a string, then its value is used for replacement. The character `%` works as an escape character: any sequence in `repl` of the form `%*d*`, with *d* between 1 and 9, stands for the value of the *d*-th captured substring; the sequence `%0` stands for the whole match; the sequence `%%` stands for a single `%`. If `repl` is a table, then the table is queried for every match, using the first capture as the key. If `repl` is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order. In any case, if the pattern specifies no captures, then it behaves as if the whole pattern was inside a capture. If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is **false** or **nil**, then there is no replacement (that is, the original match is kept in the string). Here are some examples: ``` x = string.gsub("hello world", "(%w+)", "%1 %1") --> x="hello hello world world" x = string.gsub("hello world", "%w+", "%0 %0", 1) --> x="hello hello world" x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") --> x="world hello Lua from" x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv) --> x="home = /home/roberto, user = roberto" x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) return load(s)() end) --> x="4+5 = 9" local t = {name="lua", version="5.4"} x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t) --> x="lua-5.4.tar.gz" ``` ### `string.len (s)` Receives a string and returns its length. The empty string `""` has length 0. Embedded zeros are counted, so `"a\000bc\000"` has length 5. ### `string.lower (s)` Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged. The definition of what an uppercase letter is depends on the current locale. ### `string.match (s, pattern [, init])` Looks for the first *match* of the `pattern` (see [§6.4.1](#6.4.1)) in the string `s`. If it finds one, then `match` returns the captures from the pattern; otherwise it returns **fail**. If `pattern` specifies no captures, then the whole match is returned. A third, optional numeric argument `init` specifies where to start the search; its default value is 1 and can be negative. ### `string.pack (fmt, v1, v2, ···)` Returns a binary string containing the values `v1`, `v2`, etc. serialized in binary form (packed) according to the format string `fmt` (see [§6.4.2](#6.4.2)). ### `string.packsize (fmt)` Returns the size of a string resulting from [`string.pack`](#pdf-string.pack) with the given format. The format string cannot have the variable-length options '`s`' or '`z`' (see [§6.4.2](#6.4.2)). ### `string.rep (s, n [, sep])` Returns a string that is the concatenation of `n` copies of the string `s` separated by the string `sep`. The default value for `sep` is the empty string (that is, no separator). Returns the empty string if `n` is not positive. (Note that it is very easy to exhaust the memory of your machine with a single call to this function.) ### `string.reverse (s)` Returns a string that is the string `s` reversed. ### `string.sub (s, i [, j])` Returns the substring of `s` that starts at `i` and continues until `j`; `i` and `j` can be negative. If `j` is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call `string.sub(s,1,j)` returns a prefix of `s` with length `j`, and `string.sub(s, -i)` (for a positive `i`) returns a suffix of `s` with length `i`. If, after the translation of negative indices, `i` is less than 1, it is corrected to 1. If `j` is greater than the string length, it is corrected to that length. If, after these corrections, `i` is greater than `j`, the function returns the empty string. ### `string.unpack (fmt, s [, pos])` Returns the values packed in string `s` (see [`string.pack`](#pdf-string.pack)) according to the format string `fmt` (see [§6.4.2](#6.4.2)). An optional `pos` marks where to start reading in `s` (default is 1). After the read values, this function also returns the index of the first unread byte in `s`. ### `string.upper (s)` Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged. The definition of what a lowercase letter is depends on the current locale. ### 6.4.1 – Patterns Patterns in Lua are described by regular strings, which are interpreted as patterns by the pattern-matching functions [`string.find`](#pdf-string.find), [`string.gmatch`](#pdf-string.gmatch), [`string.gsub`](#pdf-string.gsub), and [`string.match`](#pdf-string.match). This section describes the syntax and the meaning (that is, what they match) of these strings. #### Character Class: A *character class* is used to represent a set of characters. The following combinations are allowed in describing a character class: * ***x*:** (where *x* is not one of the *magic characters* `^$()%.[]*+-?`) represents the character *x* itself. * `.`: (a dot) represents all characters. * `%a`: represents all letters. * `%c`: represents all control characters. * `%d`: represents all digits. * `%g`: represents all printable characters except space. * `%l`: represents all lowercase letters. * `%p`: represents all punctuation characters. * `%s`: represents all space characters. * `%u`: represents all uppercase letters. * `%w`: represents all alphanumeric characters. * `%x`: represents all hexadecimal digits. * `%*x*`: (where *x* is any non-alphanumeric character) represents the character *x*. This is the standard way to escape the magic characters. Any non-alphanumeric character (including all punctuation characters, even the non-magical) can be preceded by a '`%`' to represent itself in a pattern. * `[*set*]`: represents the class which is the union of all characters in *set*. A range of characters can be specified by separating the end characters of the range, in ascending order, with a '`-`'. All classes `%`*x* described above can also be used as components in *set*. All other characters in *set* represent themselves. For example, `[%w_]` (or `[_%w]`) represents all alphanumeric characters plus the underscore, `[0-7]` represents the octal digits, and `[0-7%l%-]` represents the octal digits plus the lowercase letters plus the '`-`' character. You can put a closing square bracket in a set by positioning it as the first character in the set. You can put a hyphen in a set by positioning it as the first or the last character in the set. (You can also use an escape for both cases.) The interaction between ranges and classes is not defined. Therefore, patterns like `[%a-z]` or `[a-%%]` have no meaning. * `[^*set*]`: represents the complement of *set*, where *set* is interpreted as above. For all classes represented by single letters (`%a`, `%c`, etc.), the corresponding uppercase letter represents the complement of the class. For instance, `%S` represents all non-space characters. The definitions of letter, space, and other character groups depend on the current locale. In particular, the class `[a-z]` may not be equivalent to `%l`. #### Pattern Item: A *pattern item* can be * a single character class, which matches any single character in the class; * a single character class followed by '`*`', which matches sequences of zero or more characters in the class. These repetition items will always match the longest possible sequence; * a single character class followed by '`+`', which matches sequences of one or more characters in the class. These repetition items will always match the longest possible sequence; * a single character class followed by '`-`', which also matches sequences of zero or more characters in the class. Unlike '`*`', these repetition items will always match the shortest possible sequence; * a single character class followed by '`?`', which matches zero or one occurrence of a character in the class. It always matches one occurrence if possible; * `%*n*`, for *n* between 1 and 9; such item matches a substring equal to the *n*-th captured string (see below); * `%b*xy*`, where *x* and *y* are two distinct characters; such item matches strings that start with *x*, end with *y*, and where the *x* and *y* are *balanced*. This means that, if one reads the string from left to right, counting *+1* for an *x* and *-1* for a *y*, the ending *y* is the first *y* where the count reaches 0. For instance, the item `%b()` matches expressions with balanced parentheses. * `%f[*set*]`, a *frontier pattern*; such item matches an empty string at any position such that the next character belongs to *set* and the previous character does not belong to *set*. The set *set* is interpreted as previously described. The beginning and the end of the subject are handled as if they were the character '`\0`'. #### Pattern: A *pattern* is a sequence of pattern items. A caret '`^`' at the beginning of a pattern anchors the match at the beginning of the subject string. A '`$`' at the end of a pattern anchors the match at the end of the subject string. At other positions, '`^`' and '`$`' have no special meaning and represent themselves. #### Captures: A pattern can contain sub-patterns enclosed in parentheses; they describe *captures*. When a match succeeds, the substrings of the subject string that match captures are stored (*captured*) for future use. Captures are numbered according to their left parentheses. For instance, in the pattern `"(a*(.)%w(%s*))"`, the part of the string matching `"a*(.)%w(%s*)"` is stored as the first capture, and therefore has number 1; the character matching "`.`" is captured with number 2, and the part matching "`%s*`" has number 3. As a special case, the capture `()` captures the current string position (a number). For instance, if we apply the pattern `"()aa()"` on the string `"flaaap"`, there will be two captures: 3 and 5. #### Multiple matches: The function [`string.gsub`](#pdf-string.gsub) and the iterator [`string.gmatch`](#pdf-string.gmatch) match multiple occurrences of the given pattern in the subject. For these functions, a new match is considered valid only if it ends at least one byte after the end of the previous match. In other words, the pattern machine never accepts the empty string as a match immediately after another match. As an example, consider the results of the following code: ``` > string.gsub("abc", "()a*()", print); --> 1 2 --> 3 3 --> 4 4 ``` The second and third results come from Lua matching an empty string after '`b`' and another one after '`c`'. Lua does not match an empty string after '`a`', because it would end at the same position of the previous match. ### 6.4.2 – Format Strings for Pack and Unpack The first argument to [`string.pack`](#pdf-string.pack), [`string.packsize`](#pdf-string.packsize), and [`string.unpack`](#pdf-string.unpack) is a format string, which describes the layout of the structure being created or read. A format string is a sequence of conversion options. The conversion options are as follows: * `<`: sets little endian * `>`: sets big endian * `=`: sets native endian * `![*n*]`: sets maximum alignment to `n` (default is native alignment) * `b`: a signed byte (`char`) * `B`: an unsigned byte (`char`) * `h`: a signed `short` (native size) * `H`: an unsigned `short` (native size) * `l`: a signed `long` (native size) * `L`: an unsigned `long` (native size) * `j`: a `lua_Integer` * `J`: a `lua_Unsigned` * `T`: a `size_t` (native size) * `i[*n*]`: a signed `int` with `n` bytes (default is native size) * `I[*n*]`: an unsigned `int` with `n` bytes (default is native size) * `f`: a `float` (native size) * `d`: a `double` (native size) * `n`: a `lua_Number` * `c*n*`: a fixed-sized string with `n` bytes * `z`: a zero-terminated string * `s[*n*]`: a string preceded by its length coded as an unsigned integer with `n` bytes (default is a `size_t`) * `x`: one byte of padding * `X*op*`: an empty item that aligns according to option `op` (which is otherwise ignored) * '': (space) ignored (A "`[*n*]`" means an optional integral numeral.) Except for padding, spaces, and configurations (options "`xX <=>!`"), each option corresponds to an argument in [`string.pack`](#pdf-string.pack) or a result in [`string.unpack`](#pdf-string.unpack). For options "`!*n*`", "`s*n*`", "`i*n*`", and "`I*n*`", `n` can be any integer between 1 and 16. All integral options check overflows; [`string.pack`](#pdf-string.pack) checks whether the given value fits in the given size; [`string.unpack`](#pdf-string.unpack) checks whether the read value fits in a Lua integer. For the unsigned options, Lua integers are treated as unsigned values too. Any format string starts as if prefixed by "`!1=`", that is, with maximum alignment of 1 (no alignment) and native endianness. Native endianness assumes that the whole system is either big or little endian. The packing functions will not emulate correctly the behavior of mixed-endian formats. Alignment works as follows: For each option, the format gets extra padding until the data starts at an offset that is a multiple of the minimum between the option size and the maximum alignment; this minimum must be a power of 2. Options "`c`" and "`z`" are not aligned; option "`s`" follows the alignment of its starting integer. All padding is filled with zeros by [`string.pack`](#pdf-string.pack) and ignored by [`string.unpack`](#pdf-string.unpack). 6.5 – UTF-8 Support ------------------- This library provides basic support for UTF-8 encoding. It provides all its functions inside the table `utf8`. This library does not provide any support for Unicode other than the handling of the encoding. Any operation that needs the meaning of a character, such as character classification, is outside its scope. Unless stated otherwise, all functions that expect a byte position as a parameter assume that the given position is either the start of a byte sequence or one plus the length of the subject string. As in the string library, negative indices count from the end of the string. Functions that create byte sequences accept all values up to `0x7FFFFFFF`, as defined in the original UTF-8 specification; that implies byte sequences of up to six bytes. Functions that interpret byte sequences only accept valid sequences (well formed and not overlong). By default, they only accept byte sequences that result in valid Unicode code points, rejecting values greater than `10FFFF` and surrogates. A boolean argument `lax`, when available, lifts these checks, so that all values up to `0x7FFFFFFF` are accepted. (Not well formed and overlong sequences are still rejected.) ### `utf8.char (···)` Receives zero or more integers, converts each one to its corresponding UTF-8 byte sequence and returns a string with the concatenation of all these sequences. ### `utf8.charpattern` The pattern (a string, not a function) "`[\0-\x7F\xC2-\xFD][\x80-\xBF]*`" (see [§6.4.1](#6.4.1)), which matches exactly one UTF-8 byte sequence, assuming that the subject is a valid UTF-8 string. ### `utf8.codes (s [, lax])` Returns values so that the construction ``` for p, c in utf8.codes(s) do body end ``` will iterate over all UTF-8 characters in string `s`, with `p` being the position (in bytes) and `c` the code point of each character. It raises an error if it meets any invalid byte sequence. ### `utf8.codepoint (s [, i [, j [, lax]]])` Returns the code points (as integers) from all characters in `s` that start between byte position `i` and `j` (both included). The default for `i` is 1 and for `j` is `i`. It raises an error if it meets any invalid byte sequence. ### `utf8.len (s [, i [, j [, lax]]])` Returns the number of UTF-8 characters in string `s` that start between positions `i` and `j` (both inclusive). The default for `i` is 1 and for `j` is -1. If it finds any invalid byte sequence, returns **fail** plus the position of the first invalid byte. ### `utf8.offset (s, n [, i])` Returns the position (in bytes) where the encoding of the `n`-th character of `s` (counting from position `i`) starts. A negative `n` gets characters before position `i`. The default for `i` is 1 when `n` is non-negative and `#s + 1` otherwise, so that `utf8.offset(s, -n)` gets the offset of the `n`-th character from the end of the string. If the specified character is neither in the subject nor right after its end, the function returns **fail**. As a special case, when `n` is 0 the function returns the start of the encoding of the character that contains the `i`-th byte of `s`. This function assumes that `s` is a valid UTF-8 string. 6.6 – Table Manipulation ------------------------ This library provides generic functions for table manipulation. It provides all its functions inside the table `table`. Remember that, whenever an operation needs the length of a table, all caveats about the length operator apply (see [§3.4.7](#3.4.7)). All functions ignore non-numeric keys in the tables given as arguments. ### `table.concat (list [, sep [, i [, j]]])` Given a list where all elements are strings or numbers, returns the string `list[i]..sep..list[i+1] ··· sep..list[j]`. The default value for `sep` is the empty string, the default for `i` is 1, and the default for `j` is `#list`. If `i` is greater than `j`, returns the empty string. ### `table.insert (list, [pos,] value)` Inserts element `value` at position `pos` in `list`, shifting up the elements `list[pos], list[pos+1], ···, list[#list]`. The default value for `pos` is `#list+1`, so that a call `table.insert(t,x)` inserts `x` at the end of the list `t`. ### `table.move (a1, f, e, t [,a2])` Moves elements from the table `a1` to the table `a2`, performing the equivalent to the following multiple assignment: `a2[t],··· = a1[f],···,a1[e]`. The default for `a2` is `a1`. The destination range can overlap with the source range. The number of elements to be moved must fit in a Lua integer. Returns the destination table `a2`. ### `table.pack (···)` Returns a new table with all arguments stored into keys 1, 2, etc. and with a field "`n`" with the total number of arguments. Note that the resulting table may not be a sequence, if some arguments are **nil**. ### `table.remove (list [, pos])` Removes from `list` the element at position `pos`, returning the value of the removed element. When `pos` is an integer between 1 and `#list`, it shifts down the elements `list[pos+1], list[pos+2], ···, list[#list]` and erases element `list[#list]`; The index `pos` can also be 0 when `#list` is 0, or `#list + 1`. The default value for `pos` is `#list`, so that a call `table.remove(l)` removes the last element of the list `l`. ### `table.sort (list [, comp])` Sorts the list elements in a given order, *in-place*, from `list[1]` to `list[#list]`. If `comp` is given, then it must be a function that receives two list elements and returns true when the first element must come before the second in the final order (so that, after the sort, `i < j` implies `not comp(list[j],list[i])`). If `comp` is not given, then the standard Lua operator `<` is used instead. Note that the `comp` function must define a strict partial order over the elements in the list; that is, it must be asymmetric and transitive. Otherwise, no valid sort may be possible. The sort algorithm is not stable: elements considered equal by the given order may have their relative positions changed by the sort. ### `table.unpack (list [, i [, j]])` Returns the elements from the given list. This function is equivalent to ``` return list[i], list[i+1], ···, list[j] ``` By default, `i` is 1 and `j` is `#list`. 6.7 – Mathematical Functions ---------------------------- This library provides basic mathematical functions. It provides all its functions and constants inside the table `math`. Functions with the annotation "`integer/float`" give integer results for integer arguments and float results for non-integer arguments. The rounding functions [`math.ceil`](#pdf-math.ceil), [`math.floor`](#pdf-math.floor), and [`math.modf`](#pdf-math.modf) return an integer when the result fits in the range of an integer, or a float otherwise. ### `math.abs (x)` Returns the maximum value between `x` and `-x`. (integer/float) ### `math.acos (x)` Returns the arc cosine of `x` (in radians). ### `math.asin (x)` Returns the arc sine of `x` (in radians). ### `math.atan (y [, x])` Returns the arc tangent of `y/x` (in radians), but uses the signs of both arguments to find the quadrant of the result. It also handles correctly the case of `x` being zero. The default value for `x` is 1, so that the call `math.atan(y)` returns the arc tangent of `y`. ### `math.ceil (x)` Returns the smallest integral value greater than or equal to `x`. ### `math.cos (x)` Returns the cosine of `x` (assumed to be in radians). ### `math.deg (x)` Converts the angle `x` from radians to degrees. ### `math.exp (x)` Returns the value *ex* (where `e` is the base of natural logarithms). ### `math.floor (x)` Returns the largest integral value less than or equal to `x`. ### `math.fmod (x, y)` Returns the remainder of the division of `x` by `y` that rounds the quotient towards zero. (integer/float) ### `math.huge` The float value `HUGE_VAL`, a value greater than any other numeric value. ### `math.log (x [, base])` Returns the logarithm of `x` in the given base. The default for `base` is *e* (so that the function returns the natural logarithm of `x`). ### `math.max (x, ···)` Returns the argument with the maximum value, according to the Lua operator `<`. ### `math.maxinteger` An integer with the maximum value for an integer. ### `math.min (x, ···)` Returns the argument with the minimum value, according to the Lua operator `<`. ### `math.mininteger` An integer with the minimum value for an integer. ### `math.modf (x)` Returns the integral part of `x` and the fractional part of `x`. Its second result is always a float. ### `math.pi` The value of *π*. ### `math.rad (x)` Converts the angle `x` from degrees to radians. ### `math.random ([m [, n]])` When called without arguments, returns a pseudo-random float with uniform distribution in the range *[0,1)*. When called with two integers `m` and `n`, `math.random` returns a pseudo-random integer with uniform distribution in the range *[m, n]*. The call `math.random(n)`, for a positive `n`, is equivalent to `math.random(1,n)`. The call `math.random(0)` produces an integer with all bits (pseudo)random. This function uses the `xoshiro256**` algorithm to produce pseudo-random 64-bit integers, which are the results of calls with argument 0. Other results (ranges and floats) are unbiased extracted from these integers. Lua initializes its pseudo-random generator with the equivalent of a call to [`math.randomseed`](#pdf-math.randomseed) with no arguments, so that `math.random` should generate different sequences of results each time the program runs. ### `math.randomseed ([x [, y]])` When called with at least one argument, the integer parameters `x` and `y` are joined into a 128-bit *seed* that is used to reinitialize the pseudo-random generator; equal seeds produce equal sequences of numbers. The default for `y` is zero. When called with no arguments, Lua generates a seed with a weak attempt for randomness. This function returns the two seed components that were effectively used, so that setting them again repeats the sequence. To ensure a required level of randomness to the initial state (or contrarily, to have a deterministic sequence, for instance when debugging a program), you should call [`math.randomseed`](#pdf-math.randomseed) with explicit arguments. ### `math.sin (x)` Returns the sine of `x` (assumed to be in radians). ### `math.sqrt (x)` Returns the square root of `x`. (You can also use the expression `x^0.5` to compute this value.) ### `math.tan (x)` Returns the tangent of `x` (assumed to be in radians). ### `math.tointeger (x)` If the value `x` is convertible to an integer, returns that integer. Otherwise, returns **fail**. ### `math.type (x)` Returns "`integer`" if `x` is an integer, "`float`" if it is a float, or **fail** if `x` is not a number. ### `math.ult (m, n)` Returns a boolean, true if and only if integer `m` is below integer `n` when they are compared as unsigned integers. 6.8 – Input and Output Facilities --------------------------------- The I/O library provides two different styles for file manipulation. The first one uses implicit file handles; that is, there are operations to set a default input file and a default output file, and all input/output operations are done over these default files. The second style uses explicit file handles. When using implicit file handles, all operations are supplied by table `io`. When using explicit file handles, the operation [`io.open`](#pdf-io.open) returns a file handle and then all operations are supplied as methods of the file handle. The metatable for file handles provides metamethods for `__gc` and `__close` that try to close the file when called. The table `io` also provides three predefined file handles with their usual meanings from C: `io.stdin`, `io.stdout`, and `io.stderr`. The I/O library never closes these files. Unless otherwise stated, all I/O functions return **fail** on failure, plus an error message as a second result and a system-dependent error code as a third result, and some non-false value on success. On non-POSIX systems, the computation of the error message and error code in case of errors may be not thread safe, because they rely on the global C variable `errno`. ### `io.close ([file])` Equivalent to `file:close()`. Without a `file`, closes the default output file. ### `io.flush ()` Equivalent to `io.output():flush()`. ### `io.input ([file])` When called with a file name, it opens the named file (in text mode), and sets its handle as the default input file. When called with a file handle, it simply sets this file handle as the default input file. When called without arguments, it returns the current default input file. In case of errors this function raises the error, instead of returning an error code. ### `io.lines ([filename, ···])` Opens the given file name in read mode and returns an iterator function that works like `file:lines(···)` over the opened file. When the iterator function fails to read any value, it automatically closes the file. Besides the iterator function, `io.lines` returns three other values: two **nil** values as placeholders, plus the created file handle. Therefore, when used in a generic **for** loop, the file is closed also if the loop is interrupted by an error or a **break**. The call `io.lines()` (with no file name) is equivalent to `io.input():lines("l")`; that is, it iterates over the lines of the default input file. In this case, the iterator does not close the file when the loop ends. In case of errors opening the file, this function raises the error, instead of returning an error code. ### `io.open (filename [, mode])` This function opens a file, in the mode specified in the string `mode`. In case of success, it returns a new file handle. The `mode` string can be any of the following: * "`r`": read mode (the default); * "`w`": write mode; * "`a`": append mode; * "`r+`": update mode, all previous data is preserved; * "`w+`": update mode, all previous data is erased; * "`a+`": append update mode, previous data is preserved, writing is only allowed at the end of file. The `mode` string can also have a '`b`' at the end, which is needed in some systems to open the file in binary mode. ### `io.output ([file])` Similar to [`io.input`](#pdf-io.input), but operates over the default output file. ### `io.popen (prog [, mode])` This function is system dependent and is not available on all platforms. Starts the program `prog` in a separated process and returns a file handle that you can use to read data from this program (if `mode` is `"r"`, the default) or to write data to this program (if `mode` is `"w"`). ### `io.read (···)` Equivalent to `io.input():read(···)`. ### `io.tmpfile ()` In case of success, returns a handle for a temporary file. This file is opened in update mode and it is automatically removed when the program ends. ### `io.type (obj)` Checks whether `obj` is a valid file handle. Returns the string `"file"` if `obj` is an open file handle, `"closed file"` if `obj` is a closed file handle, or **fail** if `obj` is not a file handle. ### `io.write (···)` Equivalent to `io.output():write(···)`. ### `file:close ()` Closes `file`. Note that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen. When closing a file handle created with [`io.popen`](#pdf-io.popen), [`file:close`](#pdf-file:close) returns the same values returned by [`os.execute`](#pdf-os.execute). ### `file:flush ()` Saves any written data to `file`. ### `file:lines (···)` Returns an iterator function that, each time it is called, reads the file according to the given formats. When no format is given, uses "`l`" as a default. As an example, the construction ``` for c in file:lines(1) do body end ``` will iterate over all characters of the file, starting at the current position. Unlike [`io.lines`](#pdf-io.lines), this function does not close the file when the loop ends. ### `file:read (···)` Reads the file `file`, according to the given formats, which specify what to read. For each format, the function returns a string or a number with the characters read, or **fail** if it cannot read data with the specified format. (In this latter case, the function does not read subsequent formats.) When called without arguments, it uses a default format that reads the next line (see below). The available formats are * "`n`": reads a numeral and returns it as a float or an integer, following the lexical conventions of Lua. (The numeral may have leading whitespaces and a sign.) This format always reads the longest input sequence that is a valid prefix for a numeral; if that prefix does not form a valid numeral (e.g., an empty string, "`0x`", or "`3.4e-`") or it is too long (more than 200 characters), it is discarded and the format returns **fail**. * "`a`": reads the whole file, starting at the current position. On end of file, it returns the empty string; this format never fails. * "`l`": reads the next line skipping the end of line, returning **fail** on end of file. This is the default format. * "`L`": reads the next line keeping the end-of-line character (if present), returning **fail** on end of file. * ***number*:** reads a string with up to this number of bytes, returning **fail** on end of file. If `number` is zero, it reads nothing and returns an empty string, or **fail** on end of file. The formats "`l`" and "`L`" should be used only for text files. ### `file:seek ([whence [, offset]])` Sets and gets the file position, measured from the beginning of the file, to the position given by `offset` plus a base specified by the string `whence`, as follows: * "`set`": base is position 0 (beginning of the file); * "`cur`": base is current position; * "`end`": base is end of file; In case of success, `seek` returns the final file position, measured in bytes from the beginning of the file. If `seek` fails, it returns **fail**, plus a string describing the error. The default value for `whence` is `"cur"`, and for `offset` is 0. Therefore, the call `file:seek()` returns the current file position, without changing it; the call `file:seek("set")` sets the position to the beginning of the file (and returns 0); and the call `file:seek("end")` sets the position to the end of the file, and returns its size. ### `file:setvbuf (mode [, size])` Sets the buffering mode for a file. There are three available modes: * "`no`": no buffering. * "`full`": full buffering. * "`line`": line buffering. For the last two cases, `size` is a hint for the size of the buffer, in bytes. The default is an appropriate size. The specific behavior of each mode is non portable; check the underlying ISO C function `setvbuf` in your platform for more details. ### `file:write (···)` Writes the value of each of its arguments to `file`. The arguments must be strings or numbers. In case of success, this function returns `file`. 6.9 – Operating System Facilities --------------------------------- This library is implemented through table `os`. ### `os.clock ()` Returns an approximation of the amount in seconds of CPU time used by the program, as returned by the underlying ISO C function `clock`. ### `os.date ([format [, time]])` Returns a string or a table containing date and time, formatted according to the given string `format`. If the `time` argument is present, this is the time to be formatted (see the [`os.time`](#pdf-os.time) function for a description of this value). Otherwise, `date` formats the current time. If `format` starts with '`!`', then the date is formatted in Coordinated Universal Time. After this optional character, if `format` is the string "`*t`", then `date` returns a table with the following fields: `year`, `month` (1–12), `day` (1–31), `hour` (0–23), `min` (0–59), `sec` (0–61, due to leap seconds), `wday` (weekday, 1–7, Sunday is 1), `yday` (day of the year, 1–366), and `isdst` (daylight saving flag, a boolean). This last field may be absent if the information is not available. If `format` is not "`*t`", then `date` returns the date as a string, formatted according to the same rules as the ISO C function `strftime`. If `format` is absent, it defaults to "`%c`", which gives a human-readable date and time representation using the current locale. On non-POSIX systems, this function may be not thread safe because of its reliance on C function `gmtime` and C function `localtime`. ### `os.difftime (t2, t1)` Returns the difference, in seconds, from time `t1` to time `t2` (where the times are values returned by [`os.time`](#pdf-os.time)). In POSIX, Windows, and some other systems, this value is exactly `t2`*-*`t1`. ### `os.execute ([command])` This function is equivalent to the ISO C function `system`. It passes `command` to be executed by an operating system shell. Its first result is **true** if the command terminated successfully, or **fail** otherwise. After this first result the function returns a string plus a number, as follows: * "`exit`": the command terminated normally; the following number is the exit status of the command. * "`signal`": the command was terminated by a signal; the following number is the signal that terminated the command. When called without a `command`, `os.execute` returns a boolean that is true if a shell is available. ### `os.exit ([code [, close]])` Calls the ISO C function `exit` to terminate the host program. If `code` is **true**, the returned status is `EXIT_SUCCESS`; if `code` is **false**, the returned status is `EXIT_FAILURE`; if `code` is a number, the returned status is this number. The default value for `code` is **true**. If the optional second argument `close` is true, closes the Lua state before exiting. ### `os.getenv (varname)` Returns the value of the process environment variable `varname` or **fail** if the variable is not defined. ### `os.remove (filename)` Deletes the file (or empty directory, on POSIX systems) with the given name. If this function fails, it returns **fail** plus a string describing the error and the error code. Otherwise, it returns true. ### `os.rename (oldname, newname)` Renames the file or directory named `oldname` to `newname`. If this function fails, it returns **fail**, plus a string describing the error and the error code. Otherwise, it returns true. ### `os.setlocale (locale [, category])` Sets the current locale of the program. `locale` is a system-dependent string specifying a locale; `category` is an optional string describing which category to change: `"all"`, `"collate"`, `"ctype"`, `"monetary"`, `"numeric"`, or `"time"`; the default category is `"all"`. The function returns the name of the new locale, or **fail** if the request cannot be honored. If `locale` is the empty string, the current locale is set to an implementation-defined native locale. If `locale` is the string "`C`", the current locale is set to the standard C locale. When called with **nil** as the first argument, this function only returns the name of the current locale for the given category. This function may be not thread safe because of its reliance on C function `setlocale`. ### `os.time ([table])` Returns the current time when called without arguments, or a time representing the local date and time specified by the given table. This table must have fields `year`, `month`, and `day`, and may have fields `hour` (default is 12), `min` (default is 0), `sec` (default is 0), and `isdst` (default is **nil**). Other fields are ignored. For a description of these fields, see the [`os.date`](#pdf-os.date) function. When the function is called, the values in these fields do not need to be inside their valid ranges. For instance, if `sec` is -10, it means 10 seconds before the time specified by the other fields; if `hour` is 1000, it means 1000 hours after the time specified by the other fields. The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the "epoch"). In other systems, the meaning is not specified, and the number returned by `time` can be used only as an argument to [`os.date`](#pdf-os.date) and [`os.difftime`](#pdf-os.difftime). When called with a table, `os.time` also normalizes all the fields documented in the [`os.date`](#pdf-os.date) function, so that they represent the same time as before the call but with values inside their valid ranges. ### `os.tmpname ()` Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed. In POSIX systems, this function also creates a file with that name, to avoid security risks. (Someone else might create the file with wrong permissions in the time between getting the name and creating the file.) You still have to open the file to use it and to remove it (even if you do not use it). When possible, you may prefer to use [`io.tmpfile`](#pdf-io.tmpfile), which automatically removes the file when the program ends. 6.10 – The Debug Library ------------------------ This library provides the functionality of the debug interface ([§4.7](#4.7)) to Lua programs. You should exert care when using this library. Several of its functions violate basic assumptions about Lua code (e.g., that variables local to a function cannot be accessed from outside; that userdata metatables cannot be changed by Lua code; that Lua programs do not crash) and therefore can compromise otherwise secure code. Moreover, some functions in this library may be slow. All functions in this library are provided inside the `debug` table. All functions that operate over a thread have an optional first argument which is the thread to operate over. The default is always the current thread. ### `debug.debug ()` Enters an interactive mode with the user, running each string that the user enters. Using simple commands and other debug facilities, the user can inspect global and local variables, change their values, evaluate expressions, and so on. A line containing only the word `cont` finishes this function, so that the caller continues its execution. Note that commands for `debug.debug` are not lexically nested within any function and so have no direct access to local variables. ### `debug.gethook ([thread])` Returns the current hook settings of the thread, as three values: the current hook function, the current hook mask, and the current hook count, as set by the [`debug.sethook`](#pdf-debug.sethook) function. Returns **fail** if there is no active hook. ### `debug.getinfo ([thread,] f [, what])` Returns a table with information about a function. You can give the function directly or you can give a number as the value of `f`, which means the function running at level `f` of the call stack of the given thread: level 0 is the current function (`getinfo` itself); level 1 is the function that called `getinfo` (except for tail calls, which do not count in the stack); and so on. If `f` is a number greater than the number of active functions, then `getinfo` returns **fail**. The returned table can contain all the fields returned by [`lua_getinfo`](#lua_getinfo), with the string `what` describing which fields to fill in. The default for `what` is to get all information available, except the table of valid lines. If present, the option '`f`' adds a field named `func` with the function itself. If present, the option '`L`' adds a field named `activelines` with the table of valid lines. For instance, the expression `debug.getinfo(1,"n").name` returns a name for the current function, if a reasonable name can be found, and the expression `debug.getinfo(print)` returns a table with all available information about the [`print`](#pdf-print) function. ### `debug.getlocal ([thread,] f, local)` This function returns the name and the value of the local variable with index `local` of the function at level `f` of the stack. This function accesses not only explicit local variables, but also parameters and temporary values. The first parameter or local variable has index 1, and so on, following the order that they are declared in the code, counting only the variables that are active in the current scope of the function. Compile-time constants may not appear in this listing, if they were optimized away by the compiler. Negative indices refer to vararg arguments; -1 is the first vararg argument. The function returns **fail** if there is no variable with the given index, and raises an error when called with a level out of range. (You can call [`debug.getinfo`](#pdf-debug.getinfo) to check whether the level is valid.) Variable names starting with '`(`' (open parenthesis) represent variables with no known names (internal variables such as loop control variables, and variables from chunks saved without debug information). The parameter `f` may also be a function. In that case, `getlocal` returns only the name of function parameters. ### `debug.getmetatable (value)` Returns the metatable of the given `value` or **nil** if it does not have a metatable. ### `debug.getregistry ()` Returns the registry table (see [§4.3](#4.3)). ### `debug.getupvalue (f, up)` This function returns the name and the value of the upvalue with index `up` of the function `f`. The function returns **fail** if there is no upvalue with the given index. (For Lua functions, upvalues are the external local variables that the function uses, and that are consequently included in its closure.) For C functions, this function uses the empty string `""` as a name for all upvalues. Variable name '`?`' (interrogation mark) represents variables with no known names (variables from chunks saved without debug information). ### `debug.getuservalue (u, n)` Returns the `n`-th user value associated to the userdata `u` plus a boolean, **false** if the userdata does not have that value. ### `debug.setcstacklimit (limit)` Sets a new limit for the C stack. This limit controls how deeply nested calls can go in Lua, with the intent of avoiding a stack overflow. A limit too small restricts recursive calls pointlessly; a limit too large exposes the interpreter to stack-overflow crashes. Unfortunately, there is no way to know a priori the maximum safe limit for a platform. Each call made from Lua code counts one unit. Other operations (e.g., calls made from C to Lua or resuming a coroutine) may have a higher cost. This function has the following restrictions: * It can only be called from the main coroutine (thread); * It cannot be called while handling a stack-overflow error; * `limit` must be less than 40000; * `limit` cannot be less than the amount of C stack in use. If a call does not respect some restriction, it returns a false value. Otherwise, the call returns the old limit. ### `debug.sethook ([thread,] hook, mask [, count])` Sets the given function as the debug hook. The string `mask` and the number `count` describe when the hook will be called. The string mask may have any combination of the following characters, with the given meaning: * '`c`': the hook is called every time Lua calls a function; * '`r`': the hook is called every time Lua returns from a function; * '`l`': the hook is called every time Lua enters a new line of code. Moreover, with a `count` different from zero, the hook is called also after every `count` instructions. When called without arguments, [`debug.sethook`](#pdf-debug.sethook) turns off the hook. When the hook is called, its first parameter is a string describing the event that has triggered its call: `"call"`, `"tail call"`, `"return"`, `"line"`, and `"count"`. For line events, the hook also gets the new line number as its second parameter. Inside a hook, you can call `getinfo` with level 2 to get more information about the running function. (Level 0 is the `getinfo` function, and level 1 is the hook function.) ### `debug.setlocal ([thread,] level, local, value)` This function assigns the value `value` to the local variable with index `local` of the function at level `level` of the stack. The function returns **fail** if there is no local variable with the given index, and raises an error when called with a `level` out of range. (You can call `getinfo` to check whether the level is valid.) Otherwise, it returns the name of the local variable. See [`debug.getlocal`](#pdf-debug.getlocal) for more information about variable indices and names. ### `debug.setmetatable (value, table)` Sets the metatable for the given `value` to the given `table` (which can be **nil**). Returns `value`. ### `debug.setupvalue (f, up, value)` This function assigns the value `value` to the upvalue with index `up` of the function `f`. The function returns **fail** if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue. See [`debug.getupvalue`](#pdf-debug.getupvalue) for more information about upvalues. ### `debug.setuservalue (udata, value, n)` Sets the given `value` as the `n`-th user value associated to the given `udata`. `udata` must be a full userdata. Returns `udata`, or **fail** if the userdata does not have that value. ### `debug.traceback ([thread,] [message [, level]])` If `message` is present but is neither a string nor **nil**, this function returns `message` without further processing. Otherwise, it returns a string with a traceback of the call stack. The optional `message` string is appended at the beginning of the traceback. An optional `level` number tells at which level to start the traceback (default is 1, the function calling `traceback`). ### `debug.upvalueid (f, n)` Returns a unique identifier (as a light userdata) for the upvalue numbered `n` from the given function. These unique identifiers allow a program to check whether different closures share upvalues. Lua closures that share an upvalue (that is, that access a same external local variable) will return identical ids for those upvalue indices. ### `debug.upvaluejoin (f1, n1, f2, n2)` Make the `n1`-th upvalue of the Lua closure `f1` refer to the `n2`-th upvalue of the Lua closure `f2`. 7 – Lua Standalone ================== Although Lua has been designed as an extension language, to be embedded in a host C program, it is also frequently used as a standalone language. An interpreter for Lua as a standalone language, called simply `lua`, is provided with the standard distribution. The standalone interpreter includes all standard libraries. Its usage is: ``` lua [options] [script [args]] ``` The options are: * `-e *stat*`: execute string *stat*; * `-i`: enter interactive mode after running *script*; * `-l *mod*`: "require" *mod* and assign the result to global *mod*; * `-v`: print version information; * `-E`: ignore environment variables; * `-W`: turn warnings on; * `--`: stop handling options; * `-`: execute `stdin` as a file and stop handling options. After handling its options, `lua` runs the given *script*. When called without arguments, `lua` behaves as `lua -v -i` when the standard input (`stdin`) is a terminal, and as `lua -` otherwise. When called without the option `-E`, the interpreter checks for an environment variable `LUA_INIT_5_4` (or `LUA_INIT` if the versioned name is not defined) before running any argument. If the variable content has the format `@*filename*`, then `lua` executes the file. Otherwise, `lua` executes the string itself. When called with the option `-E`, Lua does not consult any environment variables. In particular, the values of [`package.path`](#pdf-package.path) and [`package.cpath`](#pdf-package.cpath) are set with the default paths defined in `luaconf.h`. The options `-e`, `-l`, and `-W` are handled in the order they appear. For instance, an invocation like ``` $ lua -e 'a=1' -llib1 script.lua ``` will first set `a` to 1, then require the library `lib1`, and finally run the file `script.lua` with no arguments. (Here `$` is the shell prompt. Your prompt may be different.) Before running any code, `lua` collects all command-line arguments in a global table called `arg`. The script name goes to index 0, the first argument after the script name goes to index 1, and so on. Any arguments before the script name (that is, the interpreter name plus its options) go to negative indices. For instance, in the call ``` $ lua -la b.lua t1 t2 ``` the table is like this: ``` arg = { [-2] = "lua", [-1] = "-la", [0] = "b.lua", [1] = "t1", [2] = "t2" } ``` If there is no script in the call, the interpreter name goes to index 0, followed by the other arguments. For instance, the call ``` $ lua -e "print(arg[1])" ``` will print "`-e`". If there is a script, the script is called with arguments `arg[1]`, ···, `arg[#arg]`. Like all chunks in Lua, the script is compiled as a vararg function. In interactive mode, Lua repeatedly prompts and waits for a line. After reading a line, Lua first try to interpret the line as an expression. If it succeeds, it prints its value. Otherwise, it interprets the line as a statement. If you write an incomplete statement, the interpreter waits for its completion by issuing a different prompt. If the global variable `_PROMPT` contains a string, then its value is used as the prompt. Similarly, if the global variable `_PROMPT2` contains a string, its value is used as the secondary prompt (issued during incomplete statements). In case of unprotected errors in the script, the interpreter reports the error to the standard error stream. If the error object is not a string but has a metamethod `__tostring`, the interpreter calls this metamethod to produce the final message. Otherwise, the interpreter converts the error object to a string and adds a stack traceback to it. When warnings are on, they are simply printed in the standard error output. When finishing normally, the interpreter closes its main Lua state (see [`lua_close`](#lua_close)). The script can avoid this step by calling [`os.exit`](#pdf-os.exit) to terminate. To allow the use of Lua as a script interpreter in Unix systems, Lua skips the first line of a file chunk if it starts with `#`. Therefore, Lua scripts can be made into executable programs by using `chmod +x` and the `#!` form, as in ``` #!/usr/local/bin/lua ``` Of course, the location of the Lua interpreter may be different in your machine. If `lua` is in your `PATH`, then ``` #!/usr/bin/env lua ``` is a more portable solution. 8 – Incompatibilities with the Previous Version =============================================== Here we list the incompatibilities that you may find when moving a program from Lua 5.3 to Lua 5.4. You can avoid some incompatibilities by compiling Lua with appropriate options (see file `luaconf.h`). However, all these compatibility options will be removed in the future. More often than not, compatibility issues arise when these compatibility options are removed. So, whenever you have the chance, you should try to test your code with a version of Lua compiled with all compatibility options turned off. That will ease transitions to newer versions of Lua. Lua versions can always change the C API in ways that do not imply source-code changes in a program, such as the numeric values for constants or the implementation of functions as macros. Therefore, you should never assume that binaries are compatible between different Lua versions. Always recompile clients of the Lua API when using a new version. Similarly, Lua versions can always change the internal representation of precompiled chunks; precompiled chunks are not compatible between different Lua versions. The standard paths in the official distribution may change between versions. 8.1 – Incompatibilities in the Language --------------------------------------- * The coercion of strings to numbers in arithmetic and bitwise operations has been removed from the core language. The string library does a similar job for arithmetic (but not for bitwise) operations using the string metamethods. However, unlike in previous versions, the new implementation preserves the implicit type of the numeral in the string. For instance, the result of `"1" + "2"` now is an integer, not a float. * Literal decimal integer constants that overflow are read as floats, instead of wrapping around. You can use hexadecimal notation for such constants if you want the old behavior (reading them as integers with wrap around). * The use of the `__lt` metamethod to emulate `__le` has been removed. When needed, this metamethod must be explicitly defined. * The semantics of the numerical **for** loop over integers changed in some details. In particular, the control variable never wraps around. * A label for a **goto** cannot be declared where a label with the same name is visible, even if this other label is declared in an enclosing block. * When finalizing an object, Lua does not ignore `__gc` metamethods that are not functions. Any value will be called, if present. (Non-callable values will generate a warning, like any other error when calling a finalizer.) 8.2 – Incompatibilities in the Libraries ---------------------------------------- * The function [`print`](#pdf-print) does not call [`tostring`](#pdf-tostring) to format its arguments; instead, it has this functionality hardwired. You should use `__tostring` to modify how values are printed. * The pseudo-random number generator used by the function [`math.random`](#pdf-math.random) now starts with a somewhat random seed. Moreover, it uses a different algorithm. * By default, the decoding functions in the [`utf8`](#pdf-utf8) library do not accept surrogates as valid code points. An extra parameter in these functions makes them more permissive. * The options "`setpause`" and "`setstepmul`" of the function [`collectgarbage`](#pdf-collectgarbage) are deprecated. You should use the new option "`incremental`" to set them. * The function [`io.lines`](#pdf-io.lines) now returns four values, instead of just one. That can be a problem when it is used as the sole argument to another function that has optional parameters, such as in `load(io.lines(filename, "L"))`. To fix that issue, you can wrap the call into parentheses, to adjust its number of results to one. 8.3 – Incompatibilities in the API ---------------------------------- * Full userdata now has an arbitrary number of associated user values. Therefore, the functions `lua_newuserdata`, `lua_setuservalue`, and `lua_getuservalue` were replaced by [`lua_newuserdatauv`](#lua_newuserdatauv), [`lua_setiuservalue`](#lua_setiuservalue), and [`lua_getiuservalue`](#lua_getiuservalue), which have an extra argument. For compatibility, the old names still work as macros assuming one single user value. Note, however, that userdata with zero user values are more efficient memory-wise. * The function [`lua_resume`](#lua_resume) has an extra parameter. This out parameter returns the number of values on the top of the stack that were yielded or returned by the coroutine. (In previous versions, those values were the entire stack.) * The function [`lua_version`](#lua_version) returns the version number, instead of an address of the version number. The Lua core should work correctly with libraries using their own static copies of the same core, so there is no need to check whether they are using the same address space. * The constant `LUA_ERRGCMM` was removed. Errors in finalizers are never propagated; instead, they generate a warning. * The options `LUA_GCSETPAUSE` and `LUA_GCSETSTEPMUL` of the function [`lua_gc`](#lua_gc) are deprecated. You should use the new option `LUA_GCINC` to set them. 9 – The Complete Syntax of Lua ============================== Here is the complete syntax of Lua in extended BNF. As usual in extended BNF, {A} means 0 or more As, and [A] means an optional A. (For operator precedences, see [§3.4.8](#3.4.8); for a description of the terminals Name, Numeral, and LiteralString, see [§3.1](#3.1).) ``` chunk ::= block block ::= {stat} [retstat] stat ::= ‘;’ | varlist ‘=’ explist | functioncall | label | break | goto Name | do block end | while exp do block end | repeat block until exp | if exp then block {elseif exp then block} [else block] end | for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end | for namelist in explist do block end | function funcname funcbody | local function Name funcbody | local attnamelist [‘=’ explist] attnamelist ::= Name attrib {‘,’ Name attrib} attrib ::= [‘<’ Name ‘>’] retstat ::= return [explist] [‘;’] label ::= ‘::’ Name ‘::’ funcname ::= Name {‘.’ Name} [‘:’ Name] varlist ::= var {‘,’ var} var ::= Name | prefixexp ‘[’ exp ‘]’ | prefixexp ‘.’ Name namelist ::= Name {‘,’ Name} explist ::= exp {‘,’ exp} exp ::= nil | false | true | Numeral | LiteralString | ‘...’ | functiondef | prefixexp | tableconstructor | exp binop exp | unop exp prefixexp ::= var | functioncall | ‘(’ exp ‘)’ functioncall ::= prefixexp args | prefixexp ‘:’ Name args args ::= ‘(’ [explist] ‘)’ | tableconstructor | LiteralString functiondef ::= function funcbody funcbody ::= ‘(’ [parlist] ‘)’ block end parlist ::= namelist [‘,’ ‘...’] | ‘...’ tableconstructor ::= ‘{’ [fieldlist] ‘}’ fieldlist ::= field {fieldsep field} [fieldsep] field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp fieldsep ::= ‘,’ | ‘;’ binop ::= ‘+’ | ‘-’ | ‘*’ | ‘/’ | ‘//’ | ‘^’ | ‘%’ | ‘&’ | ‘~’ | ‘|’ | ‘>>’ | ‘<<’ | ‘..’ | ‘<’ | ‘<=’ | ‘>’ | ‘>=’ | ‘==’ | ‘~=’ | and | or unop ::= ‘-’ | not | ‘#’ | ‘~’ ```
programming_docs
axios Handling Errors Handling Errors =============== ``` axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); }); ``` Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error. ``` axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Resolve only if the status code is less than 500 } }) ``` Using `toJSON` you get an object with more information about the HTTP error. ``` axios.get('/user/12345') .catch(function (error) { console.log(error.toJSON()); }); ``` axios Request Config Request Config ============== These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified. ``` { // `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance. baseURL: 'https://some-domain.com/api', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, // FormData or Stream // You may modify the headers object. transformRequest: [function (data, headers) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request // Must be a plain object or a URLSearchParams object // NOTE: params that are null or undefined are not rendered in the URL. params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function (params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', 'DELETE', and 'PATCH' // When no `transformRequest` is set, must be of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, // syntax alternative to send data into the body // method post // only the value is sent, not the key data: 'Country=Brasil&City=Belo Horizonte', // `timeout` specifies the number of milliseconds before the request times out. // If the request takes longer than `timeout`, the request will be aborted. timeout: 1000, // default is `0` (no timeout) // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // Return a promise and supply a valid response (see lib/adapters/README.md). adapter: function (config) { /* ... */ }, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. // Please note that only HTTP Basic auth is configurable through this parameter. // For Bearer tokens and such, use `Authorization` custom headers instead. auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` indicates the type of data that the server will respond with // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' // browser only: 'blob' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses (Node.js only) // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` allows handling of progress events for uploads // browser only onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` allows handling of progress events for downloads // browser only onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js maxContentLength: 2000, // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed maxBodyLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, no redirects will be followed. maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows options to be added like // `keepAlive` that are not enabled by default. httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // `proxy` defines the hostname, port, and protocol of the proxy server. // You can also define your proxy using the conventional `http_proxy` and // `https_proxy` environment variables. If you are using environment variables // for your proxy configuration, you can also define a `no_proxy` environment // variable as a comma-separated list of domains that should not be proxied. // Use `false` to disable proxies, ignoring environment variables. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and // supplies credentials. // This will set an `Proxy-Authorization` header, overwriting any existing // `Proxy-Authorization` custom headers you have set using `headers`. // If the proxy server uses HTTPS, then you must set the protocol to `https`. proxy: { protocol: 'https', host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` specifies a cancel token that can be used to cancel the request // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { }), // `decompress` indicates whether or not the response body should be decompressed // automatically. If set to `true` will also remove the 'content-encoding' header // from the responses objects of all decompressed responses // - Node only (XHR cannot turn off decompression) decompress: true // default } ``` axios Axios Axios ===== Promise based HTTP client for the browser and node.js Axios is a simple promise based HTTP client for the browser and node.js. Axios provides a simple to use library in a small package with a very extensible interface. axios Config Defaults Config Defaults =============== Config Defaults --------------- You can specify config defaults that will be applied to every request. ### Global axios defaults ``` axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; ``` ### Custom instance defaults ``` // Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; ``` ### Config order of precedence Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults/index.js](https://github.com/axios/axios/blob/649d739288c8e2c55829ac60e2345a0f3439c730/lib/defaults/index.js#L59), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. ``` // Create an instance using the config defaults provided by the library // At this point the timeout config value is `0` as is the default for the library const instance = axios.create(); // Override timeout default for the library // Now all requests using this instance will wait 2.5 seconds before timing out instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time instance.get('/longRequest', { timeout: 5000 }); ``` axios Response Schema Response Schema =============== The response for a request contains the following information. ``` { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response // As of HTTP/2 status text is blank or unsupported. // (HTTP/2 RFC: https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2.4) statusText: 'OK', // `headers` the HTTP headers that the server responded with // All header names are lower cased and can be accessed using the bracket notation. // Example: `response.headers['content-type']` headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {} } ``` When using `then`, you will receive the response as follows: ``` axios.get('/user/12345') .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); ``` When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](handling_errors) section. axios Notes Notes ===== A couple more notes to round it off Semver ------ Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. Promises -------- axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises). If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). TypeScript ---------- axios includes [TypeScript](http://typescriptlang.org) definitions. ``` import axios from 'axios'; axios.get('/user?ID=12345'); ``` Resources --------- * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) Credits ------- axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/%24http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular. License ------- [MIT](https://github.com/axios/axios/blob/master/LICENSE) axios Axios API Axios API ========= The Axios API Reference Requests can be made by passing the relevant config to `axios`. ##### axios(config) ``` // Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); ``` ``` // GET request for remote image in node.js axios({ method: 'get', url: 'http://bit.ly/2mTM3nY', responseType: 'stream' }) .then(function (response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) }); ``` ##### axios(url[, config]) ``` // Send a GET request (default method) axios('/user/12345'); ``` ### Request method aliases For convenience aliases have been provided for all supported request methods. ##### axios.request(config) ##### axios.get(url[, config]) ##### axios.delete(url[, config]) ##### axios.head(url[, config]) ##### axios.options(url[, config]) ##### axios.post(url[, data[, config]]) ##### axios.put(url[, data[, config]]) ##### axios.patch(url[, data[, config]]) ##### axios.postForm(url[, data[, config]]) ##### axios.putForm(url[, data[, config]]) ##### axios.patchForm(url[, data[, config]]) ###### NOTE When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. axios Getting Started Getting Started =============== Promise based HTTP client for the browser and node.js What is Axios? ============== Axios is a *[promise-based](https://javascript.info/promise-basics)* HTTP Client for [`node.js`](https://nodejs.org) and the browser. It is *[isomorphic](https://www.lullabot.com/articles/what-is-an-isomorphic-application)* (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js `http` module, while on the client (browser) it uses XMLHttpRequests. Features ======== * Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser * Make [http](http://nodejs.org/api/http.html) requests from node.js * Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API * Intercept request and response * Transform request and response data * Cancel requests * Timeouts * Query parameters serialization with support for nested entries * Automatic request body serialization to: + JSON (`application/json`) + Multipart / FormData (`multipart/form-data`) + URL encoded form (`application/x-www-form-urlencoded`) * Posting HTML forms as JSON * Automatic JSON data handling in response * Progress capturing for browsers and node.js with extra info (speed rate, remaining time) * Setting bandwidth limits for node.js * Compatible with spec-compliant FormData and Blob (including `node.js`) * Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) Installing ========== Using npm: ``` $ npm install axios ``` Using bower: ``` $ bower install axios ``` Using yarn: ``` $ yarn add axios ``` Using jsDelivr CDN: ``` <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> ``` Using unpkg CDN: ``` <script src="https://unpkg.com/axios/dist/axios.min.js"></script> ``` Prebuilt CommonJS modules for direct importing with require (if your module bundler failed to resolve them automatically) ``` const axios = require('axios/dist/browser/axios.cjs'); // browser const axios = require('axios/dist/node/axios.cjs'); // node ``` axios Interceptors Interceptors ============ You can intercept requests or responses before they are handled by `then` or `catch`. ``` // Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error); }); ``` If you need to remove an interceptor later you can. ``` const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor); ``` You can add interceptors to a custom instance of axios. ``` const instance = axios.create(); instance.interceptors.request.use(function () {/*...*/}); ``` axios Cancellation Cancellation ============ Cancelling requests ------------------- Setting the `timeout` property in an axios call handles **response** related timeouts. In some cases (e.g. network connection becomes unavailable) an axios call would benefit from cancelling the **connection** early. Without cancellation, the axios call can hang until the parent code/stack times out (might be a few minutes in a server-side applications). To terminate an axios call you can use following methods: * `signal` * `cancelToken` (deprecated) Combining `timeout` and cancellation method (e.g. `signal`) should cover **response** related timeouts AND **connection** related timeouts. ### `signal`: AbortController Starting from `v0.22.0` Axios supports [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to cancel requests in fetch API way: ``` const controller = new AbortController(); axios.get('/foo/bar', { signal: controller.signal }).then(function(response) { //... }); // cancel the request controller.abort() ``` Example with a timeout using latest [`AbortSignal.timeout()`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout) API [nodejs 17.3+]: ``` axios.get('/foo/bar', { signal: AbortSignal.timeout(5000) //Aborts request after 5 seconds }).then(function(response) { //... }); ``` Example with a timeout helper function: ``` function newAbortSignal(timeoutMs) { const abortController = new AbortController(); setTimeout(() => abortController.abort(), timeoutMs || 0); return abortController.signal; } axios.get('/foo/bar', { signal: newAbortSignal(5000) //Aborts request after 5 seconds }).then(function(response) { //... }); ``` ### CancelToken `deprecated` You can also cancel a request using a *CancelToken*. > The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises). > > > This API is deprecated since `v0.22.0` and shouldn't be used in new projects > > You can create a cancel token using the `CancelToken.source` factory as shown below: ``` const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.'); ``` You can also create a cancel token by passing an executor function to the `CancelToken` constructor: ``` const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; }) }); // cancel the request cancel(); ``` > Note: you can cancel several requests with the same cancel token / signal. > > During the transition period, you can use both cancellation APIs, even for the same request: ``` const controller = new AbortController(); const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token, signal: controller.signal }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.'); // OR controller.abort(); // the message parameter is not supported ```
programming_docs
axios Minimal Example Minimal Example =============== A little example of using axios note: CommonJS usage -------------------- In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach: ``` const axios = require('axios').default; // axios.<method> will now provide autocomplete and parameter typings ``` Example ======= Performing a `GET` request ``` const axios = require('axios'); // Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .finally(function () { // always executed }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .finally(function () { // always executed }); // Want to use async/await? Add the `async` keyword to your outer function/method. async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } } ``` > **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet Explorer and older browsers, so use with caution. > > axios The Axios Instance The Axios Instance ================== ### Creating an instance You can create a new instance of axios with a custom config. ##### axios.create([config]) ``` const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); ``` ### Instance methods The available instance methods are listed below. The specified config will be merged with the instance config. ##### axios#request(config) ##### axios#get(url[, config]) ##### axios#delete(url[, config]) ##### axios#head(url[, config]) ##### axios#options(url[, config]) ##### axios#post(url[, data[, config]]) ##### axios#put(url[, data[, config]]) ##### axios#patch(url[, data[, config]]) ##### axios#getUri([config]) axios Translating the documentation Translating the documentation ============================= To make Axios accessible to as many people as possible, it is important that these docs can be read in all languages. We always appreciate anyone who wants to help translate the documentation. This guide provides instructions for adding a translation to this documentation. Structure --------- Every translation is composed of a configuration file, `{language-shortcut}.lang.js` (for example, `en.lang.js` or `de.lang.js`) and the translated documentation files in `posts/{language-shortcut}/*.md` (for example `posts/en` or `posts/de`). `{language-shortcut}` should be replaced with your language's [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) two-letter code. Configuring your language ------------------------- * Copy `en.lang.js`. * Rename it to `{language-shortcut}.lang.js`. * Replace `display` with the name of your language, in your language. For example, if you're translating german, place “Deutsch” instead of “German”. * Replace prefix with `/{language-shortcut}/`. * Translate the values in the `p` and `t` fields. * Translate all the properties labeled `text` in the sidebar. **Note:** Since the latest version of this documentation, links in the sidebar no longer need to be updated. ### Registering the configuration Once you've finished configuring your language and translating the phrases and links in the configuration file, you'll need to register it in the root configuration. To do this, open `inert.config.js` and add the following line near the top: ``` const {language-shortcut}Config = require('./{language-shortcut}.config.js'); ``` Of course, remember to replace `{language-shortuct}` with the correct [ISO 369-1](https://en.wikipedia.org/wiki/ISO_639-1) code (in the variable name, too!). Now, look for the `langs` constant. If this constant is located above your `require` statement, move your `require` statement above it. To the `langs` list, add the following object: ``` const langs = [ ... { name: 'Some name that uniquely identifies your language, for example "English" or "German"', prefix: "The same prefix as in the configuration file", config: {language-shortcut}Config // The configuration object you imported earlier } ... ]; ``` Now, you can begin translating the files. Copy the folder `posts/en` into a new folder `posts/{language-shortcut}` and translate all the files (don't translate the filenames, of course). If you hit any problems, feel free to [create and issue](https://github.com/axios/axios-docs/issues/new/choose). axios POST Requests POST Requests ============= How to perform POST requests with Axios Performing a `POST` request --------------------------- ### JSON ``` axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` Performing multiple concurrent requests ``` function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } const [acct, perm] = await Promise.all([getUserAccount(), getUserPermissions()]); // OR Promise.all([getUserAccount(), getUserPermissions()]) .then(function ([acct, perm]) { // ... }); ``` Post an HTML form as JSON ``` const {data} = await axios.post('/user', document.querySelector('#my-form'), { headers: { 'Content-Type': 'application/json' } }) ``` ### Forms * Multipart (`multipart/form-data`) ``` const {data} = await axios.post('https://httpbin.org/post', { firstName: 'Fred', lastName: 'Flintstone', orders: [1, 2, 3], photo: document.querySelector('#fileInput').files }, { headers: { 'Content-Type': 'multipart/form-data' } } ) ``` * URL encoded form (`application/x-www-form-urlencoded`) ``` const {data} = await axios.post('https://httpbin.org/post', { firstName: 'Fred', lastName: 'Flintstone', orders: [1, 2, 3] }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) ``` axios URL-Encoding Bodies URL-Encoding Bodies =================== By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following approaches. ### Browser In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows: ``` const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params); ``` > Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment). > > Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library: ``` const qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 })); ``` Or in another way (ES6), ``` import qs from 'qs'; const data = { 'bar': 123 }; const options = { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, data: qs.stringify(data), url, }; axios(options); ``` ### Node.js #### Query string In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows: ``` const querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' })); ``` or ['URLSearchParams'](https://nodejs.org/api/url.html#url_class_urlsearchparams) from ['url module'](https://nodejs.org/api/url.html) as follows: ``` const url = require('url'); const params = new url.URLSearchParams({ foo: 'bar' }); axios.post('http://something.com/', params.toString()); ``` You can also use the [`qs`](https://github.com/ljharb/qs) library. > Note: The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (<https://github.com/nodejs/node-v0.x-archive/issues/1665>). > > ### 🆕 Automatic serialization Axios will automatically serialize the data object to urlencoded format if the `content-type` header is set to `application/x-www-form-urlencoded`. This works both in the browser and in `node.js`: ``` const data = { x: 1, arr: [1, 2, 3], arr2: [1, [2], 3], users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}], }; await axios.post('https://postman-echo.com/post', data, {headers: {'content-type': 'application/x-www-form-urlencoded'}} ); ``` The server will handle it as ``` { x: '1', 'arr[]': [ '1', '2', '3' ], 'arr2[0]': '1', 'arr2[1][0]': '2', 'arr2[2]': '3', 'arr3[]': [ '1', '2', '3' ], 'users[0][name]': 'Peter', 'users[0][surname]': 'griffin', 'users[1][name]': 'Thomas', 'users[1][surname]': 'Anderson' } ``` If your server framework's request body parser (like `body-parser` of `express.js`) supports nested objects decoding, you will automatically receive the same server object that you submitted. Echo server example (`express.js`) : ``` var app = express(); app.use(bodyParser.urlencoded({ extended: true })); // support url-encoded bodies app.post('/', function (req, res, next) { res.send(JSON.stringify(req.body)); }); server = app.listen(3000); ``` axios Multipart Bodies Multipart Bodies ================ Posting data as `multipart/form-data` ------------------------------------- ### Using FormData API #### Browser ``` const form = new FormData(); form.append('my_field', 'my value'); form.append('my_buffer', new Blob([1,2,3])); form.append('my_file', fileInput.files[0]); axios.post('https://example.com', form) ``` The same result can be achieved using the internal Axios serializer and corresponding shorthand method: ``` axios.postForm('https://httpbin.org/post', { my_field: 'my value', my_buffer: new Blob([1,2,3]), my_file: fileInput.files // FileList will be unwrapped as sepate fields }); ``` HTML form can be passes directly as a request payload #### Node.js ``` import axios from 'axios'; const form = new FormData(); form.append('my_field', 'my value'); form.append('my_buffer', new Blob(['some content'])); axios.post('https://example.com', form) ``` Since node.js does not currently support creating a `Blob` from a file, you can use a third-party package for this purpose. ``` import {fileFromPath} from 'formdata-node/file-from-path' form.append('my_field', 'my value'); form.append('my_file', await fileFromPath('/foo/bar.jpg')); axios.post('https://example.com', form) ``` For Axios older than `v1.3.0` you must import `form-data` package. ``` const FormData = require('form-data'); const form = new FormData(); form.append('my_field', 'my value'); form.append('my_buffer', new Buffer(10)); form.append('my_file', fs.createReadStream('/foo/bar.jpg')); axios.post('https://example.com', form) ``` ### 🆕 Automatic serialization Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request Content-Type header is set to `multipart/form-data`. The following request will submit the data in a FormData format (Browser & Node.js): ``` import axios from 'axios'; axios.post('https://httpbin.org/post', { user: { name: 'Dmitriy' }, file: fs.createReadStream('/foo/bar.jpg') }, { headers: { 'Content-Type': 'multipart/form-data' } }).then(({data})=> console.log(data)); ``` Axios FormData serializer supports some special endings to perform the following operations: * `{}` - serialize the value with JSON.stringify * `[]` - unwrap the array-like object as separate fields with the same key > NOTE: unwrap/expand operation will be used by default on arrays and FileList objects > > FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases: * `visitor: Function` - user-defined visitor function that will be called recursively to serialize the data object to a `FormData` object by following custom rules. * `dots: boolean = false` - use dot notation instead of brackets to serialize arrays and objects; * `metaTokens: boolean = true` - add the special ending (e.g `user{}: '{"name": "John"}'`) in the FormData key. The back-end body-parser could potentially use this meta-information to automatically parse the value as JSON. * `indexes: null|false|true = false` - controls how indexes will be added to unwrapped keys of `flat` array-like objects + `null` - don't add brackets (`arr: 1`, `arr: 2`, `arr: 3`) + `false`(default) - add empty brackets (`arr[]: 1`, `arr[]: 2`, `arr[]: 3`) + `true` - add brackets with indexes (`arr[0]: 1`, `arr[1]: 2`, `arr[2]: 3`) Let's say we have an object like this one: ``` const obj = { x: 1, arr: [1, 2, 3], arr2: [1, [2], 3], users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}], 'obj2{}': [{x:1}] }; ``` The following steps will be executed by the Axios serializer internally: ``` const formData= new FormData(); formData.append('x', '1'); formData.append('arr[]', '1'); formData.append('arr[]', '2'); formData.append('arr[]', '3'); formData.append('arr2[0]', '1'); formData.append('arr2[1][0]', '2'); formData.append('arr2[2]', '3'); formData.append('users[0][name]', 'Peter'); formData.append('users[0][surname]', 'Griffin'); formData.append('users[1][name]', 'Thomas'); formData.append('users[1][surname]', 'Anderson'); formData.append('obj2{}', '[{"x":1}]'); ``` ``` import axios from 'axios'; axios.post('https://httpbin.org/post', { 'myObj{}': {x: 1, s: "foo"}, 'files[]': document.querySelector('#fileInput').files }, { headers: { 'Content-Type': 'multipart/form-data' } }).then(({data})=> console.log(data)); ``` Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm` which are just the corresponding http methods with the content-type header preset to `multipart/form-data`. `FileList` object can be passed directly: ``` await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files) ``` All files will be sent with the same field names: `files[]`; nginx_lua_module ngx_http_lua_module ngx\_http\_lua\_module ====================== Name ---- ngx\_http\_lua\_module - Embed the power of Lua into Nginx HTTP Servers. *This module is not distributed with the Nginx source.* See [the installation instructions](#installation). Table of Contents ----------------- * [Name](#name) * [Status](#status) * [Version](#version) * [Synopsis](#synopsis) * [Description](#description) * [Typical Uses](#typical-uses) * [Nginx Compatibility](#nginx-compatibility) * [Installation](#installation) + [Building as a dynamic module](#building-as-a-dynamic-module) + [C Macro Configurations](#c-macro-configurations) + [Installation on Ubuntu 11.10](#installation-on-ubuntu-1110) * [Community](#community) + [English Mailing List](#english-mailing-list) + [Chinese Mailing List](#chinese-mailing-list) * [Code Repository](#code-repository) * [Bugs and Patches](#bugs-and-patches) * [Lua/LuaJIT bytecode support](#lualuajit-bytecode-support) * [System Environment Variable Support](#system-environment-variable-support) * [HTTP 1.0 support](#http-10-support) * [Statically Linking Pure Lua Modules](#statically-linking-pure-lua-modules) * [Data Sharing within an Nginx Worker](#data-sharing-within-an-nginx-worker) * [Known Issues](#known-issues) + [TCP socket connect operation issues](#tcp-socket-connect-operation-issues) + [Lua Coroutine Yielding/Resuming](#lua-coroutine-yieldingresuming) + [Lua Variable Scope](#lua-variable-scope) + [Locations Configured by Subrequest Directives of Other Modules](#locations-configured-by-subrequest-directives-of-other-modules) + [Cosockets Not Available Everywhere](#cosockets-not-available-everywhere) + [Special Escaping Sequences](#special-escaping-sequences) + [Mixing with SSI Not Supported](#mixing-with-ssi-not-supported) + [SPDY Mode Not Fully Supported](#spdy-mode-not-fully-supported) + [Missing data on short circuited requests](#missing-data-on-short-circuited-requests) * [TODO](#todo) * [Changes](#changes) * [Test Suite](#test-suite) * [Copyright and License](#copyright-and-license) * [See Also](#see-also) * [Directives](#directives) * [Nginx API for Lua](#nginx-api-for-lua) * [Obsolete Sections](#obsolete-sections) + [Special PCRE Sequences](#special-pcre-sequences) Status ------ Production ready. Version ------- This document describes ngx\_lua [v0.10.13](https://github.com/openresty/lua-nginx-module/tags) released on 22 April 2018. Synopsis -------- ``` # set search paths for pure Lua external libraries (';;' is the default path): lua_package_path '/foo/bar/?.lua;/blah/?.lua;;'; # set search paths for Lua external libraries written in C (can also use ';;'): lua_package_cpath '/bar/baz/?.so;/blah/blah/?.so;;'; server { location /lua_content { # MIME type determined by default_type: default_type 'text/plain'; content_by_lua_block { ngx.say('Hello,world!') } } location /nginx_var { # MIME type determined by default_type: default_type 'text/plain'; # try access /nginx_var?a=hello,world content_by_lua_block { ngx.say(ngx.var.arg_a) } } location = /request_body { client_max_body_size 50k; client_body_buffer_size 50k; content_by_lua_block { ngx.req.read_body() -- explicitly read the req body local data = ngx.req.get_body_data() if data then ngx.say("body data:") ngx.print(data) return end -- body may get buffered in a temp file: local file = ngx.req.get_body_file() if file then ngx.say("body is in file ", file) else ngx.say("no body found") end } } # transparent non-blocking I/O in Lua via subrequests # (well, a better way is to use cosockets) location = /lua { # MIME type determined by default_type: default_type 'text/plain'; content_by_lua_block { local res = ngx.location.capture("/some_other_location") if res then ngx.say("status: ", res.status) ngx.say("body:") ngx.print(res.body) end } } location = /foo { rewrite_by_lua_block { res = ngx.location.capture("/memc", { args = { cmd = "incr", key = ngx.var.uri } } ) } proxy_pass http://blah.blah.com; } location = /mixed { rewrite_by_lua_file /path/to/rewrite.lua; access_by_lua_file /path/to/access.lua; content_by_lua_file /path/to/content.lua; } # use nginx var in code path # CAUTION: contents in nginx var must be carefully filtered, # otherwise there'll be great security risk! location ~ ^/app/([-_a-zA-Z0-9/]+) { set $path $1; content_by_lua_file /path/to/lua/app/root/$path.lua; } location / { client_max_body_size 100k; client_body_buffer_size 100k; access_by_lua_block { -- check the client IP address is in our black list if ngx.var.remote_addr == "132.5.72.3" then ngx.exit(ngx.HTTP_FORBIDDEN) end -- check if the URI contains bad words if ngx.var.uri and string.match(ngx.var.request_body, "evil") then return ngx.redirect("/terms_of_use.html") end -- tests passed } # proxy_pass/fastcgi_pass/etc settings } } ``` Description ----------- This module embeds Lua, via the standard Lua 5.1 interpreter or [LuaJIT 2.0/2.1](http://luajit.org/luajit.html), into Nginx and by leveraging Nginx's subrequests, allows the integration of the powerful Lua threads (Lua coroutines) into the Nginx event model. Unlike [Apache's mod\_lua](https://httpd.apache.org/docs/trunk/mod/mod_lua.html) and [Lighttpd's mod\_magnet](http://redmine.lighttpd.net/wiki/1/Docs:ModMagnet), Lua code executed using this module can be *100% non-blocking* on network traffic as long as the [Nginx API for Lua](#nginx-api-for-lua) provided by this module is used to handle requests to upstream services such as MySQL, PostgreSQL, Memcached, Redis, or upstream HTTP web services. At least the following Lua libraries and Nginx modules can be used with this ngx\_lua module: * [lua-resty-memcached](https://github.com/openresty/lua-resty-memcached) * [lua-resty-mysql](https://github.com/openresty/lua-resty-mysql) * [lua-resty-redis](https://github.com/openresty/lua-resty-redis) * [lua-resty-dns](https://github.com/openresty/lua-resty-dns) * [lua-resty-upload](https://github.com/openresty/lua-resty-upload) * [lua-resty-websocket](https://github.com/openresty/lua-resty-websocket) * [lua-resty-lock](https://github.com/openresty/lua-resty-lock) * [lua-resty-logger-socket](https://github.com/cloudflare/lua-resty-logger-socket) * [lua-resty-lrucache](https://github.com/openresty/lua-resty-lrucache) * [lua-resty-string](https://github.com/openresty/lua-resty-string) * [ngx\_memc](http://github.com/openresty/memc-nginx-module) * [ngx\_postgres](https://github.com/FRiCKLE/ngx_postgres) * [ngx\_redis2](http://github.com/openresty/redis2-nginx-module) * [ngx\_redis](http://wiki.nginx.org/HttpRedisModule) * [ngx\_proxy](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) * [ngx\_fastcgi](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html) Almost all the Nginx modules can be used with this ngx\_lua module by means of [ngx.location.capture](#ngxlocationcapture) or [ngx.location.capture\_multi](#ngxlocationcapture_multi) but it is recommended to use those `lua-resty-*` libraries instead of creating subrequests to access the Nginx upstream modules because the former is usually much more flexible and memory-efficient. The Lua interpreter or LuaJIT instance is shared across all the requests in a single nginx worker process but request contexts are segregated using lightweight Lua coroutines. Loaded Lua modules persist in the nginx worker process level resulting in a small memory footprint in Lua even when under heavy loads. This module is plugged into NGINX's "http" subsystem so it can only speaks downstream communication protocols in the HTTP family (HTTP 0.9/1.0/1.1/2.0, WebSockets, and etc). If you want to do generic TCP communications with the downstream clients, then you should use the [ngx\_stream\_lua](https://github.com/openresty/stream-lua-nginx-module#readme) module instead which has a compatible Lua API. Typical Uses ------------ Just to name a few: * Mashup'ing and processing outputs of various nginx upstream outputs (proxy, drizzle, postgres, redis, memcached, and etc) in Lua, * doing arbitrarily complex access control and security checks in Lua before requests actually reach the upstream backends, * manipulating response headers in an arbitrary way (by Lua) * fetching backend information from external storage backends (like redis, memcached, mysql, postgresql) and use that information to choose which upstream backend to access on-the-fly, * coding up arbitrarily complex web applications in a content handler using synchronous but still non-blocking access to the database backends and other storage, * doing very complex URL dispatch in Lua at rewrite phase, * using Lua to implement advanced caching mechanism for Nginx's subrequests and arbitrary locations. The possibilities are unlimited as the module allows bringing together various elements within Nginx as well as exposing the power of the Lua language to the user. The module provides the full flexibility of scripting while offering performance levels comparable with native C language programs both in terms of CPU time as well as memory footprint. This is particularly the case when LuaJIT 2.x is enabled. Other scripting language implementations typically struggle to match this performance level. The Lua state (Lua VM instance) is shared across all the requests handled by a single nginx worker process to minimize memory use. Nginx Compatibility ------------------- The latest version of this module is compatible with the following versions of Nginx: * 1.13.x (last tested: 1.13.6) * 1.12.x * 1.11.x (last tested: 1.11.2) * 1.10.x * 1.9.x (last tested: 1.9.15) * 1.8.x * 1.7.x (last tested: 1.7.10) * 1.6.x Nginx cores older than 1.6.0 (exclusive) are *not* supported. Installation ------------ It is *highly* recommended to use [OpenResty releases](http://openresty.org) which integrate Nginx, ngx\_lua, LuaJIT 2.1, as well as other powerful companion Nginx modules and Lua libraries. It is discouraged to build this module with nginx yourself since it is tricky to set up exactly right. Also, the stock nginx cores have various limitations and long standing bugs that can make some of this modules' features become disabled, not work properly, or run slower. The same applies to LuaJIT as well. OpenResty includes its own version of LuaJIT which gets specifically optimized and enhanced for the OpenResty environment. Alternatively, ngx\_lua can be manually compiled into Nginx: 1. Install LuaJIT 2.0 or 2.1 (recommended) or Lua 5.1 (Lua 5.2 is *not* supported yet). LuaJIT can be downloaded from the [LuaJIT project website](http://luajit.org/download.html) and Lua 5.1, from the [Lua project website](http://www.lua.org/). Some distribution package managers also distribute LuaJIT and/or Lua. 2. Download the latest version of the ngx\_devel\_kit (NDK) module [HERE](https://github.com/simplresty/ngx_devel_kit/tags). 3. Download the latest version of ngx\_lua [HERE](https://github.com/openresty/lua-nginx-module/tags). 4. Download the latest version of Nginx [HERE](http://nginx.org/) (See [Nginx Compatibility](#nginx-compatibility)) Build the source with this module: ``` wget 'http://nginx.org/download/nginx-1.13.6.tar.gz' tar -xzvf nginx-1.13.6.tar.gz cd nginx-1.13.6/ # tell nginx's build system where to find LuaJIT 2.0: export LUAJIT_LIB=/path/to/luajit/lib export LUAJIT_INC=/path/to/luajit/include/luajit-2.0 # tell nginx's build system where to find LuaJIT 2.1: export LUAJIT_LIB=/path/to/luajit/lib export LUAJIT_INC=/path/to/luajit/include/luajit-2.1 # or tell where to find Lua if using Lua instead: #export LUA_LIB=/path/to/lua/lib #export LUA_INC=/path/to/lua/include # Here we assume Nginx is to be installed under /opt/nginx/. ./configure --prefix=/opt/nginx \ --with-ld-opt="-Wl,-rpath,/path/to/luajit-or-lua/lib" \ --add-module=/path/to/ngx_devel_kit \ --add-module=/path/to/lua-nginx-module # Note that you may also want to add `./configure` options which are used in your # current nginx build. # You can get usually those options using command nginx -V # you can change the parallism number 2 below to fit the number of spare CPU cores in your # machine. make -j2 make install ``` ### Building as a dynamic module Starting from NGINX 1.9.11, you can also compile this module as a dynamic module, by using the `--add-dynamic-module=PATH` option instead of `--add-module=PATH` on the `./configure` command line above. And then you can explicitly load the module in your `nginx.conf` via the [load\_module](http://nginx.org/en/docs/ngx_core_module.html#load_module) directive, for example, ``` load_module /path/to/modules/ndk_http_module.so; # assuming NDK is built as a dynamic module too load_module /path/to/modules/ngx_http_lua_module.so; ``` ### C Macro Configurations While building this module either via OpenResty or with the NGINX core, you can define the following C macros via the C compiler options: * `NGX_LUA_USE_ASSERT` When defined, will enable assertions in the ngx\_lua C code base. Recommended for debugging or testing builds. It can introduce some (small) runtime overhead when enabled. This macro was first introduced in the `v0.9.10` release. * `NGX_LUA_ABORT_AT_PANIC` When the Lua/LuaJIT VM panics, ngx\_lua will instruct the current nginx worker process to quit gracefully by default. By specifying this C macro, ngx\_lua will abort the current nginx worker process (which usually result in a core dump file) immediately. This option is useful for debugging VM panics. This option was first introduced in the `v0.9.8` release. * `NGX_LUA_NO_FFI_API` Excludes pure C API functions for FFI-based Lua API for NGINX (as required by [lua-resty-core](https://github.com/openresty/lua-resty-core#readme), for example). Enabling this macro can make the resulting binary code size smaller. To enable one or more of these macros, just pass extra C compiler options to the `./configure` script of either NGINX or OpenResty. For instance, ``` ./configure --with-cc-opt="-DNGX_LUA_USE_ASSERT -DNGX_LUA_ABORT_AT_PANIC" ``` ### Installation on Ubuntu 11.10 Note that it is recommended to use LuaJIT 2.0 or LuaJIT 2.1 instead of the standard Lua 5.1 interpreter wherever possible. If the standard Lua 5.1 interpreter is required however, run the following command to install it from the Ubuntu repository: ``` apt-get install -y lua5.1 liblua5.1-0 liblua5.1-0-dev ``` Everything should be installed correctly, except for one small tweak. Library name `liblua.so` has been changed in liblua5.1 package, it only comes with `liblua5.1.so`, which needs to be symlinked to `/usr/lib` so it could be found during the configuration process. ``` ln -s /usr/lib/x86_64-linux-gnu/liblua5.1.so /usr/lib/liblua.so ``` Community --------- ### English Mailing List The [openresty-en](https://groups.google.com/group/openresty-en) mailing list is for English speakers. ### Chinese Mailing List The [openresty](https://groups.google.com/group/openresty) mailing list is for Chinese speakers. Code Repository --------------- The code repository of this project is hosted on github at [openresty/lua-nginx-module](https://github.com/openresty/lua-nginx-module). Bugs and Patches ---------------- Please submit bug reports, wishlists, or patches by 1. creating a ticket on the [GitHub Issue Tracker](https://github.com/openresty/lua-nginx-module/issues), 2. or posting to the [OpenResty community](#community). Lua/LuaJIT bytecode support --------------------------- As from the `v0.5.0rc32` release, all `*_by_lua_file` configure directives (such as [content\_by\_lua\_file](#content_by_lua_file)) support loading Lua 5.1 and LuaJIT 2.0/2.1 raw bytecode files directly. Please note that the bytecode format used by LuaJIT 2.0/2.1 is not compatible with that used by the standard Lua 5.1 interpreter. So if using LuaJIT 2.0/2.1 with ngx\_lua, LuaJIT compatible bytecode files must be generated as shown: ``` /path/to/luajit/bin/luajit -b /path/to/input_file.lua /path/to/output_file.ljbc ``` The `-bg` option can be used to include debug information in the LuaJIT bytecode file: ``` /path/to/luajit/bin/luajit -bg /path/to/input_file.lua /path/to/output_file.ljbc ``` Please refer to the official LuaJIT documentation on the `-b` option for more details: <http://luajit.org/running.html#opt_b> Also, the bytecode files generated by LuaJIT 2.1 is *not* compatible with LuaJIT 2.0, and vice versa. The support for LuaJIT 2.1 bytecode was first added in ngx\_lua v0.9.3. Similarly, if using the standard Lua 5.1 interpreter with ngx\_lua, Lua compatible bytecode files must be generated using the `luac` commandline utility as shown: ``` luac -o /path/to/output_file.luac /path/to/input_file.lua ``` Unlike as with LuaJIT, debug information is included in standard Lua 5.1 bytecode files by default. This can be striped out by specifying the `-s` option as shown: ``` luac -s -o /path/to/output_file.luac /path/to/input_file.lua ``` Attempts to load standard Lua 5.1 bytecode files into ngx\_lua instances linked to LuaJIT 2.0/2.1 or vice versa, will result in an error message, such as that below, being logged into the Nginx `error.log` file: ``` [error] 13909#0: *1 failed to load Lua inlined code: bad byte-code header in /path/to/test_file.luac ``` Loading bytecode files via the Lua primitives like `require` and `dofile` should always work as expected. System Environment Variable Support ----------------------------------- If you want to access the system environment variable, say, `foo`, in Lua via the standard Lua API [os.getenv](http://www.lua.org/manual/5.1/manual.html#pdf-os.getenv), then you should also list this environment variable name in your `nginx.conf` file via the [env directive](http://nginx.org/en/docs/ngx_core_module.html#env). For example, ``` env foo; ``` HTTP 1.0 support ---------------- The HTTP 1.0 protocol does not support chunked output and requires an explicit `Content-Length` header when the response body is not empty in order to support the HTTP 1.0 keep-alive. So when a HTTP 1.0 request is made and the [lua\_http10\_buffering](#lua_http10_buffering) directive is turned `on`, ngx\_lua will buffer the output of [ngx.say](#ngxsay) and [ngx.print](#ngxprint) calls and also postpone sending response headers until all the response body output is received. At that time ngx\_lua can calculate the total length of the body and construct a proper `Content-Length` header to return to the HTTP 1.0 client. If the `Content-Length` response header is set in the running Lua code, however, this buffering will be disabled even if the [lua\_http10\_buffering](#lua_http10_buffering) directive is turned `on`. For large streaming output responses, it is important to disable the [lua\_http10\_buffering](#lua_http10_buffering) directive to minimise memory usage. Note that common HTTP benchmark tools such as `ab` and `http_load` issue HTTP 1.0 requests by default. To force `curl` to send HTTP 1.0 requests, use the `-0` option. Statically Linking Pure Lua Modules ----------------------------------- When LuaJIT 2.x is used, it is possible to statically link the bytecode of pure Lua modules into the Nginx executable. Basically you use the `luajit` executable to compile `.lua` Lua module files to `.o` object files containing the exported bytecode data, and then link the `.o` files directly in your Nginx build. Below is a trivial example to demonstrate this. Consider that we have the following `.lua` file named `foo.lua`: ``` -- foo.lua local _M = {} function _M.go() print("Hello from foo") end return _M ``` And then we compile this `.lua` file to `foo.o` file: ``` /path/to/luajit/bin/luajit -bg foo.lua foo.o ``` What matters here is the name of the `.lua` file, which determines how you use this module later on the Lua land. The file name `foo.o` does not matter at all except the `.o` file extension (which tells `luajit` what output format is used). If you want to strip the Lua debug information from the resulting bytecode, you can just specify the `-b` option above instead of `-bg`. Then when building Nginx or OpenResty, pass the `--with-ld-opt="foo.o"` option to the `./configure` script: ``` ./configure --with-ld-opt="/path/to/foo.o" ... ``` Finally, you can just do the following in any Lua code run by ngx\_lua: ``` local foo = require "foo" foo.go() ``` And this piece of code no longer depends on the external `foo.lua` file any more because it has already been compiled into the `nginx` executable. If you want to use dot in the Lua module name when calling `require`, as in ``` local foo = require "resty.foo" ``` then you need to rename the `foo.lua` file to `resty_foo.lua` before compiling it down to a `.o` file with the `luajit` command-line utility. It is important to use exactly the same version of LuaJIT when compiling `.lua` files to `.o` files as building nginx + ngx\_lua. This is because the LuaJIT bytecode format may be incompatible between different LuaJIT versions. When the bytecode format is incompatible, you will see a Lua runtime error saying that the Lua module is not found. When you have multiple `.lua` files to compile and link, then just specify their `.o` files at the same time in the value of the `--with-ld-opt` option. For instance, ``` ./configure --with-ld-opt="/path/to/foo.o /path/to/bar.o" ... ``` If you have just too many `.o` files, then it might not be feasible to name them all in a single command. In this case, you can build a static library (or archive) for your `.o` files, as in ``` ar rcus libmyluafiles.a *.o ``` then you can link the `myluafiles` archive as a whole to your nginx executable: ``` ./configure \ --with-ld-opt="-L/path/to/lib -Wl,--whole-archive -lmyluafiles -Wl,--no-whole-archive" ``` where `/path/to/lib` is the path of the directory containing the `libmyluafiles.a` file. It should be noted that the linker option `--whole-archive` is required here because otherwise our archive will be skipped because no symbols in our archive are mentioned in the main parts of the nginx executable. Data Sharing within an Nginx Worker ----------------------------------- To globally share data among all the requests handled by the same nginx worker process, encapsulate the shared data into a Lua module, use the Lua `require` builtin to import the module, and then manipulate the shared data in Lua. This works because required Lua modules are loaded only once and all coroutines will share the same copy of the module (both its code and data). Note however that Lua global variables (note, not module-level variables) WILL NOT persist between requests because of the one-coroutine-per-request isolation design. Here is a complete small example: ``` -- mydata.lua local _M = {} local data = { dog = 3, cat = 4, pig = 5, } function _M.get_age(name) return data[name] end return _M ``` and then accessing it from `nginx.conf`: ``` location /lua { content_by_lua_block { local mydata = require "mydata" ngx.say(mydata.get_age("dog")) } } ``` The `mydata` module in this example will only be loaded and run on the first request to the location `/lua`, and all subsequent requests to the same nginx worker process will use the reloaded instance of the module as well as the same copy of the data in it, until a `HUP` signal is sent to the Nginx master process to force a reload. This data sharing technique is essential for high performance Lua applications based on this module. Note that this data sharing is on a *per-worker* basis and not on a *per-server* basis. That is, when there are multiple nginx worker processes under an Nginx master, data sharing cannot cross the process boundary between these workers. It is usually recommended to share read-only data this way. You can also share changeable data among all the concurrent requests of each nginx worker process as long as there is *no* nonblocking I/O operations (including [ngx.sleep](#ngxsleep)) in the middle of your calculations. As long as you do not give the control back to the nginx event loop and ngx\_lua's light thread scheduler (even implicitly), there can never be any race conditions in between. For this reason, always be very careful when you want to share changeable data on the worker level. Buggy optimizations can easily lead to hard-to-debug race conditions under load. If server-wide data sharing is required, then use one or more of the following approaches: 1. Use the [ngx.shared.DICT](#ngxshareddict) API provided by this module. 2. Use only a single nginx worker and a single server (this is however not recommended when there is a multi core CPU or multiple CPUs in a single machine). 3. Use data storage mechanisms such as `memcached`, `redis`, `MySQL` or `PostgreSQL`. [The OpenResty bundle](http://openresty.org) associated with this module comes with a set of companion Nginx modules and Lua libraries that provide interfaces with these data storage mechanisms. Known Issues ------------ ### TCP socket connect operation issues The [tcpsock:connect](#tcpsockconnect) method may indicate `success` despite connection failures such as with `Connection Refused` errors. However, later attempts to manipulate the cosocket object will fail and return the actual error status message generated by the failed connect operation. This issue is due to limitations in the Nginx event model and only appears to affect Mac OS X. ### Lua Coroutine Yielding/Resuming * Because Lua's `dofile` and `require` builtins are currently implemented as C functions in both Lua 5.1 and LuaJIT 2.0/2.1, if the Lua file being loaded by `dofile` or `require` invokes [ngx.location.capture\*](#ngxlocationcapture), [ngx.exec](#ngxexec), [ngx.exit](#ngxexit), or other API functions requiring yielding in the *top-level* scope of the Lua file, then the Lua error "attempt to yield across C-call boundary" will be raised. To avoid this, put these calls requiring yielding into your own Lua functions in the Lua file instead of the top-level scope of the file. * As the standard Lua 5.1 interpreter's VM is not fully resumable, the methods [ngx.location.capture](#ngxlocationcapture), [ngx.location.capture\_multi](#ngxlocationcapture_multi), [ngx.redirect](#ngxredirect), [ngx.exec](#ngxexec), and [ngx.exit](#ngxexit) cannot be used within the context of a Lua [pcall()](http://www.lua.org/manual/5.1/manual.html#pdf-pcall) or [xpcall()](http://www.lua.org/manual/5.1/manual.html#pdf-xpcall) or even the first line of the `for ... in ...` statement when the standard Lua 5.1 interpreter is used and the `attempt to yield across metamethod/C-call boundary` error will be produced. Please use LuaJIT 2.x, which supports a fully resumable VM, to avoid this. ### Lua Variable Scope Care must be taken when importing modules and this form should be used: ``` local xxx = require('xxx') ``` instead of the old deprecated form: ``` require('xxx') ``` Here is the reason: by design, the global environment has exactly the same lifetime as the Nginx request handler associated with it. Each request handler has its own set of Lua global variables and that is the idea of request isolation. The Lua module is actually loaded by the first Nginx request handler and is cached by the `require()` built-in in the `package.loaded` table for later reference, and the `module()` builtin used by some Lua modules has the side effect of setting a global variable to the loaded module table. But this global variable will be cleared at the end of the request handler, and every subsequent request handler all has its own (clean) global environment. So one will get Lua exception for accessing the `nil` value. The use of Lua global variables is a generally inadvisable in the ngx\_lua context as: 1. the misuse of Lua globals has detrimental side effects on concurrent requests when such variables should instead be local in scope, 2. Lua global variables require Lua table look-ups in the global environment which is computationally expensive, and 3. some Lua global variable references may include typing errors which make such difficult to debug. It is therefore *highly* recommended to always declare such within an appropriate local scope instead. ``` -- Avoid foo = 123 -- Recommended local foo = 123 -- Avoid function foo() return 123 end -- Recommended local function foo() return 123 end ``` To find all instances of Lua global variables in your Lua code, run the [lua-releng tool](https://github.com/openresty/nginx-devel-utils/blob/master/lua-releng) across all `.lua` source files: ``` $ lua-releng Checking use of Lua global variables in file lib/foo/bar.lua ... 1 [1489] SETGLOBAL 7 -1 ; contains 55 [1506] GETGLOBAL 7 -3 ; setvar 3 [1545] GETGLOBAL 3 -4 ; varexpand ``` The output says that the line 1489 of file `lib/foo/bar.lua` writes to a global variable named `contains`, the line 1506 reads from the global variable `setvar`, and line 1545 reads the global `varexpand`. This tool will guarantee that local variables in the Lua module functions are all declared with the `local` keyword, otherwise a runtime exception will be thrown. It prevents undesirable race conditions while accessing such variables. See [Data Sharing within an Nginx Worker](#data-sharing-within-an-nginx-worker) for the reasons behind this. ### Locations Configured by Subrequest Directives of Other Modules The [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture\_multi](#ngxlocationcapture_multi) directives cannot capture locations that include the [add\_before\_body](http://nginx.org/en/docs/http/ngx_http_addition_module.html#add_before_body), [add\_after\_body](http://nginx.org/en/docs/http/ngx_http_addition_module.html#add_after_body), [auth\_request](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html#auth_request), [echo\_location](http://github.com/openresty/echo-nginx-module#echo_location), [echo\_location\_async](http://github.com/openresty/echo-nginx-module#echo_location_async), [echo\_subrequest](http://github.com/openresty/echo-nginx-module#echo_subrequest), or [echo\_subrequest\_async](http://github.com/openresty/echo-nginx-module#echo_subrequest_async) directives. ``` location /foo { content_by_lua_block { res = ngx.location.capture("/bar") } } location /bar { echo_location /blah; } location /blah { echo "Success!"; } ``` ``` $ curl -i http://example.com/foo ``` will not work as expected. ### Cosockets Not Available Everywhere Due to internal limitations in the nginx core, the cosocket API is disabled in the following contexts: [set\_by\_lua\*](#set_by_lua), [log\_by\_lua\*](#log_by_lua), [header\_filter\_by\_lua\*](#header_filter_by_lua), and [body\_filter\_by\_lua](#body_filter_by_lua). The cosockets are currently also disabled in the [init\_by\_lua\*](#init_by_lua) and [init\_worker\_by\_lua\*](#init_worker_by_lua) directive contexts but we may add support for these contexts in the future because there is no limitation in the nginx core (or the limitation might be worked around). There exists a work-around, however, when the original context does *not* need to wait for the cosocket results. That is, creating a zero-delay timer via the [ngx.timer.at](#ngxtimerat) API and do the cosocket results in the timer handler, which runs asynchronously as to the original context creating the timer. ### Special Escaping Sequences **NOTE** Following the `v0.9.17` release, this pitfall can be avoided by using the `*_by_lua_block {}` configuration directives. PCRE sequences such as `\d`, `\s`, or `\w`, require special attention because in string literals, the backslash character, `\`, is stripped out by both the Lua language parser and by the nginx config file parser before processing if not within a `*_by_lua_block {}` directive. So the following snippet will not work as expected: ``` # nginx.conf ? location /test { ? content_by_lua ' ? local regex = "\d+" -- THIS IS WRONG OUTSIDE OF A *_by_lua_block DIRECTIVE ? local m = ngx.re.match("hello, 1234", regex) ? if m then ngx.say(m[0]) else ngx.say("not matched!") end ? '; ? } # evaluates to "not matched!" ``` To avoid this, *double* escape the backslash: ``` # nginx.conf location /test { content_by_lua ' local regex = "\\\\d+" local m = ngx.re.match("hello, 1234", regex) if m then ngx.say(m[0]) else ngx.say("not matched!") end '; } # evaluates to "1234" ``` Here, `\\\\d+` is stripped down to `\\d+` by the Nginx config file parser and this is further stripped down to `\d+` by the Lua language parser before running. Alternatively, the regex pattern can be presented as a long-bracketed Lua string literal by encasing it in "long brackets", `[[...]]`, in which case backslashes have to only be escaped once for the Nginx config file parser. ``` # nginx.conf location /test { content_by_lua ' local regex = [[\\d+]] local m = ngx.re.match("hello, 1234", regex) if m then ngx.say(m[0]) else ngx.say("not matched!") end '; } # evaluates to "1234" ``` Here, `[[\\d+]]` is stripped down to `[[\d+]]` by the Nginx config file parser and this is processed correctly. Note that a longer from of the long bracket, `[=[...]=]`, may be required if the regex pattern contains `[...]` sequences. The `[=[...]=]` form may be used as the default form if desired. ``` # nginx.conf location /test { content_by_lua ' local regex = [=[[0-9]+]=] local m = ngx.re.match("hello, 1234", regex) if m then ngx.say(m[0]) else ngx.say("not matched!") end '; } # evaluates to "1234" ``` An alternative approach to escaping PCRE sequences is to ensure that Lua code is placed in external script files and executed using the various `*_by_lua_file` directives. With this approach, the backslashes are only stripped by the Lua language parser and therefore only need to be escaped once each. ``` -- test.lua local regex = "\\d+" local m = ngx.re.match("hello, 1234", regex) if m then ngx.say(m[0]) else ngx.say("not matched!") end -- evaluates to "1234" ``` Within external script files, PCRE sequences presented as long-bracketed Lua string literals do not require modification. ``` -- test.lua local regex = [[\d+]] local m = ngx.re.match("hello, 1234", regex) if m then ngx.say(m[0]) else ngx.say("not matched!") end -- evaluates to "1234" ``` As noted earlier, PCRE sequences presented within `*_by_lua_block {}` directives (available following the `v0.9.17` release) do not require modification. ``` # nginx.conf location /test { content_by_lua_block { local regex = [[\d+]] local m = ngx.re.match("hello, 1234", regex) if m then ngx.say(m[0]) else ngx.say("not matched!") end } } # evaluates to "1234" ``` ### Mixing with SSI Not Supported Mixing SSI with ngx\_lua in the same Nginx request is not supported at all. Just use ngx\_lua exclusively. Everything you can do with SSI can be done atop ngx\_lua anyway and it can be more efficient when using ngx\_lua. ### SPDY Mode Not Fully Supported Certain Lua APIs provided by ngx\_lua do not work in Nginx's SPDY mode yet: [ngx.location.capture](#ngxlocationcapture), [ngx.location.capture\_multi](#ngxlocationcapture_multi), and [ngx.req.socket](#ngxreqsocket). ### Missing data on short circuited requests Nginx may terminate a request early with (at least): * 400 (Bad Request) * 405 (Not Allowed) * 408 (Request Timeout) * 413 (Request Entity Too Large) * 414 (Request URI Too Large) * 494 (Request Headers Too Large) * 499 (Client Closed Request) * 500 (Internal Server Error) * 501 (Not Implemented) This means that phases that normally run are skipped, such as the rewrite or access phase. This also means that later phases that are run regardless, e.g. [log\_by\_lua](#log_by_lua), will not have access to information that is normally set in those phases. TODO ---- * cosocket: implement LuaSocket's unconnected UDP API. * port this module to the "datagram" subsystem of NGINX for implementing general UDP servers instead of HTTP servers in Lua. For example, ``` datagram { server { listen 1953; handler_by_lua_block { -- custom Lua code implementing the special UDP server... } } } ``` * shm: implement a "shared queue API" to complement the existing [shared dict](#lua_shared_dict) API. * cosocket: add support in the context of [init\_by\_lua\*](#init_by_lua). * cosocket: implement the `bind()` method for stream-typed cosockets. * cosocket: pool-based backend concurrency level control: implement automatic `connect` queueing when the backend concurrency exceeds its connection pool limit. * cosocket: review and merge aviramc's [patch](https://github.com/openresty/lua-nginx-module/pull/290) for adding the `bsdrecv` method. * add new API function `ngx.resp.add_header` to emulate the standard `add_header` config directive. * review and apply vadim-pavlov's patch for [ngx.location.capture](#ngxlocationcapture)'s `extra_headers` option * use `ngx_hash_t` to optimize the built-in header look-up process for [ngx.req.set\_header](#ngxreqset_header), [ngx.header.HEADER](#ngxheaderheader), and etc. * add configure options for different strategies of handling the cosocket connection exceeding in the pools. * add directives to run Lua codes when nginx stops. * add `ignore_resp_headers`, `ignore_resp_body`, and `ignore_resp` options to [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture\_multi](#ngxlocationcapture_multi) methods, to allow micro performance tuning on the user side. * add automatic Lua code time slicing support by yielding and resuming the Lua VM actively via Lua's debug hooks. * add `stat` mode similar to [mod\_lua](https://httpd.apache.org/docs/trunk/mod/mod_lua.html). * cosocket: add client SSL certificate support. Changes ------- The changes made in every release of this module are listed in the change logs of the OpenResty bundle: <http://openresty.org/#Changes> Test Suite ---------- The following dependencies are required to run the test suite: * Nginx version >= 1.4.2 * Perl modules: + Test::Nginx: <https://github.com/openresty/test-nginx> * Nginx modules: + [ngx\_devel\_kit](https://github.com/simplresty/ngx_devel_kit) + [ngx\_set\_misc](https://github.com/openresty/set-misc-nginx-module) + [ngx\_auth\_request](http://mdounin.ru/files/ngx_http_auth_request_module-0.2.tar.gz) (this is not needed if you're using Nginx 1.5.4+. + [ngx\_echo](https://github.com/openresty/echo-nginx-module) + [ngx\_memc](https://github.com/openresty/memc-nginx-module) + [ngx\_srcache](https://github.com/openresty/srcache-nginx-module) + ngx\_lua (i.e., this module) + [ngx\_lua\_upstream](https://github.com/openresty/lua-upstream-nginx-module) + [ngx\_headers\_more](https://github.com/openresty/headers-more-nginx-module) + [ngx\_drizzle](https://github.com/openresty/drizzle-nginx-module) + [ngx\_rds\_json](https://github.com/openresty/rds-json-nginx-module) + [ngx\_coolkit](https://github.com/FRiCKLE/ngx_coolkit) + [ngx\_redis2](https://github.com/openresty/redis2-nginx-module) The order in which these modules are added during configuration is important because the position of any filter module in the filtering chain determines the final output, for example. The correct adding order is shown above. * 3rd-party Lua libraries: + [lua-cjson](http://www.kyne.com.au/%7Emark/software/lua-cjson.php) * Applications: + mysql: create database 'ngx\_test', grant all privileges to user 'ngx\_test', password is 'ngx\_test' + memcached: listening on the default port, 11211. + redis: listening on the default port, 6379. See also the [developer build script](https://github.com/openresty/lua-nginx-module/blob/master/util/build.sh) for more details on setting up the testing environment. To run the whole test suite in the default testing mode: ``` cd /path/to/lua-nginx-module export PATH=/path/to/your/nginx/sbin:$PATH prove -I/path/to/test-nginx/lib -r t ``` To run specific test files: ``` cd /path/to/lua-nginx-module export PATH=/path/to/your/nginx/sbin:$PATH prove -I/path/to/test-nginx/lib t/002-content.t t/003-errors.t ``` To run a specific test block in a particular test file, add the line `--- ONLY` to the test block you want to run, and then use the `prove` utility to run that `.t` file. There are also various testing modes based on mockeagain, valgrind, and etc. Refer to the [Test::Nginx documentation](http://search.cpan.org/perldoc?Test::Nginx) for more details for various advanced testing modes. See also the test reports for the Nginx test cluster running on Amazon EC2: <http://qa.openresty.org>. Copyright and License --------------------- This module is licensed under the BSD license. Copyright (C) 2009-2017, by Xiaozhe Wang (chaoslawful) [[email protected]](mailto:[email protected]). Copyright (C) 2009-2018, by Yichun "agentzh" Zhang (章亦春) [[email protected]](mailto:[email protected]), OpenResty Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. See Also -------- * [ngx\_stream\_lua\_module](https://github.com/openresty/stream-lua-nginx-module#readme) for an official port of this module for the NGINX "stream" subsystem (doing generic downstream TCP communications). * [lua-resty-memcached](https://github.com/openresty/lua-resty-memcached) library based on ngx\_lua cosocket. * [lua-resty-redis](https://github.com/openresty/lua-resty-redis) library based on ngx\_lua cosocket. * [lua-resty-mysql](https://github.com/openresty/lua-resty-mysql) library based on ngx\_lua cosocket. * [lua-resty-upload](https://github.com/openresty/lua-resty-upload) library based on ngx\_lua cosocket. * [lua-resty-dns](https://github.com/openresty/lua-resty-dns) library based on ngx\_lua cosocket. * [lua-resty-websocket](https://github.com/openresty/lua-resty-websocket) library for both WebSocket server and client, based on ngx\_lua cosocket. * [lua-resty-string](https://github.com/openresty/lua-resty-string) library based on [LuaJIT FFI](http://luajit.org/ext_ffi.html). * [lua-resty-lock](https://github.com/openresty/lua-resty-lock) library for a nonblocking simple lock API. * [lua-resty-cookie](https://github.com/cloudflare/lua-resty-cookie) library for HTTP cookie manipulation. * [Routing requests to different MySQL queries based on URI arguments](http://openresty.org/#RoutingMySQLQueriesBasedOnURIArgs) * [Dynamic Routing Based on Redis and Lua](http://openresty.org/#DynamicRoutingBasedOnRedis) * [Using LuaRocks with ngx\_lua](http://openresty.org/#UsingLuaRocks) * [Introduction to ngx\_lua](https://github.com/openresty/lua-nginx-module/wiki/Introduction) * [ngx\_devel\_kit](https://github.com/simplresty/ngx_devel_kit) * [echo-nginx-module](http://github.com/openresty/echo-nginx-module) * [drizzle-nginx-module](http://github.com/openresty/drizzle-nginx-module) * [postgres-nginx-module](https://github.com/FRiCKLE/ngx_postgres) * [memc-nginx-module](http://github.com/openresty/memc-nginx-module) * [The OpenResty bundle](http://openresty.org) * [Nginx Systemtap Toolkit](https://github.com/openresty/nginx-systemtap-toolkit) Directives ---------- * [lua\_capture\_error\_log](#lua_capture_error_log) * [lua\_use\_default\_type](#lua_use_default_type) * [lua\_malloc\_trim](#lua_malloc_trim) * [lua\_code\_cache](#lua_code_cache) * [lua\_regex\_cache\_max\_entries](#lua_regex_cache_max_entries) * [lua\_regex\_match\_limit](#lua_regex_match_limit) * [lua\_package\_path](#lua_package_path) * [lua\_package\_cpath](#lua_package_cpath) * [init\_by\_lua](#init_by_lua) * [init\_by\_lua\_block](#init_by_lua_block) * [init\_by\_lua\_file](#init_by_lua_file) * [init\_worker\_by\_lua](#init_worker_by_lua) * [init\_worker\_by\_lua\_block](#init_worker_by_lua_block) * [init\_worker\_by\_lua\_file](#init_worker_by_lua_file) * [set\_by\_lua](#set_by_lua) * [set\_by\_lua\_block](#set_by_lua_block) * [set\_by\_lua\_file](#set_by_lua_file) * [content\_by\_lua](#content_by_lua) * [content\_by\_lua\_block](#content_by_lua_block) * [content\_by\_lua\_file](#content_by_lua_file) * [rewrite\_by\_lua](#rewrite_by_lua) * [rewrite\_by\_lua\_block](#rewrite_by_lua_block) * [rewrite\_by\_lua\_file](#rewrite_by_lua_file) * [access\_by\_lua](#access_by_lua) * [access\_by\_lua\_block](#access_by_lua_block) * [access\_by\_lua\_file](#access_by_lua_file) * [header\_filter\_by\_lua](#header_filter_by_lua) * [header\_filter\_by\_lua\_block](#header_filter_by_lua_block) * [header\_filter\_by\_lua\_file](#header_filter_by_lua_file) * [body\_filter\_by\_lua](#body_filter_by_lua) * [body\_filter\_by\_lua\_block](#body_filter_by_lua_block) * [body\_filter\_by\_lua\_file](#body_filter_by_lua_file) * [log\_by\_lua](#log_by_lua) * [log\_by\_lua\_block](#log_by_lua_block) * [log\_by\_lua\_file](#log_by_lua_file) * [balancer\_by\_lua\_block](#balancer_by_lua_block) * [balancer\_by\_lua\_file](#balancer_by_lua_file) * [lua\_need\_request\_body](#lua_need_request_body) * [ssl\_certificate\_by\_lua\_block](#ssl_certificate_by_lua_block) * [ssl\_certificate\_by\_lua\_file](#ssl_certificate_by_lua_file) * [ssl\_session\_fetch\_by\_lua\_block](#ssl_session_fetch_by_lua_block) * [ssl\_session\_fetch\_by\_lua\_file](#ssl_session_fetch_by_lua_file) * [ssl\_session\_store\_by\_lua\_block](#ssl_session_store_by_lua_block) * [ssl\_session\_store\_by\_lua\_file](#ssl_session_store_by_lua_file) * [lua\_shared\_dict](#lua_shared_dict) * [lua\_socket\_connect\_timeout](#lua_socket_connect_timeout) * [lua\_socket\_send\_timeout](#lua_socket_send_timeout) * [lua\_socket\_send\_lowat](#lua_socket_send_lowat) * [lua\_socket\_read\_timeout](#lua_socket_read_timeout) * [lua\_socket\_buffer\_size](#lua_socket_buffer_size) * [lua\_socket\_pool\_size](#lua_socket_pool_size) * [lua\_socket\_keepalive\_timeout](#lua_socket_keepalive_timeout) * [lua\_socket\_log\_errors](#lua_socket_log_errors) * [lua\_ssl\_ciphers](#lua_ssl_ciphers) * [lua\_ssl\_crl](#lua_ssl_crl) * [lua\_ssl\_protocols](#lua_ssl_protocols) * [lua\_ssl\_trusted\_certificate](#lua_ssl_trusted_certificate) * [lua\_ssl\_verify\_depth](#lua_ssl_verify_depth) * [lua\_http10\_buffering](#lua_http10_buffering) * [rewrite\_by\_lua\_no\_postpone](#rewrite_by_lua_no_postpone) * [access\_by\_lua\_no\_postpone](#access_by_lua_no_postpone) * [lua\_transform\_underscores\_in\_response\_headers](#lua_transform_underscores_in_response_headers) * [lua\_check\_client\_abort](#lua_check_client_abort) * [lua\_max\_pending\_timers](#lua_max_pending_timers) * [lua\_max\_running\_timers](#lua_max_running_timers) The basic building blocks of scripting Nginx with Lua are directives. Directives are used to specify when the user Lua code is run and how the result will be used. Below is a diagram showing the order in which directives are executed. ### lua\_capture\_error\_log **syntax:** *lua\_capture\_error\_log size* **default:** *none* **context:** *http* Enables a buffer of the specified `size` for capturing all the nginx error log message data (not just those produced by this module or the nginx http subsystem, but everything) without touching files or disks. You can use units like `k` and `m` in the `size` value, as in ``` lua_capture_error_log 100k; ``` As a rule of thumb, a 4KB buffer can usually hold about 20 typical error log messages. So do the maths! This buffer never grows. If it is full, new error log messages will replace the oldest ones in the buffer. The size of the buffer must be bigger than the maximum length of a single error log message (which is 4K in OpenResty and 2K in stock NGINX). You can read the messages in the buffer on the Lua land via the [get\_logs()](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#get_logs) function of the [ngx.errlog](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#readme) module of the [lua-resty-core](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#readme) library. This Lua API function will return the captured error log messages and also remove these already read from the global capturing buffer, making room for any new error log data. For this reason, the user should not configure this buffer to be too big if the user read the buffered error log data fast enough. Note that the log level specified in the standard [error\_log](http://nginx.org/r/error_log) directive *does* have effect on this capturing facility. It only captures log messages of a level no lower than the specified log level in the [error\_log](http://nginx.org/r/error_log) directive. The user can still choose to set an even higher filtering log level on the fly via the Lua API function [errlog.set\_filter\_level](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#set_filter_level). So it is more flexible than the static [error\_log](http://nginx.org/r/error_log) directive. It is worth noting that there is no way to capture the debugging logs without building OpenResty or NGINX with the `./configure` option `--with-debug`. And enabling debugging logs is strongly discouraged in production builds due to high overhead. This directive was first introduced in the `v0.10.9` release. ### lua\_use\_default\_type **syntax:** *lua\_use\_default\_type on | off* **default:** *lua\_use\_default\_type on* **context:** *http, server, location, location if* Specifies whether to use the MIME type specified by the [default\_type](http://nginx.org/en/docs/http/ngx_http_core_module.html#default_type) directive for the default value of the `Content-Type` response header. Deactivate this directive if a default `Content-Type` response header for Lua request handlers is not desired. This directive is turned on by default. This directive was first introduced in the `v0.9.1` release. ### lua\_malloc\_trim **syntax:** *lua\_malloc\_trim <request-count>* **default:** *lua\_malloc\_trim 1000* **context:** *http* Asks the underlying `libc` runtime library to release its cached free memory back to the operating system every `N` requests processed by the NGINX core. By default, `N` is 1000. You can configure the request count by using your own numbers. Smaller numbers mean more frequent releases, which may introduce higher CPU time consumption and smaller memory footprint while larger numbers usually lead to less CPU time overhead and relatively larger memory footprint. Just tune the number for your own use cases. Configuring the argument to `0` essentially turns off the periodical memory trimming altogether. ``` lua_malloc_trim 0; # turn off trimming completely ``` The current implementation uses an NGINX log phase handler to do the request counting. So the appearance of the [log\_subrequest on](http://nginx.org/en/docs/http/ngx_http_core_module.html#log_subrequest) directives in `nginx.conf` may make the counting faster when subrequests are involved. By default, only "main requests" count. Note that this directive does *not* affect the memory allocated by LuaJIT's own allocator based on the `mmap` system call. This directive was first introduced in the `v0.10.7` release. ### lua\_code\_cache **syntax:** *lua\_code\_cache on | off* **default:** *lua\_code\_cache on* **context:** *http, server, location, location if* Enables or disables the Lua code cache for Lua code in `*_by_lua_file` directives (like [set\_by\_lua\_file](#set_by_lua_file) and [content\_by\_lua\_file](#content_by_lua_file)) and Lua modules. When turning off, every request served by ngx\_lua will run in a separate Lua VM instance, starting from the `0.9.3` release. So the Lua files referenced in [set\_by\_lua\_file](#set_by_lua_file), [content\_by\_lua\_file](#content_by_lua_file), [access\_by\_lua\_file](#access_by_lua_file), and etc will not be cached and all Lua modules used will be loaded from scratch. With this in place, developers can adopt an edit-and-refresh approach. Please note however, that Lua code written inlined within nginx.conf such as those specified by [set\_by\_lua](#set_by_lua), [content\_by\_lua](#content_by_lua), [access\_by\_lua](#access_by_lua), and [rewrite\_by\_lua](#rewrite_by_lua) will not be updated when you edit the inlined Lua code in your `nginx.conf` file because only the Nginx config file parser can correctly parse the `nginx.conf` file and the only way is to reload the config file by sending a `HUP` signal or just to restart Nginx. Even when the code cache is enabled, Lua files which are loaded by `dofile` or `loadfile` in \*\_by\_lua\_file cannot be cached (unless you cache the results yourself). Usually you can either use the [init\_by\_lua](#init_by_lua) or [init\_by\_lua\_file](#init-by_lua_file) directives to load all such files or just make these Lua files true Lua modules and load them via `require`. The ngx\_lua module does not support the `stat` mode available with the Apache `mod_lua` module (yet). Disabling the Lua code cache is strongly discouraged for production use and should only be used during development as it has a significant negative impact on overall performance. For example, the performance of a "hello world" Lua example can drop by an order of magnitude after disabling the Lua code cache. ### lua\_regex\_cache\_max\_entries **syntax:** *lua\_regex\_cache\_max\_entries <num>* **default:** *lua\_regex\_cache\_max\_entries 1024* **context:** *http* Specifies the maximum number of entries allowed in the worker process level compiled regex cache. The regular expressions used in [ngx.re.match](#ngxrematch), [ngx.re.gmatch](#ngxregmatch), [ngx.re.sub](#ngxresub), and [ngx.re.gsub](#ngxregsub) will be cached within this cache if the regex option `o` (i.e., compile-once flag) is specified. The default number of entries allowed is 1024 and when this limit is reached, new regular expressions will not be cached (as if the `o` option was not specified) and there will be one, and only one, warning in the `error.log` file: ``` 2011/08/27 23:18:26 [warn] 31997#0: *1 lua exceeding regex cache max entries (1024), ... ``` If you are using the `ngx.re.*` implementation of [lua-resty-core](https://github.com/openresty/lua-resty-core) by loading the `resty.core.regex` module (or just the `resty.core` module), then an LRU cache is used for the regex cache being used here. Do not activate the `o` option for regular expressions (and/or `replace` string arguments for [ngx.re.sub](#ngxresub) and [ngx.re.gsub](#ngxregsub)) that are generated *on the fly* and give rise to infinite variations to avoid hitting the specified limit. ### lua\_regex\_match\_limit **syntax:** *lua\_regex\_match\_limit <num>* **default:** *lua\_regex\_match\_limit 0* **context:** *http* Specifies the "match limit" used by the PCRE library when executing the [ngx.re API](#ngxrematch). To quote the PCRE manpage, "the limit ... has the effect of limiting the amount of backtracking that can take place." When the limit is hit, the error string "pcre\_exec() failed: -8" will be returned by the [ngx.re API](#ngxrematch) functions on the Lua land. When setting the limit to 0, the default "match limit" when compiling the PCRE library is used. And this is the default value of this directive. This directive was first introduced in the `v0.8.5` release. ### lua\_package\_path **syntax:** *lua\_package\_path <lua-style-path-str>* **default:** *The content of LUA\_PATH environment variable or Lua's compiled-in defaults.* **context:** *http* Sets the Lua module search path used by scripts specified by [set\_by\_lua](#set_by_lua), [content\_by\_lua](#content_by_lua) and others. The path string is in standard Lua path form, and `;;` can be used to stand for the original search paths. As from the `v0.5.0rc29` release, the special notation `$prefix` or `${prefix}` can be used in the search path string to indicate the path of the `server prefix` usually determined by the `-p PATH` command-line option while starting the Nginx server. ### lua\_package\_cpath **syntax:** *lua\_package\_cpath <lua-style-cpath-str>* **default:** *The content of LUA\_CPATH environment variable or Lua's compiled-in defaults.* **context:** *http* Sets the Lua C-module search path used by scripts specified by [set\_by\_lua](#set_by_lua), [content\_by\_lua](#content_by_lua) and others. The cpath string is in standard Lua cpath form, and `;;` can be used to stand for the original cpath. As from the `v0.5.0rc29` release, the special notation `$prefix` or `${prefix}` can be used in the search path string to indicate the path of the `server prefix` usually determined by the `-p PATH` command-line option while starting the Nginx server. ### init\_by\_lua **syntax:** *init\_by\_lua <lua-script-str>* **context:** *http* **phase:** *loading-config* **NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [init\_by\_lua\_block](#init_by_lua_block) directive instead. Runs the Lua code specified by the argument `<lua-script-str>` on the global Lua VM level when the Nginx master process (if any) is loading the Nginx config file. When Nginx receives the `HUP` signal and starts reloading the config file, the Lua VM will also be re-created and `init_by_lua` will run again on the new Lua VM. In case that the [lua\_code\_cache](#lua_code_cache) directive is turned off (default on), the `init_by_lua` handler will run upon every request because in this special mode a standalone Lua VM is always created for each request. Usually you can pre-load Lua modules at server start-up by means of this hook and take advantage of modern operating systems' copy-on-write (COW) optimization. Here is an example for pre-loading Lua modules: ``` # this runs before forking out nginx worker processes: init_by_lua_block { require "cjson" } server { location = /api { content_by_lua_block { -- the following require() will just return -- the alrady loaded module from package.loaded: ngx.say(require "cjson".encode{dog = 5, cat = 6}) } } } ``` You can also initialize the [lua\_shared\_dict](#lua_shared_dict) shm storage at this phase. Here is an example for this: ``` lua_shared_dict dogs 1m; init_by_lua_block { local dogs = ngx.shared.dogs; dogs:set("Tom", 56) } server { location = /api { content_by_lua_block { local dogs = ngx.shared.dogs; ngx.say(dogs:get("Tom")) } } } ``` But note that, the [lua\_shared\_dict](#lua_shared_dict)'s shm storage will not be cleared through a config reload (via the `HUP` signal, for example). So if you do *not* want to re-initialize the shm storage in your `init_by_lua` code in this case, then you just need to set a custom flag in the shm storage and always check the flag in your `init_by_lua` code. Because the Lua code in this context runs before Nginx forks its worker processes (if any), data or code loaded here will enjoy the [Copy-on-write (COW)](http://en.wikipedia.org/wiki/Copy-on-write) feature provided by many operating systems among all the worker processes, thus saving a lot of memory. Do *not* initialize your own Lua global variables in this context because use of Lua global variables have performance penalties and can lead to global namespace pollution (see the [Lua Variable Scope](#lua-variable-scope) section for more details). The recommended way is to use proper [Lua module](http://www.lua.org/manual/5.1/manual.html#5.3) files (but do not use the standard Lua function [module()](http://www.lua.org/manual/5.1/manual.html#pdf-module) to define Lua modules because it pollutes the global namespace as well) and call [require()](http://www.lua.org/manual/5.1/manual.html#pdf-require) to load your own module files in `init_by_lua` or other contexts ([require()](http://www.lua.org/manual/5.1/manual.html#pdf-require) does cache the loaded Lua modules in the global `package.loaded` table in the Lua registry so your modules will only loaded once for the whole Lua VM instance). Only a small set of the [Nginx API for Lua](#nginx-api-for-lua) is supported in this context: * Logging APIs: [ngx.log](#ngxlog) and [print](#print), * Shared Dictionary API: [ngx.shared.DICT](#ngxshareddict). More Nginx APIs for Lua may be supported in this context upon future user requests. Basically you can safely use Lua libraries that do blocking I/O in this very context because blocking the master process during server start-up is completely okay. Even the Nginx core does blocking I/O (at least on resolving upstream's host names) at the configure-loading phase. You should be very careful about potential security vulnerabilities in your Lua code registered in this context because the Nginx master process is often run under the `root` account. This directive was first introduced in the `v0.5.5` release. ### init\_by\_lua\_block **syntax:** *init\_by\_lua\_block { lua-script }* **context:** *http* **phase:** *loading-config* Similar to the [init\_by\_lua](#init_by_lua) directive except that this directive inlines the Lua source directly inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires special character escaping). For instance, ``` init_by_lua_block { print("I need no extra escaping here, for example: \r\nblah") } ``` This directive was first introduced in the `v0.9.17` release. ### init\_by\_lua\_file **syntax:** *init\_by\_lua\_file <path-to-lua-script-file>* **context:** *http* **phase:** *loading-config* Equivalent to [init\_by\_lua](#init_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code or [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. This directive was first introduced in the `v0.5.5` release. ### init\_worker\_by\_lua **syntax:** *init\_worker\_by\_lua <lua-script-str>* **context:** *http* **phase:** *starting-worker* **NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [init\_worker\_by\_lua\_block](#init_worker_by_lua_block) directive instead. Runs the specified Lua code upon every Nginx worker process's startup when the master process is enabled. When the master process is disabled, this hook will just run after [init\_by\_lua\*](#init_by_lua). This hook is often used to create per-worker reoccurring timers (via the [ngx.timer.at](#ngxtimerat) Lua API), either for backend health-check or other timed routine work. Below is an example, ``` init_worker_by_lua ' local delay = 3 -- in seconds local new_timer = ngx.timer.at local log = ngx.log local ERR = ngx.ERR local check check = function(premature) if not premature then -- do the health check or other routine work local ok, err = new_timer(delay, check) if not ok then log(ERR, "failed to create timer: ", err) return end end end local hdl, err = new_timer(delay, check) if not hdl then log(ERR, "failed to create timer: ", err) return end '; ``` This directive was first introduced in the `v0.9.5` release. This hook no longer runs in the cache manager and cache loader processes since the `v0.10.12` release. ### init\_worker\_by\_lua\_block **syntax:** *init\_worker\_by\_lua\_block { lua-script }* **context:** *http* **phase:** *starting-worker* Similar to the [init\_worker\_by\_lua](#init_worker_by_lua) directive except that this directive inlines the Lua source directly inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires special character escaping). For instance, ``` init_worker_by_lua_block { print("I need no extra escaping here, for example: \r\nblah") } ``` This directive was first introduced in the `v0.9.17` release. This hook no longer runs in the cache manager and cache loader processes since the `v0.10.12` release. ### init\_worker\_by\_lua\_file **syntax:** *init\_worker\_by\_lua\_file <lua-file-path>* **context:** *http* **phase:** *starting-worker* Similar to [init\_worker\_by\_lua](#init_worker_by_lua), but accepts the file path to a Lua source file or Lua bytecode file. This directive was first introduced in the `v0.9.5` release. This hook no longer runs in the cache manager and cache loader processes since the `v0.10.12` release. ### set\_by\_lua **syntax:** *set\_by\_lua $res <lua-script-str> [$arg1 $arg2 ...]* **context:** *server, server if, location, location if* **phase:** *rewrite* **NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [set\_by\_lua\_block](#set_by_lua_block) directive instead. Executes code specified in `<lua-script-str>` with optional input arguments `$arg1 $arg2 ...`, and returns string output to `$res`. The code in `<lua-script-str>` can make [API calls](#nginx-api-for-lua) and can retrieve input arguments from the `ngx.arg` table (index starts from `1` and increases sequentially). This directive is designed to execute short, fast running code blocks as the Nginx event loop is blocked during code execution. Time consuming code sequences should therefore be avoided. This directive is implemented by injecting custom commands into the standard [ngx\_http\_rewrite\_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html)'s command list. Because [ngx\_http\_rewrite\_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html) does not support nonblocking I/O in its commands, Lua APIs requiring yielding the current Lua "light thread" cannot work in this directive. At least the following API functions are currently disabled within the context of `set_by_lua`: * Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send\_headers](#ngxsend_headers)) * Control API functions (e.g., [ngx.exit](#ngxexit)) * Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture\_multi](#ngxlocationcapture_multi)) * Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)). * Sleeping API function [ngx.sleep](#ngxsleep). In addition, note that this directive can only write out a value to a single Nginx variable at a time. However, a workaround is possible using the [ngx.var.VARIABLE](#ngxvarvariable) interface. ``` location /foo { set $diff ''; # we have to predefine the $diff variable here set_by_lua $sum ' local a = 32 local b = 56 ngx.var.diff = a - b; -- write to $diff directly return a + b; -- return the $sum value normally '; echo "sum = $sum, diff = $diff"; } ``` This directive can be freely mixed with all directives of the [ngx\_http\_rewrite\_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html), [set-misc-nginx-module](http://github.com/openresty/set-misc-nginx-module), and [array-var-nginx-module](http://github.com/openresty/array-var-nginx-module) modules. All of these directives will run in the same order as they appear in the config file. ``` set $foo 32; set_by_lua $bar 'return tonumber(ngx.var.foo) + 1'; set $baz "bar: $bar"; # $baz == "bar: 33" ``` As from the `v0.5.0rc29` release, Nginx variable interpolation is disabled in the `<lua-script-str>` argument of this directive and therefore, the dollar sign character (`$`) can be used directly. This directive requires the [ngx\_devel\_kit](https://github.com/simplresty/ngx_devel_kit) module. ### set\_by\_lua\_block **syntax:** *set\_by\_lua\_block $res { lua-script }* **context:** *server, server if, location, location if* **phase:** *rewrite* Similar to the [set\_by\_lua](#set_by_lua) directive except that 1. this directive inlines the Lua source directly inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires special character escaping), and 2. this directive does not support extra arguments after the Lua script as in [set\_by\_lua](#set_by_lua). For example, ``` set_by_lua_block $res { return 32 + math.cos(32) } # $res now has the value "32.834223360507" or alike. ``` No special escaping is required in the Lua code block. This directive was first introduced in the `v0.9.17` release. ### set\_by\_lua\_file **syntax:** *set\_by\_lua\_file $res <path-to-lua-script-file> [$arg1 $arg2 ...]* **context:** *server, server if, location, location if* **phase:** *rewrite* Equivalent to [set\_by\_lua](#set_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. Nginx variable interpolation is supported in the `<path-to-lua-script-file>` argument string of this directive. But special care must be taken for injection attacks. When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached and the Nginx config must be reloaded each time the Lua source file is modified. The Lua code cache can be temporarily disabled during development by switching [lua\_code\_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx. This directive requires the [ngx\_devel\_kit](https://github.com/simplresty/ngx_devel_kit) module. ### content\_by\_lua **syntax:** *content\_by\_lua <lua-script-str>* **context:** *location, location if* **phase:** *content* **NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [content\_by\_lua\_block](#content_by_lua_block) directive instead. Acts as a "content handler" and executes Lua code string specified in `<lua-script-str>` for every request. The Lua code may make [API calls](#nginx-api-for-lua) and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox). Do not use this directive and other content handler directives in the same location. For example, this directive and the [proxy\_pass](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass) directive should not be used in the same location. ### content\_by\_lua\_block **syntax:** *content\_by\_lua\_block { lua-script }* **context:** *location, location if* **phase:** *content* Similar to the [content\_by\_lua](#content_by_lua) directive except that this directive inlines the Lua source directly inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires special character escaping). For instance, ``` content_by_lua_block { ngx.say("I need no extra escaping here, for example: \r\nblah") } ``` This directive was first introduced in the `v0.9.17` release. ### content\_by\_lua\_file **syntax:** *content\_by\_lua\_file <path-to-lua-script-file>* **context:** *location, location if* **phase:** *content* Equivalent to [content\_by\_lua](#content_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. Nginx variables can be used in the `<path-to-lua-script-file>` string to provide flexibility. This however carries some risks and is not ordinarily recommended. When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached and the Nginx config must be reloaded each time the Lua source file is modified. The Lua code cache can be temporarily disabled during development by switching [lua\_code\_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx. Nginx variables are supported in the file path for dynamic dispatch, for example: ``` # CAUTION: contents in nginx var must be carefully filtered, # otherwise there'll be great security risk! location ~ ^/app/([-_a-zA-Z0-9/]+) { set $path $1; content_by_lua_file /path/to/lua/app/root/$path.lua; } ``` But be very careful about malicious user inputs and always carefully validate or filter out the user-supplied path components. ### rewrite\_by\_lua **syntax:** *rewrite\_by\_lua <lua-script-str>* **context:** *http, server, location, location if* **phase:** *rewrite tail* **NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [rewrite\_by\_lua\_block](#rewrite_by_lua_block) directive instead. Acts as a rewrite phase handler and executes Lua code string specified in `<lua-script-str>` for every request. The Lua code may make [API calls](#nginx-api-for-lua) and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox). Note that this handler always runs *after* the standard [ngx\_http\_rewrite\_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html). So the following will work as expected: ``` location /foo { set $a 12; # create and initialize $a set $b ""; # create and initialize $b rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1'; echo "res = $b"; } ``` because `set $a 12` and `set $b ""` run *before* [rewrite\_by\_lua](#rewrite_by_lua). On the other hand, the following will not work as expected: ``` ? location /foo { ? set $a 12; # create and initialize $a ? set $b ''; # create and initialize $b ? rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1'; ? if ($b = '13') { ? rewrite ^ /bar redirect; ? break; ? } ? ? echo "res = $b"; ? } ``` because `if` runs *before* [rewrite\_by\_lua](#rewrite_by_lua) even if it is placed after [rewrite\_by\_lua](#rewrite_by_lua) in the config. The right way of doing this is as follows: ``` location /foo { set $a 12; # create and initialize $a set $b ''; # create and initialize $b rewrite_by_lua ' ngx.var.b = tonumber(ngx.var.a) + 1 if tonumber(ngx.var.b) == 13 then return ngx.redirect("/bar"); end '; echo "res = $b"; } ``` Note that the [ngx\_eval](http://www.grid.net.ru/nginx/eval.en.html) module can be approximated by using [rewrite\_by\_lua](#rewrite_by_lua). For example, ``` location / { eval $res { proxy_pass http://foo.com/check-spam; } if ($res = 'spam') { rewrite ^ /terms-of-use.html redirect; } fastcgi_pass ...; } ``` can be implemented in ngx\_lua as: ``` location = /check-spam { internal; proxy_pass http://foo.com/check-spam; } location / { rewrite_by_lua ' local res = ngx.location.capture("/check-spam") if res.body == "spam" then return ngx.redirect("/terms-of-use.html") end '; fastcgi_pass ...; } ``` Just as any other rewrite phase handlers, [rewrite\_by\_lua](#rewrite_by_lua) also runs in subrequests. Note that when calling `ngx.exit(ngx.OK)` within a [rewrite\_by\_lua](#rewrite_by_lua) handler, the nginx request processing control flow will still continue to the content handler. To terminate the current request from within a [rewrite\_by\_lua](#rewrite_by_lua) handler, calling [ngx.exit](#ngxexit) with status >= 200 (`ngx.HTTP_OK`) and status < 300 (`ngx.HTTP_SPECIAL_RESPONSE`) for successful quits and `ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)` (or its friends) for failures. If the [ngx\_http\_rewrite\_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html)'s [rewrite](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite) directive is used to change the URI and initiate location re-lookups (internal redirections), then any [rewrite\_by\_lua](#rewrite_by_lua) or [rewrite\_by\_lua\_file](#rewrite_by_lua_file) code sequences within the current location will not be executed. For example, ``` location /foo { rewrite ^ /bar; rewrite_by_lua 'ngx.exit(503)'; } location /bar { ... } ``` Here the Lua code `ngx.exit(503)` will never run. This will be the case if `rewrite ^ /bar last` is used as this will similarly initiate an internal redirection. If the `break` modifier is used instead, there will be no internal redirection and the `rewrite_by_lua` code will be executed. The `rewrite_by_lua` code will always run at the end of the `rewrite` request-processing phase unless [rewrite\_by\_lua\_no\_postpone](#rewrite_by_lua_no_postpone) is turned on. ### rewrite\_by\_lua\_block **syntax:** *rewrite\_by\_lua\_block { lua-script }* **context:** *http, server, location, location if* **phase:** *rewrite tail* Similar to the [rewrite\_by\_lua](#rewrite_by_lua) directive except that this directive inlines the Lua source directly inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires special character escaping). For instance, ``` rewrite_by_lua_block { do_something("hello, world!\nhiya\n") } ``` This directive was first introduced in the `v0.9.17` release. ### rewrite\_by\_lua\_file **syntax:** *rewrite\_by\_lua\_file <path-to-lua-script-file>* **context:** *http, server, location, location if* **phase:** *rewrite tail* Equivalent to [rewrite\_by\_lua](#rewrite_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. Nginx variables can be used in the `<path-to-lua-script-file>` string to provide flexibility. This however carries some risks and is not ordinarily recommended. When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached and the Nginx config must be reloaded each time the Lua source file is modified. The Lua code cache can be temporarily disabled during development by switching [lua\_code\_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx. The `rewrite_by_lua_file` code will always run at the end of the `rewrite` request-processing phase unless [rewrite\_by\_lua\_no\_postpone](#rewrite_by_lua_no_postpone) is turned on. Nginx variables are supported in the file path for dynamic dispatch just as in [content\_by\_lua\_file](#content_by_lua_file). ### access\_by\_lua **syntax:** *access\_by\_lua <lua-script-str>* **context:** *http, server, location, location if* **phase:** *access tail* **NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [access\_by\_lua\_block](#access_by_lua_block) directive instead. Acts as an access phase handler and executes Lua code string specified in `<lua-script-str>` for every request. The Lua code may make [API calls](#nginx-api-for-lua) and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox). Note that this handler always runs *after* the standard [ngx\_http\_access\_module](http://nginx.org/en/docs/http/ngx_http_access_module.html). So the following will work as expected: ``` location / { deny 192.168.1.1; allow 192.168.1.0/24; allow 10.1.1.0/16; deny all; access_by_lua ' local res = ngx.location.capture("/mysql", { ... }) ... '; # proxy_pass/fastcgi_pass/... } ``` That is, if a client IP address is in the blacklist, it will be denied before the MySQL query for more complex authentication is executed by [access\_by\_lua](#access_by_lua). Note that the [ngx\_auth\_request](http://mdounin.ru/hg/ngx_http_auth_request_module/) module can be approximated by using [access\_by\_lua](#access_by_lua): ``` location / { auth_request /auth; # proxy_pass/fastcgi_pass/postgres_pass/... } ``` can be implemented in ngx\_lua as: ``` location / { access_by_lua ' local res = ngx.location.capture("/auth") if res.status == ngx.HTTP_OK then return end if res.status == ngx.HTTP_FORBIDDEN then ngx.exit(res.status) end ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) '; # proxy_pass/fastcgi_pass/postgres_pass/... } ``` As with other access phase handlers, [access\_by\_lua](#access_by_lua) will *not* run in subrequests. Note that when calling `ngx.exit(ngx.OK)` within a [access\_by\_lua](#access_by_lua) handler, the nginx request processing control flow will still continue to the content handler. To terminate the current request from within a [access\_by\_lua](#access_by_lua) handler, calling [ngx.exit](#ngxexit) with status >= 200 (`ngx.HTTP_OK`) and status < 300 (`ngx.HTTP_SPECIAL_RESPONSE`) for successful quits and `ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)` (or its friends) for failures. Starting from the `v0.9.20` release, you can use the [access\_by\_lua\_no\_postpone](#access_by_lua_no_postpone) directive to control when to run this handler inside the "access" request-processing phase of NGINX. ### access\_by\_lua\_block **syntax:** *access\_by\_lua\_block { lua-script }* **context:** *http, server, location, location if* **phase:** *access tail* Similar to the [access\_by\_lua](#access_by_lua) directive except that this directive inlines the Lua source directly inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires special character escaping). For instance, ``` access_by_lua_block { do_something("hello, world!\nhiya\n") } ``` This directive was first introduced in the `v0.9.17` release. ### access\_by\_lua\_file **syntax:** *access\_by\_lua\_file <path-to-lua-script-file>* **context:** *http, server, location, location if* **phase:** *access tail* Equivalent to [access\_by\_lua](#access_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. Nginx variables can be used in the `<path-to-lua-script-file>` string to provide flexibility. This however carries some risks and is not ordinarily recommended. When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached and the Nginx config must be reloaded each time the Lua source file is modified. The Lua code cache can be temporarily disabled during development by switching [lua\_code\_cache](#lua_code_cache) `off` in `nginx.conf` to avoid repeatedly reloading Nginx. Nginx variables are supported in the file path for dynamic dispatch just as in [content\_by\_lua\_file](#content_by_lua_file). ### header\_filter\_by\_lua **syntax:** *header\_filter\_by\_lua <lua-script-str>* **context:** *http, server, location, location if* **phase:** *output-header-filter* **NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [header\_filter\_by\_lua\_block](#header_filter_by_lua_block) directive instead. Uses Lua code specified in `<lua-script-str>` to define an output header filter. Note that the following API functions are currently disabled within this context: * Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send\_headers](#ngxsend_headers)) * Control API functions (e.g., [ngx.redirect](#ngxredirect) and [ngx.exec](#ngxexec)) * Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture\_multi](#ngxlocationcapture_multi)) * Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)). Here is an example of overriding a response header (or adding one if absent) in our Lua header filter: ``` location / { proxy_pass http://mybackend; header_filter_by_lua 'ngx.header.Foo = "blah"'; } ``` This directive was first introduced in the `v0.2.1rc20` release. ### header\_filter\_by\_lua\_block **syntax:** *header\_filter\_by\_lua\_block { lua-script }* **context:** *http, server, location, location if* **phase:** *output-header-filter* Similar to the [header\_filter\_by\_lua](#header_filter_by_lua) directive except that this directive inlines the Lua source directly inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires special character escaping). For instance, ``` header_filter_by_lua_block { ngx.header["content-length"] = nil } ``` This directive was first introduced in the `v0.9.17` release. ### header\_filter\_by\_lua\_file **syntax:** *header\_filter\_by\_lua\_file <path-to-lua-script-file>* **context:** *http, server, location, location if* **phase:** *output-header-filter* Equivalent to [header\_filter\_by\_lua](#header_filter_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. This directive was first introduced in the `v0.2.1rc20` release. ### body\_filter\_by\_lua **syntax:** *body\_filter\_by\_lua <lua-script-str>* **context:** *http, server, location, location if* **phase:** *output-body-filter* **NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [body\_filter\_by\_lua\_block](#body_filter_by_lua_block) directive instead. Uses Lua code specified in `<lua-script-str>` to define an output body filter. The input data chunk is passed via [ngx.arg](#ngxarg)[1] (as a Lua string value) and the "eof" flag indicating the end of the response body data stream is passed via [ngx.arg](#ngxarg)[2] (as a Lua boolean value). Behind the scene, the "eof" flag is just the `last_buf` (for main requests) or `last_in_chain` (for subrequests) flag of the Nginx chain link buffers. (Before the `v0.7.14` release, the "eof" flag does not work at all in subrequests.) The output data stream can be aborted immediately by running the following Lua statement: ``` return ngx.ERROR ``` This will truncate the response body and usually result in incomplete and also invalid responses. The Lua code can pass its own modified version of the input data chunk to the downstream Nginx output body filters by overriding [ngx.arg](#ngxarg)[1] with a Lua string or a Lua table of strings. For example, to transform all the lowercase letters in the response body, we can just write: ``` location / { proxy_pass http://mybackend; body_filter_by_lua 'ngx.arg[1] = string.upper(ngx.arg[1])'; } ``` When setting `nil` or an empty Lua string value to `ngx.arg[1]`, no data chunk will be passed to the downstream Nginx output filters at all. Likewise, new "eof" flag can also be specified by setting a boolean value to [ngx.arg](#ngxarg)[2]. For example, ``` location /t { echo hello world; echo hiya globe; body_filter_by_lua ' local chunk = ngx.arg[1] if string.match(chunk, "hello") then ngx.arg[2] = true -- new eof return end -- just throw away any remaining chunk data ngx.arg[1] = nil '; } ``` Then `GET /t` will just return the output ``` hello world ``` That is, when the body filter sees a chunk containing the word "hello", then it will set the "eof" flag to true immediately, resulting in truncated but still valid responses. When the Lua code may change the length of the response body, then it is required to always clear out the `Content-Length` response header (if any) in a header filter to enforce streaming output, as in ``` location /foo { # fastcgi_pass/proxy_pass/... header_filter_by_lua_block { ngx.header.content_length = nil } body_filter_by_lua 'ngx.arg[1] = string.len(ngx.arg[1]) .. "\\n"'; } ``` Note that the following API functions are currently disabled within this context due to the limitations in NGINX output filter's current implementation: * Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send\_headers](#ngxsend_headers)) * Control API functions (e.g., [ngx.exit](#ngxexit) and [ngx.exec](#ngxexec)) * Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture\_multi](#ngxlocationcapture_multi)) * Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)). Nginx output filters may be called multiple times for a single request because response body may be delivered in chunks. Thus, the Lua code specified by in this directive may also run multiple times in the lifetime of a single HTTP request. This directive was first introduced in the `v0.5.0rc32` release. ### body\_filter\_by\_lua\_block **syntax:** *body\_filter\_by\_lua\_block { lua-script-str }* **context:** *http, server, location, location if* **phase:** *output-body-filter* Similar to the [body\_filter\_by\_lua](#body_filter_by_lua) directive except that this directive inlines the Lua source directly inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires special character escaping). For instance, ``` body_filter_by_lua_block { local data, eof = ngx.arg[1], ngx.arg[2] } ``` This directive was first introduced in the `v0.9.17` release. ### body\_filter\_by\_lua\_file **syntax:** *body\_filter\_by\_lua\_file <path-to-lua-script-file>* **context:** *http, server, location, location if* **phase:** *output-body-filter* Equivalent to [body\_filter\_by\_lua](#body_filter_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. This directive was first introduced in the `v0.5.0rc32` release. ### log\_by\_lua **syntax:** *log\_by\_lua <lua-script-str>* **context:** *http, server, location, location if* **phase:** *log* **NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [log\_by\_lua\_block](#log_by_lua_block) directive instead. Runs the Lua source code inlined as the `<lua-script-str>` at the `log` request processing phase. This does not replace the current access logs, but runs before. Note that the following API functions are currently disabled within this context: * Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send\_headers](#ngxsend_headers)) * Control API functions (e.g., [ngx.exit](#ngxexit)) * Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture\_multi](#ngxlocationcapture_multi)) * Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)). Here is an example of gathering average data for [$upstream\_response\_time](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#var_upstream_response_time): ``` lua_shared_dict log_dict 5M; server { location / { proxy_pass http://mybackend; log_by_lua ' local log_dict = ngx.shared.log_dict local upstream_time = tonumber(ngx.var.upstream_response_time) local sum = log_dict:get("upstream_time-sum") or 0 sum = sum + upstream_time log_dict:set("upstream_time-sum", sum) local newval, err = log_dict:incr("upstream_time-nb", 1) if not newval and err == "not found" then log_dict:add("upstream_time-nb", 0) log_dict:incr("upstream_time-nb", 1) end '; } location = /status { content_by_lua_block { local log_dict = ngx.shared.log_dict local sum = log_dict:get("upstream_time-sum") local nb = log_dict:get("upstream_time-nb") if nb and sum then ngx.say("average upstream response time: ", sum / nb, " (", nb, " reqs)") else ngx.say("no data yet") end } } } ``` This directive was first introduced in the `v0.5.0rc31` release. ### log\_by\_lua\_block **syntax:** *log\_by\_lua\_block { lua-script }* **context:** *http, server, location, location if* **phase:** *log* Similar to the [log\_by\_lua](#log_by_lua) directive except that this directive inlines the Lua source directly inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires special character escaping). For instance, ``` log_by_lua_block { print("I need no extra escaping here, for example: \r\nblah") } ``` This directive was first introduced in the `v0.9.17` release. ### log\_by\_lua\_file **syntax:** *log\_by\_lua\_file <path-to-lua-script-file>* **context:** *http, server, location, location if* **phase:** *log* Equivalent to [log\_by\_lua](#log_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. This directive was first introduced in the `v0.5.0rc31` release. ### balancer\_by\_lua\_block **syntax:** *balancer\_by\_lua\_block { lua-script }* **context:** *upstream* **phase:** *content* This directive runs Lua code as an upstream balancer for any upstream entities defined by the `upstream {}` configuration block. For instance, ``` upstream foo { server 127.0.0.1; balancer_by_lua_block { -- use Lua to do something interesting here -- as a dynamic balancer } } server { location / { proxy_pass http://foo; } } ``` The resulting Lua load balancer can work with any existing nginx upstream modules like [ngx\_proxy](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) and [ngx\_fastcgi](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html). Also, the Lua load balancer can work with the standard upstream connection pool mechanism, i.e., the standard [keepalive](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive) directive. Just ensure that the [keepalive](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive) directive is used *after* this `balancer_by_lua_block` directive in a single `upstream {}` configuration block. The Lua load balancer can totally ignore the list of servers defined in the `upstream {}` block and select peer from a completely dynamic server list (even changing per request) via the [ngx.balancer](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.md) module from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library. The Lua code handler registered by this directive might get called more than once in a single downstream request when the nginx upstream mechanism retries the request on conditions specified by directives like the [proxy\_next\_upstream](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_next_upstream) directive. This Lua code execution context does not support yielding, so Lua APIs that may yield (like cosockets and "light threads") are disabled in this context. One can usually work around this limitation by doing such operations in an earlier phase handler (like [access\_by\_lua\*](#access_by_lua)) and passing along the result into this context via the [ngx.ctx](#ngxctx) table. This directive was first introduced in the `v0.10.0` release. ### balancer\_by\_lua\_file **syntax:** *balancer\_by\_lua\_file <path-to-lua-script-file>* **context:** *upstream* **phase:** *content* Equivalent to [balancer\_by\_lua\_block](#balancer_by_lua_block), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. This directive was first introduced in the `v0.10.0` release. ### lua\_need\_request\_body **syntax:** *lua\_need\_request\_body <on|off>* **default:** *off* **context:** *http, server, location, location if* **phase:** *depends on usage* Determines whether to force the request body data to be read before running rewrite/access/access\_by\_lua\* or not. The Nginx core does not read the client request body by default and if request body data is required, then this directive should be turned `on` or the [ngx.req.read\_body](#ngxreqread_body) function should be called within the Lua code. To read the request body data within the [$request\_body](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_body) variable, [client\_body\_buffer\_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) must have the same value as [client\_max\_body\_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size). Because when the content length exceeds [client\_body\_buffer\_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) but less than [client\_max\_body\_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size), Nginx will buffer the data into a temporary file on the disk, which will lead to empty value in the [$request\_body](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_body) variable. If the current location includes [rewrite\_by\_lua\*](#rewrite_by_lua) directives, then the request body will be read just before the [rewrite\_by\_lua\*](#rewrite_by_lua) code is run (and also at the `rewrite` phase). Similarly, if only [content\_by\_lua](#content_by_lua) is specified, the request body will not be read until the content handler's Lua code is about to run (i.e., the request body will be read during the content phase). It is recommended however, to use the [ngx.req.read\_body](#ngxreqread_body) and [ngx.req.discard\_body](#ngxreqdiscard_body) functions for finer control over the request body reading process instead. This also applies to [access\_by\_lua\*](#access_by_lua). ### ssl\_certificate\_by\_lua\_block **syntax:** *ssl\_certificate\_by\_lua\_block { lua-script }* **context:** *server* **phase:** *right-before-SSL-handshake* This directive runs user Lua code when NGINX is about to start the SSL handshake for the downstream SSL (https) connections. It is particularly useful for setting the SSL certificate chain and the corresponding private key on a per-request basis. It is also useful to load such handshake configurations nonblockingly from the remote (for example, with the [cosocket](#ngxsockettcp) API). And one can also do per-request OCSP stapling handling in pure Lua here as well. Another typical use case is to do SSL handshake traffic control nonblockingly in this context, with the help of the [lua-resty-limit-traffic#readme](https://github.com/openresty/lua-resty-limit-traffic) library, for example. One can also do interesting things with the SSL handshake requests from the client side, like rejecting old SSL clients using the SSLv3 protocol or even below selectively. The [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md) and [ngx.ocsp](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ocsp.md) Lua modules provided by the [lua-resty-core](https://github.com/openresty/lua-resty-core/#readme) library are particularly useful in this context. You can use the Lua API offered by these two Lua modules to manipulate the SSL certificate chain and private key for the current SSL connection being initiated. This Lua handler does not run at all, however, when NGINX/OpenSSL successfully resumes the SSL session via SSL session IDs or TLS session tickets for the current SSL connection. In other words, this Lua handler only runs when NGINX has to initiate a full SSL handshake. Below is a trivial example using the [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md) module at the same time: ``` server { listen 443 ssl; server_name test.com; ssl_certificate_by_lua_block { print("About to initiate a new SSL handshake!") } location / { root html; } } ``` See more complicated examples in the [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md) and [ngx.ocsp](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ocsp.md) Lua modules' official documentation. Uncaught Lua exceptions in the user Lua code immediately abort the current SSL session, so does the [ngx.exit](#ngxexit) call with an error code like `ngx.ERROR`. This Lua code execution context *does* support yielding, so Lua APIs that may yield (like cosockets, sleeping, and "light threads") are enabled in this context. Note, however, you still need to configure the [ssl\_certificate](http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate) and [ssl\_certificate\_key](http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate_key) directives even though you will not use this static certificate and private key at all. This is because the NGINX core requires their appearance otherwise you are seeing the following error while starting NGINX: ``` nginx: [emerg] no ssl configured for the server ``` This directive currently requires the following NGINX core patch to work correctly: <http://mailman.nginx.org/pipermail/nginx-devel/2016-January/007748.html> The bundled version of the NGINX core in OpenResty 1.9.7.2 (or above) already has this patch applied. Furthermore, one needs at least OpenSSL 1.0.2e for this directive to work. This directive was first introduced in the `v0.10.0` release. ### ssl\_certificate\_by\_lua\_file **syntax:** *ssl\_certificate\_by\_lua\_file <path-to-lua-script-file>* **context:** *server* **phase:** *right-before-SSL-handshake* Equivalent to [ssl\_certificate\_by\_lua\_block](#ssl_certificate_by_lua_block), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. This directive was first introduced in the `v0.10.0` release. ### ssl\_session\_fetch\_by\_lua\_block **syntax:** *ssl\_session\_fetch\_by\_lua\_block { lua-script }* **context:** *http* **phase:** *right-before-SSL-handshake* This directive runs Lua code to look up and load the SSL session (if any) according to the session ID provided by the current SSL handshake request for the downstream. The Lua API for obtaining the current session ID and loading a cached SSL session data is provided in the [ngx.ssl.session](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl/session.md) Lua module shipped with the [lua-resty-core](https://github.com/openresty/lua-resty-core#readme) library. Lua APIs that may yield, like [ngx.sleep](#ngxsleep) and [cosockets](#ngxsockettcp), are enabled in this context. This hook, together with the [ssl\_session\_store\_by\_lua\*](#ssl_session_store_by_lua_block) hook, can be used to implement distributed caching mechanisms in pure Lua (based on the [cosocket](#ngxsockettcp) API, for example). If a cached SSL session is found and loaded into the current SSL connection context, SSL session resumption can then get immediately initiated and bypass the full SSL handshake process which is very expensive in terms of CPU time. Please note that TLS session tickets are very different and it is the clients' responsibility to cache the SSL session state when session tickets are used. SSL session resumptions based on TLS session tickets would happen automatically without going through this hook (nor the [ssl\_session\_store\_by\_lua\_block](#ssl_session_store_by_lua) hook). This hook is mainly for older or less capable SSL clients that can only do SSL sessions by session IDs. When [ssl\_certificate\_by\_lua\*](#ssl_certificate_by_lua_block) is specified at the same time, this hook usually runs before [ssl\_certificate\_by\_lua\*](#ssl_certificate_by_lua_block). When the SSL session is found and successfully loaded for the current SSL connection, SSL session resumption will happen and thus bypass the [ssl\_certificate\_by\_lua\*](#ssl_certificate_by_lua_block) hook completely. In this case, NGINX also bypasses the [ssl\_session\_store\_by\_lua\_block](#ssl_session_store_by_lua) hook, for obvious reasons. To easily test this hook locally with a modern web browser, you can temporarily put the following line in your https server block to disable the TLS session ticket support: ``` ssl_session_tickets off; ``` But do not forget to comment this line out before publishing your site to the world. If you are using the [official pre-built packages](http://openresty.org/en/linux-packages.html) for [OpenResty](https://openresty.org/) 1.11.2.1 or later, then everything should work out of the box. If you are using OpenSSL libraries not provided by [OpenResty](https://openresty.org), then you need to apply the following patch for OpenSSL 1.0.2h or later: <https://github.com/openresty/openresty/blob/master/patches/openssl-1.0.2h-sess_set_get_cb_yield.patch> If you are not using the NGINX core shipped with [OpenResty](https://openresty.org) 1.11.2.1 or later, then you need to apply the following patch to the standard NGINX core 1.11.2 or later: <http://openresty.org/download/nginx-1.11.2-nonblocking_ssl_handshake_hooks.patch> This directive was first introduced in the `v0.10.6` release. Note that: this directive is only allowed to used in **http context** from the `v0.10.7` release (because SSL session resumption happens before server name dispatch). ### ssl\_session\_fetch\_by\_lua\_file **syntax:** *ssl\_session\_fetch\_by\_lua\_file <path-to-lua-script-file>* **context:** *http* **phase:** *right-before-SSL-handshake* Equivalent to [ssl\_session\_fetch\_by\_lua\_block](#ssl_session_fetch_by_lua_block), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or rather, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. This directive was first introduced in the `v0.10.6` release. Note that: this directive is only allowed to used in **http context** from the `v0.10.7` release (because SSL session resumption happens before server name dispatch). ### ssl\_session\_store\_by\_lua\_block **syntax:** *ssl\_session\_store\_by\_lua\_block { lua-script }* **context:** *http* **phase:** *right-after-SSL-handshake* This directive runs Lua code to fetch and save the SSL session (if any) according to the session ID provided by the current SSL handshake request for the downstream. The saved or cached SSL session data can be used for future SSL connections to resume SSL sessions without going through the full SSL handshake process (which is very expensive in terms of CPU time). Lua APIs that may yield, like [ngx.sleep](#ngxsleep) and [cosockets](#ngxsockettcp), are *disabled* in this context. You can still, however, use the [ngx.timer.at](#ngxtimerat) API to create 0-delay timers to save the SSL session data asynchronously to external services (like `redis` or `memcached`). The Lua API for obtaining the current session ID and the associated session state data is provided in the [ngx.ssl.session](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl/session.md#readme) Lua module shipped with the [lua-resty-core](https://github.com/openresty/lua-resty-core#readme) library. To easily test this hook locally with a modern web browser, you can temporarily put the following line in your https server block to disable the TLS session ticket support: ``` ssl_session_tickets off; ``` But do not forget to comment this line out before publishing your site to the world. This directive was first introduced in the `v0.10.6` release. Note that: this directive is only allowed to used in **http context** from the `v0.10.7` release (because SSL session resumption happens before server name dispatch). ### ssl\_session\_store\_by\_lua\_file **syntax:** *ssl\_session\_store\_by\_lua\_file <path-to-lua-script-file>* **context:** *http* **phase:** *right-after-SSL-handshake* Equivalent to [ssl\_session\_store\_by\_lua\_block](#ssl_session_store_by_lua_block), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or rather, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. This directive was first introduced in the `v0.10.6` release. Note that: this directive is only allowed to used in **http context** from the `v0.10.7` release (because SSL session resumption happens before server name dispatch). ### lua\_shared\_dict **syntax:** *lua\_shared\_dict <name> <size>* **default:** *no* **context:** *http* **phase:** *depends on usage* Declares a shared memory zone, `<name>`, to serve as storage for the shm based Lua dictionary `ngx.shared.<name>`. Shared memory zones are always shared by all the nginx worker processes in the current nginx server instance. The `<size>` argument accepts size units such as `k` and `m`: ``` http { lua_shared_dict dogs 10m; ... } ``` The hard-coded minimum size is 8KB while the practical minimum size depends on actual user data set (some people start with 12KB). See [ngx.shared.DICT](#ngxshareddict) for details. This directive was first introduced in the `v0.3.1rc22` release. ### lua\_socket\_connect\_timeout **syntax:** *lua\_socket\_connect\_timeout <time>* **default:** *lua\_socket\_connect\_timeout 60s* **context:** *http, server, location* This directive controls the default timeout value used in TCP/unix-domain socket object's [connect](#tcpsockconnect) method and can be overridden by the [settimeout](#tcpsocksettimeout) or [settimeouts](#tcpsocksettimeouts) methods. The `<time>` argument can be an integer, with an optional time unit, like `s` (second), `ms` (millisecond), `m` (minute). The default time unit is `s`, i.e., "second". The default setting is `60s`. This directive was first introduced in the `v0.5.0rc1` release. ### lua\_socket\_send\_timeout **syntax:** *lua\_socket\_send\_timeout <time>* **default:** *lua\_socket\_send\_timeout 60s* **context:** *http, server, location* Controls the default timeout value used in TCP/unix-domain socket object's [send](#tcpsocksend) method and can be overridden by the [settimeout](#tcpsocksettimeout) or [settimeouts](#tcpsocksettimeouts) methods. The `<time>` argument can be an integer, with an optional time unit, like `s` (second), `ms` (millisecond), `m` (minute). The default time unit is `s`, i.e., "second". The default setting is `60s`. This directive was first introduced in the `v0.5.0rc1` release. ### lua\_socket\_send\_lowat **syntax:** *lua\_socket\_send\_lowat <size>* **default:** *lua\_socket\_send\_lowat 0* **context:** *http, server, location* Controls the `lowat` (low water) value for the cosocket send buffer. ### lua\_socket\_read\_timeout **syntax:** *lua\_socket\_read\_timeout <time>* **default:** *lua\_socket\_read\_timeout 60s* **context:** *http, server, location* **phase:** *depends on usage* This directive controls the default timeout value used in TCP/unix-domain socket object's [receive](#tcpsockreceive) method and iterator functions returned by the [receiveuntil](#tcpsockreceiveuntil) method. This setting can be overridden by the [settimeout](#tcpsocksettimeout) or [settimeouts](#tcpsocksettimeouts) methods. The `<time>` argument can be an integer, with an optional time unit, like `s` (second), `ms` (millisecond), `m` (minute). The default time unit is `s`, i.e., "second". The default setting is `60s`. This directive was first introduced in the `v0.5.0rc1` release. ### lua\_socket\_buffer\_size **syntax:** *lua\_socket\_buffer\_size <size>* **default:** *lua\_socket\_buffer\_size 4k/8k* **context:** *http, server, location* Specifies the buffer size used by cosocket reading operations. This buffer does not have to be that big to hold everything at the same time because cosocket supports 100% non-buffered reading and parsing. So even `1` byte buffer size should still work everywhere but the performance could be terrible. This directive was first introduced in the `v0.5.0rc1` release. ### lua\_socket\_pool\_size **syntax:** *lua\_socket\_pool\_size <size>* **default:** *lua\_socket\_pool\_size 30* **context:** *http, server, location* Specifies the size limit (in terms of connection count) for every cosocket connection pool associated with every remote server (i.e., identified by either the host-port pair or the unix domain socket file path). Default to 30 connections for every pool. When the connection pool exceeds the available size limit, the least recently used (idle) connection already in the pool will be closed to make room for the current connection. Note that the cosocket connection pool is per nginx worker process rather than per nginx server instance, so size limit specified here also applies to every single nginx worker process. This directive was first introduced in the `v0.5.0rc1` release. ### lua\_socket\_keepalive\_timeout **syntax:** *lua\_socket\_keepalive\_timeout <time>* **default:** *lua\_socket\_keepalive\_timeout 60s* **context:** *http, server, location* This directive controls the default maximal idle time of the connections in the cosocket built-in connection pool. When this timeout reaches, idle connections will be closed and removed from the pool. This setting can be overridden by cosocket objects' [setkeepalive](#tcpsocksetkeepalive) method. The `<time>` argument can be an integer, with an optional time unit, like `s` (second), `ms` (millisecond), `m` (minute). The default time unit is `s`, i.e., "second". The default setting is `60s`. This directive was first introduced in the `v0.5.0rc1` release. ### lua\_socket\_log\_errors **syntax:** *lua\_socket\_log\_errors on|off* **default:** *lua\_socket\_log\_errors on* **context:** *http, server, location* This directive can be used to toggle error logging when a failure occurs for the TCP or UDP cosockets. If you are already doing proper error handling and logging in your Lua code, then it is recommended to turn this directive off to prevent data flushing in your nginx error log files (which is usually rather expensive). This directive was first introduced in the `v0.5.13` release. ### lua\_ssl\_ciphers **syntax:** *lua\_ssl\_ciphers <ciphers>* **default:** *lua\_ssl\_ciphers DEFAULT* **context:** *http, server, location* Specifies the enabled ciphers for requests to a SSL/TLS server in the [tcpsock:sslhandshake](#tcpsocksslhandshake) method. The ciphers are specified in the format understood by the OpenSSL library. The full list can be viewed using the “openssl ciphers” command. This directive was first introduced in the `v0.9.11` release. ### lua\_ssl\_crl **syntax:** *lua\_ssl\_crl <file>* **default:** *no* **context:** *http, server, location* Specifies a file with revoked certificates (CRL) in the PEM format used to verify the certificate of the SSL/TLS server in the [tcpsock:sslhandshake](#tcpsocksslhandshake) method. This directive was first introduced in the `v0.9.11` release. ### lua\_ssl\_protocols **syntax:** *lua\_ssl\_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2] [TLSv1.3]* **default:** *lua\_ssl\_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2* **context:** *http, server, location* Enables the specified protocols for requests to a SSL/TLS server in the [tcpsock:sslhandshake](#tcpsocksslhandshake) method. The support for the `TLSv1.3` parameter requires version `v0.10.12` *and* OpenSSL 1.1.1. This directive was first introduced in the `v0.9.11` release. ### lua\_ssl\_trusted\_certificate **syntax:** *lua\_ssl\_trusted\_certificate <file>* **default:** *no* **context:** *http, server, location* Specifies a file path with trusted CA certificates in the PEM format used to verify the certificate of the SSL/TLS server in the [tcpsock:sslhandshake](#tcpsocksslhandshake) method. This directive was first introduced in the `v0.9.11` release. See also [lua\_ssl\_verify\_depth](#lua_ssl_verify_depth). ### lua\_ssl\_verify\_depth **syntax:** *lua\_ssl\_verify\_depth <number>* **default:** *lua\_ssl\_verify\_depth 1* **context:** *http, server, location* Sets the verification depth in the server certificates chain. This directive was first introduced in the `v0.9.11` release. See also [lua\_ssl\_trusted\_certificate](#lua_ssl_trusted_certificate). ### lua\_http10\_buffering **syntax:** *lua\_http10\_buffering on|off* **default:** *lua\_http10\_buffering on* **context:** *http, server, location, location-if* Enables or disables automatic response buffering for HTTP 1.0 (or older) requests. This buffering mechanism is mainly used for HTTP 1.0 keep-alive which relies on a proper `Content-Length` response header. If the Lua code explicitly sets a `Content-Length` response header before sending the headers (either explicitly via [ngx.send\_headers](#ngxsend_headers) or implicitly via the first [ngx.say](#ngxsay) or [ngx.print](#ngxprint) call), then the HTTP 1.0 response buffering will be disabled even when this directive is turned on. To output very large response data in a streaming fashion (via the [ngx.flush](#ngxflush) call, for example), this directive MUST be turned off to minimize memory usage. This directive is turned `on` by default. This directive was first introduced in the `v0.5.0rc19` release. ### rewrite\_by\_lua\_no\_postpone **syntax:** *rewrite\_by\_lua\_no\_postpone on|off* **default:** *rewrite\_by\_lua\_no\_postpone off* **context:** *http* Controls whether or not to disable postponing [rewrite\_by\_lua\*](#rewrite_by_lua) directives to run at the end of the `rewrite` request-processing phase. By default, this directive is turned off and the Lua code is postponed to run at the end of the `rewrite` phase. This directive was first introduced in the `v0.5.0rc29` release. ### access\_by\_lua\_no\_postpone **syntax:** *access\_by\_lua\_no\_postpone on|off* **default:** *access\_by\_lua\_no\_postpone off* **context:** *http* Controls whether or not to disable postponing [access\_by\_lua\*](#access_by_lua) directives to run at the end of the `access` request-processing phase. By default, this directive is turned off and the Lua code is postponed to run at the end of the `access` phase. This directive was first introduced in the `v0.9.20` release. ### lua\_transform\_underscores\_in\_response\_headers **syntax:** *lua\_transform\_underscores\_in\_response\_headers on|off* **default:** *lua\_transform\_underscores\_in\_response\_headers on* **context:** *http, server, location, location-if* Controls whether to transform underscores (`_`) in the response header names specified in the [ngx.header.HEADER](#ngxheaderheader) API to hypens (`-`). This directive was first introduced in the `v0.5.0rc32` release. ### lua\_check\_client\_abort **syntax:** *lua\_check\_client\_abort on|off* **default:** *lua\_check\_client\_abort off* **context:** *http, server, location, location-if* This directive controls whether to check for premature client connection abortion. When this directive is on, the ngx\_lua module will monitor the premature connection close event on the downstream connections and when there is such an event, it will call the user Lua function callback (registered by [ngx.on\_abort](#ngxon_abort)) or just stop and clean up all the Lua "light threads" running in the current request's request handler when there is no user callback function registered. According to the current implementation, however, if the client closes the connection before the Lua code finishes reading the request body data via [ngx.req.socket](#ngxreqsocket), then ngx\_lua will neither stop all the running "light threads" nor call the user callback (if [ngx.on\_abort](#ngxon_abort) has been called). Instead, the reading operation on [ngx.req.socket](#ngxreqsocket) will just return the error message "client aborted" as the second return value (the first return value is surely `nil`). When TCP keepalive is disabled, it is relying on the client side to close the socket gracefully (by sending a `FIN` packet or something like that). For (soft) real-time web applications, it is highly recommended to configure the [TCP keepalive](http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) support in your system's TCP stack implementation in order to detect "half-open" TCP connections in time. For example, on Linux, you can configure the standard [listen](http://nginx.org/en/docs/http/ngx_http_core_module.html#listen) directive in your `nginx.conf` file like this: ``` listen 80 so_keepalive=2s:2s:8; ``` On FreeBSD, you can only tune the system-wide configuration for TCP keepalive, for example: ``` # sysctl net.inet.tcp.keepintvl=2000 # sysctl net.inet.tcp.keepidle=2000 ``` This directive was first introduced in the `v0.7.4` release. See also [ngx.on\_abort](#ngxon_abort). ### lua\_max\_pending\_timers **syntax:** *lua\_max\_pending\_timers <count>* **default:** *lua\_max\_pending\_timers 1024* **context:** *http* Controls the maximum number of pending timers allowed. Pending timers are those timers that have not expired yet. When exceeding this limit, the [ngx.timer.at](#ngxtimerat) call will immediately return `nil` and the error string "too many pending timers". This directive was first introduced in the `v0.8.0` release. ### lua\_max\_running\_timers **syntax:** *lua\_max\_running\_timers <count>* **default:** *lua\_max\_running\_timers 256* **context:** *http* Controls the maximum number of "running timers" allowed. Running timers are those timers whose user callback functions are still running. When exceeding this limit, Nginx will stop running the callbacks of newly expired timers and log an error message "N lua\_max\_running\_timers are not enough" where "N" is the current value of this directive. This directive was first introduced in the `v0.8.0` release. Nginx API for Lua ----------------- * [Introduction](#introduction) * [ngx.arg](#ngxarg) * [ngx.var.VARIABLE](#ngxvarvariable) * [Core constants](#core-constants) * [HTTP method constants](#http-method-constants) * [HTTP status constants](#http-status-constants) * [Nginx log level constants](#nginx-log-level-constants) * [print](#print) * [ngx.ctx](#ngxctx) * [ngx.location.capture](#ngxlocationcapture) * [ngx.location.capture\_multi](#ngxlocationcapture_multi) * [ngx.status](#ngxstatus) * [ngx.header.HEADER](#ngxheaderheader) * [ngx.resp.get\_headers](#ngxrespget_headers) * [ngx.req.is\_internal](#ngxreqis_internal) * [ngx.req.start\_time](#ngxreqstart_time) * [ngx.req.http\_version](#ngxreqhttp_version) * [ngx.req.raw\_header](#ngxreqraw_header) * [ngx.req.get\_method](#ngxreqget_method) * [ngx.req.set\_method](#ngxreqset_method) * [ngx.req.set\_uri](#ngxreqset_uri) * [ngx.req.set\_uri\_args](#ngxreqset_uri_args) * [ngx.req.get\_uri\_args](#ngxreqget_uri_args) * [ngx.req.get\_post\_args](#ngxreqget_post_args) * [ngx.req.get\_headers](#ngxreqget_headers) * [ngx.req.set\_header](#ngxreqset_header) * [ngx.req.clear\_header](#ngxreqclear_header) * [ngx.req.read\_body](#ngxreqread_body) * [ngx.req.discard\_body](#ngxreqdiscard_body) * [ngx.req.get\_body\_data](#ngxreqget_body_data) * [ngx.req.get\_body\_file](#ngxreqget_body_file) * [ngx.req.set\_body\_data](#ngxreqset_body_data) * [ngx.req.set\_body\_file](#ngxreqset_body_file) * [ngx.req.init\_body](#ngxreqinit_body) * [ngx.req.append\_body](#ngxreqappend_body) * [ngx.req.finish\_body](#ngxreqfinish_body) * [ngx.req.socket](#ngxreqsocket) * [ngx.exec](#ngxexec) * [ngx.redirect](#ngxredirect) * [ngx.send\_headers](#ngxsend_headers) * [ngx.headers\_sent](#ngxheaders_sent) * [ngx.print](#ngxprint) * [ngx.say](#ngxsay) * [ngx.log](#ngxlog) * [ngx.flush](#ngxflush) * [ngx.exit](#ngxexit) * [ngx.eof](#ngxeof) * [ngx.sleep](#ngxsleep) * [ngx.escape\_uri](#ngxescape_uri) * [ngx.unescape\_uri](#ngxunescape_uri) * [ngx.encode\_args](#ngxencode_args) * [ngx.decode\_args](#ngxdecode_args) * [ngx.encode\_base64](#ngxencode_base64) * [ngx.decode\_base64](#ngxdecode_base64) * [ngx.crc32\_short](#ngxcrc32_short) * [ngx.crc32\_long](#ngxcrc32_long) * [ngx.hmac\_sha1](#ngxhmac_sha1) * [ngx.md5](#ngxmd5) * [ngx.md5\_bin](#ngxmd5_bin) * [ngx.sha1\_bin](#ngxsha1_bin) * [ngx.quote\_sql\_str](#ngxquote_sql_str) * [ngx.today](#ngxtoday) * [ngx.time](#ngxtime) * [ngx.now](#ngxnow) * [ngx.update\_time](#ngxupdate_time) * [ngx.localtime](#ngxlocaltime) * [ngx.utctime](#ngxutctime) * [ngx.cookie\_time](#ngxcookie_time) * [ngx.http\_time](#ngxhttp_time) * [ngx.parse\_http\_time](#ngxparse_http_time) * [ngx.is\_subrequest](#ngxis_subrequest) * [ngx.re.match](#ngxrematch) * [ngx.re.find](#ngxrefind) * [ngx.re.gmatch](#ngxregmatch) * [ngx.re.sub](#ngxresub) * [ngx.re.gsub](#ngxregsub) * [ngx.shared.DICT](#ngxshareddict) * [ngx.shared.DICT.get](#ngxshareddictget) * [ngx.shared.DICT.get\_stale](#ngxshareddictget_stale) * [ngx.shared.DICT.set](#ngxshareddictset) * [ngx.shared.DICT.safe\_set](#ngxshareddictsafe_set) * [ngx.shared.DICT.add](#ngxshareddictadd) * [ngx.shared.DICT.safe\_add](#ngxshareddictsafe_add) * [ngx.shared.DICT.replace](#ngxshareddictreplace) * [ngx.shared.DICT.delete](#ngxshareddictdelete) * [ngx.shared.DICT.incr](#ngxshareddictincr) * [ngx.shared.DICT.lpush](#ngxshareddictlpush) * [ngx.shared.DICT.rpush](#ngxshareddictrpush) * [ngx.shared.DICT.lpop](#ngxshareddictlpop) * [ngx.shared.DICT.rpop](#ngxshareddictrpop) * [ngx.shared.DICT.llen](#ngxshareddictllen) * [ngx.shared.DICT.ttl](#ngxshareddictttl) * [ngx.shared.DICT.expire](#ngxshareddictexpire) * [ngx.shared.DICT.flush\_all](#ngxshareddictflush_all) * [ngx.shared.DICT.flush\_expired](#ngxshareddictflush_expired) * [ngx.shared.DICT.get\_keys](#ngxshareddictget_keys) * [ngx.shared.DICT.capacity](#ngxshareddictcapacity) * [ngx.shared.DICT.free\_space](#ngxshareddictfree_space) * [ngx.socket.udp](#ngxsocketudp) * [udpsock:setpeername](#udpsocksetpeername) * [udpsock:send](#udpsocksend) * [udpsock:receive](#udpsockreceive) * [udpsock:close](#udpsockclose) * [udpsock:settimeout](#udpsocksettimeout) * [ngx.socket.stream](#ngxsocketstream) * [ngx.socket.tcp](#ngxsockettcp) * [tcpsock:connect](#tcpsockconnect) * [tcpsock:sslhandshake](#tcpsocksslhandshake) * [tcpsock:send](#tcpsocksend) * [tcpsock:receive](#tcpsockreceive) * [tcpsock:receiveuntil](#tcpsockreceiveuntil) * [tcpsock:close](#tcpsockclose) * [tcpsock:settimeout](#tcpsocksettimeout) * [tcpsock:settimeouts](#tcpsocksettimeouts) * [tcpsock:setoption](#tcpsocksetoption) * [tcpsock:setkeepalive](#tcpsocksetkeepalive) * [tcpsock:getreusedtimes](#tcpsockgetreusedtimes) * [ngx.socket.connect](#ngxsocketconnect) * [ngx.get\_phase](#ngxget_phase) * [ngx.thread.spawn](#ngxthreadspawn) * [ngx.thread.wait](#ngxthreadwait) * [ngx.thread.kill](#ngxthreadkill) * [ngx.on\_abort](#ngxon_abort) * [ngx.timer.at](#ngxtimerat) * [ngx.timer.every](#ngxtimerevery) * [ngx.timer.running\_count](#ngxtimerrunning_count) * [ngx.timer.pending\_count](#ngxtimerpending_count) * [ngx.config.subsystem](#ngxconfigsubsystem) * [ngx.config.debug](#ngxconfigdebug) * [ngx.config.prefix](#ngxconfigprefix) * [ngx.config.nginx\_version](#ngxconfignginx_version) * [ngx.config.nginx\_configure](#ngxconfignginx_configure) * [ngx.config.ngx\_lua\_version](#ngxconfigngx_lua_version) * [ngx.worker.exiting](#ngxworkerexiting) * [ngx.worker.pid](#ngxworkerpid) * [ngx.worker.count](#ngxworkercount) * [ngx.worker.id](#ngxworkerid) * [ngx.semaphore](#ngxsemaphore) * [ngx.balancer](#ngxbalancer) * [ngx.ssl](#ngxssl) * [ngx.ocsp](#ngxocsp) * [ndk.set\_var.DIRECTIVE](#ndkset_vardirective) * [coroutine.create](#coroutinecreate) * [coroutine.resume](#coroutineresume) * [coroutine.yield](#coroutineyield) * [coroutine.wrap](#coroutinewrap) * [coroutine.running](#coroutinerunning) * [coroutine.status](#coroutinestatus) ### Introduction The various `*_by_lua`, `*_by_lua_block` and `*_by_lua_file` configuration directives serve as gateways to the Lua API within the `nginx.conf` file. The Nginx Lua API described below can only be called within the user Lua code run in the context of these configuration directives. The API is exposed to Lua in the form of two standard packages `ngx` and `ndk`. These packages are in the default global scope within ngx\_lua and are always available within ngx\_lua directives. The packages can be introduced into external Lua modules like this: ``` local say = ngx.say local _M = {} function _M.foo(a) say(a) end return _M ``` Use of the [package.seeall](http://www.lua.org/manual/5.1/manual.html#pdf-package.seeall) flag is strongly discouraged due to its various bad side-effects. It is also possible to directly require the packages in external Lua modules: ``` local ngx = require "ngx" local ndk = require "ndk" ``` The ability to require these packages was introduced in the `v0.2.1rc19` release. Network I/O operations in user code should only be done through the Nginx Lua API calls as the Nginx event loop may be blocked and performance drop off dramatically otherwise. Disk operations with relatively small amount of data can be done using the standard Lua `io` library but huge file reading and writing should be avoided wherever possible as they may block the Nginx process significantly. Delegating all network and disk I/O operations to Nginx's subrequests (via the [ngx.location.capture](#ngxlocationcapture) method and similar) is strongly recommended for maximum performance. ### ngx.arg **syntax:** *val = ngx.arg[index]* **context:** *set\_by\_lua\*, body\_filter\_by\_lua\** When this is used in the context of the [set\_by\_lua\*](#set_by_lua) directives, this table is read-only and holds the input arguments to the config directives: ``` value = ngx.arg[n] ``` Here is an example ``` location /foo { set $a 32; set $b 56; set_by_lua $sum 'return tonumber(ngx.arg[1]) + tonumber(ngx.arg[2])' $a $b; echo $sum; } ``` that writes out `88`, the sum of `32` and `56`. When this table is used in the context of [body\_filter\_by\_lua\*](#body_filter_by_lua), the first element holds the input data chunk to the output filter code and the second element holds the boolean flag for the "eof" flag indicating the end of the whole output data stream. The data chunk and "eof" flag passed to the downstream Nginx output filters can also be overridden by assigning values directly to the corresponding table elements. When setting `nil` or an empty Lua string value to `ngx.arg[1]`, no data chunk will be passed to the downstream Nginx output filters at all. ### ngx.var.VARIABLE **syntax:** *ngx.var.VAR\_NAME* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\** Read and write Nginx variable values. ``` value = ngx.var.some_nginx_variable_name ngx.var.some_nginx_variable_name = value ``` Note that only already defined nginx variables can be written to. For example: ``` location /foo { set $my_var ''; # this line is required to create $my_var at config time content_by_lua_block { ngx.var.my_var = 123; ... } } ``` That is, nginx variables cannot be created on-the-fly. Some special nginx variables like `$args` and `$limit_rate` can be assigned a value, many others are not, like `$query_string`, `$arg_PARAMETER`, and `$http_NAME`. Nginx regex group capturing variables `$1`, `$2`, `$3`, and etc, can be read by this interface as well, by writing `ngx.var[1]`, `ngx.var[2]`, `ngx.var[3]`, and etc. Setting `ngx.var.Foo` to a `nil` value will unset the `$Foo` Nginx variable. ``` ngx.var.args = nil ``` **CAUTION** When reading from an Nginx variable, Nginx will allocate memory in the per-request memory pool which is freed only at request termination. So when you need to read from an Nginx variable repeatedly in your Lua code, cache the Nginx variable value to your own Lua variable, for example, ``` local val = ngx.var.some_var --- use the val repeatedly later ``` to prevent (temporary) memory leaking within the current request's lifetime. Another way of caching the result is to use the [ngx.ctx](#ngxctx) table. Undefined NGINX variables are evaluated to `nil` while uninitialized (but defined) NGINX variables are evaluated to an empty Lua string. This API requires a relatively expensive metamethod call and it is recommended to avoid using it on hot code paths. ### Core constants **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, \*log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** ``` ngx.OK (0) ngx.ERROR (-1) ngx.AGAIN (-2) ngx.DONE (-4) ngx.DECLINED (-5) ``` Note that only three of these constants are utilized by the [Nginx API for Lua](#nginx-api-for-lua) (i.e., [ngx.exit](#ngxexit) accepts `ngx.OK`, `ngx.ERROR`, and `ngx.DECLINED` as input). ``` ngx.null ``` The `ngx.null` constant is a `NULL` light userdata usually used to represent nil values in Lua tables etc and is similar to the [lua-cjson](http://www.kyne.com.au/%7Emark/software/lua-cjson.php) library's `cjson.null` constant. This constant was first introduced in the `v0.5.0rc5` release. The `ngx.DECLINED` constant was first introduced in the `v0.5.0rc19` release. ### HTTP method constants **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** ``` ngx.HTTP_GET ngx.HTTP_HEAD ngx.HTTP_PUT ngx.HTTP_POST ngx.HTTP_DELETE ngx.HTTP_OPTIONS (added in the v0.5.0rc24 release) ngx.HTTP_MKCOL (added in the v0.8.2 release) ngx.HTTP_COPY (added in the v0.8.2 release) ngx.HTTP_MOVE (added in the v0.8.2 release) ngx.HTTP_PROPFIND (added in the v0.8.2 release) ngx.HTTP_PROPPATCH (added in the v0.8.2 release) ngx.HTTP_LOCK (added in the v0.8.2 release) ngx.HTTP_UNLOCK (added in the v0.8.2 release) ngx.HTTP_PATCH (added in the v0.8.2 release) ngx.HTTP_TRACE (added in the v0.8.2 release) ``` These constants are usually used in [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture\_multi](#ngxlocationcapture_multi) method calls. ### HTTP status constants **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** ``` value = ngx.HTTP_CONTINUE (100) (first added in the v0.9.20 release) value = ngx.HTTP_SWITCHING_PROTOCOLS (101) (first added in the v0.9.20 release) value = ngx.HTTP_OK (200) value = ngx.HTTP_CREATED (201) value = ngx.HTTP_ACCEPTED (202) (first added in the v0.9.20 release) value = ngx.HTTP_NO_CONTENT (204) (first added in the v0.9.20 release) value = ngx.HTTP_PARTIAL_CONTENT (206) (first added in the v0.9.20 release) value = ngx.HTTP_SPECIAL_RESPONSE (300) value = ngx.HTTP_MOVED_PERMANENTLY (301) value = ngx.HTTP_MOVED_TEMPORARILY (302) value = ngx.HTTP_SEE_OTHER (303) value = ngx.HTTP_NOT_MODIFIED (304) value = ngx.HTTP_TEMPORARY_REDIRECT (307) (first added in the v0.9.20 release) value = ngx.HTTP_PERMANENT_REDIRECT (308) value = ngx.HTTP_BAD_REQUEST (400) value = ngx.HTTP_UNAUTHORIZED (401) value = ngx.HTTP_PAYMENT_REQUIRED (402) (first added in the v0.9.20 release) value = ngx.HTTP_FORBIDDEN (403) value = ngx.HTTP_NOT_FOUND (404) value = ngx.HTTP_NOT_ALLOWED (405) value = ngx.HTTP_NOT_ACCEPTABLE (406) (first added in the v0.9.20 release) value = ngx.HTTP_REQUEST_TIMEOUT (408) (first added in the v0.9.20 release) value = ngx.HTTP_CONFLICT (409) (first added in the v0.9.20 release) value = ngx.HTTP_GONE (410) value = ngx.HTTP_UPGRADE_REQUIRED (426) (first added in the v0.9.20 release) value = ngx.HTTP_TOO_MANY_REQUESTS (429) (first added in the v0.9.20 release) value = ngx.HTTP_CLOSE (444) (first added in the v0.9.20 release) value = ngx.HTTP_ILLEGAL (451) (first added in the v0.9.20 release) value = ngx.HTTP_INTERNAL_SERVER_ERROR (500) value = ngx.HTTP_METHOD_NOT_IMPLEMENTED (501) value = ngx.HTTP_BAD_GATEWAY (502) (first added in the v0.9.20 release) value = ngx.HTTP_SERVICE_UNAVAILABLE (503) value = ngx.HTTP_GATEWAY_TIMEOUT (504) (first added in the v0.3.1rc38 release) value = ngx.HTTP_VERSION_NOT_SUPPORTED (505) (first added in the v0.9.20 release) value = ngx.HTTP_INSUFFICIENT_STORAGE (507) (first added in the v0.9.20 release) ``` ### Nginx log level constants **context:** *init\_by\_lua\*, init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** ``` ngx.STDERR ngx.EMERG ngx.ALERT ngx.CRIT ngx.ERR ngx.WARN ngx.NOTICE ngx.INFO ngx.DEBUG ``` These constants are usually used by the [ngx.log](#ngxlog) method. ### print **syntax:** *print(...)* **context:** *init\_by\_lua\*, init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Writes argument values into the nginx `error.log` file with the `ngx.NOTICE` log level. It is equivalent to ``` ngx.log(ngx.NOTICE, ...) ``` Lua `nil` arguments are accepted and result in literal `"nil"` strings while Lua booleans result in literal `"true"` or `"false"` strings. And the `ngx.null` constant will yield the `"null"` string output. There is a hard coded `2048` byte limitation on error message lengths in the Nginx core. This limit includes trailing newlines and leading time stamps. If the message size exceeds this limit, Nginx will truncate the message text accordingly. This limit can be manually modified by editing the `NGX_MAX_ERROR_STR` macro definition in the `src/core/ngx_log.h` file in the Nginx source tree. ### ngx.ctx **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\** This table can be used to store per-request Lua context data and has a life time identical to the current request (as with the Nginx variables). Consider the following example, ``` location /test { rewrite_by_lua_block { ngx.ctx.foo = 76 } access_by_lua_block { ngx.ctx.foo = ngx.ctx.foo + 3 } content_by_lua_block { ngx.say(ngx.ctx.foo) } } ``` Then `GET /test` will yield the output ``` 79 ``` That is, the `ngx.ctx.foo` entry persists across the rewrite, access, and content phases of a request. Every request, including subrequests, has its own copy of the table. For example: ``` location /sub { content_by_lua_block { ngx.say("sub pre: ", ngx.ctx.blah) ngx.ctx.blah = 32 ngx.say("sub post: ", ngx.ctx.blah) } } location /main { content_by_lua_block { ngx.ctx.blah = 73 ngx.say("main pre: ", ngx.ctx.blah) local res = ngx.location.capture("/sub") ngx.print(res.body) ngx.say("main post: ", ngx.ctx.blah) } } ``` Then `GET /main` will give the output ``` main pre: 73 sub pre: nil sub post: 32 main post: 73 ``` Here, modification of the `ngx.ctx.blah` entry in the subrequest does not affect the one in the parent request. This is because they have two separate versions of `ngx.ctx.blah`. Internal redirection will destroy the original request `ngx.ctx` data (if any) and the new request will have an empty `ngx.ctx` table. For instance, ``` location /new { content_by_lua_block { ngx.say(ngx.ctx.foo) } } location /orig { content_by_lua_block { ngx.ctx.foo = "hello" ngx.exec("/new") } } ``` Then `GET /orig` will give ``` nil ``` rather than the original `"hello"` value. Arbitrary data values, including Lua closures and nested tables, can be inserted into this "magic" table. It also allows the registration of custom meta methods. Overriding `ngx.ctx` with a new Lua table is also supported, for example, ``` ngx.ctx = { foo = 32, bar = 54 } ``` When being used in the context of [init\_worker\_by\_lua\*](#init_worker_by_lua), this table just has the same lifetime of the current Lua handler. The `ngx.ctx` lookup requires relatively expensive metamethod calls and it is much slower than explicitly passing per-request data along by your own function arguments. So do not abuse this API for saving your own function arguments because it usually has quite some performance impact. Because of the metamethod magic, never "local" the `ngx.ctx` table outside your Lua function scope on the Lua module level due to [worker-level data sharing](#data-sharing-within-an-nginx-worker). For example, the following is bad: ``` -- mymodule.lua local _M = {} -- the following line is bad since ngx.ctx is a per-request -- data while this <code>ctx</code> variable is on the Lua module level -- and thus is per-nginx-worker. local ctx = ngx.ctx function _M.main() ctx.foo = "bar" end return _M ``` Use the following instead: ``` -- mymodule.lua local _M = {} function _M.main(ctx) ctx.foo = "bar" end return _M ``` That is, let the caller pass the `ctx` table explicitly via a function argument. ### ngx.location.capture **syntax:** *res = ngx.location.capture(uri, options?)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Issues a synchronous but still non-blocking *Nginx Subrequest* using `uri`. Nginx's subrequests provide a powerful way to make non-blocking internal requests to other locations configured with disk file directory or *any* other nginx C modules like `ngx_proxy`, `ngx_fastcgi`, `ngx_memc`, `ngx_postgres`, `ngx_drizzle`, and even ngx\_lua itself and etc etc etc. Also note that subrequests just mimic the HTTP interface but there is *no* extra HTTP/TCP traffic *nor* IPC involved. Everything works internally, efficiently, on the C level. Subrequests are completely different from HTTP 301/302 redirection (via [ngx.redirect](#ngxredirect)) and internal redirection (via [ngx.exec](#ngxexec)). You should always read the request body (by either calling [ngx.req.read\_body](#ngxreqread_body) or configuring [lua\_need\_request\_body](#lua_need_request_body) on) before initiating a subrequest. This API function (as well as [ngx.location.capture\_multi](#ngxlocationcapture_multi)) always buffers the whole response body of the subrequest in memory. Thus, you should use [cosockets](#ngxsockettcp) and streaming processing instead if you have to handle large subrequest responses. Here is a basic example: ``` res = ngx.location.capture(uri) ``` Returns a Lua table with 4 slots: `res.status`, `res.header`, `res.body`, and `res.truncated`. `res.status` holds the response status code for the subrequest response. `res.header` holds all the response headers of the subrequest and it is a normal Lua table. For multi-value response headers, the value is a Lua (array) table that holds all the values in the order that they appear. For instance, if the subrequest response headers contain the following lines: ``` Set-Cookie: a=3 Set-Cookie: foo=bar Set-Cookie: baz=blah ``` Then `res.header["Set-Cookie"]` will be evaluated to the table value `{"a=3", "foo=bar", "baz=blah"}`. `res.body` holds the subrequest's response body data, which might be truncated. You always need to check the `res.truncated` boolean flag to see if `res.body` contains truncated data. The data truncation here can only be caused by those unrecoverable errors in your subrequests like the cases that the remote end aborts the connection prematurely in the middle of the response body data stream or a read timeout happens when your subrequest is receiving the response body data from the remote. URI query strings can be concatenated to URI itself, for instance, ``` res = ngx.location.capture('/foo/bar?a=3&b=4') ``` Named locations like `@foo` are not allowed due to a limitation in the nginx core. Use normal locations combined with the `internal` directive to prepare internal-only locations. An optional option table can be fed as the second argument, which supports the options: * `method` specify the subrequest's request method, which only accepts constants like `ngx.HTTP_POST`. * `body` specify the subrequest's request body (string value only). * `args` specify the subrequest's URI query arguments (both string value and Lua tables are accepted) * `ctx` specify a Lua table to be the [ngx.ctx](#ngxctx) table for the subrequest. It can be the current request's [ngx.ctx](#ngxctx) table, which effectively makes the parent and its subrequest to share exactly the same context table. This option was first introduced in the `v0.3.1rc25` release. * `vars` take a Lua table which holds the values to set the specified Nginx variables in the subrequest as this option's value. This option was first introduced in the `v0.3.1rc31` release. * `copy_all_vars` specify whether to copy over all the Nginx variable values of the current request to the subrequest in question. modifications of the nginx variables in the subrequest will not affect the current (parent) request. This option was first introduced in the `v0.3.1rc31` release. * `share_all_vars` specify whether to share all the Nginx variables of the subrequest with the current (parent) request. modifications of the Nginx variables in the subrequest will affect the current (parent) request. Enabling this option may lead to hard-to-debug issues due to bad side-effects and is considered bad and harmful. Only enable this option when you completely know what you are doing. * `always_forward_body` when set to true, the current (parent) request's request body will always be forwarded to the subrequest being created if the `body` option is not specified. The request body read by either [ngx.req.read\_body()](#ngxreqread_body) or [lua\_need\_request\_body on](#lua_need_request_body) will be directly forwarded to the subrequest without copying the whole request body data when creating the subrequest (no matter the request body data is buffered in memory buffers or temporary files). By default, this option is `false` and when the `body` option is not specified, the request body of the current (parent) request is only forwarded when the subrequest takes the `PUT` or `POST` request method. Issuing a POST subrequest, for example, can be done as follows ``` res = ngx.location.capture( '/foo/bar', { method = ngx.HTTP_POST, body = 'hello, world' } ) ``` See HTTP method constants methods other than POST. The `method` option is `ngx.HTTP_GET` by default. The `args` option can specify extra URI arguments, for instance, ``` ngx.location.capture('/foo?a=1', { args = { b = 3, c = ':' } } ) ``` is equivalent to ``` ngx.location.capture('/foo?a=1&b=3&c=%3a') ``` that is, this method will escape argument keys and values according to URI rules and concatenate them together into a complete query string. The format for the Lua table passed as the `args` argument is identical to the format used in the [ngx.encode\_args](#ngxencode_args) method. The `args` option can also take plain query strings: ``` ngx.location.capture('/foo?a=1', { args = 'b=3&c=%3a' } } ) ``` This is functionally identical to the previous examples. The `share_all_vars` option controls whether to share nginx variables among the current request and its subrequests. If this option is set to `true`, then the current request and associated subrequests will share the same Nginx variable scope. Hence, changes to Nginx variables made by a subrequest will affect the current request. Care should be taken in using this option as variable scope sharing can have unexpected side effects. The `args`, `vars`, or `copy_all_vars` options are generally preferable instead. This option is set to `false` by default ``` location /other { set $dog "$dog world"; echo "$uri dog: $dog"; } location /lua { set $dog 'hello'; content_by_lua_block { res = ngx.location.capture("/other", { share_all_vars = true }); ngx.print(res.body) ngx.say(ngx.var.uri, ": ", ngx.var.dog) } } ``` Accessing location `/lua` gives ``` /other dog: hello world /lua: hello world ``` The `copy_all_vars` option provides a copy of the parent request's Nginx variables to subrequests when such subrequests are issued. Changes made to these variables by such subrequests will not affect the parent request or any other subrequests sharing the parent request's variables. ``` location /other { set $dog "$dog world"; echo "$uri dog: $dog"; } location /lua { set $dog 'hello'; content_by_lua_block { res = ngx.location.capture("/other", { copy_all_vars = true }); ngx.print(res.body) ngx.say(ngx.var.uri, ": ", ngx.var.dog) } } ``` Request `GET /lua` will give the output ``` /other dog: hello world /lua: hello ``` Note that if both `share_all_vars` and `copy_all_vars` are set to true, then `share_all_vars` takes precedence. In addition to the two settings above, it is possible to specify values for variables in the subrequest using the `vars` option. These variables are set after the sharing or copying of variables has been evaluated, and provides a more efficient method of passing specific values to a subrequest over encoding them as URL arguments and unescaping them in the Nginx config file. ``` location /other { content_by_lua_block { ngx.say("dog = ", ngx.var.dog) ngx.say("cat = ", ngx.var.cat) } } location /lua { set $dog ''; set $cat ''; content_by_lua_block { res = ngx.location.capture("/other", { vars = { dog = "hello", cat = 32 }}); ngx.print(res.body) } } ``` Accessing `/lua` will yield the output ``` dog = hello cat = 32 ``` The `ctx` option can be used to specify a custom Lua table to serve as the [ngx.ctx](#ngxctx) table for the subrequest. ``` location /sub { content_by_lua_block { ngx.ctx.foo = "bar"; } } location /lua { content_by_lua_block { local ctx = {} res = ngx.location.capture("/sub", { ctx = ctx }) ngx.say(ctx.foo); ngx.say(ngx.ctx.foo); } } ``` Then request `GET /lua` gives ``` bar nil ``` It is also possible to use this `ctx` option to share the same [ngx.ctx](#ngxctx) table between the current (parent) request and the subrequest: ``` location /sub { content_by_lua_block { ngx.ctx.foo = "bar"; } } location /lua { content_by_lua_block { res = ngx.location.capture("/sub", { ctx = ngx.ctx }) ngx.say(ngx.ctx.foo); } } ``` Request `GET /lua` yields the output ``` bar ``` Note that subrequests issued by [ngx.location.capture](#ngxlocationcapture) inherit all the request headers of the current request by default and that this may have unexpected side effects on the subrequest responses. For example, when using the standard `ngx_proxy` module to serve subrequests, an "Accept-Encoding: gzip" header in the main request may result in gzipped responses that cannot be handled properly in Lua code. Original request headers should be ignored by setting [proxy\_pass\_request\_headers](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass_request_headers) to `off` in subrequest locations. When the `body` option is not specified and the `always_forward_body` option is false (the default value), the `POST` and `PUT` subrequests will inherit the request bodies of the parent request (if any). There is a hard-coded upper limit on the number of concurrent subrequests possible for every main request. In older versions of Nginx, the limit was `50` concurrent subrequests and in more recent versions, Nginx `1.1.x` onwards, this was increased to `200` concurrent subrequests. When this limit is exceeded, the following error message is added to the `error.log` file: ``` [error] 13983#0: *1 subrequests cycle while processing "/uri" ``` The limit can be manually modified if required by editing the definition of the `NGX_HTTP_MAX_SUBREQUESTS` macro in the `nginx/src/http/ngx_http_request.h` file in the Nginx source tree. Please also refer to restrictions on capturing locations configured by [subrequest directives of other modules](#locations-configured-by-subrequest-directives-of-other-modules). ### ngx.location.capture\_multi **syntax:** *res1, res2, ... = ngx.location.capture\_multi({ {uri, options?}, {uri, options?}, ... })* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Just like [ngx.location.capture](#ngxlocationcapture), but supports multiple subrequests running in parallel. This function issues several parallel subrequests specified by the input table and returns their results in the same order. For example, ``` res1, res2, res3 = ngx.location.capture_multi{ { "/foo", { args = "a=3&b=4" } }, { "/bar" }, { "/baz", { method = ngx.HTTP_POST, body = "hello" } }, } if res1.status == ngx.HTTP_OK then ... end if res2.body == "BLAH" then ... end ``` This function will not return until all the subrequests terminate. The total latency is the longest latency of the individual subrequests rather than the sum. Lua tables can be used for both requests and responses when the number of subrequests to be issued is not known in advance: ``` -- construct the requests table local reqs = {} table.insert(reqs, { "/mysql" }) table.insert(reqs, { "/postgres" }) table.insert(reqs, { "/redis" }) table.insert(reqs, { "/memcached" }) -- issue all the requests at once and wait until they all return local resps = { ngx.location.capture_multi(reqs) } -- loop over the responses table for i, resp in ipairs(resps) do -- process the response table "resp" end ``` The [ngx.location.capture](#ngxlocationcapture) function is just a special form of this function. Logically speaking, the [ngx.location.capture](#ngxlocationcapture) can be implemented like this ``` ngx.location.capture = function (uri, args) return ngx.location.capture_multi({ {uri, args} }) end ``` Please also refer to restrictions on capturing locations configured by [subrequest directives of other modules](#locations-configured-by-subrequest-directives-of-other-modules). ### ngx.status **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\** Read and write the current request's response status. This should be called before sending out the response headers. ``` ngx.status = ngx.HTTP_CREATED status = ngx.status ``` Setting `ngx.status` after the response header is sent out has no effect but leaving an error message in your nginx's error log file: ``` attempt to set ngx.status after sending out response headers ``` ### ngx.header.HEADER **syntax:** *ngx.header.HEADER = VALUE* **syntax:** *value = ngx.header.HEADER* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\** Set, add to, or clear the current request's `HEADER` response header that is to be sent. Underscores (`_`) in the header names will be replaced by hyphens (`-`) by default. This transformation can be turned off via the [lua\_transform\_underscores\_in\_response\_headers](#lua_transform_underscores_in_response_headers) directive. The header names are matched case-insensitively. ``` -- equivalent to ngx.header["Content-Type"] = 'text/plain' ngx.header.content_type = 'text/plain'; ngx.header["X-My-Header"] = 'blah blah'; ``` Multi-value headers can be set this way: ``` ngx.header['Set-Cookie'] = {'a=32; path=/', 'b=4; path=/'} ``` will yield ``` Set-Cookie: a=32; path=/ Set-Cookie: b=4; path=/ ``` in the response headers. Only Lua tables are accepted (Only the last element in the table will take effect for standard headers such as `Content-Type` that only accept a single value). ``` ngx.header.content_type = {'a', 'b'} ``` is equivalent to ``` ngx.header.content_type = 'b' ``` Setting a slot to `nil` effectively removes it from the response headers: ``` ngx.header["X-My-Header"] = nil; ``` The same applies to assigning an empty table: ``` ngx.header["X-My-Header"] = {}; ``` Setting `ngx.header.HEADER` after sending out response headers (either explicitly with [ngx.send\_headers](#ngxsend_headers) or implicitly with [ngx.print](#ngxprint) and similar) will log an error message. Reading `ngx.header.HEADER` will return the value of the response header named `HEADER`. Underscores (`_`) in the header names will also be replaced by dashes (`-`) and the header names will be matched case-insensitively. If the response header is not present at all, `nil` will be returned. This is particularly useful in the context of [header\_filter\_by\_lua\*](#header_filter_by_lua), for example, ``` location /test { set $footer ''; proxy_pass http://some-backend; header_filter_by_lua_block { if ngx.header["X-My-Header"] == "blah" then ngx.var.footer = "some value" end } echo_after_body $footer; } ``` For multi-value headers, all of the values of header will be collected in order and returned as a Lua table. For example, response headers ``` Foo: bar Foo: baz ``` will result in ``` {"bar", "baz"} ``` to be returned when reading `ngx.header.Foo`. Note that `ngx.header` is not a normal Lua table and as such, it is not possible to iterate through it using the Lua `ipairs` function. For reading *request* headers, use the [ngx.req.get\_headers](#ngxreqget_headers) function instead. ### ngx.resp.get\_headers **syntax:** *headers, err = ngx.resp.get\_headers(max\_headers?, raw?)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, balancer\_by\_lua\** Returns a Lua table holding all the current response headers for the current request. ``` local h, err = ngx.resp.get_headers() if err == "truncated" then -- one can choose to ignore or reject the current response here end for k, v in pairs(h) do ... end ``` This function has the same signature as [ngx.req.get\_headers](#ngxreqget_headers) except getting response headers instead of request headers. Note that a maximum of 100 response headers are parsed by default (including those with the same name) and that additional response headers are silently discarded to guard against potential denial of service attacks. Since `v0.10.13`, when the limit is exceeded, it will return a second value which is the string `"truncated"`. This API was first introduced in the `v0.9.5` release. ### ngx.req.is\_internal **syntax:** *is\_internal = ngx.req.is\_internal()* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\** Returns a boolean indicating whether the current request is an "internal request", i.e., a request initiated from inside the current nginx server instead of from the client side. Subrequests are all internal requests and so are requests after internal redirects. This API was first introduced in the `v0.9.20` release. ### ngx.req.start\_time **syntax:** *secs = ngx.req.start\_time()* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\** Returns a floating-point number representing the timestamp (including milliseconds as the decimal part) when the current request was created. The following example emulates the `$request_time` variable value (provided by [ngx\_http\_log\_module](http://nginx.org/en/docs/http/ngx_http_log_module.html)) in pure Lua: ``` local request_time = ngx.now() - ngx.req.start_time() ``` This function was first introduced in the `v0.7.7` release. See also [ngx.now](#ngxnow) and [ngx.update\_time](#ngxupdate_time). ### ngx.req.http\_version **syntax:** *num = ngx.req.http\_version()* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\** Returns the HTTP version number for the current request as a Lua number. Current possible values are 2.0, 1.0, 1.1, and 0.9. Returns `nil` for unrecognized values. This method was first introduced in the `v0.7.17` release. ### ngx.req.raw\_header **syntax:** *str = ngx.req.raw\_header(no\_request\_line?)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\** Returns the original raw HTTP protocol header received by the Nginx server. By default, the request line and trailing `CR LF` terminator will also be included. For example, ``` ngx.print(ngx.req.raw_header()) ``` gives something like this: ``` GET /t HTTP/1.1 Host: localhost Connection: close Foo: bar ``` You can specify the optional `no_request_line` argument as a `true` value to exclude the request line from the result. For example, ``` ngx.print(ngx.req.raw_header(true)) ``` outputs something like this: ``` Host: localhost Connection: close Foo: bar ``` This method was first introduced in the `v0.7.17` release. This method does not work in HTTP/2 requests yet. ### ngx.req.get\_method **syntax:** *method\_name = ngx.req.get\_method()* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, balancer\_by\_lua\** Retrieves the current request's request method name. Strings like `"GET"` and `"POST"` are returned instead of numerical [method constants](#http-method-constants). If the current request is an Nginx subrequest, then the subrequest's method name will be returned. This method was first introduced in the `v0.5.6` release. See also [ngx.req.set\_method](#ngxreqset_method). ### ngx.req.set\_method **syntax:** *ngx.req.set\_method(method\_id)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\** Overrides the current request's request method with the `method_id` argument. Currently only numerical [method constants](#http-method-constants) are supported, like `ngx.HTTP_POST` and `ngx.HTTP_GET`. If the current request is an Nginx subrequest, then the subrequest's method will be overridden. This method was first introduced in the `v0.5.6` release. See also [ngx.req.get\_method](#ngxreqget_method). ### ngx.req.set\_uri **syntax:** *ngx.req.set\_uri(uri, jump?)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\** Rewrite the current request's (parsed) URI by the `uri` argument. The `uri` argument must be a Lua string and cannot be of zero length, or a Lua exception will be thrown. The optional boolean `jump` argument can trigger location rematch (or location jump) as [ngx\_http\_rewrite\_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html)'s [rewrite](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite) directive, that is, when `jump` is `true` (default to `false`), this function will never return and it will tell Nginx to try re-searching locations with the new URI value at the later `post-rewrite` phase and jumping to the new location. Location jump will not be triggered otherwise, and only the current request's URI will be modified, which is also the default behavior. This function will return but with no returned values when the `jump` argument is `false` or absent altogether. For example, the following nginx config snippet ``` rewrite ^ /foo last; ``` can be coded in Lua like this: ``` ngx.req.set_uri("/foo", true) ``` Similarly, Nginx config ``` rewrite ^ /foo break; ``` can be coded in Lua as ``` ngx.req.set_uri("/foo", false) ``` or equivalently, ``` ngx.req.set_uri("/foo") ``` The `jump` argument can only be set to `true` in [rewrite\_by\_lua\*](#rewrite_by_lua). Use of jump in other contexts is prohibited and will throw out a Lua exception. A more sophisticated example involving regex substitutions is as follows ``` location /test { rewrite_by_lua_block { local uri = ngx.re.sub(ngx.var.uri, "^/test/(.*)", "/$1", "o") ngx.req.set_uri(uri) } proxy_pass http://my_backend; } ``` which is functionally equivalent to ``` location /test { rewrite ^/test/(.*) /$1 break; proxy_pass http://my_backend; } ``` Note that it is not possible to use this interface to rewrite URI arguments and that [ngx.req.set\_uri\_args](#ngxreqset_uri_args) should be used for this instead. For instance, Nginx config ``` rewrite ^ /foo?a=3? last; ``` can be coded as ``` ngx.req.set_uri_args("a=3") ngx.req.set_uri("/foo", true) ``` or ``` ngx.req.set_uri_args({a = 3}) ngx.req.set_uri("/foo", true) ``` This interface was first introduced in the `v0.3.1rc14` release. ### ngx.req.set\_uri\_args **syntax:** *ngx.req.set\_uri\_args(args)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\** Rewrite the current request's URI query arguments by the `args` argument. The `args` argument can be either a Lua string, as in ``` ngx.req.set_uri_args("a=3&b=hello%20world") ``` or a Lua table holding the query arguments' key-value pairs, as in ``` ngx.req.set_uri_args({ a = 3, b = "hello world" }) ``` where in the latter case, this method will escape argument keys and values according to the URI escaping rule. Multi-value arguments are also supported: ``` ngx.req.set_uri_args({ a = 3, b = {5, 6} }) ``` which will result in a query string like `a=3&b=5&b=6`. This interface was first introduced in the `v0.3.1rc13` release. See also [ngx.req.set\_uri](#ngxreqset_uri). ### ngx.req.get\_uri\_args **syntax:** *args, err = ngx.req.get\_uri\_args(max\_args?)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, balancer\_by\_lua\** Returns a Lua table holding all the current request URL query arguments. ``` location = /test { content_by_lua_block { local args, err = ngx.req.get_uri_args() if err == "truncated" then -- one can choose to ignore or reject the current request here end for key, val in pairs(args) do if type(val) == "table" then ngx.say(key, ": ", table.concat(val, ", ")) else ngx.say(key, ": ", val) end end } } ``` Then `GET /test?foo=bar&bar=baz&bar=blah` will yield the response body ``` foo: bar bar: baz, blah ``` Multiple occurrences of an argument key will result in a table value holding all the values for that key in order. Keys and values are unescaped according to URI escaping rules. In the settings above, `GET /test?a%20b=1%61+2` will yield: ``` a b: 1a 2 ``` Arguments without the `=<value>` parts are treated as boolean arguments. `GET /test?foo&bar` will yield: ``` foo: true bar: true ``` That is, they will take Lua boolean values `true`. However, they are different from arguments taking empty string values. `GET /test?foo=&bar=` will give something like ``` foo: bar: ``` Empty key arguments are discarded. `GET /test?=hello&=world` will yield an empty output for instance. Updating query arguments via the nginx variable `$args` (or `ngx.var.args` in Lua) at runtime is also supported: ``` ngx.var.args = "a=3&b=42" local args, err = ngx.req.get_uri_args() ``` Here the `args` table will always look like ``` {a = 3, b = 42} ``` regardless of the actual request query string. Note that a maximum of 100 request arguments are parsed by default (including those with the same name) and that additional request arguments are silently discarded to guard against potential denial of service attacks. Since `v0.10.13`, when the limit is exceeded, it will return a second value which is the string `"truncated"`. However, the optional `max_args` function argument can be used to override this limit: ``` local args, err = ngx.req.get_uri_args(10) if err == "truncated" then -- one can choose to ignore or reject the current request here end ``` This argument can be set to zero to remove the limit and to process all request arguments received: ``` local args, err = ngx.req.get_uri_args(0) ``` Removing the `max_args` cap is strongly discouraged. ### ngx.req.get\_post\_args **syntax:** *args, err = ngx.req.get\_post\_args(max\_args?)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\** Returns a Lua table holding all the current request POST query arguments (of the MIME type `application/x-www-form-urlencoded`). Call [ngx.req.read\_body](#ngxreqread_body) to read the request body first or turn on the [lua\_need\_request\_body](#lua_need_request_body) directive to avoid errors. ``` location = /test { content_by_lua_block { ngx.req.read_body() local args, err = ngx.req.get_post_args() if err == "truncated" then -- one can choose to ignore or reject the current request here end if not args then ngx.say("failed to get post args: ", err) return end for key, val in pairs(args) do if type(val) == "table" then ngx.say(key, ": ", table.concat(val, ", ")) else ngx.say(key, ": ", val) end end } } ``` Then ``` # Post request with the body 'foo=bar&bar=baz&bar=blah' $ curl --data 'foo=bar&bar=baz&bar=blah' localhost/test ``` will yield the response body like ``` foo: bar bar: baz, blah ``` Multiple occurrences of an argument key will result in a table value holding all of the values for that key in order. Keys and values will be unescaped according to URI escaping rules. With the settings above, ``` # POST request with body 'a%20b=1%61+2' $ curl -d 'a%20b=1%61+2' localhost/test ``` will yield: ``` a b: 1a 2 ``` Arguments without the `=<value>` parts are treated as boolean arguments. `POST /test` with the request body `foo&bar` will yield: ``` foo: true bar: true ``` That is, they will take Lua boolean values `true`. However, they are different from arguments taking empty string values. `POST /test` with request body `foo=&bar=` will return something like ``` foo: bar: ``` Empty key arguments are discarded. `POST /test` with body `=hello&=world` will yield empty outputs for instance. Note that a maximum of 100 request arguments are parsed by default (including those with the same name) and that additional request arguments are silently discarded to guard against potential denial of service attacks. Since `v0.10.13`, when the limit is exceeded, it will return a second value which is the string `"truncated"`. However, the optional `max_args` function argument can be used to override this limit: ``` local args, err = ngx.req.get_post_args(10) if err == "truncated" then -- one can choose to ignore or reject the current request here end ``` This argument can be set to zero to remove the limit and to process all request arguments received: ``` local args, err = ngx.req.get_post_args(0) ``` Removing the `max_args` cap is strongly discouraged. ### ngx.req.get\_headers **syntax:** *headers, err = ngx.req.get\_headers(max\_headers?, raw?)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\** Returns a Lua table holding all the current request headers. ``` local h, err = ngx.req.get_headers() if err == "truncated" then -- one can choose to ignore or reject the current request here end for k, v in pairs(h) do ... end ``` To read an individual header: ``` ngx.say("Host: ", ngx.req.get_headers()["Host"]) ``` Note that the [ngx.var.HEADER](#ngxvarvariable) API call, which uses core [$http\_HEADER](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_http_) variables, may be more preferable for reading individual request headers. For multiple instances of request headers such as: ``` Foo: foo Foo: bar Foo: baz ``` the value of `ngx.req.get_headers()["Foo"]` will be a Lua (array) table such as: ``` {"foo", "bar", "baz"} ``` Note that a maximum of 100 request headers are parsed by default (including those with the same name) and that additional request headers are silently discarded to guard against potential denial of service attacks. Since `v0.10.13`, when the limit is exceeded, it will return a second value which is the string `"truncated"`. However, the optional `max_headers` function argument can be used to override this limit: ``` local headers, err = ngx.req.get_headers(10) if err == "truncated" then -- one can choose to ignore or reject the current request here end ``` This argument can be set to zero to remove the limit and to process all request headers received: ``` local headers, err = ngx.req.get_headers(0) ``` Removing the `max_headers` cap is strongly discouraged. Since the `0.6.9` release, all the header names in the Lua table returned are converted to the pure lower-case form by default, unless the `raw` argument is set to `true` (default to `false`). Also, by default, an `__index` metamethod is added to the resulting Lua table and will normalize the keys to a pure lowercase form with all underscores converted to dashes in case of a lookup miss. For example, if a request header `My-Foo-Header` is present, then the following invocations will all pick up the value of this header correctly: ``` ngx.say(headers.my_foo_header) ngx.say(headers["My-Foo-Header"]) ngx.say(headers["my-foo-header"]) ``` The `__index` metamethod will not be added when the `raw` argument is set to `true`. ### ngx.req.set\_header **syntax:** *ngx.req.set\_header(header\_name, header\_value)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\** Set the current request's request header named `header_name` to value `header_value`, overriding any existing ones. By default, all the subrequests subsequently initiated by [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture\_multi](#ngxlocationcapture_multi) will inherit the new header. Here is an example of setting the `Content-Type` header: ``` ngx.req.set_header("Content-Type", "text/css") ``` The `header_value` can take an array list of values, for example, ``` ngx.req.set_header("Foo", {"a", "abc"}) ``` will produce two new request headers: ``` Foo: a Foo: abc ``` and old `Foo` headers will be overridden if there is any. When the `header_value` argument is `nil`, the request header will be removed. So ``` ngx.req.set_header("X-Foo", nil) ``` is equivalent to ``` ngx.req.clear_header("X-Foo") ``` ### ngx.req.clear\_header **syntax:** *ngx.req.clear\_header(header\_name)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\** Clears the current request's request header named `header_name`. None of the current request's existing subrequests will be affected but subsequently initiated subrequests will inherit the change by default. ### ngx.req.read\_body **syntax:** *ngx.req.read\_body()* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Reads the client request body synchronously without blocking the Nginx event loop. ``` ngx.req.read_body() local args = ngx.req.get_post_args() ``` If the request body is already read previously by turning on [lua\_need\_request\_body](#lua_need_request_body) or by using other modules, then this function does not run and returns immediately. If the request body has already been explicitly discarded, either by the [ngx.req.discard\_body](#ngxreqdiscard_body) function or other modules, this function does not run and returns immediately. In case of errors, such as connection errors while reading the data, this method will throw out a Lua exception *or* terminate the current request with a 500 status code immediately. The request body data read using this function can be retrieved later via [ngx.req.get\_body\_data](#ngxreqget_body_data) or, alternatively, the temporary file name for the body data cached to disk using [ngx.req.get\_body\_file](#ngxreqget_body_file). This depends on 1. whether the current request body is already larger than the [client\_body\_buffer\_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size), 2. and whether [client\_body\_in\_file\_only](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_in_file_only) has been switched on. In cases where current request may have a request body and the request body data is not required, The [ngx.req.discard\_body](#ngxreqdiscard_body) function must be used to explicitly discard the request body to avoid breaking things under HTTP 1.1 keepalive or HTTP 1.1 pipelining. This function was first introduced in the `v0.3.1rc17` release. ### ngx.req.discard\_body **syntax:** *ngx.req.discard\_body()* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Explicitly discard the request body, i.e., read the data on the connection and throw it away immediately (without using the request body by any means). This function is an asynchronous call and returns immediately. If the request body has already been read, this function does nothing and returns immediately. This function was first introduced in the `v0.3.1rc17` release. See also [ngx.req.read\_body](#ngxreqread_body). ### ngx.req.get\_body\_data **syntax:** *data = ngx.req.get\_body\_data()* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, log\_by\_lua\** Retrieves in-memory request body data. It returns a Lua string rather than a Lua table holding all the parsed query arguments. Use the [ngx.req.get\_post\_args](#ngxreqget_post_args) function instead if a Lua table is required. This function returns `nil` if 1. the request body has not been read, 2. the request body has been read into disk temporary files, 3. or the request body has zero size. If the request body has not been read yet, call [ngx.req.read\_body](#ngxreqread_body) first (or turned on [lua\_need\_request\_body](#lua_need_request_body) to force this module to read the request body. This is not recommended however). If the request body has been read into disk files, try calling the [ngx.req.get\_body\_file](#ngxreqget_body_file) function instead. To force in-memory request bodies, try setting [client\_body\_buffer\_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) to the same size value in [client\_max\_body\_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size). Note that calling this function instead of using `ngx.var.request_body` or `ngx.var.echo_request_body` is more efficient because it can save one dynamic memory allocation and one data copy. This function was first introduced in the `v0.3.1rc17` release. See also [ngx.req.get\_body\_file](#ngxreqget_body_file). ### ngx.req.get\_body\_file **syntax:** *file\_name = ngx.req.get\_body\_file()* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Retrieves the file name for the in-file request body data. Returns `nil` if the request body has not been read or has been read into memory. The returned file is read only and is usually cleaned up by Nginx's memory pool. It should not be manually modified, renamed, or removed in Lua code. If the request body has not been read yet, call [ngx.req.read\_body](#ngxreqread_body) first (or turned on [lua\_need\_request\_body](#lua_need_request_body) to force this module to read the request body. This is not recommended however). If the request body has been read into memory, try calling the [ngx.req.get\_body\_data](#ngxreqget_body_data) function instead. To force in-file request bodies, try turning on [client\_body\_in\_file\_only](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_in_file_only). This function was first introduced in the `v0.3.1rc17` release. See also [ngx.req.get\_body\_data](#ngxreqget_body_data). ### ngx.req.set\_body\_data **syntax:** *ngx.req.set\_body\_data(data)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Set the current request's request body using the in-memory data specified by the `data` argument. If the current request's request body has not been read, then it will be properly discarded. When the current request's request body has been read into memory or buffered into a disk file, then the old request body's memory will be freed or the disk file will be cleaned up immediately, respectively. This function was first introduced in the `v0.3.1rc18` release. See also [ngx.req.set\_body\_file](#ngxreqset_body_file). ### ngx.req.set\_body\_file **syntax:** *ngx.req.set\_body\_file(file\_name, auto\_clean?)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Set the current request's request body using the in-file data specified by the `file_name` argument. If the optional `auto_clean` argument is given a `true` value, then this file will be removed at request completion or the next time this function or [ngx.req.set\_body\_data](#ngxreqset_body_data) are called in the same request. The `auto_clean` is default to `false`. Please ensure that the file specified by the `file_name` argument exists and is readable by an Nginx worker process by setting its permission properly to avoid Lua exception errors. If the current request's request body has not been read, then it will be properly discarded. When the current request's request body has been read into memory or buffered into a disk file, then the old request body's memory will be freed or the disk file will be cleaned up immediately, respectively. This function was first introduced in the `v0.3.1rc18` release. See also [ngx.req.set\_body\_data](#ngxreqset_body_data). ### ngx.req.init\_body **syntax:** *ngx.req.init\_body(buffer\_size?)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Creates a new blank request body for the current request and inializes the buffer for later request body data writing via the [ngx.req.append\_body](#ngxreqappend_body) and [ngx.req.finish\_body](#ngxreqfinish_body) APIs. If the `buffer_size` argument is specified, then its value will be used for the size of the memory buffer for body writing with [ngx.req.append\_body](#ngxreqappend_body). If the argument is omitted, then the value specified by the standard [client\_body\_buffer\_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) directive will be used instead. When the data can no longer be hold in the memory buffer for the request body, then the data will be flushed onto a temporary file just like the standard request body reader in the Nginx core. It is important to always call the [ngx.req.finish\_body](#ngxreqfinish_body) after all the data has been appended onto the current request body. Also, when this function is used together with [ngx.req.socket](#ngxreqsocket), it is required to call [ngx.req.socket](#ngxreqsocket) *before* this function, or you will get the "request body already exists" error message. The usage of this function is often like this: ``` ngx.req.init_body(128 * 1024) -- buffer is 128KB for chunk in next_data_chunk() do ngx.req.append_body(chunk) -- each chunk can be 4KB end ngx.req.finish_body() ``` This function can be used with [ngx.req.append\_body](#ngxreqappend_body), [ngx.req.finish\_body](#ngxreqfinish_body), and [ngx.req.socket](#ngxreqsocket) to implement efficient input filters in pure Lua (in the context of [rewrite\_by\_lua\*](#rewrite_by_lua) or [access\_by\_lua\*](#access_by_lua)), which can be used with other Nginx content handler or upstream modules like [ngx\_http\_proxy\_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) and [ngx\_http\_fastcgi\_module](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html). This function was first introduced in the `v0.5.11` release. ### ngx.req.append\_body **syntax:** *ngx.req.append\_body(data\_chunk)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Append new data chunk specified by the `data_chunk` argument onto the existing request body created by the [ngx.req.init\_body](#ngxreqinit_body) call. When the data can no longer be hold in the memory buffer for the request body, then the data will be flushed onto a temporary file just like the standard request body reader in the Nginx core. It is important to always call the [ngx.req.finish\_body](#ngxreqfinish_body) after all the data has been appended onto the current request body. This function can be used with [ngx.req.init\_body](#ngxreqinit_body), [ngx.req.finish\_body](#ngxreqfinish_body), and [ngx.req.socket](#ngxreqsocket) to implement efficient input filters in pure Lua (in the context of [rewrite\_by\_lua\*](#rewrite_by_lua) or [access\_by\_lua\*](#access_by_lua)), which can be used with other Nginx content handler or upstream modules like [ngx\_http\_proxy\_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) and [ngx\_http\_fastcgi\_module](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html). This function was first introduced in the `v0.5.11` release. See also [ngx.req.init\_body](#ngxreqinit_body). ### ngx.req.finish\_body **syntax:** *ngx.req.finish\_body()* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Completes the construction process of the new request body created by the [ngx.req.init\_body](#ngxreqinit_body) and [ngx.req.append\_body](#ngxreqappend_body) calls. This function can be used with [ngx.req.init\_body](#ngxreqinit_body), [ngx.req.append\_body](#ngxreqappend_body), and [ngx.req.socket](#ngxreqsocket) to implement efficient input filters in pure Lua (in the context of [rewrite\_by\_lua\*](#rewrite_by_lua) or [access\_by\_lua\*](#access_by_lua)), which can be used with other Nginx content handler or upstream modules like [ngx\_http\_proxy\_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) and [ngx\_http\_fastcgi\_module](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html). This function was first introduced in the `v0.5.11` release. See also [ngx.req.init\_body](#ngxreqinit_body). ### ngx.req.socket **syntax:** *tcpsock, err = ngx.req.socket()* **syntax:** *tcpsock, err = ngx.req.socket(raw)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Returns a read-only cosocket object that wraps the downstream connection. Only [receive](#tcpsockreceive) and [receiveuntil](#tcpsockreceiveuntil) methods are supported on this object. In case of error, `nil` will be returned as well as a string describing the error. The socket object returned by this method is usually used to read the current request's body in a streaming fashion. Do not turn on the [lua\_need\_request\_body](#lua_need_request_body) directive, and do not mix this call with [ngx.req.read\_body](#ngxreqread_body) and [ngx.req.discard\_body](#ngxreqdiscard_body). If any request body data has been pre-read into the Nginx core request header buffer, the resulting cosocket object will take care of this to avoid potential data loss resulting from such pre-reading. Chunked request bodies are not yet supported in this API. Since the `v0.9.0` release, this function accepts an optional boolean `raw` argument. When this argument is `true`, this function returns a full-duplex cosocket object wrapping around the raw downstream connection socket, upon which you can call the [receive](#tcpsockreceive), [receiveuntil](#tcpsockreceiveuntil), and [send](#tcpsocksend) methods. When the `raw` argument is `true`, it is required that no pending data from any previous [ngx.say](#ngxsay), [ngx.print](#ngxprint), or [ngx.send\_headers](#ngxsend_headers) calls exists. So if you have these downstream output calls previously, you should call [ngx.flush(true)](#ngxflush) before calling `ngx.req.socket(true)` to ensure that there is no pending output data. If the request body has not been read yet, then this "raw socket" can also be used to read the request body. You can use the "raw request socket" returned by `ngx.req.socket(true)` to implement fancy protocols like [WebSocket](http://en.wikipedia.org/wiki/WebSocket), or just emit your own raw HTTP response header or body data. You can refer to the [lua-resty-websocket library](https://github.com/openresty/lua-resty-websocket) for a real world example. This function was first introduced in the `v0.5.0rc1` release. ### ngx.exec **syntax:** *ngx.exec(uri, args?)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Does an internal redirect to `uri` with `args` and is similar to the [echo\_exec](http://github.com/openresty/echo-nginx-module#echo_exec) directive of the [echo-nginx-module](http://github.com/openresty/echo-nginx-module). ``` ngx.exec('/some-location'); ngx.exec('/some-location', 'a=3&b=5&c=6'); ngx.exec('/some-location?a=3&b=5', 'c=6'); ``` The optional second `args` can be used to specify extra URI query arguments, for example: ``` ngx.exec("/foo", "a=3&b=hello%20world") ``` Alternatively, a Lua table can be passed for the `args` argument for ngx\_lua to carry out URI escaping and string concatenation. ``` ngx.exec("/foo", { a = 3, b = "hello world" }) ``` The result is exactly the same as the previous example. The format for the Lua table passed as the `args` argument is identical to the format used in the [ngx.encode\_args](#ngxencode_args) method. Named locations are also supported but the second `args` argument will be ignored if present and the querystring for the new target is inherited from the referring location (if any). `GET /foo/file.php?a=hello` will return "hello" and not "goodbye" in the example below ``` location /foo { content_by_lua_block { ngx.exec("@bar", "a=goodbye"); } } location @bar { content_by_lua_block { local args = ngx.req.get_uri_args() for key, val in pairs(args) do if key == "a" then ngx.say(val) end end } } ``` Note that the `ngx.exec` method is different from [ngx.redirect](#ngxredirect) in that it is purely an internal redirect and that no new external HTTP traffic is involved. Also note that this method call terminates the processing of the current request and that it *must* be called before [ngx.send\_headers](#ngxsend_headers) or explicit response body outputs by either [ngx.print](#ngxprint) or [ngx.say](#ngxsay). It is recommended that a coding style that combines this method call with the `return` statement, i.e., `return ngx.exec(...)` be adopted when this method call is used in contexts other than [header\_filter\_by\_lua\*](#header_filter_by_lua) to reinforce the fact that the request processing is being terminated. ### ngx.redirect **syntax:** *ngx.redirect(uri, status?)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Issue an `HTTP 301` or `302` redirection to `uri`. The optional `status` parameter specifies the HTTP status code to be used. The following status codes are supported right now: * `301` * `302` (default) * `303` * `307` * `308` It is `302` (`ngx.HTTP_MOVED_TEMPORARILY`) by default. Here is an example assuming the current server name is `localhost` and that it is listening on port 1984: ``` return ngx.redirect("/foo") ``` which is equivalent to ``` return ngx.redirect("/foo", ngx.HTTP_MOVED_TEMPORARILY) ``` Redirecting arbitrary external URLs is also supported, for example: ``` return ngx.redirect("http://www.google.com") ``` We can also use the numerical code directly as the second `status` argument: ``` return ngx.redirect("/foo", 301) ``` This method is similar to the [rewrite](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite) directive with the `redirect` modifier in the standard [ngx\_http\_rewrite\_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html), for example, this `nginx.conf` snippet ``` rewrite ^ /foo? redirect; # nginx config ``` is equivalent to the following Lua code ``` return ngx.redirect('/foo'); -- Lua code ``` while ``` rewrite ^ /foo? permanent; # nginx config ``` is equivalent to ``` return ngx.redirect('/foo', ngx.HTTP_MOVED_PERMANENTLY) -- Lua code ``` URI arguments can be specified as well, for example: ``` return ngx.redirect('/foo?a=3&b=4') ``` Note that this method call terminates the processing of the current request and that it *must* be called before [ngx.send\_headers](#ngxsend_headers) or explicit response body outputs by either [ngx.print](#ngxprint) or [ngx.say](#ngxsay). It is recommended that a coding style that combines this method call with the `return` statement, i.e., `return ngx.redirect(...)` be adopted when this method call is used in contexts other than [header\_filter\_by\_lua\*](#header_filter_by_lua) to reinforce the fact that the request processing is being terminated. ### ngx.send\_headers **syntax:** *ok, err = ngx.send\_headers()* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Explicitly send out the response headers. Since `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise. Note that there is normally no need to manually send out response headers as ngx\_lua will automatically send headers out before content is output with [ngx.say](#ngxsay) or [ngx.print](#ngxprint) or when [content\_by\_lua\*](#content_by_lua) exits normally. ### ngx.headers\_sent **syntax:** *value = ngx.headers\_sent* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Returns `true` if the response headers have been sent (by ngx\_lua), and `false` otherwise. This API was first introduced in ngx\_lua v0.3.1rc6. ### ngx.print **syntax:** *ok, err = ngx.print(...)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Emits arguments concatenated to the HTTP client (as response body). If response headers have not been sent, this function will send headers out first and then output body data. Since `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise. Lua `nil` values will output `"nil"` strings and Lua boolean values will output `"true"` and `"false"` literal strings respectively. Nested arrays of strings are permitted and the elements in the arrays will be sent one by one: ``` local table = { "hello, ", {"world: ", true, " or ", false, {": ", nil}} } ngx.print(table) ``` will yield the output ``` hello, world: true or false: nil ``` Non-array table arguments will cause a Lua exception to be thrown. The `ngx.null` constant will yield the `"null"` string output. This is an asynchronous call and will return immediately without waiting for all the data to be written into the system send buffer. To run in synchronous mode, call `ngx.flush(true)` after calling `ngx.print`. This can be particularly useful for streaming output. See [ngx.flush](#ngxflush) for more details. Please note that both `ngx.print` and [ngx.say](#ngxsay) will always invoke the whole Nginx output body filter chain, which is an expensive operation. So be careful when calling either of these two in a tight loop; buffer the data yourself in Lua and save the calls. ### ngx.say **syntax:** *ok, err = ngx.say(...)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Just as [ngx.print](#ngxprint) but also emit a trailing newline. ### ngx.log **syntax:** *ngx.log(log\_level, ...)* **context:** *init\_by\_lua\*, init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Log arguments concatenated to error.log with the given logging level. Lua `nil` arguments are accepted and result in literal `"nil"` string while Lua booleans result in literal `"true"` or `"false"` string outputs. And the `ngx.null` constant will yield the `"null"` string output. The `log_level` argument can take constants like `ngx.ERR` and `ngx.WARN`. Check out [Nginx log level constants](#nginx-log-level-constants) for details. There is a hard coded `2048` byte limitation on error message lengths in the Nginx core. This limit includes trailing newlines and leading time stamps. If the message size exceeds this limit, Nginx will truncate the message text accordingly. This limit can be manually modified by editing the `NGX_MAX_ERROR_STR` macro definition in the `src/core/ngx_log.h` file in the Nginx source tree. ### ngx.flush **syntax:** *ok, err = ngx.flush(wait?)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Flushes response output to the client. `ngx.flush` accepts an optional boolean `wait` argument (Default: `false`) first introduced in the `v0.3.1rc34` release. When called with the default argument, it issues an asynchronous call (Returns immediately without waiting for output data to be written into the system send buffer). Calling the function with the `wait` argument set to `true` switches to synchronous mode. In synchronous mode, the function will not return until all output data has been written into the system send buffer or until the [send\_timeout](http://nginx.org/en/docs/http/ngx_http_core_module.html#send_timeout) setting has expired. Note that using the Lua coroutine mechanism means that this function does not block the Nginx event loop even in the synchronous mode. When `ngx.flush(true)` is called immediately after [ngx.print](#ngxprint) or [ngx.say](#ngxsay), it causes the latter functions to run in synchronous mode. This can be particularly useful for streaming output. Note that `ngx.flush` is not functional when in the HTTP 1.0 output buffering mode. See [HTTP 1.0 support](#http-10-support). Since `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise. ### ngx.exit **syntax:** *ngx.exit(status)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** When `status >= 200` (i.e., `ngx.HTTP_OK` and above), it will interrupt the execution of the current request and return status code to nginx. When `status == 0` (i.e., `ngx.OK`), it will only quit the current phase handler (or the content handler if the [content\_by\_lua\*](#content_by_lua) directive is used) and continue to run later phases (if any) for the current request. The `status` argument can be `ngx.OK`, `ngx.ERROR`, `ngx.HTTP_NOT_FOUND`, `ngx.HTTP_MOVED_TEMPORARILY`, or other [HTTP status constants](#http-status-constants). To return an error page with custom contents, use code snippets like this: ``` ngx.status = ngx.HTTP_GONE ngx.say("This is our own content") -- to cause quit the whole request rather than the current phase handler ngx.exit(ngx.HTTP_OK) ``` The effect in action: ``` $ curl -i http://localhost/test HTTP/1.1 410 Gone Server: nginx/1.0.6 Date: Thu, 15 Sep 2011 00:51:48 GMT Content-Type: text/plain Transfer-Encoding: chunked Connection: keep-alive This is our own content ``` Number literals can be used directly as the argument, for instance, ``` ngx.exit(501) ``` Note that while this method accepts all [HTTP status constants](#http-status-constants) as input, it only accepts `ngx.OK` and `ngx.ERROR` of the [core constants](#core-constants). Also note that this method call terminates the processing of the current request and that it is recommended that a coding style that combines this method call with the `return` statement, i.e., `return ngx.exit(...)` be used to reinforce the fact that the request processing is being terminated. When being used in the contexts of [header\_filter\_by\_lua\*](#header_filter_by_lua), [balancer\_by\_lua\*](#balancer_by_lua_block), and [ssl\_session\_store\_by\_lua\*](#ssl_session_store_by_lua_block), `ngx.exit()` is an asynchronous operation and will return immediately. This behavior may change in future and it is recommended that users always use `return` in combination as suggested above. ### ngx.eof **syntax:** *ok, err = ngx.eof()* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Explicitly specify the end of the response output stream. In the case of HTTP 1.1 chunked encoded output, it will just trigger the Nginx core to send out the "last chunk". When you disable the HTTP 1.1 keep-alive feature for your downstream connections, you can rely on well written HTTP clients to close the connection actively for you when you call this method. This trick can be used do back-ground jobs without letting the HTTP clients to wait on the connection, as in the following example: ``` location = /async { keepalive_timeout 0; content_by_lua_block { ngx.say("got the task!") ngx.eof() -- well written HTTP clients will close the connection at this point -- access MySQL, PostgreSQL, Redis, Memcached, and etc here... } } ``` But if you create subrequests to access other locations configured by Nginx upstream modules, then you should configure those upstream modules to ignore client connection abortions if they are not by default. For example, by default the standard [ngx\_http\_proxy\_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) will terminate both the subrequest and the main request as soon as the client closes the connection, so it is important to turn on the [proxy\_ignore\_client\_abort](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ignore_client_abort) directive in your location block configured by [ngx\_http\_proxy\_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html): ``` proxy_ignore_client_abort on; ``` A better way to do background jobs is to use the [ngx.timer.at](#ngxtimerat) API. Since `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise. ### ngx.sleep **syntax:** *ngx.sleep(seconds)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Sleeps for the specified seconds without blocking. One can specify time resolution up to 0.001 seconds (i.e., one milliseconds). Behind the scene, this method makes use of the Nginx timers. Since the `0.7.20` release, The `0` time argument can also be specified. This method was introduced in the `0.5.0rc30` release. ### ngx.escape\_uri **syntax:** *newstr = ngx.escape\_uri(str)* **context:** *init\_by\_lua\*, init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Escape `str` as a URI component. ### ngx.unescape\_uri **syntax:** *newstr = ngx.unescape\_uri(str)* **context:** *init\_by\_lua\*, init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\** Unescape `str` as an escaped URI component. For example, ``` ngx.say(ngx.unescape_uri("b%20r56+7")) ``` gives the output ``` b r56 7 ``` ### ngx.encode\_args **syntax:** *str = ngx.encode\_args(table)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\** Encode the Lua table to a query args string according to the URI encoded rules. For example, ``` ngx.encode_args({foo = 3, ["b r"] = "hello world"}) ``` yields ``` foo=3&b%20r=hello%20world ``` The table keys must be Lua strings. Multi-value query args are also supported. Just use a Lua table for the argument's value, for example: ``` ngx.encode_args({baz = {32, "hello"}}) ``` gives ``` baz=32&baz=hello ``` If the value table is empty and the effect is equivalent to the `nil` value. Boolean argument values are also supported, for instance, ``` ngx.encode_args({a = true, b = 1}) ``` yields ``` a&b=1 ``` If the argument value is `false`, then the effect is equivalent to the `nil` value. This method was first introduced in the `v0.3.1rc27` release. ### ngx.decode\_args **syntax:** *table, err = ngx.decode\_args(str, max\_args?)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Decodes a URI encoded query-string into a Lua table. This is the inverse function of [ngx.encode\_args](#ngxencode_args). The optional `max_args` argument can be used to specify the maximum number of arguments parsed from the `str` argument. By default, a maximum of 100 request arguments are parsed (including those with the same name) and that additional URI arguments are silently discarded to guard against potential denial of service attacks. Since `v0.10.13`, when the limit is exceeded, it will return a second value which is the string `"truncated"`. This argument can be set to zero to remove the limit and to process all request arguments received: ``` local args = ngx.decode_args(str, 0) ``` Removing the `max_args` cap is strongly discouraged. This method was introduced in the `v0.5.0rc29`. ### ngx.encode\_base64 **syntax:** *newstr = ngx.encode\_base64(str, no\_padding?)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Encodes `str` to a base64 digest. Since the `0.9.16` release, an optional boolean-typed `no_padding` argument can be specified to control whether the base64 padding should be appended to the resulting digest (default to `false`, i.e., with padding enabled). ### ngx.decode\_base64 **syntax:** *newstr = ngx.decode\_base64(str)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Decodes the `str` argument as a base64 digest to the raw form. Returns `nil` if `str` is not well formed. ### ngx.crc32\_short **syntax:** *intval = ngx.crc32\_short(str)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Calculates the CRC-32 (Cyclic Redundancy Code) digest for the `str` argument. This method performs better on relatively short `str` inputs (i.e., less than 30 ~ 60 bytes), as compared to [ngx.crc32\_long](#ngxcrc32_long). The result is exactly the same as [ngx.crc32\_long](#ngxcrc32_long). Behind the scene, it is just a thin wrapper around the `ngx_crc32_short` function defined in the Nginx core. This API was first introduced in the `v0.3.1rc8` release. ### ngx.crc32\_long **syntax:** *intval = ngx.crc32\_long(str)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Calculates the CRC-32 (Cyclic Redundancy Code) digest for the `str` argument. This method performs better on relatively long `str` inputs (i.e., longer than 30 ~ 60 bytes), as compared to [ngx.crc32\_short](#ngxcrc32_short). The result is exactly the same as [ngx.crc32\_short](#ngxcrc32_short). Behind the scene, it is just a thin wrapper around the `ngx_crc32_long` function defined in the Nginx core. This API was first introduced in the `v0.3.1rc8` release. ### ngx.hmac\_sha1 **syntax:** *digest = ngx.hmac\_sha1(secret\_key, str)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Computes the [HMAC-SHA1](http://en.wikipedia.org/wiki/HMAC) digest of the argument `str` and turns the result using the secret key `<secret_key>`. The raw binary form of the `HMAC-SHA1` digest will be generated, use [ngx.encode\_base64](#ngxencode_base64), for example, to encode the result to a textual representation if desired. For example, ``` local key = "thisisverysecretstuff" local src = "some string we want to sign" local digest = ngx.hmac_sha1(key, src) ngx.say(ngx.encode_base64(digest)) ``` yields the output ``` R/pvxzHC4NLtj7S+kXFg/NePTmk= ``` This API requires the OpenSSL library enabled in the Nginx build (usually by passing the `--with-http_ssl_module` option to the `./configure` script). This function was first introduced in the `v0.3.1rc29` release. ### ngx.md5 **syntax:** *digest = ngx.md5(str)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Returns the hexadecimal representation of the MD5 digest of the `str` argument. For example, ``` location = /md5 { content_by_lua_block { ngx.say(ngx.md5("hello")) } } ``` yields the output ``` 5d41402abc4b2a76b9719d911017c592 ``` See [ngx.md5\_bin](#ngxmd5_bin) if the raw binary MD5 digest is required. ### ngx.md5\_bin **syntax:** *digest = ngx.md5\_bin(str)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Returns the binary form of the MD5 digest of the `str` argument. See [ngx.md5](#ngxmd5) if the hexadecimal form of the MD5 digest is required. ### ngx.sha1\_bin **syntax:** *digest = ngx.sha1\_bin(str)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Returns the binary form of the SHA-1 digest of the `str` argument. This function requires SHA-1 support in the Nginx build. (This usually just means OpenSSL should be installed while building Nginx). This function was first introduced in the `v0.5.0rc6`. ### ngx.quote\_sql\_str **syntax:** *quoted\_value = ngx.quote\_sql\_str(raw\_value)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Returns a quoted SQL string literal according to the MySQL quoting rules. ### ngx.today **syntax:** *str = ngx.today()* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Returns current date (in the format `yyyy-mm-dd`) from the nginx cached time (no syscall involved unlike Lua's date library). This is the local time. ### ngx.time **syntax:** *secs = ngx.time()* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Returns the elapsed seconds from the epoch for the current time stamp from the nginx cached time (no syscall involved unlike Lua's date library). Updates of the Nginx time cache can be forced by calling [ngx.update\_time](#ngxupdate_time) first. ### ngx.now **syntax:** *secs = ngx.now()* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Returns a floating-point number for the elapsed time in seconds (including milliseconds as the decimal part) from the epoch for the current time stamp from the nginx cached time (no syscall involved unlike Lua's date library). You can forcibly update the Nginx time cache by calling [ngx.update\_time](#ngxupdate_time) first. This API was first introduced in `v0.3.1rc32`. ### ngx.update\_time **syntax:** *ngx.update\_time()* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Forcibly updates the Nginx current time cache. This call involves a syscall and thus has some overhead, so do not abuse it. This API was first introduced in `v0.3.1rc32`. ### ngx.localtime **syntax:** *str = ngx.localtime()* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Returns the current time stamp (in the format `yyyy-mm-dd hh:mm:ss`) of the nginx cached time (no syscall involved unlike Lua's [os.date](http://www.lua.org/manual/5.1/manual.html#pdf-os.date) function). This is the local time. ### ngx.utctime **syntax:** *str = ngx.utctime()* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Returns the current time stamp (in the format `yyyy-mm-dd hh:mm:ss`) of the nginx cached time (no syscall involved unlike Lua's [os.date](http://www.lua.org/manual/5.1/manual.html#pdf-os.date) function). This is the UTC time. ### ngx.cookie\_time **syntax:** *str = ngx.cookie\_time(sec)* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Returns a formatted string can be used as the cookie expiration time. The parameter `sec` is the time stamp in seconds (like those returned from [ngx.time](#ngxtime)). ``` ngx.say(ngx.cookie_time(1290079655)) -- yields "Thu, 18-Nov-10 11:27:35 GMT" ``` ### ngx.http\_time **syntax:** *str = ngx.http\_time(sec)* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Returns a formated string can be used as the http header time (for example, being used in `Last-Modified` header). The parameter `sec` is the time stamp in seconds (like those returned from [ngx.time](#ngxtime)). ``` ngx.say(ngx.http_time(1290079655)) -- yields "Thu, 18 Nov 2010 11:27:35 GMT" ``` ### ngx.parse\_http\_time **syntax:** *sec = ngx.parse\_http\_time(str)* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Parse the http time string (as returned by [ngx.http\_time](#ngxhttp_time)) into seconds. Returns the seconds or `nil` if the input string is in bad forms. ``` local time = ngx.parse_http_time("Thu, 18 Nov 2010 11:27:35 GMT") if time == nil then ... end ``` ### ngx.is\_subrequest **syntax:** *value = ngx.is\_subrequest* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\** Returns `true` if the current request is an nginx subrequest, or `false` otherwise. ### ngx.re.match **syntax:** *captures, err = ngx.re.match(subject, regex, options?, ctx?, res\_table?)* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Matches the `subject` string using the Perl compatible regular expression `regex` with the optional `options`. Only the first occurrence of the match is returned, or `nil` if no match is found. In case of errors, like seeing a bad regular expression or exceeding the PCRE stack limit, `nil` and a string describing the error will be returned. When a match is found, a Lua table `captures` is returned, where `captures[0]` holds the whole substring being matched, and `captures[1]` holds the first parenthesized sub-pattern's capturing, `captures[2]` the second, and so on. ``` local m, err = ngx.re.match("hello, 1234", "[0-9]+") if m then -- m[0] == "1234" else if err then ngx.log(ngx.ERR, "error: ", err) return end ngx.say("match not found") end ``` ``` local m, err = ngx.re.match("hello, 1234", "([0-9])[0-9]+") -- m[0] == "1234" -- m[1] == "1" ``` Named captures are also supported since the `v0.7.14` release and are returned in the same Lua table as key-value pairs as the numbered captures. ``` local m, err = ngx.re.match("hello, 1234", "([0-9])(?<remaining>[0-9]+)") -- m[0] == "1234" -- m[1] == "1" -- m[2] == "234" -- m["remaining"] == "234" ``` Unmatched subpatterns will have `false` values in their `captures` table fields. ``` local m, err = ngx.re.match("hello, world", "(world)|(hello)|(?<named>howdy)") -- m[0] == "hello" -- m[1] == false -- m[2] == "hello" -- m[3] == false -- m["named"] == false ``` Specify `options` to control how the match operation will be performed. The following option characters are supported: ``` a anchored mode (only match from the beginning) d enable the DFA mode (or the longest token match semantics). this requires PCRE 6.0+ or else a Lua exception will be thrown. first introduced in ngx_lua v0.3.1rc30. D enable duplicate named pattern support. This allows named subpattern names to be repeated, returning the captures in an array-like Lua table. for example, local m = ngx.re.match("hello, world", "(?<named>\w+), (?<named>\w+)", "D") -- m["named"] == {"hello", "world"} this option was first introduced in the v0.7.14 release. this option requires at least PCRE 8.12. i case insensitive mode (similar to Perl's /i modifier) j enable PCRE JIT compilation, this requires PCRE 8.21+ which must be built with the --enable-jit option. for optimum performance, this option should always be used together with the 'o' option. first introduced in ngx_lua v0.3.1rc30. J enable the PCRE Javascript compatible mode. this option was first introduced in the v0.7.14 release. this option requires at least PCRE 8.12. m multi-line mode (similar to Perl's /m modifier) o compile-once mode (similar to Perl's /o modifier), to enable the worker-process-level compiled-regex cache s single-line mode (similar to Perl's /s modifier) u UTF-8 mode. this requires PCRE to be built with the --enable-utf8 option or else a Lua exception will be thrown. U similar to "u" but disables PCRE's UTF-8 validity check on the subject string. first introduced in ngx_lua v0.8.1. x extended mode (similar to Perl's /x modifier) ``` These options can be combined: ``` local m, err = ngx.re.match("hello, world", "HEL LO", "ix") -- m[0] == "hello" ``` ``` local m, err = ngx.re.match("hello, 美好生活", "HELLO, (.{2})", "iu") -- m[0] == "hello, 美好" -- m[1] == "美好" ``` The `o` option is useful for performance tuning, because the regex pattern in question will only be compiled once, cached in the worker-process level, and shared among all requests in the current Nginx worker process. The upper limit of the regex cache can be tuned via the [lua\_regex\_cache\_max\_entries](#lua_regex_cache_max_entries) directive. The optional fourth argument, `ctx`, can be a Lua table holding an optional `pos` field. When the `pos` field in the `ctx` table argument is specified, `ngx.re.match` will start matching from that offset (starting from 1). Regardless of the presence of the `pos` field in the `ctx` table, `ngx.re.match` will always set this `pos` field to the position *after* the substring matched by the whole pattern in case of a successful match. When match fails, the `ctx` table will be left intact. ``` local ctx = {} local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx) -- m[0] = "1234" -- ctx.pos == 5 ``` ``` local ctx = { pos = 2 } local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx) -- m[0] = "234" -- ctx.pos == 5 ``` The `ctx` table argument combined with the `a` regex modifier can be used to construct a lexer atop `ngx.re.match`. Note that, the `options` argument is not optional when the `ctx` argument is specified and that the empty Lua string (`""`) must be used as placeholder for `options` if no meaningful regex options are required. This method requires the PCRE library enabled in Nginx. ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)). To confirm that PCRE JIT is enabled, activate the Nginx debug log by adding the `--with-debug` option to Nginx or OpenResty's `./configure` script. Then, enable the "debug" error log level in `error_log` directive. The following message will be generated if PCRE JIT is enabled: ``` pcre JIT compiling result: 1 ``` Starting from the `0.9.4` release, this function also accepts a 5th argument, `res_table`, for letting the caller supply the Lua table used to hold all the capturing results. Starting from `0.9.6`, it is the caller's responsibility to ensure this table is empty. This is very useful for recycling Lua tables and saving GC and table allocation overhead. This feature was introduced in the `v0.2.1rc11` release. ### ngx.re.find **syntax:** *from, to, err = ngx.re.find(subject, regex, options?, ctx?, nth?)* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Similar to [ngx.re.match](#ngxrematch) but only returns the beginning index (`from`) and end index (`to`) of the matched substring. The returned indexes are 1-based and can be fed directly into the [string.sub](http://www.lua.org/manual/5.1/manual.html#pdf-string.sub) API function to obtain the matched substring. In case of errors (like bad regexes or any PCRE runtime errors), this API function returns two `nil` values followed by a string describing the error. If no match is found, this function just returns a `nil` value. Below is an example: ``` local s = "hello, 1234" local from, to, err = ngx.re.find(s, "([0-9]+)", "jo") if from then ngx.say("from: ", from) ngx.say("to: ", to) ngx.say("matched: ", string.sub(s, from, to)) else if err then ngx.say("error: ", err) return end ngx.say("not matched!") end ``` This example produces the output ``` from: 8 to: 11 matched: 1234 ``` Because this API function does not create new Lua strings nor new Lua tables, it is much faster than [ngx.re.match](#ngxrematch). It should be used wherever possible. Since the `0.9.3` release, an optional 5th argument, `nth`, is supported to specify which (submatch) capture's indexes to return. When `nth` is 0 (which is the default), the indexes for the whole matched substring is returned; when `nth` is 1, then the 1st submatch capture's indexes are returned; when `nth` is 2, then the 2nd submatch capture is returned, and so on. When the specified submatch does not have a match, then two `nil` values will be returned. Below is an example for this: ``` local str = "hello, 1234" local from, to = ngx.re.find(str, "([0-9])([0-9]+)", "jo", nil, 2) if from then ngx.say("matched 2nd submatch: ", string.sub(str, from, to)) -- yields "234" end ``` This API function was first introduced in the `v0.9.2` release. ### ngx.re.gmatch **syntax:** *iterator, err = ngx.re.gmatch(subject, regex, options?)* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Similar to [ngx.re.match](#ngxrematch), but returns a Lua iterator instead, so as to let the user programmer iterate all the matches over the `<subject>` string argument with the PCRE `regex`. In case of errors, like seeing an ill-formed regular expression, `nil` and a string describing the error will be returned. Here is a small example to demonstrate its basic usage: ``` local iterator, err = ngx.re.gmatch("hello, world!", "([a-z]+)", "i") if not iterator then ngx.log(ngx.ERR, "error: ", err) return end local m m, err = iterator() -- m[0] == m[1] == "hello" if err then ngx.log(ngx.ERR, "error: ", err) return end m, err = iterator() -- m[0] == m[1] == "world" if err then ngx.log(ngx.ERR, "error: ", err) return end m, err = iterator() -- m == nil if err then ngx.log(ngx.ERR, "error: ", err) return end ``` More often we just put it into a Lua loop: ``` local it, err = ngx.re.gmatch("hello, world!", "([a-z]+)", "i") if not it then ngx.log(ngx.ERR, "error: ", err) return end while true do local m, err = it() if err then ngx.log(ngx.ERR, "error: ", err) return end if not m then -- no match found (any more) break end -- found a match ngx.say(m[0]) ngx.say(m[1]) end ``` The optional `options` argument takes exactly the same semantics as the [ngx.re.match](#ngxrematch) method. The current implementation requires that the iterator returned should only be used in a single request. That is, one should *not* assign it to a variable belonging to persistent namespace like a Lua package. This method requires the PCRE library enabled in Nginx. ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)). This feature was first introduced in the `v0.2.1rc12` release. ### ngx.re.sub **syntax:** *newstr, n, err = ngx.re.sub(subject, regex, replace, options?)* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Substitutes the first match of the Perl compatible regular expression `regex` on the `subject` argument string with the string or function argument `replace`. The optional `options` argument has exactly the same meaning as in [ngx.re.match](#ngxrematch). This method returns the resulting new string as well as the number of successful substitutions. In case of failures, like syntax errors in the regular expressions or the `<replace>` string argument, it will return `nil` and a string describing the error. When the `replace` is a string, then it is treated as a special template for string replacement. For example, ``` local newstr, n, err = ngx.re.sub("hello, 1234", "([0-9])[0-9]", "[$0][$1]") if newstr then -- newstr == "hello, [12][1]34" -- n == 1 else ngx.log(ngx.ERR, "error: ", err) return end ``` where `$0` referring to the whole substring matched by the pattern and `$1` referring to the first parenthesized capturing substring. Curly braces can also be used to disambiguate variable names from the background string literals: ``` local newstr, n, err = ngx.re.sub("hello, 1234", "[0-9]", "${0}00") -- newstr == "hello, 100234" -- n == 1 ``` Literal dollar sign characters (`$`) in the `replace` string argument can be escaped by another dollar sign, for instance, ``` local newstr, n, err = ngx.re.sub("hello, 1234", "[0-9]", "$$") -- newstr == "hello, $234" -- n == 1 ``` Do not use backlashes to escape dollar signs; it will not work as expected. When the `replace` argument is of type "function", then it will be invoked with the "match table" as the argument to generate the replace string literal for substitution. The "match table" fed into the `replace` function is exactly the same as the return value of [ngx.re.match](#ngxrematch). Here is an example: ``` local func = function (m) return "[" .. m[0] .. "][" .. m[1] .. "]" end local newstr, n, err = ngx.re.sub("hello, 1234", "( [0-9] ) [0-9]", func, "x") -- newstr == "hello, [12][1]34" -- n == 1 ``` The dollar sign characters in the return value of the `replace` function argument are not special at all. This method requires the PCRE library enabled in Nginx. ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)). This feature was first introduced in the `v0.2.1rc13` release. ### ngx.re.gsub **syntax:** *newstr, n, err = ngx.re.gsub(subject, regex, replace, options?)* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Just like [ngx.re.sub](#ngxresub), but does global substitution. Here is some examples: ``` local newstr, n, err = ngx.re.gsub("hello, world", "([a-z])[a-z]+", "[$0,$1]", "i") if newstr then -- newstr == "[hello,h], [world,w]" -- n == 2 else ngx.log(ngx.ERR, "error: ", err) return end ``` ``` local func = function (m) return "[" .. m[0] .. "," .. m[1] .. "]" end local newstr, n, err = ngx.re.gsub("hello, world", "([a-z])[a-z]+", func, "i") -- newstr == "[hello,h], [world,w]" -- n == 2 ``` This method requires the PCRE library enabled in Nginx. ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)). This feature was first introduced in the `v0.2.1rc15` release. ### ngx.shared.DICT **syntax:** *dict = ngx.shared.DICT* **syntax:** *dict = ngx.shared[name\_var]* **context:** *init\_by\_lua\*, init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Fetching the shm-based Lua dictionary object for the shared memory zone named `DICT` defined by the [lua\_shared\_dict](#lua_shared_dict) directive. Shared memory zones are always shared by all the nginx worker processes in the current nginx server instance. The resulting object `dict` has the following methods: * [get](#ngxshareddictget) * [get\_stale](#ngxshareddictget_stale) * [set](#ngxshareddictset) * [safe\_set](#ngxshareddictsafe_set) * [add](#ngxshareddictadd) * [safe\_add](#ngxshareddictsafe_add) * [replace](#ngxshareddictreplace) * [delete](#ngxshareddictdelete) * [incr](#ngxshareddictincr) * [lpush](#ngxshareddictlpush) * [rpush](#ngxshareddictrpush) * [lpop](#ngxshareddictlpop) * [rpop](#ngxshareddictrpop) * [llen](#ngxshareddictllen) * [ttl](#ngxshareddictttl) * [expire](#ngxshareddictexpire) * [flush\_all](#ngxshareddictflush_all) * [flush\_expired](#ngxshareddictflush_expired) * [get\_keys](#ngxshareddictget_keys) * [capacity](#ngxshareddictcapacity) * [free\_space](#ngxshareddictfree_space) All these methods are *atomic* operations, that is, safe from concurrent accesses from multiple nginx worker processes for the same `lua_shared_dict` zone. Here is an example: ``` http { lua_shared_dict dogs 10m; server { location /set { content_by_lua_block { local dogs = ngx.shared.dogs dogs:set("Jim", 8) ngx.say("STORED") } } location /get { content_by_lua_block { local dogs = ngx.shared.dogs ngx.say(dogs:get("Jim")) } } } } ``` Let us test it: ``` $ curl localhost/set STORED $ curl localhost/get 8 $ curl localhost/get 8 ``` The number `8` will be consistently output when accessing `/get` regardless of how many Nginx workers there are because the `dogs` dictionary resides in the shared memory and visible to *all* of the worker processes. The shared dictionary will retain its contents through a server config reload (either by sending the `HUP` signal to the Nginx process or by using the `-s reload` command-line option). The contents in the dictionary storage will be lost, however, when the Nginx server quits. This feature was first introduced in the `v0.3.1rc22` release. ### ngx.shared.DICT.get **syntax:** *value, flags = ngx.shared.DICT:get(key)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Retrieving the value in the dictionary [ngx.shared.DICT](#ngxshareddict) for the key `key`. If the key does not exist or has expired, then `nil` will be returned. In case of errors, `nil` and a string describing the error will be returned. The value returned will have the original data type when they were inserted into the dictionary, for example, Lua booleans, numbers, or strings. The first argument to this method must be the dictionary object itself, for example, ``` local cats = ngx.shared.cats local value, flags = cats.get(cats, "Marry") ``` or use Lua's syntactic sugar for method calls: ``` local cats = ngx.shared.cats local value, flags = cats:get("Marry") ``` These two forms are fundamentally equivalent. If the user flags is `0` (the default), then no flags value will be returned. This feature was first introduced in the `v0.3.1rc22` release. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.get\_stale **syntax:** *value, flags, stale = ngx.shared.DICT:get\_stale(key)* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Similar to the [get](#ngxshareddictget) method but returns the value even if the key has already expired. Returns a 3rd value, `stale`, indicating whether the key has expired or not. Note that the value of an expired key is not guaranteed to be available so one should never rely on the availability of expired items. This method was first introduced in the `0.8.6` release. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.set **syntax:** *success, err, forcible = ngx.shared.DICT:set(key, value, exptime?, flags?)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Unconditionally sets a key-value pair into the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). Returns three values: * `success`: boolean value to indicate whether the key-value pair is stored or not. * `err`: textual error message, can be `"no memory"`. * `forcible`: a boolean value to indicate whether other valid items have been removed forcibly when out of storage in the shared memory zone. The `value` argument inserted can be Lua booleans, numbers, strings, or `nil`. Their value type will also be stored into the dictionary and the same data type can be retrieved later via the [get](#ngxshareddictget) method. The optional `exptime` argument specifies expiration time (in seconds) for the inserted key-value pair. The time resolution is `0.001` seconds. If the `exptime` takes the value `0` (which is the default), then the item will never expire. The optional `flags` argument specifies a user flags value associated with the entry to be stored. It can also be retrieved later with the value. The user flags is stored as an unsigned 32-bit integer internally. Defaults to `0`. The user flags argument was first introduced in the `v0.5.0rc2` release. When it fails to allocate memory for the current key-value item, then `set` will try removing existing items in the storage according to the Least-Recently Used (LRU) algorithm. Note that, LRU takes priority over expiration time here. If up to tens of existing items have been removed and the storage left is still insufficient (either due to the total capacity limit specified by [lua\_shared\_dict](#lua_shared_dict) or memory segmentation), then the `err` return value will be `no memory` and `success` will be `false`. If this method succeeds in storing the current item by forcibly removing other not-yet-expired items in the dictionary via LRU, the `forcible` return value will be `true`. If it stores the item without forcibly removing other valid items, then the return value `forcible` will be `false`. The first argument to this method must be the dictionary object itself, for example, ``` local cats = ngx.shared.cats local succ, err, forcible = cats.set(cats, "Marry", "it is a nice cat!") ``` or use Lua's syntactic sugar for method calls: ``` local cats = ngx.shared.cats local succ, err, forcible = cats:set("Marry", "it is a nice cat!") ``` These two forms are fundamentally equivalent. This feature was first introduced in the `v0.3.1rc22` release. Please note that while internally the key-value pair is set atomically, the atomicity does not go across the method call boundary. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.safe\_set **syntax:** *ok, err = ngx.shared.DICT:safe\_set(key, value, exptime?, flags?)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Similar to the [set](#ngxshareddictset) method, but never overrides the (least recently used) unexpired items in the store when running out of storage in the shared memory zone. In this case, it will immediately return `nil` and the string "no memory". This feature was first introduced in the `v0.7.18` release. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.add **syntax:** *success, err, forcible = ngx.shared.DICT:add(key, value, exptime?, flags?)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Just like the [set](#ngxshareddictset) method, but only stores the key-value pair into the dictionary [ngx.shared.DICT](#ngxshareddict) if the key does *not* exist. If the `key` argument already exists in the dictionary (and not expired for sure), the `success` return value will be `false` and the `err` return value will be `"exists"`. This feature was first introduced in the `v0.3.1rc22` release. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.safe\_add **syntax:** *ok, err = ngx.shared.DICT:safe\_add(key, value, exptime?, flags?)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Similar to the [add](#ngxshareddictadd) method, but never overrides the (least recently used) unexpired items in the store when running out of storage in the shared memory zone. In this case, it will immediately return `nil` and the string "no memory". This feature was first introduced in the `v0.7.18` release. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.replace **syntax:** *success, err, forcible = ngx.shared.DICT:replace(key, value, exptime?, flags?)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Just like the [set](#ngxshareddictset) method, but only stores the key-value pair into the dictionary [ngx.shared.DICT](#ngxshareddict) if the key *does* exist. If the `key` argument does *not* exist in the dictionary (or expired already), the `success` return value will be `false` and the `err` return value will be `"not found"`. This feature was first introduced in the `v0.3.1rc22` release. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.delete **syntax:** *ngx.shared.DICT:delete(key)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Unconditionally removes the key-value pair from the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). It is equivalent to `ngx.shared.DICT:set(key, nil)`. This feature was first introduced in the `v0.3.1rc22` release. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.incr **syntax:** *newval, err, forcible? = ngx.shared.DICT:incr(key, value, init?, init\_ttl?)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** **optional requirement:** `resty.core.shdict` or `resty.core` Increments the (numerical) value for `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict) by the step value `value`. Returns the new resulting number if the operation is successfully completed or `nil` and an error message otherwise. When the key does not exist or has already expired in the shared dictionary, 1. if the `init` argument is not specified or takes the value `nil`, this method will return `nil` and the error string `"not found"`, or 2. if the `init` argument takes a number value, this method will create a new `key` with the value `init + value`. Like the [add](#ngxshareddictadd) method, it also overrides the (least recently used) unexpired items in the store when running out of storage in the shared memory zone. The optional `init_ttl` argument specifies expiration time (in seconds) of the value when it is initialized via the `init` argument. The time resolution is `0.001` seconds. If `init_ttl` takes the value `0` (which is the default), then the item will never expire. This argument cannot be provided without providing the `init` argument as well, and has no effect if the value already exists (e.g., if it was previously inserted via [set](#ngxshareddictset) or the likes). **Note:** Usage of the `init_ttl` argument requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library. Example: ``` require "resty.core" local cats = ngx.shared.cats local newval, err = cats:incr("black_cats", 1, 0, 0.1) print(newval) -- 1 ngx.sleep(0.2) local val, err = cats:get("black_cats") print(val) -- nil ``` The `forcible` return value will always be `nil` when the `init` argument is not specified. If this method succeeds in storing the current item by forcibly removing other not-yet-expired items in the dictionary via LRU, the `forcible` return value will be `true`. If it stores the item without forcibly removing other valid items, then the return value `forcible` will be `false`. If the original value is not a valid Lua number in the dictionary, it will return `nil` and `"not a number"`. The `value` argument and `init` argument can be any valid Lua numbers, like negative numbers or floating-point numbers. This method was first introduced in the `v0.3.1rc22` release. The optional `init` parameter was first added in the `v0.10.6` release. The optional `init_ttl` parameter was introduced in the `v0.10.12rc2` release. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.lpush **syntax:** *length, err = ngx.shared.DICT:lpush(key, value)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Inserts the specified (numerical or string) `value` at the head of the list named `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). Returns the number of elements in the list after the push operation. If `key` does not exist, it is created as an empty list before performing the push operation. When the `key` already takes a value that is not a list, it will return `nil` and `"value not a list"`. It never overrides the (least recently used) unexpired items in the store when running out of storage in the shared memory zone. In this case, it will immediately return `nil` and the string "no memory". This feature was first introduced in the `v0.10.6` release. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.rpush **syntax:** *length, err = ngx.shared.DICT:rpush(key, value)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Similar to the [lpush](#ngxshareddictlpush) method, but inserts the specified (numerical or string) `value` at the tail of the list named `key`. This feature was first introduced in the `v0.10.6` release. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.lpop **syntax:** *val, err = ngx.shared.DICT:lpop(key)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Removes and returns the first element of the list named `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). If `key` does not exist, it will return `nil`. When the `key` already takes a value that is not a list, it will return `nil` and `"value not a list"`. This feature was first introduced in the `v0.10.6` release. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.rpop **syntax:** *val, err = ngx.shared.DICT:rpop(key)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Removes and returns the last element of the list named `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). If `key` does not exist, it will return `nil`. When the `key` already takes a value that is not a list, it will return `nil` and `"value not a list"`. This feature was first introduced in the `v0.10.6` release. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.llen **syntax:** *len, err = ngx.shared.DICT:llen(key)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Returns the number of elements in the list named `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). If key does not exist, it is interpreted as an empty list and 0 is returned. When the `key` already takes a value that is not a list, it will return `nil` and `"value not a list"`. This feature was first introduced in the `v0.10.6` release. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.ttl **syntax:** *ttl, err = ngx.shared.DICT:ttl(key)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** **requires:** `resty.core.shdict` or `resty.core` Retrieves the remaining TTL (time-to-live in seconds) of a key-value pair in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). Returns the TTL as a number if the operation is successfully completed or `nil` and an error message otherwise. If the key does not exist (or has already expired), this method will return `nil` and the error string `"not found"`. The TTL is originally determined by the `exptime` argument of the [set](#ngxshareddictset), [add](#ngxshareddictadd), [replace](#ngxshareddictreplace) (and the likes) methods. It has a time resolution of `0.001` seconds. A value of `0` means that the item will never expire. Example: ``` require "resty.core" local cats = ngx.shared.cats local succ, err = cats:set("Marry", "a nice cat", 0.5) ngx.sleep(0.2) local ttl, err = cats:ttl("Marry") ngx.say(ttl) -- 0.3 ``` This feature was first introduced in the `v0.10.11` release. **Note:** This method requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.expire **syntax:** *success, err = ngx.shared.DICT:expire(key, exptime)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** **requires:** `resty.core.shdict` or `resty.core` Updates the `exptime` (in second) of a key-value pair in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). Returns a boolean indicating success if the operation completes or `nil` and an error message otherwise. If the key does not exist, this method will return `nil` and the error string `"not found"`. The `exptime` argument has a resolution of `0.001` seconds. If `exptime` is `0`, then the item will never expire. Example: ``` require "resty.core" local cats = ngx.shared.cats local succ, err = cats:set("Marry", "a nice cat", 0.1) succ, err = cats:expire("Marry", 0.5) ngx.sleep(0.2) local val, err = cats:get("Marry") ngx.say(val) -- "a nice cat" ``` This feature was first introduced in the `v0.10.11` release. **Note:** This method requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.flush\_all **syntax:** *ngx.shared.DICT:flush\_all()* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Flushes out all the items in the dictionary. This method does not actuall free up all the memory blocks in the dictionary but just marks all the existing items as expired. This feature was first introduced in the `v0.5.0rc17` release. See also [ngx.shared.DICT.flush\_expired](#ngxshareddictflush_expired) and [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.flush\_expired **syntax:** *flushed = ngx.shared.DICT:flush\_expired(max\_count?)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Flushes out the expired items in the dictionary, up to the maximal number specified by the optional `max_count` argument. When the `max_count` argument is given `0` or not given at all, then it means unlimited. Returns the number of items that have actually been flushed. Unlike the [flush\_all](#ngxshareddictflush_all) method, this method actually free up the memory used by the expired items. This feature was first introduced in the `v0.6.3` release. See also [ngx.shared.DICT.flush\_all](#ngxshareddictflush_all) and [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.get\_keys **syntax:** *keys = ngx.shared.DICT:get\_keys(max\_count?)* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Fetch a list of the keys from the dictionary, up to `<max_count>`. By default, only the first 1024 keys (if any) are returned. When the `<max_count>` argument is given the value `0`, then all the keys will be returned even there is more than 1024 keys in the dictionary. **CAUTION** Avoid calling this method on dictionaries with a very large number of keys as it may lock the dictionary for significant amount of time and block Nginx worker processes trying to access the dictionary. This feature was first introduced in the `v0.7.3` release. ### ngx.shared.DICT.capacity **syntax:** *capacity\_bytes = ngx.shared.DICT:capacity()* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** **requires:** `resty.core.shdict` or `resty.core` Retrieves the capacity in bytes for the shm-based dictionary [ngx.shared.DICT](#ngxshareddict) declared with the [lua\_shared\_dict](#lua_shared_dict) directive. Example: ``` require "resty.core.shdict" local cats = ngx.shared.cats local capacity_bytes = cats:capacity() ``` This feature was first introduced in the `v0.10.11` release. **Note:** This method requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library. This feature requires at least nginx core version `0.7.3`. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.shared.DICT.free\_space **syntax:** *free\_page\_bytes = ngx.shared.DICT:free\_space()* **context:** *init\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** **requires:** `resty.core.shdict` or `resty.core` Retrieves the free page size in bytes for the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). **Note:** The memory for ngx.shared.DICT is allocated via the nginx slab allocator which has each slot for data size ranges like ~8, 9~16, 17~32, ..., 1025~2048, 2048~ bytes. And pages are assigned to a slot if there is no room in already assigned pages for the slot. So even if the return value of the `free_space` method is zero, there may be room in already assigned pages, so you may successfully set a new key value pair to the shared dict without getting `true` for `forcible` or non nil `err` from the `ngx.shared.DICT.set`. On the other hand, if already assigned pages for a slot are full and a new key value pair is added to the slot and there is no free page, you may get `true` for `forcible` or non nil `err` from the `ngx.shared.DICT.set` method. Example: ``` require "resty.core.shdict" local cats = ngx.shared.cats local free_page_bytes = cats:free_space() ``` This feature was first introduced in the `v0.10.11` release. **Note:** This method requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library. This feature requires at least nginx core version `1.11.7`. See also [ngx.shared.DICT](#ngxshareddict). ### ngx.socket.udp **syntax:** *udpsock = ngx.socket.udp()* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Creates and returns a UDP or datagram-oriented unix domain socket object (also known as one type of the "cosocket" objects). The following methods are supported on this object: * [setpeername](#udpsocksetpeername) * [send](#udpsocksend) * [receive](#udpsockreceive) * [close](#udpsockclose) * [settimeout](#udpsocksettimeout) It is intended to be compatible with the UDP API of the [LuaSocket](http://w3.impa.br/%7Ediego/software/luasocket/udp.html) library but is 100% nonblocking out of the box. This feature was first introduced in the `v0.5.7` release. See also [ngx.socket.tcp](#ngxsockettcp). ### udpsock:setpeername **syntax:** *ok, err = udpsock:setpeername(host, port)* **syntax:** *ok, err = udpsock:setpeername("unix:/path/to/unix-domain.socket")* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Attempts to connect a UDP socket object to a remote server or to a datagram unix domain socket file. Because the datagram protocol is actually connection-less, this method does not really establish a "connection", but only just set the name of the remote peer for subsequent read/write operations. Both IP addresses and domain names can be specified as the `host` argument. In case of domain names, this method will use Nginx core's dynamic resolver to parse the domain name without blocking and it is required to configure the [resolver](http://nginx.org/en/docs/http/ngx_http_core_module.html#resolver) directive in the `nginx.conf` file like this: ``` resolver 8.8.8.8; # use Google's public DNS nameserver ``` If the nameserver returns multiple IP addresses for the host name, this method will pick up one randomly. In case of error, the method returns `nil` followed by a string describing the error. In case of success, the method returns `1`. Here is an example for connecting to a UDP (memcached) server: ``` location /test { resolver 8.8.8.8; content_by_lua_block { local sock = ngx.socket.udp() local ok, err = sock:setpeername("my.memcached.server.domain", 11211) if not ok then ngx.say("failed to connect to memcached: ", err) return end ngx.say("successfully connected to memcached!") sock:close() } } ``` Since the `v0.7.18` release, connecting to a datagram unix domain socket file is also possible on Linux: ``` local sock = ngx.socket.udp() local ok, err = sock:setpeername("unix:/tmp/some-datagram-service.sock") if not ok then ngx.say("failed to connect to the datagram unix domain socket: ", err) return end ``` assuming the datagram service is listening on the unix domain socket file `/tmp/some-datagram-service.sock` and the client socket will use the "autobind" feature on Linux. Calling this method on an already connected socket object will cause the original connection to be closed first. This method was first introduced in the `v0.5.7` release. ### udpsock:send **syntax:** *ok, err = udpsock:send(data)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Sends data on the current UDP or datagram unix domain socket object. In case of success, it returns `1`. Otherwise, it returns `nil` and a string describing the error. The input argument `data` can either be a Lua string or a (nested) Lua table holding string fragments. In case of table arguments, this method will copy all the string elements piece by piece to the underlying Nginx socket send buffers, which is usually optimal than doing string concatenation operations on the Lua land. This feature was first introduced in the `v0.5.7` release. ### udpsock:receive **syntax:** *data, err = udpsock:receive(size?)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Receives data from the UDP or datagram unix domain socket object with an optional receive buffer size argument, `size`. This method is a synchronous operation and is 100% nonblocking. In case of success, it returns the data received; in case of error, it returns `nil` with a string describing the error. If the `size` argument is specified, then this method will use this size as the receive buffer size. But when this size is greater than `8192`, then `8192` will be used instead. If no argument is specified, then the maximal buffer size, `8192` is assumed. Timeout for the reading operation is controlled by the [lua\_socket\_read\_timeout](#lua_socket_read_timeout) config directive and the [settimeout](#udpsocksettimeout) method. And the latter takes priority. For example: ``` sock:settimeout(1000) -- one second timeout local data, err = sock:receive() if not data then ngx.say("failed to read a packet: ", err) return end ngx.say("successfully read a packet: ", data) ``` It is important here to call the [settimeout](#udpsocksettimeout) method *before* calling this method. This feature was first introduced in the `v0.5.7` release. ### udpsock:close **syntax:** *ok, err = udpsock:close()* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Closes the current UDP or datagram unix domain socket. It returns the `1` in case of success and returns `nil` with a string describing the error otherwise. Socket objects that have not invoked this method (and associated connections) will be closed when the socket object is released by the Lua GC (Garbage Collector) or the current client HTTP request finishes processing. This feature was first introduced in the `v0.5.7` release. ### udpsock:settimeout **syntax:** *udpsock:settimeout(time)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Set the timeout value in milliseconds for subsequent socket operations (like [receive](#udpsockreceive)). Settings done by this method takes priority over those config directives, like [lua\_socket\_read\_timeout](#lua_socket_read_timeout). This feature was first introduced in the `v0.5.7` release. ### ngx.socket.stream Just an alias to [ngx.socket.tcp](#ngxsockettcp). If the stream-typed cosocket may also connect to a unix domain socket, then this API name is preferred. This API function was first added to the `v0.10.1` release. ### ngx.socket.tcp **syntax:** *tcpsock = ngx.socket.tcp()* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Creates and returns a TCP or stream-oriented unix domain socket object (also known as one type of the "cosocket" objects). The following methods are supported on this object: * [connect](#tcpsockconnect) * [sslhandshake](#tcpsocksslhandshake) * [send](#tcpsocksend) * [receive](#tcpsockreceive) * [close](#tcpsockclose) * [settimeout](#tcpsocksettimeout) * [settimeouts](#tcpsocksettimeouts) * [setoption](#tcpsocksetoption) * [receiveuntil](#tcpsockreceiveuntil) * [setkeepalive](#tcpsocksetkeepalive) * [getreusedtimes](#tcpsockgetreusedtimes) It is intended to be compatible with the TCP API of the [LuaSocket](http://w3.impa.br/%7Ediego/software/luasocket/tcp.html) library but is 100% nonblocking out of the box. Also, we introduce some new APIs to provide more functionalities. The cosocket object created by this API function has exactly the same lifetime as the Lua handler creating it. So never pass the cosocket object to any other Lua handler (including ngx.timer callback functions) and never share the cosocket object between different NGINX requests. For every cosocket object's underlying connection, if you do not explicitly close it (via [close](#tcpsockclose)) or put it back to the connection pool (via [setkeepalive](#tcpsocksetkeepalive)), then it is automatically closed when one of the following two events happens: * the current request handler completes, or * the Lua cosocket object value gets collected by the Lua GC. Fatal errors in cosocket operations always automatically close the current connection (note that, read timeout error is the only error that is not fatal), and if you call [close](#tcpsockclose) on a closed connection, you will get the "closed" error. Starting from the `0.9.9` release, the cosocket object here is full-duplex, that is, a reader "light thread" and a writer "light thread" can operate on a single cosocket object simultaneously (both "light threads" must belong to the same Lua handler though, see reasons above). But you cannot have two "light threads" both reading (or writing or connecting) the same cosocket, otherwise you might get an error like "socket busy reading" when calling the methods of the cosocket object. This feature was first introduced in the `v0.5.0rc1` release. See also [ngx.socket.udp](#ngxsocketudp). ### tcpsock:connect **syntax:** *ok, err = tcpsock:connect(host, port, options\_table?)* **syntax:** *ok, err = tcpsock:connect("unix:/path/to/unix-domain.socket", options\_table?)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Attempts to connect a TCP socket object to a remote server or to a stream unix domain socket file without blocking. Before actually resolving the host name and connecting to the remote backend, this method will always look up the connection pool for matched idle connections created by previous calls of this method (or the [ngx.socket.connect](#ngxsocketconnect) function). Both IP addresses and domain names can be specified as the `host` argument. In case of domain names, this method will use Nginx core's dynamic resolver to parse the domain name without blocking and it is required to configure the [resolver](http://nginx.org/en/docs/http/ngx_http_core_module.html#resolver) directive in the `nginx.conf` file like this: ``` resolver 8.8.8.8; # use Google's public DNS nameserver ``` If the nameserver returns multiple IP addresses for the host name, this method will pick up one randomly. In case of error, the method returns `nil` followed by a string describing the error. In case of success, the method returns `1`. Here is an example for connecting to a TCP server: ``` location /test { resolver 8.8.8.8; content_by_lua_block { local sock = ngx.socket.tcp() local ok, err = sock:connect("www.google.com", 80) if not ok then ngx.say("failed to connect to google: ", err) return end ngx.say("successfully connected to google!") sock:close() } } ``` Connecting to a Unix Domain Socket file is also possible: ``` local sock = ngx.socket.tcp() local ok, err = sock:connect("unix:/tmp/memcached.sock") if not ok then ngx.say("failed to connect to the memcached unix domain socket: ", err) return end ``` assuming memcached (or something else) is listening on the unix domain socket file `/tmp/memcached.sock`. Timeout for the connecting operation is controlled by the [lua\_socket\_connect\_timeout](#lua_socket_connect_timeout) config directive and the [settimeout](#tcpsocksettimeout) method. And the latter takes priority. For example: ``` local sock = ngx.socket.tcp() sock:settimeout(1000) -- one second timeout local ok, err = sock:connect(host, port) ``` It is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling this method. Calling this method on an already connected socket object will cause the original connection to be closed first. An optional Lua table can be specified as the last argument to this method to specify various connect options: * `pool` specify a custom name for the connection pool being used. If omitted, then the connection pool name will be generated from the string template `"<host>:<port>"` or `"<unix-socket-path>"`. The support for the options table argument was first introduced in the `v0.5.7` release. This method was first introduced in the `v0.5.0rc1` release. ### tcpsock:sslhandshake **syntax:** *session, err = tcpsock:sslhandshake(reused\_session?, server\_name?, ssl\_verify?, send\_status\_req?)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Does SSL/TLS handshake on the currently established connection. The optional `reused_session` argument can take a former SSL session userdata returned by a previous `sslhandshake` call for exactly the same target. For short-lived connections, reusing SSL sessions can usually speed up the handshake by one order by magnitude but it is not so useful if the connection pool is enabled. This argument defaults to `nil`. If this argument takes the boolean `false` value, no SSL session userdata would return by this call and only a Lua boolean will be returned as the first return value; otherwise the current SSL session will always be returned as the first argument in case of successes. The optional `server_name` argument is used to specify the server name for the new TLS extension Server Name Indication (SNI). Use of SNI can make different servers share the same IP address on the server side. Also, when SSL verification is enabled, this `server_name` argument is also used to validate the server name specified in the server certificate sent from the remote. The optional `ssl_verify` argument takes a Lua boolean value to control whether to perform SSL verification. When set to `true`, the server certificate will be verified according to the CA certificates specified by the [lua\_ssl\_trusted\_certificate](#lua_ssl_trusted_certificate) directive. You may also need to adjust the [lua\_ssl\_verify\_depth](#lua_ssl_verify_depth) directive to control how deep we should follow along the certificate chain. Also, when the `ssl_verify` argument is true and the `server_name` argument is also specified, the latter will be used to validate the server name in the server certificate. The optional `send_status_req` argument takes a boolean that controls whether to send the OCSP status request in the SSL handshake request (which is for requesting OCSP stapling). For connections that have already done SSL/TLS handshake, this method returns immediately. This method was first introduced in the `v0.9.11` release. ### tcpsock:send **syntax:** *bytes, err = tcpsock:send(data)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Sends data without blocking on the current TCP or Unix Domain Socket connection. This method is a synchronous operation that will not return until *all* the data has been flushed into the system socket send buffer or an error occurs. In case of success, it returns the total number of bytes that have been sent. Otherwise, it returns `nil` and a string describing the error. The input argument `data` can either be a Lua string or a (nested) Lua table holding string fragments. In case of table arguments, this method will copy all the string elements piece by piece to the underlying Nginx socket send buffers, which is usually optimal than doing string concatenation operations on the Lua land. Timeout for the sending operation is controlled by the [lua\_socket\_send\_timeout](#lua_socket_send_timeout) config directive and the [settimeout](#tcpsocksettimeout) method. And the latter takes priority. For example: ``` sock:settimeout(1000) -- one second timeout local bytes, err = sock:send(request) ``` It is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling this method. In case of any connection errors, this method always automatically closes the current connection. This feature was first introduced in the `v0.5.0rc1` release. ### tcpsock:receive **syntax:** *data, err, partial = tcpsock:receive(size)* **syntax:** *data, err, partial = tcpsock:receive(pattern?)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Receives data from the connected socket according to the reading pattern or size. This method is a synchronous operation just like the [send](#tcpsocksend) method and is 100% nonblocking. In case of success, it returns the data received; in case of error, it returns `nil` with a string describing the error and the partial data received so far. If a number-like argument is specified (including strings that look like numbers), then it is interpreted as a size. This method will not return until it reads exactly this size of data or an error occurs. If a non-number-like string argument is specified, then it is interpreted as a "pattern". The following patterns are supported: * `'*a'`: reads from the socket until the connection is closed. No end-of-line translation is performed; * `'*l'`: reads a line of text from the socket. The line is terminated by a `Line Feed` (LF) character (ASCII 10), optionally preceded by a `Carriage Return` (CR) character (ASCII 13). The CR and LF characters are not included in the returned line. In fact, all CR characters are ignored by the pattern. If no argument is specified, then it is assumed to be the pattern `'*l'`, that is, the line reading pattern. Timeout for the reading operation is controlled by the [lua\_socket\_read\_timeout](#lua_socket_read_timeout) config directive and the [settimeout](#tcpsocksettimeout) method. And the latter takes priority. For example: ``` sock:settimeout(1000) -- one second timeout local line, err, partial = sock:receive() if not line then ngx.say("failed to read a line: ", err) return end ngx.say("successfully read a line: ", line) ``` It is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling this method. Since the `v0.8.8` release, this method no longer automatically closes the current connection when the read timeout error happens. For other connection errors, this method always automatically closes the connection. This feature was first introduced in the `v0.5.0rc1` release. ### tcpsock:receiveuntil **syntax:** *iterator = tcpsock:receiveuntil(pattern, options?)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** This method returns an iterator Lua function that can be called to read the data stream until it sees the specified pattern or an error occurs. Here is an example for using this method to read a data stream with the boundary sequence `--abcedhb`: ``` local reader = sock:receiveuntil("\r\n--abcedhb") local data, err, partial = reader() if not data then ngx.say("failed to read the data stream: ", err) end ngx.say("read the data stream: ", data) ``` When called without any argument, the iterator function returns the received data right *before* the specified pattern string in the incoming data stream. So for the example above, if the incoming data stream is `'hello, world! -agentzh\r\n--abcedhb blah blah'`, then the string `'hello, world! -agentzh'` will be returned. In case of error, the iterator function will return `nil` along with a string describing the error and the partial data bytes that have been read so far. The iterator function can be called multiple times and can be mixed safely with other cosocket method calls or other iterator function calls. The iterator function behaves differently (i.e., like a real iterator) when it is called with a `size` argument. That is, it will read that `size` of data on each invocation and will return `nil` at the last invocation (either sees the boundary pattern or meets an error). For the last successful invocation of the iterator function, the `err` return value will be `nil` too. The iterator function will be reset after the last successful invocation that returns `nil` data and `nil` error. Consider the following example: ``` local reader = sock:receiveuntil("\r\n--abcedhb") while true do local data, err, partial = reader(4) if not data then if err then ngx.say("failed to read the data stream: ", err) break end ngx.say("read done") break end ngx.say("read chunk: [", data, "]") end ``` Then for the incoming data stream `'hello, world! -agentzh\r\n--abcedhb blah blah'`, we shall get the following output from the sample code above: ``` read chunk: [hell] read chunk: [o, w] read chunk: [orld] read chunk: [! -a] read chunk: [gent] read chunk: [zh] read done ``` Note that, the actual data returned *might* be a little longer than the size limit specified by the `size` argument when the boundary pattern has ambiguity for streaming parsing. Near the boundary of the data stream, the data string actually returned could also be shorter than the size limit. Timeout for the iterator function's reading operation is controlled by the [lua\_socket\_read\_timeout](#lua_socket_read_timeout) config directive and the [settimeout](#tcpsocksettimeout) method. And the latter takes priority. For example: ``` local readline = sock:receiveuntil("\r\n") sock:settimeout(1000) -- one second timeout line, err, partial = readline() if not line then ngx.say("failed to read a line: ", err) return end ngx.say("successfully read a line: ", line) ``` It is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling the iterator function (note that the `receiveuntil` call is irrelevant here). As from the `v0.5.1` release, this method also takes an optional `options` table argument to control the behavior. The following options are supported: * `inclusive` The `inclusive` takes a boolean value to control whether to include the pattern string in the returned data string. Default to `false`. For example, ``` local reader = tcpsock:receiveuntil("_END_", { inclusive = true }) local data = reader() ngx.say(data) ``` Then for the input data stream `"hello world _END_ blah blah blah"`, then the example above will output `hello world _END_`, including the pattern string `_END_` itself. Since the `v0.8.8` release, this method no longer automatically closes the current connection when the read timeout error happens. For other connection errors, this method always automatically closes the connection. This method was first introduced in the `v0.5.0rc1` release. ### tcpsock:close **syntax:** *ok, err = tcpsock:close()* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Closes the current TCP or stream unix domain socket. It returns the `1` in case of success and returns `nil` with a string describing the error otherwise. Note that there is no need to call this method on socket objects that have invoked the [setkeepalive](#tcpsocksetkeepalive) method because the socket object is already closed (and the current connection is saved into the built-in connection pool). Socket objects that have not invoked this method (and associated connections) will be closed when the socket object is released by the Lua GC (Garbage Collector) or the current client HTTP request finishes processing. This feature was first introduced in the `v0.5.0rc1` release. ### tcpsock:settimeout **syntax:** *tcpsock:settimeout(time)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Set the timeout value in milliseconds for subsequent socket operations ([connect](#tcpsockconnect), [receive](#tcpsockreceive), and iterators returned from [receiveuntil](#tcpsockreceiveuntil)). Settings done by this method takes priority over those config directives, i.e., [lua\_socket\_connect\_timeout](#lua_socket_connect_timeout), [lua\_socket\_send\_timeout](#lua_socket_send_timeout), and [lua\_socket\_read\_timeout](#lua_socket_read_timeout). Note that this method does *not* affect the [lua\_socket\_keepalive\_timeout](#lua_socket_keepalive_timeout) setting; the `timeout` argument to the [setkeepalive](#tcpsocksetkeepalive) method should be used for this purpose instead. This feature was first introduced in the `v0.5.0rc1` release. ### tcpsock:settimeouts **syntax:** *tcpsock:settimeouts(connect\_timeout, send\_timeout, read\_timeout)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Sets the connect timeout thresold, send timeout threshold, and read timeout threshold, respetively, in milliseconds, for subsequent socket operations ([connect](#tcpsockconnect), [send](#tcpsocksend), [receive](#tcpsockreceive), and iterators returned from [receiveuntil](#tcpsockreceiveuntil)). Settings done by this method takes priority over those config directives, i.e., [lua\_socket\_connect\_timeout](#lua_socket_connect_timeout), [lua\_socket\_send\_timeout](#lua_socket_send_timeout), and [lua\_socket\_read\_timeout](#lua_socket_read_timeout). You are recommended to use [settimeouts](#tcpsocksettimeouts) instead of [settimeout](#tcpsocksettimeout). Note that this method does *not* affect the [lua\_socket\_keepalive\_timeout](#lua_socket_keepalive_timeout) setting; the `timeout` argument to the [setkeepalive](#tcpsocksetkeepalive) method should be used for this purpose instead. This feature was first introduced in the `v0.10.7` release. ### tcpsock:setoption **syntax:** *tcpsock:setoption(option, value?)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** This function is added for [LuaSocket](http://w3.impa.br/%7Ediego/software/luasocket/tcp.html) API compatibility and does nothing for now. Its functionality will be implemented in future. This feature was first introduced in the `v0.5.0rc1` release. ### tcpsock:setkeepalive **syntax:** *ok, err = tcpsock:setkeepalive(timeout?, size?)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Puts the current socket's connection immediately into the cosocket built-in connection pool and keep it alive until other [connect](#tcpsockconnect) method calls request it or the associated maximal idle timeout is expired. The first optional argument, `timeout`, can be used to specify the maximal idle timeout (in milliseconds) for the current connection. If omitted, the default setting in the [lua\_socket\_keepalive\_timeout](#lua_socket_keepalive_timeout) config directive will be used. If the `0` value is given, then the timeout interval is unlimited. The second optional argument, `size`, can be used to specify the maximal number of connections allowed in the connection pool for the current server (i.e., the current host-port pair or the unix domain socket file path). Note that the size of the connection pool cannot be changed once the pool is created. When this argument is omitted, the default setting in the [lua\_socket\_pool\_size](#lua_socket_pool_size) config directive will be used. When the connection pool exceeds the available size limit, the least recently used (idle) connection already in the pool will be closed to make room for the current connection. Note that the cosocket connection pool is per Nginx worker process rather than per Nginx server instance, so the size limit specified here also applies to every single Nginx worker process. Idle connections in the pool will be monitored for any exceptional events like connection abortion or unexpected incoming data on the line, in which cases the connection in question will be closed and removed from the pool. In case of success, this method returns `1`; otherwise, it returns `nil` and a string describing the error. When the system receive buffer for the current connection has unread data, then this method will return the "connection in dubious state" error message (as the second return value) because the previous session has unread data left behind for the next session and the connection is not safe to be reused. This method also makes the current cosocket object enter the "closed" state, so there is no need to manually call the [close](#tcpsockclose) method on it afterwards. This feature was first introduced in the `v0.5.0rc1` release. ### tcpsock:getreusedtimes **syntax:** *count, err = tcpsock:getreusedtimes()* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** This method returns the (successfully) reused times for the current connection. In case of error, it returns `nil` and a string describing the error. If the current connection does not come from the built-in connection pool, then this method always returns `0`, that is, the connection has never been reused (yet). If the connection comes from the connection pool, then the return value is always non-zero. So this method can also be used to determine if the current connection comes from the pool. This feature was first introduced in the `v0.5.0rc1` release. ### ngx.socket.connect **syntax:** *tcpsock, err = ngx.socket.connect(host, port)* **syntax:** *tcpsock, err = ngx.socket.connect("unix:/path/to/unix-domain.socket")* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\** This function is a shortcut for combining [ngx.socket.tcp()](#ngxsockettcp) and the [connect()](#tcpsockconnect) method call in a single operation. It is actually implemented like this: ``` local sock = ngx.socket.tcp() local ok, err = sock:connect(...) if not ok then return nil, err end return sock ``` There is no way to use the [settimeout](#tcpsocksettimeout) method to specify connecting timeout for this method and the [lua\_socket\_connect\_timeout](#lua_socket_connect_timeout) directive must be set at configure time instead. This feature was first introduced in the `v0.5.0rc1` release. ### ngx.get\_phase **syntax:** *str = ngx.get\_phase()* **context:** *init\_by\_lua\*, init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Retrieves the current running phase name. Possible return values are * `init` for the context of [init\_by\_lua\*](#init_by_lua). * `init_worker` for the context of [init\_worker\_by\_lua\*](#init_worker_by_lua). * `ssl_cert` for the context of [ssl\_certificate\_by\_lua\*](#ssl_certificate_by_lua_block). * `ssl_session_fetch` for the context of [ssl\_session\_fetch\_by\_lua\*](#ssl_session_fetch_by_lua_block). * `ssl_session_store` for the context of [ssl\_session\_store\_by\_lua\*](#ssl_session_store_by_lua_block). * `set` for the context of [set\_by\_lua\*](#set_by_lua). * `rewrite` for the context of [rewrite\_by\_lua\*](#rewrite_by_lua). * `balancer` for the context of [balancer\_by\_lua\*](#balancer_by_lua_block). * `access` for the context of [access\_by\_lua\*](#access_by_lua). * `content` for the context of [content\_by\_lua\*](#content_by_lua). * `header_filter` for the context of [header\_filter\_by\_lua\*](#header_filter_by_lua). * `body_filter` for the context of [body\_filter\_by\_lua\*](#body_filter_by_lua). * `log` for the context of [log\_by\_lua\*](#log_by_lua). * `timer` for the context of user callback functions for [ngx.timer.\*](#ngxtimerat). This API was first introduced in the `v0.5.10` release. ### ngx.thread.spawn **syntax:** *co = ngx.thread.spawn(func, arg1, arg2, ...)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Spawns a new user "light thread" with the Lua function `func` as well as those optional arguments `arg1`, `arg2`, and etc. Returns a Lua thread (or Lua coroutine) object represents this "light thread". "Light threads" are just a special kind of Lua coroutines that are scheduled by the ngx\_lua module. Before `ngx.thread.spawn` returns, the `func` will be called with those optional arguments until it returns, aborts with an error, or gets yielded due to I/O operations via the [Nginx API for Lua](#nginx-api-for-lua) (like [tcpsock:receive](#tcpsockreceive)). After `ngx.thread.spawn` returns, the newly-created "light thread" will keep running asynchronously usually at various I/O events. All the Lua code chunks running by [rewrite\_by\_lua](#rewrite_by_lua), [access\_by\_lua](#access_by_lua), and [content\_by\_lua](#content_by_lua) are in a boilerplate "light thread" created automatically by ngx\_lua. Such boilerplate "light thread" are also called "entry threads". By default, the corresponding Nginx handler (e.g., [rewrite\_by\_lua](#rewrite_by_lua) handler) will not terminate until 1. both the "entry thread" and all the user "light threads" terminates, 2. a "light thread" (either the "entry thread" or a user "light thread" aborts by calling [ngx.exit](#ngxexit), [ngx.exec](#ngxexec), [ngx.redirect](#ngxredirect), or [ngx.req.set\_uri(uri, true)](#ngxreqset_uri), or 3. the "entry thread" terminates with a Lua error. When the user "light thread" terminates with a Lua error, however, it will not abort other running "light threads" like the "entry thread" does. Due to the limitation in the Nginx subrequest model, it is not allowed to abort a running Nginx subrequest in general. So it is also prohibited to abort a running "light thread" that is pending on one ore more Nginx subrequests. You must call [ngx.thread.wait](#ngxthreadwait) to wait for those "light thread" to terminate before quitting the "world". A notable exception here is that you can abort pending subrequests by calling [ngx.exit](#ngxexit) with and only with the status code `ngx.ERROR` (-1), `408`, `444`, or `499`. The "light threads" are not scheduled in a pre-emptive way. In other words, no time-slicing is performed automatically. A "light thread" will keep running exclusively on the CPU until 1. a (nonblocking) I/O operation cannot be completed in a single run, 2. it calls [coroutine.yield](#coroutineyield) to actively give up execution, or 3. it is aborted by a Lua error or an invocation of [ngx.exit](#ngxexit), [ngx.exec](#ngxexec), [ngx.redirect](#ngxredirect), or [ngx.req.set\_uri(uri, true)](#ngxreqset_uri). For the first two cases, the "light thread" will usually be resumed later by the ngx\_lua scheduler unless a "stop-the-world" event happens. User "light threads" can create "light threads" themselves. And normal user coroutines created by [coroutine.create](#coroutinecreate) can also create "light threads". The coroutine (be it a normal Lua coroutine or a "light thread") that directly spawns the "light thread" is called the "parent coroutine" for the "light thread" newly spawned. The "parent coroutine" can call [ngx.thread.wait](#ngxthreadwait) to wait on the termination of its child "light thread". You can call coroutine.status() and coroutine.yield() on the "light thread" coroutines. The status of the "light thread" coroutine can be "zombie" if 1. the current "light thread" already terminates (either successfully or with an error), 2. its parent coroutine is still alive, and 3. its parent coroutine is not waiting on it with [ngx.thread.wait](#ngxthreadwait). The following example demonstrates the use of coroutine.yield() in the "light thread" coroutines to do manual time-slicing: ``` local yield = coroutine.yield function f() local self = coroutine.running() ngx.say("f 1") yield(self) ngx.say("f 2") yield(self) ngx.say("f 3") end local self = coroutine.running() ngx.say("0") yield(self) ngx.say("1") ngx.thread.spawn(f) ngx.say("2") yield(self) ngx.say("3") yield(self) ngx.say("4") ``` Then it will generate the output ``` 0 1 f 1 2 f 2 3 f 3 4 ``` "Light threads" are mostly useful for making concurrent upstream requests in a single Nginx request handler, much like a generalized version of [ngx.location.capture\_multi](#ngxlocationcapture_multi) that can work with all the [Nginx API for Lua](#nginx-api-for-lua). The following example demonstrates parallel requests to MySQL, Memcached, and upstream HTTP services in a single Lua handler, and outputting the results in the order that they actually return (similar to Facebook's BigPipe model): ``` -- query mysql, memcached, and a remote http service at the same time, -- output the results in the order that they -- actually return the results. local mysql = require "resty.mysql" local memcached = require "resty.memcached" local function query_mysql() local db = mysql:new() db:connect{ host = "127.0.0.1", port = 3306, database = "test", user = "monty", password = "mypass" } local res, err, errno, sqlstate = db:query("select * from cats order by id asc") db:set_keepalive(0, 100) ngx.say("mysql done: ", cjson.encode(res)) end local function query_memcached() local memc = memcached:new() memc:connect("127.0.0.1", 11211) local res, err = memc:get("some_key") ngx.say("memcached done: ", res) end local function query_http() local res = ngx.location.capture("/my-http-proxy") ngx.say("http done: ", res.body) end ngx.thread.spawn(query_mysql) -- create thread 1 ngx.thread.spawn(query_memcached) -- create thread 2 ngx.thread.spawn(query_http) -- create thread 3 ``` This API was first enabled in the `v0.7.0` release. ### ngx.thread.wait **syntax:** *ok, res1, res2, ... = ngx.thread.wait(thread1, thread2, ...)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\** Waits on one or more child "light threads" and returns the results of the first "light thread" that terminates (either successfully or with an error). The arguments `thread1`, `thread2`, and etc are the Lua thread objects returned by earlier calls of [ngx.thread.spawn](#ngxthreadspawn). The return values have exactly the same meaning as [coroutine.resume](#coroutineresume), that is, the first value returned is a boolean value indicating whether the "light thread" terminates successfully or not, and subsequent values returned are the return values of the user Lua function that was used to spawn the "light thread" (in case of success) or the error object (in case of failure). Only the direct "parent coroutine" can wait on its child "light thread", otherwise a Lua exception will be raised. The following example demonstrates the use of `ngx.thread.wait` and [ngx.location.capture](#ngxlocationcapture) to emulate [ngx.location.capture\_multi](#ngxlocationcapture_multi): ``` local capture = ngx.location.capture local spawn = ngx.thread.spawn local wait = ngx.thread.wait local say = ngx.say local function fetch(uri) return capture(uri) end local threads = { spawn(fetch, "/foo"), spawn(fetch, "/bar"), spawn(fetch, "/baz") } for i = 1, #threads do local ok, res = wait(threads[i]) if not ok then say(i, ": failed to run: ", res) else say(i, ": status: ", res.status) say(i, ": body: ", res.body) end end ``` Here it essentially implements the "wait all" model. And below is an example demonstrating the "wait any" model: ``` function f() ngx.sleep(0.2) ngx.say("f: hello") return "f done" end function g() ngx.sleep(0.1) ngx.say("g: hello") return "g done" end local tf, err = ngx.thread.spawn(f) if not tf then ngx.say("failed to spawn thread f: ", err) return end ngx.say("f thread created: ", coroutine.status(tf)) local tg, err = ngx.thread.spawn(g) if not tg then ngx.say("failed to spawn thread g: ", err) return end ngx.say("g thread created: ", coroutine.status(tg)) ok, res = ngx.thread.wait(tf, tg) if not ok then ngx.say("failed to wait: ", res) return end ngx.say("res: ", res) -- stop the "world", aborting other running threads ngx.exit(ngx.OK) ``` And it will generate the following output: ``` f thread created: running g thread created: running g: hello res: g done ``` This API was first enabled in the `v0.7.0` release. ### ngx.thread.kill **syntax:** *ok, err = ngx.thread.kill(thread)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, ngx.timer.\** Kills a running "light thread" created by [ngx.thread.spawn](#ngxthreadspawn). Returns a true value when successful or `nil` and a string describing the error otherwise. According to the current implementation, only the parent coroutine (or "light thread") can kill a thread. Also, a running "light thread" with pending NGINX subrequests (initiated by [ngx.location.capture](#ngxlocationcapture) for example) cannot be killed due to a limitation in the NGINX core. This API was first enabled in the `v0.9.9` release. ### ngx.on\_abort **syntax:** *ok, err = ngx.on\_abort(callback)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\** Registers a user Lua function as the callback which gets called automatically when the client closes the (downstream) connection prematurely. Returns `1` if the callback is registered successfully or returns `nil` and a string describing the error otherwise. All the [Nginx API for Lua](#nginx-api-for-lua) can be used in the callback function because the function is run in a special "light thread", just as those "light threads" created by [ngx.thread.spawn](#ngxthreadspawn). The callback function can decide what to do with the client abortion event all by itself. For example, it can simply ignore the event by doing nothing and the current Lua request handler will continue executing without interruptions. And the callback function can also decide to terminate everything by calling [ngx.exit](#ngxexit), for example, ``` local function my_cleanup() -- custom cleanup work goes here, like cancelling a pending DB transaction -- now abort all the "light threads" running in the current request handler ngx.exit(499) end local ok, err = ngx.on_abort(my_cleanup) if not ok then ngx.log(ngx.ERR, "failed to register the on_abort callback: ", err) ngx.exit(500) end ``` When [lua\_check\_client\_abort](#lua_check_client_abort) is set to `off` (which is the default), then this function call will always return the error message "lua\_check\_client\_abort is off". According to the current implementation, this function can only be called once in a single request handler; subsequent calls will return the error message "duplicate call". This API was first introduced in the `v0.7.4` release. See also [lua\_check\_client\_abort](#lua_check_client_abort). ### ngx.timer.at **syntax:** *hdl, err = ngx.timer.at(delay, callback, user\_arg1, user\_arg2, ...)* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Creates an Nginx timer with a user callback function as well as optional user arguments. The first argument, `delay`, specifies the delay for the timer, in seconds. One can specify fractional seconds like `0.001` to mean 1 millisecond here. `0` delay can also be specified, in which case the timer will immediately expire when the current handler yields execution. The second argument, `callback`, can be any Lua function, which will be invoked later in a background "light thread" after the delay specified. The user callback will be called automatically by the Nginx core with the arguments `premature`, `user_arg1`, `user_arg2`, and etc, where the `premature` argument takes a boolean value indicating whether it is a premature timer expiration or not, and `user_arg1`, `user_arg2`, and etc, are those (extra) user arguments specified when calling `ngx.timer.at` as the remaining arguments. Premature timer expiration happens when the Nginx worker process is trying to shut down, as in an Nginx configuration reload triggered by the `HUP` signal or in an Nginx server shutdown. When the Nginx worker is trying to shut down, one can no longer call `ngx.timer.at` to create new timers with nonzero delays and in that case `ngx.timer.at` will return a "conditional false" value and a string describing the error, that is, "process exiting". Starting from the `v0.9.3` release, it is allowed to create zero-delay timers even when the Nginx worker process starts shutting down. When a timer expires, the user Lua code in the timer callback is running in a "light thread" detached completely from the original request creating the timer. So objects with the same lifetime as the request creating them, like [cosockets](#ngxsockettcp), cannot be shared between the original request and the timer user callback function. Here is a simple example: ``` location / { ... log_by_lua_block { local function push_data(premature, uri, args, status) -- push the data uri, args, and status to the remote -- via ngx.socket.tcp or ngx.socket.udp -- (one may want to buffer the data in Lua a bit to -- save I/O operations) end local ok, err = ngx.timer.at(0, push_data, ngx.var.uri, ngx.var.args, ngx.header.status) if not ok then ngx.log(ngx.ERR, "failed to create timer: ", err) return end } } ``` One can also create infinite re-occurring timers, for instance, a timer getting triggered every `5` seconds, by calling `ngx.timer.at` recursively in the timer callback function. Here is such an example, ``` local delay = 5 local handler handler = function (premature) -- do some routine job in Lua just like a cron job if premature then return end local ok, err = ngx.timer.at(delay, handler) if not ok then ngx.log(ngx.ERR, "failed to create the timer: ", err) return end end local ok, err = ngx.timer.at(delay, handler) if not ok then ngx.log(ngx.ERR, "failed to create the timer: ", err) return end ``` It is recommended, however, to use the [ngx.timer.every](#ngxtimerevery) API function instead for creating recurring timers since it is more robust. Because timer callbacks run in the background and their running time will not add to any client request's response time, they can easily accumulate in the server and exhaust system resources due to either Lua programming mistakes or just too much client traffic. To prevent extreme consequences like crashing the Nginx server, there are built-in limitations on both the number of "pending timers" and the number of "running timers" in an Nginx worker process. The "pending timers" here mean timers that have not yet been expired and "running timers" are those whose user callbacks are currently running. The maximal number of pending timers allowed in an Nginx worker is controlled by the [lua\_max\_pending\_timers](#lua_max_pending_timers) directive. The maximal number of running timers is controlled by the [lua\_max\_running\_timers](#lua_max_running_timers) directive. According to the current implementation, each "running timer" will take one (fake) connection record from the global connection record list configured by the standard [worker\_connections](http://nginx.org/en/docs/ngx_core_module.html#worker_connections) directive in `nginx.conf`. So ensure that the [worker\_connections](http://nginx.org/en/docs/ngx_core_module.html#worker_connections) directive is set to a large enough value that takes into account both the real connections and fake connections required by timer callbacks (as limited by the [lua\_max\_running\_timers](#lua_max_running_timers) directive). A lot of the Lua APIs for Nginx are enabled in the context of the timer callbacks, like stream/datagram cosockets ([ngx.socket.tcp](#ngxsockettcp) and [ngx.socket.udp](#ngxsocketudp)), shared memory dictionaries ([ngx.shared.DICT](#ngxshareddict)), user coroutines ([coroutine.\*](#coroutinecreate)), user "light threads" ([ngx.thread.\*](#ngxthreadspawn)), [ngx.exit](#ngxexit), [ngx.now](#ngxnow)/[ngx.time](#ngxtime), [ngx.md5](#ngxmd5)/[ngx.sha1\_bin](#ngxsha1_bin), are all allowed. But the subrequest API (like [ngx.location.capture](#ngxlocationcapture)), the [ngx.req.\*](#ngxreqstart_time) API, the downstream output API (like [ngx.say](#ngxsay), [ngx.print](#ngxprint), and [ngx.flush](#ngxflush)) are explicitly disabled in this context. You can pass most of the standard Lua values (nils, booleans, numbers, strings, tables, closures, file handles, and etc) into the timer callback, either explicitly as user arguments or implicitly as upvalues for the callback closure. There are several exceptions, however: you *cannot* pass any thread objects returned by [coroutine.create](#coroutinecreate) and [ngx.thread.spawn](#ngxthreadspawn) or any cosocket objects returned by [ngx.socket.tcp](#ngxsockettcp), [ngx.socket.udp](#ngxsocketudp), and [ngx.req.socket](#ngxreqsocket) because these objects' lifetime is bound to the request context creating them while the timer callback is detached from the creating request's context (by design) and runs in its own (fake) request context. If you try to share the thread or cosocket objects across the boundary of the creating request, then you will get the "no co ctx found" error (for threads) or "bad request" (for cosockets). It is fine, however, to create all these objects inside your timer callback. This API was first introduced in the `v0.8.0` release. ### ngx.timer.every **syntax:** *hdl, err = ngx.timer.every(delay, callback, user\_arg1, user\_arg2, ...)* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Similar to the [ngx.timer.at](#ngxtimerat) API function, but 1. `delay` *cannot* be zero, 2. timer will be created every `delay` seconds until the current Nginx worker process starts exiting. When success, returns a "conditional true" value (but not a `true`). Otherwise, returns a "conditional false" value and a string describing the error. This API also respect the [lua\_max\_pending\_timers](#lua_max_pending_timers) and [lua\_max\_running\_timers](#lua_max_running_timers). This API was first introduced in the `v0.10.9` release. ### ngx.timer.running\_count **syntax:** *count = ngx.timer.running\_count()* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Returns the number of timers currently running. This directive was first introduced in the `v0.9.20` release. ### ngx.timer.pending\_count **syntax:** *count = ngx.timer.pending\_count()* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Returns the number of pending timers. This directive was first introduced in the `v0.9.20` release. ### ngx.config.subsystem **syntax:** *subsystem = ngx.config.subsystem* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, init\_by\_lua\*, init\_worker\_by\_lua\** This string field indicates the current NGINX subsystem the current Lua environment is based on. For this module, this field always takes the string value `"http"`. For [ngx\_stream\_lua\_module](https://github.com/openresty/stream-lua-nginx-module#readme), however, this field takes the value `"stream"`. This field was first introduced in the `0.10.1`. ### ngx.config.debug **syntax:** *debug = ngx.config.debug* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, init\_by\_lua\*, init\_worker\_by\_lua\** This boolean field indicates whether the current Nginx is a debug build, i.e., being built by the `./configure` option `--with-debug`. This field was first introduced in the `0.8.7`. ### ngx.config.prefix **syntax:** *prefix = ngx.config.prefix()* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, init\_by\_lua\*, init\_worker\_by\_lua\** Returns the Nginx server "prefix" path, as determined by the `-p` command-line option when running the nginx executable, or the path specified by the `--prefix` command-line option when building Nginx with the `./configure` script. This function was first introduced in the `0.9.2`. ### ngx.config.nginx\_version **syntax:** *ver = ngx.config.nginx\_version* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, init\_by\_lua\*, init\_worker\_by\_lua\** This field take an integral value indicating the version number of the current Nginx core being used. For example, the version number `1.4.3` results in the Lua number 1004003. This API was first introduced in the `0.9.3` release. ### ngx.config.nginx\_configure **syntax:** *str = ngx.config.nginx\_configure()* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, init\_by\_lua\** This function returns a string for the NGINX `./configure` command's arguments string. This API was first introduced in the `0.9.5` release. ### ngx.config.ngx\_lua\_version **syntax:** *ver = ngx.config.ngx\_lua\_version* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, init\_by\_lua\** This field take an integral value indicating the version number of the current `ngx_lua` module being used. For example, the version number `0.9.3` results in the Lua number 9003. This API was first introduced in the `0.9.3` release. ### ngx.worker.exiting **syntax:** *exiting = ngx.worker.exiting()* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, init\_by\_lua\*, init\_worker\_by\_lua\** This function returns a boolean value indicating whether the current Nginx worker process already starts exiting. Nginx worker process exiting happens on Nginx server quit or configuration reload (aka HUP reload). This API was first introduced in the `0.9.3` release. ### ngx.worker.pid **syntax:** *pid = ngx.worker.pid()* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, init\_by\_lua\*, init\_worker\_by\_lua\** This function returns a Lua number for the process ID (PID) of the current Nginx worker process. This API is more efficient than `ngx.var.pid` and can be used in contexts where the [ngx.var.VARIABLE](#ngxvarvariable) API cannot be used (like [init\_worker\_by\_lua](#init_worker_by_lua)). This API was first introduced in the `0.9.5` release. ### ngx.worker.count **syntax:** *count = ngx.worker.count()* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, init\_by\_lua\*, init\_worker\_by\_lua\** Returns the total number of the Nginx worker processes (i.e., the value configured by the [worker\_processes](http://nginx.org/en/docs/ngx_core_module.html#worker_processes) directive in `nginx.conf`). This API was first introduced in the `0.9.20` release. ### ngx.worker.id **syntax:** *count = ngx.worker.id()* **context:** *set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, init\_worker\_by\_lua\** Returns the ordinal number of the current Nginx worker processes (starting from number 0). So if the total number of workers is `N`, then this method may return a number between 0 and `N - 1` (inclusive). This function returns meaningful values only for NGINX 1.9.1+. With earlier versions of NGINX, it always returns `nil`. See also [ngx.worker.count](#ngxworkercount). This API was first introduced in the `0.9.20` release. ### ngx.semaphore **syntax:** *local semaphore = require "ngx.semaphore"* This is a Lua module that implements a classic-style semaphore API for efficient synchronizations among different "light threads". Sharing the same semaphore among different "light threads" created in different (request) contexts are also supported as long as the "light threads" reside in the same NGINX worker process and the [lua\_code\_cache](#lua_code_cache) directive is turned on (which is the default). This Lua module does not ship with this ngx\_lua module itself rather it is shipped with the [lua-resty-core](https://github.com/openresty/lua-resty-core) library. Please refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/semaphore.md) for this `ngx.semaphore` Lua module in [lua-resty-core](https://github.com/openresty/lua-resty-core) for more details. This feature requires at least ngx\_lua `v0.10.0`. ### ngx.balancer **syntax:** *local balancer = require "ngx.balancer"* This is a Lua module that provides a Lua API to allow defining completely dynamic load balancers in pure Lua. This Lua module does not ship with this ngx\_lua module itself rather it is shipped with the [lua-resty-core](https://github.com/openresty/lua-resty-core) library. Please refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.md) for this `ngx.balancer` Lua module in [lua-resty-core](https://github.com/openresty/lua-resty-core) for more details. This feature requires at least ngx\_lua `v0.10.0`. ### ngx.ssl **syntax:** *local ssl = require "ngx.ssl"* This Lua module provides API functions to control the SSL handshake process in contexts like [ssl\_certificate\_by\_lua\*](#ssl_certificate_by_lua_block). This Lua module does not ship with this ngx\_lua module itself rather it is shipped with the [lua-resty-core](https://github.com/openresty/lua-resty-core) library. Please refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md) for this `ngx.ssl` Lua module for more details. This feature requires at least ngx\_lua `v0.10.0`. ### ngx.ocsp **syntax:** *local ocsp = require "ngx.ocsp"* This Lua module provides API to perform OCSP queries, OCSP response validations, and OCSP stapling planting. Usually, this module is used together with the [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md) module in the context of [ssl\_certificate\_by\_lua\*](#ssl_certificate_by_lua_block). This Lua module does not ship with this ngx\_lua module itself rather it is shipped with the [lua-resty-core](https://github.com/openresty/lua-resty-core) library. Please refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/ocsp-cert-by-lua-2/lib/ngx/ocsp.md) for this `ngx.ocsp` Lua module for more details. This feature requires at least ngx\_lua `v0.10.0`. ### ndk.set\_var.DIRECTIVE **syntax:** *res = ndk.set\_var.DIRECTIVE\_NAME* **context:** *init\_worker\_by\_lua\*, set\_by\_lua\*, rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, log\_by\_lua\*, ngx.timer.\*, balancer\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** This mechanism allows calling other nginx C modules' directives that are implemented by [Nginx Devel Kit](https://github.com/simplresty/ngx_devel_kit) (NDK)'s set\_var submodule's `ndk_set_var_value`. For example, the following [set-misc-nginx-module](http://github.com/openresty/set-misc-nginx-module) directives can be invoked this way: * [set\_quote\_sql\_str](http://github.com/openresty/set-misc-nginx-module#set_quote_sql_str) * [set\_quote\_pgsql\_str](http://github.com/openresty/set-misc-nginx-module#set_quote_pgsql_str) * [set\_quote\_json\_str](http://github.com/openresty/set-misc-nginx-module#set_quote_json_str) * [set\_unescape\_uri](http://github.com/openresty/set-misc-nginx-module#set_unescape_uri) * [set\_escape\_uri](http://github.com/openresty/set-misc-nginx-module#set_escape_uri) * [set\_encode\_base32](http://github.com/openresty/set-misc-nginx-module#set_encode_base32) * [set\_decode\_base32](http://github.com/openresty/set-misc-nginx-module#set_decode_base32) * [set\_encode\_base64](http://github.com/openresty/set-misc-nginx-module#set_encode_base64) * [set\_decode\_base64](http://github.com/openresty/set-misc-nginx-module#set_decode_base64) * [set\_encode\_hex](http://github.com/openresty/set-misc-nginx-module#set_encode_base64) * [set\_decode\_hex](http://github.com/openresty/set-misc-nginx-module#set_decode_base64) * [set\_sha1](http://github.com/openresty/set-misc-nginx-module#set_encode_base64) * [set\_md5](http://github.com/openresty/set-misc-nginx-module#set_decode_base64) For instance, ``` local res = ndk.set_var.set_escape_uri('a/b'); -- now res == 'a%2fb' ``` Similarly, the following directives provided by [encrypted-session-nginx-module](http://github.com/openresty/encrypted-session-nginx-module) can be invoked from within Lua too: * [set\_encrypt\_session](http://github.com/openresty/encrypted-session-nginx-module#set_encrypt_session) * [set\_decrypt\_session](http://github.com/openresty/encrypted-session-nginx-module#set_decrypt_session) This feature requires the [ngx\_devel\_kit](https://github.com/simplresty/ngx_devel_kit) module. ### coroutine.create **syntax:** *co = coroutine.create(f)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, init\_by\_lua\*, ngx.timer.\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Creates a user Lua coroutines with a Lua function, and returns a coroutine object. Similar to the standard Lua [coroutine.create](http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.create) API, but works in the context of the Lua coroutines created by ngx\_lua. This API was first usable in the context of [init\_by\_lua\*](#init_by_lua) since the `0.9.2`. This API was first introduced in the `v0.6.0` release. ### coroutine.resume **syntax:** *ok, ... = coroutine.resume(co, ...)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, init\_by\_lua\*, ngx.timer.\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Resumes the executation of a user Lua coroutine object previously yielded or just created. Similar to the standard Lua [coroutine.resume](http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.resume) API, but works in the context of the Lua coroutines created by ngx\_lua. This API was first usable in the context of [init\_by\_lua\*](#init_by_lua) since the `0.9.2`. This API was first introduced in the `v0.6.0` release. ### coroutine.yield **syntax:** *... = coroutine.yield(...)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, init\_by\_lua\*, ngx.timer.\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Yields the execution of the current user Lua coroutine. Similar to the standard Lua [coroutine.yield](http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.yield) API, but works in the context of the Lua coroutines created by ngx\_lua. This API was first usable in the context of [init\_by\_lua\*](#init_by_lua) since the `0.9.2`. This API was first introduced in the `v0.6.0` release. ### coroutine.wrap **syntax:** *co = coroutine.wrap(f)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, init\_by\_lua\*, ngx.timer.\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Similar to the standard Lua [coroutine.wrap](http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.wrap) API, but works in the context of the Lua coroutines created by ngx\_lua. This API was first usable in the context of [init\_by\_lua\*](#init_by_lua) since the `0.9.2`. This API was first introduced in the `v0.6.0` release. ### coroutine.running **syntax:** *co = coroutine.running()* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, init\_by\_lua\*, ngx.timer.\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Identical to the standard Lua [coroutine.running](http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.running) API. This API was first usable in the context of [init\_by\_lua\*](#init_by_lua) since the `0.9.2`. This API was first enabled in the `v0.6.0` release. ### coroutine.status **syntax:** *status = coroutine.status(co)* **context:** *rewrite\_by\_lua\*, access\_by\_lua\*, content\_by\_lua\*, init\_by\_lua\*, ngx.timer.\*, header\_filter\_by\_lua\*, body\_filter\_by\_lua\*, ssl\_certificate\_by\_lua\*, ssl\_session\_fetch\_by\_lua\*, ssl\_session\_store\_by\_lua\** Identical to the standard Lua [coroutine.status](http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.status) API. This API was first usable in the context of [init\_by\_lua\*](#init_by_lua) since the `0.9.2`. This API was first enabled in the `v0.6.0` release. Obsolete Sections ----------------- This section is just holding obsolete documentation sections that have been either renamed or removed so that existing links over the web are still valid. ### Special PCRE Sequences This section has been renamed to [Special Escaping Sequences](#special-escaping-sequences).
programming_docs
d core.sync.mutex core.sync.mutex =============== The mutex module provides a primitive for maintaining mutually exclusive access. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) Authors: Sean Kelly Source [core/sync/mutex.d](https://github.com/dlang/druntime/blob/master/src/core/sync/mutex.d) class **Mutex**: object.Object.Monitor; This class represents a general purpose, recursive mutex. Implemented using `pthread_mutex` on Posix and `CRITICAL_SECTION` on Windows. Examples: ``` import core.thread : Thread; class Resource { Mutex mtx; int cargo; this() shared @safe nothrow { mtx = new shared Mutex(); cargo = 42; } void useResource() shared @safe nothrow @nogc { mtx.lock_nothrow(); (cast() cargo) += 1; mtx.unlock_nothrow(); } } shared Resource res = new shared Resource(); auto otherThread = new Thread( { foreach (i; 0 .. 10000) res.useResource(); }).start(); foreach (i; 0 .. 10000) res.useResource(); otherThread.join(); assert (res.cargo == 20042); ``` nothrow @nogc @trusted this(); shared nothrow @nogc @trusted this(); Initializes a mutex object. nothrow @nogc @trusted this(Object obj); shared nothrow @nogc @trusted this(Object obj); Initializes a mutex object and sets it as the monitor for `obj`. In `obj` must not already have a monitor. @trusted void **lock**(); shared @trusted void **lock**(); final nothrow @nogc @trusted void **lock\_nothrow**(this Q)() Constraints: if (is(Q == Mutex) || is(Q == shared(Mutex))); If this lock is not already held by the caller, the lock is acquired, then the internal counter is incremented by one. Note `Mutex.lock` does not throw, but a class derived from Mutex can throw. Use `lock_nothrow` in `nothrow @nogc` code. @trusted void **unlock**(); shared @trusted void **unlock**(); final nothrow @nogc @trusted void **unlock\_nothrow**(this Q)() Constraints: if (is(Q == Mutex) || is(Q == shared(Mutex))); Decrements the internal lock count by one. If this brings the count to zero, the lock is released. Note `Mutex.unlock` does not throw, but a class derived from Mutex can throw. Use `unlock_nothrow` in `nothrow @nogc` code. @trusted bool **tryLock**(); shared @trusted bool **tryLock**(); final nothrow @nogc @trusted bool **tryLock\_nothrow**(this Q)() Constraints: if (is(Q == Mutex) || is(Q == shared(Mutex))); If the lock is held by another caller, the method returns. Otherwise, the lock is acquired if it is not already held, and then the internal counter is incremented by one. Returns: true if the lock was acquired and false if not. Note `Mutex.tryLock` does not throw, but a class derived from Mutex can throw. Use `tryLock_nothrow` in `nothrow @nogc` code. d core.time core.time ========= Module containing core time functionality, such as [`Duration`](#Duration) (which represents a duration of time) or [`MonoTime`](#MonoTime) (which represents a timestamp of the system's monotonic clock). Various functions take a string (or strings) to represent a unit of time (e.g. `convert!("days", "hours")(numDays)`). The valid strings to use with such functions are "years", "months", "weeks", "days", "hours", "minutes", "seconds", "msecs" (milliseconds), "usecs" (microseconds), "hnsecs" (hecto-nanoseconds - i.e. 100 ns) or some subset thereof. There are a few functions that also allow "nsecs", but very little actually has precision greater than hnsecs. Cheat Sheet| Symbol | Description | | *Types* | | [`Duration`](#Duration) | Represents a duration of time of weeks or less (kept internally as hnsecs). (e.g. 22 days or 700 seconds). | | [`TickDuration`](#TickDuration) | Represents a duration of time in system clock ticks, using the highest precision that the system provides. | | [`MonoTime`](#MonoTime) | Represents a monotonic timestamp in system clock ticks, using the highest precision that the system provides. | | *Functions* | | [`convert`](#convert) | Generic way of converting between two time units. | | [`dur`](#dur) | Allows constructing a [`Duration`](#Duration) from the given time units with the given length. | | [`weeks`](#weeks) [`days`](#days) [`hours`](#hours) [`minutes`](#minutes) [`seconds`](#seconds) [`msecs`](#msecs) [`usecs`](#usecs) [`hnsecs`](#hnsecs) [`nsecs`](#nsecs) | Convenience aliases for [`dur`](#dur). | | [`abs`](#abs) | Returns the absolute value of a duration. | Conversions| | From [`Duration`](#Duration) | From [`TickDuration`](#TickDuration) | From units | | To [`Duration`](#Duration) | - | `tickDuration.`[`to`](std_conv#to)`!Duration()` | `dur!"msecs"(5)` or `5.msecs()` | | To [`TickDuration`](#TickDuration) | `duration.`[`to`](std_conv#to)`!TickDuration()` | - | `TickDuration.from!"msecs"(msecs)` | | To units | `duration.total!"days"` | `tickDuration.msecs` | `convert!("days", "msecs")(msecs)` | License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Jonathan M Davis](http://jmdavisprog.com) and Kato Shoichi Source [core/time.d](https://github.com/dlang/druntime/blob/master/src/core/time.d) enum **ClockType**: int; What type of clock to use with [`MonoTime`](#MonoTime) / [`MonoTimeImpl`](#MonoTimeImpl) or `std.datetime.Clock.currTime`. They default to `ClockType.normal`, and most programs do not need to ever deal with the others. The other `ClockType`s are provided so that other clocks provided by the underlying C, system calls can be used with [`MonoTimeImpl`](#MonoTimeImpl) or `std.datetime.Clock.currTime` without having to use the C API directly. In the case of the monotonic time, [`MonoTimeImpl`](#MonoTimeImpl) is templatized on `ClockType`, whereas with `std.datetime.Clock.currTime`, its a runtime argument, since in the case of the monotonic time, the type of the clock affects the resolution of a [`MonoTimeImpl`](#MonoTimeImpl) object, whereas with [`std.datetime.SysTime`](std_datetime#SysTime), its resolution is always hecto-nanoseconds regardless of the source of the time. `ClockType.normal`, `ClockType.coarse`, and `ClockType.precise` work with both `Clock.currTime` and [`MonoTimeImpl`](#MonoTimeImpl). `ClockType.second` only works with `Clock.currTime`. The others only work with [`MonoTimeImpl`](#MonoTimeImpl). **normal** Use the normal clock. **bootTime** Linux,OpenBSD-Only Uses `CLOCK_BOOTTIME`. **coarse** Use the coarse clock, not the normal one (e.g. on Linux, that would be `CLOCK_REALTIME_COARSE` instead of `CLOCK_REALTIME` for `clock_gettime` if a function is using the realtime clock). It's generally faster to get the time with the coarse clock than the normal clock, but it's less precise (e.g. 1 msec instead of 1 usec or 1 nsec). Howeover, it *is* guaranteed to still have sub-second precision (just not as high as with `ClockType.normal`). On systems which do not support a coarser clock, `MonoTimeImpl!(ClockType.coarse)` will internally use the same clock as `Monotime` does, and `Clock.currTime!(ClockType.coarse)` will use the same clock as `Clock.currTime`. This is because the coarse clock is doing the same thing as the normal clock (just at lower precision), whereas some of the other clock types (e.g. `ClockType.processCPUTime`) mean something fundamentally different. So, treating those as `ClockType.normal` on systems where they weren't natively supported would give misleading results. Most programs should not use the coarse clock, exactly because it's less precise, and most programs don't need to get the time often enough to care, but for those rare programs that need to get the time extremely frequently (e.g. hundreds of thousands of times a second) but don't care about high precision, the coarse clock might be appropriate. Currently, only Linux and FreeBSD/DragonFlyBSD support a coarser clock, and on other platforms, it's treated as `ClockType.normal`. **precise** Uses a more precise clock than the normal one (which is already very precise), but it takes longer to get the time. Similarly to `ClockType.coarse`, if it's used on a system that does not support a more precise clock than the normal one, it's treated as equivalent to `ClockType.normal`. Currently, only FreeBSD/DragonFlyBSD supports a more precise clock, where it uses `CLOCK_MONOTONIC_PRECISE` for the monotonic time and `CLOCK_REALTIME_PRECISE` for the wall clock time. **processCPUTime** Linux,OpenBSD,Solaris-Only Uses `CLOCK_PROCESS_CPUTIME_ID`. **raw** Linux-Only Uses `CLOCK_MONOTONIC_RAW`. **second** Uses a clock that has a precision of one second (contrast to the coarse clock, which has sub-second precision like the normal clock does). FreeBSD/DragonFlyBSD are the only systems which specifically have a clock set up for this (it has `CLOCK_SECOND` to use with `clock_gettime` which takes advantage of an in-kernel cached value), but on other systems, the fastest function available will be used, and the resulting `SysTime` will be rounded down to the second if the clock that was used gave the time at a more precise resolution. So, it's guaranteed that the time will be given at a precision of one second and it's likely the case that will be faster than `ClockType.normal`, since there tend to be several options on a system to get the time at low resolutions, and they tend to be faster than getting the time at high resolutions. So, the primary difference between `ClockType.coarse` and `ClockType.second` is that `ClockType.coarse` sacrifices some precision in order to get speed but is still fairly precise, whereas `ClockType.second` tries to be as fast as possible at the expense of all sub-second precision. **threadCPUTime** Linux,OpenBSD,Solaris-Only Uses `CLOCK_THREAD_CPUTIME_ID`. **uptime** DragonFlyBSD,FreeBSD,OpenBSD-Only Uses `CLOCK_UPTIME`. **uptimeCoarse** FreeBSD-Only Uses `CLOCK_UPTIME_FAST`. **uptimePrecise** FreeBSD-Only Uses `CLOCK_UPTIME_PRECISE`. struct **Duration**; Represents a duration of time of weeks or less (kept internally as hnsecs). (e.g. 22 days or 700 seconds). It is used when representing a duration of time - such as how long to sleep with [`core.thread.Thread.sleep`](core_thread#Thread.sleep). In std.datetime, it is also used as the result of various arithmetic operations on time points. Use the [`dur`](#dur) function or one of its non-generic aliases to create `Duration`s. It's not possible to create a Duration of months or years, because the variable number of days in a month or year makes it impossible to convert between months or years and smaller units without a specific date. So, nothing uses `Duration`s when dealing with months or years. Rather, functions specific to months and years are defined. For instance, [`std.datetime.Date`](std_datetime#Date) has `add!"years"` and `add!"months"` for adding years and months rather than creating a Duration of years or months and adding that to a [`std.datetime.Date`](std_datetime#Date). But Duration is used when dealing with weeks or smaller. Examples: ``` import std.datetime; assert(dur!"days"(12) == dur!"hnsecs"(10_368_000_000_000L)); assert(dur!"hnsecs"(27) == dur!"hnsecs"(27)); assert(std.datetime.Date(2010, 9, 7) + dur!"days"(5) == std.datetime.Date(2010, 9, 12)); assert(days(-12) == dur!"hnsecs"(-10_368_000_000_000L)); assert(hnsecs(-27) == dur!"hnsecs"(-27)); assert(std.datetime.Date(2010, 9, 7) - std.datetime.Date(2010, 10, 3) == days(-26)); ``` Examples: ``` import core.time; // using the dur template auto numDays = dur!"days"(12); // using the days function numDays = days(12); // alternatively using UFCS syntax numDays = 12.days; auto myTime = 100.msecs + 20_000.usecs + 30_000.hnsecs; assert(myTime == 123.msecs); ``` static pure nothrow @nogc @property @safe Duration **zero**(); A `Duration` of `0`. It's shorter than doing something like `dur!"seconds"(0)` and more explicit than `Duration.init`. static pure nothrow @nogc @property @safe Duration **max**(); Largest `Duration` possible. static pure nothrow @nogc @property @safe Duration **min**(); Most negative `Duration` possible. const pure nothrow @nogc @safe int **opCmp**(Duration rhs); Compares this `Duration` with the given `Duration`. Returns: | | | | --- | --- | | this < rhs | < 0 | | this == rhs | 0 | | this > rhs | > 0 | const nothrow @nogc Duration **opBinary**(string op, D)(D rhs) Constraints: if ((op == "+" || op == "-" || op == "%") && is(immutable(D) == immutable(Duration)) || (op == "+" || op == "-") && is(immutable(D) == immutable(TickDuration))); Adds, subtracts or calculates the modulo of two durations. The legal types of arithmetic for `Duration` using this operator are | | | | | | | --- | --- | --- | --- | --- | | Duration | + | Duration | --> | Duration | | Duration | - | Duration | --> | Duration | | Duration | % | Duration | --> | Duration | | Duration | + | TickDuration | --> | Duration | | Duration | - | TickDuration | --> | Duration | Parameters: | | | | --- | --- | | D `rhs` | The duration to add to or subtract from this `Duration`. | const nothrow @nogc Duration **opBinaryRight**(string op, D)(D lhs) Constraints: if ((op == "+" || op == "-") && is(immutable(D) == immutable(TickDuration))); Adds or subtracts two durations. The legal types of arithmetic for `Duration` using this operator are | | | | | | | --- | --- | --- | --- | --- | | TickDuration | + | Duration | --> | Duration | | TickDuration | - | Duration | --> | Duration | Parameters: | | | | --- | --- | | D `lhs` | The `TickDuration` to add to this `Duration` or to subtract this `Duration` from. | nothrow @nogc ref Duration **opOpAssign**(string op, D)(scope const D rhs) Constraints: if ((op == "+" || op == "-" || op == "%") && is(immutable(D) == immutable(Duration)) || (op == "+" || op == "-") && is(immutable(D) == immutable(TickDuration))); Adds, subtracts or calculates the modulo of two durations as well as assigning the result to this `Duration`. The legal types of arithmetic for `Duration` using this operator are | | | | | | | --- | --- | --- | --- | --- | | Duration | + | Duration | --> | Duration | | Duration | - | Duration | --> | Duration | | Duration | % | Duration | --> | Duration | | Duration | + | TickDuration | --> | Duration | | Duration | - | TickDuration | --> | Duration | Parameters: | | | | --- | --- | | D `rhs` | The duration to add to or subtract from this `Duration`. | const nothrow @nogc Duration **opBinary**(string op)(long value) Constraints: if (op == "\*" || op == "/"); Multiplies or divides the duration by an integer value. The legal types of arithmetic for `Duration` using this operator overload are | | | | | | | --- | --- | --- | --- | --- | | Duration | \* | long | --> | Duration | | Duration | / | long | --> | Duration | Parameters: | | | | --- | --- | | long `value` | The value to multiply this `Duration` by. | nothrow @nogc ref Duration **opOpAssign**(string op)(long value) Constraints: if (op == "\*" || op == "/"); Multiplies/Divides the duration by an integer value as well as assigning the result to this `Duration`. The legal types of arithmetic for `Duration` using this operator overload are | | | | | | | --- | --- | --- | --- | --- | | Duration | \* | long | --> | Duration | | Duration | / | long | --> | Duration | Parameters: | | | | --- | --- | | long `value` | The value to multiply/divide this `Duration` by. | const nothrow @nogc long **opBinary**(string op)(Duration rhs) Constraints: if (op == "/"); Divides two durations. The legal types of arithmetic for `Duration` using this operator are | | | | | | | --- | --- | --- | --- | --- | | Duration | / | Duration | --> | long | Parameters: | | | | --- | --- | | Duration `rhs` | The duration to divide this `Duration` by. | const nothrow @nogc Duration **opBinaryRight**(string op)(long value) Constraints: if (op == "\*"); Multiplies an integral value and a `Duration`. The legal types of arithmetic for `Duration` using this operator overload are | | | | | | | --- | --- | --- | --- | --- | | long | \* | Duration | --> | Duration | Parameters: | | | | --- | --- | | long `value` | The number of units to multiply this `Duration` by. | const nothrow @nogc Duration **opUnary**(string op)() Constraints: if (op == "-"); Returns the negation of this `Duration`. const nothrow @nogc TickDuration **opCast**(T)() Constraints: if (is(immutable(T) == immutable(TickDuration))); Returns a [`TickDuration`](#TickDuration) with the same number of hnsecs as this `Duration`. Note that the conventional way to convert between `Duration` and `TickDuration` is using [`std.conv.to`](std_conv#to), e.g.: `duration.to!TickDuration()` const nothrow @nogc bool **opCast**(T : bool)(); Allow Duration to be used as a boolean. Returns: `true` if this duration is non-zero. template **split**(units...) if (allAreAcceptedUnits!("weeks", "days", "hours", "minutes", "seconds", "msecs", "usecs", "hnsecs", "nsecs")(units) && unitsAreInDescendingOrder(units)) Splits out the Duration into the given units. split takes the list of time units to split out as template arguments. The time unit strings must be given in decreasing order. How it returns the values for those units depends on the overload used. The overload which accepts function arguments takes integral types in the order that the time unit strings were given, and those integers are passed by `ref`. split assigns the values for the units to each corresponding integer. Any integral type may be used, but no attempt is made to prevent integer overflow, so don't use small integral types in circumstances where the values for those units aren't likely to fit in an integral type that small. The overload with no arguments returns the values for the units in a struct with members whose names are the same as the given time unit strings. The members are all `long`s. This overload will also work with no time strings being given, in which case *all* of the time units from weeks through hnsecs will be provided (but no nsecs, since it would always be `0`). For both overloads, the entire value of the Duration is split among the units (rather than splitting the Duration across all units and then only providing the values for the requested units), so if only one unit is given, the result is equivalent to [`total`](#total). `"nsecs"` is accepted by split, but `"years"` and `"months"` are not. For negative durations, all of the split values will be negative. Examples: ``` { auto d = dur!"days"(12) + dur!"minutes"(7) + dur!"usecs"(501223); long days; int seconds; short msecs; d.split!("days", "seconds", "msecs")(days, seconds, msecs); assert(days == 12); assert(seconds == 7 * 60); assert(msecs == 501); auto splitStruct = d.split!("days", "seconds", "msecs")(); assert(splitStruct.days == 12); assert(splitStruct.seconds == 7 * 60); assert(splitStruct.msecs == 501); auto fullSplitStruct = d.split(); assert(fullSplitStruct.weeks == 1); assert(fullSplitStruct.days == 5); assert(fullSplitStruct.hours == 0); assert(fullSplitStruct.minutes == 7); assert(fullSplitStruct.seconds == 0); assert(fullSplitStruct.msecs == 501); assert(fullSplitStruct.usecs == 223); assert(fullSplitStruct.hnsecs == 0); assert(d.split!"minutes"().minutes == d.total!"minutes"); } { auto d = dur!"days"(12); assert(d.split!"weeks"().weeks == 1); assert(d.split!"days"().days == 12); assert(d.split().weeks == 1); assert(d.split().days == 5); } { auto d = dur!"days"(7) + dur!"hnsecs"(42); assert(d.split!("seconds", "nsecs")().nsecs == 4200); } { auto d = dur!"days"(-7) + dur!"hours"(-9); auto result = d.split!("days", "hours")(); assert(result.days == -7); assert(result.hours == -9); } ``` const nothrow @nogc void **split**(Args...)(out Args args) Constraints: if (units.length != 0 && (args.length == units.length) && allAreMutableIntegralTypes!Args); const nothrow @nogc auto **split**(); Ditto const nothrow @nogc @property long **total**(string units)() Constraints: if (units == "weeks" || units == "days" || units == "hours" || units == "minutes" || units == "seconds" || units == "msecs" || units == "usecs" || units == "hnsecs" || units == "nsecs"); Returns the total number of the given units in this `Duration`. So, unlike `split`, it does not strip out the larger units. Examples: ``` assert(dur!"weeks"(12).total!"weeks" == 12); assert(dur!"weeks"(12).total!"days" == 84); assert(dur!"days"(13).total!"weeks" == 1); assert(dur!"days"(13).total!"days" == 13); assert(dur!"hours"(49).total!"days" == 2); assert(dur!"hours"(49).total!"hours" == 49); assert(dur!"nsecs"(2007).total!"hnsecs" == 20); assert(dur!"nsecs"(2007).total!"nsecs" == 2000); ``` const pure nothrow @safe string **toString**(); Converts this `Duration` to a `string`. The string is meant to be human readable, not machine parseable (e.g. whether there is an `'s'` on the end of the unit name usually depends on whether it's plural or not, and empty units are not included unless the Duration is `zero`). Any code needing a specific string format should use `total` or `split` to get the units needed to create the desired string format and create the string itself. The format returned by toString may or may not change in the future. Examples: ``` assert(Duration.zero.toString() == "0 hnsecs"); assert(weeks(5).toString() == "5 weeks"); assert(days(2).toString() == "2 days"); assert(hours(1).toString() == "1 hour"); assert(minutes(19).toString() == "19 minutes"); assert(seconds(42).toString() == "42 secs"); assert(msecs(42).toString() == "42 ms"); assert(usecs(27).toString() == "27 μs"); assert(hnsecs(5).toString() == "5 hnsecs"); assert(seconds(121).toString() == "2 minutes and 1 sec"); assert((minutes(5) + seconds(3) + usecs(4)).toString() == "5 minutes, 3 secs, and 4 μs"); assert(seconds(-42).toString() == "-42 secs"); assert(usecs(-5239492).toString() == "-5 secs, -239 ms, and -492 μs"); ``` const pure nothrow @nogc @property @safe bool **isNegative**(); Returns whether this `Duration` is negative. pure nothrow @nogc @safe T **to**(string units, T, D)(D td) Constraints: if (is(immutable(D) == immutable(TickDuration)) && (units == "seconds" || units == "msecs" || units == "usecs" || units == "hnsecs" || units == "nsecs")); Converts a `TickDuration` to the given units as either an integral value or a floating point value. Parameters: | | | | --- | --- | | units | The units to convert to. Accepts `"seconds"` and smaller only. | | T | The type to convert to (either an integral type or a floating point type). | | D `td` | The TickDuration to convert | Examples: ``` auto t = TickDuration.from!"seconds"(1000); long tl = to!("seconds",long)(t); assert(tl == 1000); import core.stdc.math : fabs; double td = to!("seconds",double)(t); assert(fabs(td - 1000) < 0.001); ``` pure nothrow @nogc @safe Duration **dur**(string units)(long length) Constraints: if (units == "weeks" || units == "days" || units == "hours" || units == "minutes" || units == "seconds" || units == "msecs" || units == "usecs" || units == "hnsecs" || units == "nsecs"); alias **weeks** = dur!"**weeks**".dur; alias **days** = dur!"**days**".dur; alias **hours** = dur!"**hours**".dur; alias **minutes** = dur!"**minutes**".dur; alias **seconds** = dur!"**seconds**".dur; alias **msecs** = dur!"**msecs**".dur; alias **usecs** = dur!"**usecs**".dur; alias **hnsecs** = dur!"**hnsecs**".dur; alias **nsecs** = dur!"**nsecs**".dur; These allow you to construct a `Duration` from the given time units with the given length. You can either use the generic function `dur` and give it the units as a `string` or use the named aliases. The possible values for units are `"weeks"`, `"days"`, `"hours"`, `"minutes"`, `"seconds"`, `"msecs"` (milliseconds), `"usecs"`, (microseconds), `"hnsecs"` (hecto-nanoseconds, i.e. 100 ns), and `"nsecs"`. Parameters: | | | | --- | --- | | units | The time units of the `Duration` (e.g. `"days"`). | | long `length` | The number of units in the `Duration`. | Examples: ``` // Generic assert(dur!"weeks"(142).total!"weeks" == 142); assert(dur!"days"(142).total!"days" == 142); assert(dur!"hours"(142).total!"hours" == 142); assert(dur!"minutes"(142).total!"minutes" == 142); assert(dur!"seconds"(142).total!"seconds" == 142); assert(dur!"msecs"(142).total!"msecs" == 142); assert(dur!"usecs"(142).total!"usecs" == 142); assert(dur!"hnsecs"(142).total!"hnsecs" == 142); assert(dur!"nsecs"(142).total!"nsecs" == 100); // Non-generic assert(weeks(142).total!"weeks" == 142); assert(days(142).total!"days" == 142); assert(hours(142).total!"hours" == 142); assert(minutes(142).total!"minutes" == 142); assert(seconds(142).total!"seconds" == 142); assert(msecs(142).total!"msecs" == 142); assert(usecs(142).total!"usecs" == 142); assert(hnsecs(142).total!"hnsecs" == 142); assert(nsecs(142).total!"nsecs" == 100); ``` alias **MonoTime** = MonoTimeImpl!ClockType.normal.MonoTimeImpl; alias for `MonoTimeImpl` instantiated with `ClockType.normal`. This is what most programs should use. It's also what much of `MonoTimeImpl` uses in its documentation (particularly in the examples), because that's what's going to be used in most code. struct **MonoTimeImpl**(ClockType clockType); Represents a timestamp of the system's monotonic clock. A monotonic clock is one which always goes forward and never moves backwards, unlike the system's wall clock time (as represented by [`std.datetime.SysTime`](std_datetime#SysTime)). The system's wall clock time can be adjusted by the user or by the system itself via services such as NTP, so it is unreliable to use the wall clock time for timing. Timers which use the wall clock time could easily end up never going off due to changes made to the wall clock time or otherwise waiting for a different period of time than that specified by the programmer. However, because the monotonic clock always increases at a fixed rate and is not affected by adjustments to the wall clock time, it is ideal for use with timers or anything which requires high precision timing. So, MonoTime should be used for anything involving timers and timing, whereas [`std.datetime.SysTime`](std_datetime#SysTime) should be used when the wall clock time is required. The monotonic clock has no relation to wall clock time. Rather, it holds its time as the number of ticks of the clock which have occurred since the clock started (typically when the system booted up). So, to determine how much time has passed between two points in time, one monotonic time is subtracted from the other to determine the number of ticks which occurred between the two points of time, and those ticks are divided by the number of ticks that occur every second (as represented by MonoTime.ticksPerSecond) to get a meaningful duration of time. Normally, MonoTime does these calculations for the programmer, but the `ticks` and `ticksPerSecond` properties are provided for those who require direct access to the system ticks. The normal way that MonoTime would be used is ``` MonoTime before = MonoTime.currTime; // do stuff... MonoTime after = MonoTime.currTime; Duration timeElapsed = after - before; ``` [`MonoTime`](#MonoTime) is an alias to `MonoTimeImpl!(ClockType.normal)` and is what most programs should use for the monotonic clock, so that's what is used in most of `MonoTimeImpl`'s documentation. But `MonoTimeImpl` can be instantiated with other clock types for those rare programs that need it. See Also: [`ClockType`](#ClockType) static nothrow @nogc @property @trusted MonoTimeImpl **currTime**(); The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific. On Windows, `QueryPerformanceCounter` is used. On Mac OS X, `mach_absolute_time` is used, while on other POSIX systems, `clock_gettime` is used. Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux. MonoTimeImpl **zero**(); A `MonoTime` of `0` ticks. It's provided to be consistent with `Duration.zero`, and it's more explicit than `MonoTime.init`. MonoTimeImpl **max**(); Largest `MonoTime` possible. MonoTimeImpl **min**(); Most negative `MonoTime` possible. const pure nothrow @nogc int **opCmp**(MonoTimeImpl rhs); Compares this MonoTime with the given MonoTime. Returns: | | | | --- | --- | | this < rhs | < 0 | | this == rhs | 0 | | this > rhs | > 0 | const pure nothrow @nogc Duration **opBinary**(string op)(MonoTimeImpl rhs) Constraints: if (op == "-"); Subtracting two MonoTimes results in a [`Duration`](#Duration) representing the amount of time which elapsed between them. The primary way that programs should time how long something takes is to do ``` MonoTime before = MonoTime.currTime; // do stuff MonoTime after = MonoTime.currTime; // How long it took. Duration timeElapsed = after - before; ``` or to use a wrapper (such as a stop watch type) which does that. Warning: Because [`Duration`](#Duration) is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail ``` auto before = MonoTime.currTime; // do stuff auto after = MonoTime.currTime; auto timeElapsed = after - before; assert(before + timeElapsed == after); ``` This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's `ticks` property and keep all calculations in ticks rather than using [`Duration`](#Duration). const pure nothrow @nogc MonoTimeImpl **opBinary**(string op)(Duration rhs) Constraints: if (op == "+" || op == "-"); pure nothrow @nogc ref MonoTimeImpl **opOpAssign**(string op)(Duration rhs) Constraints: if (op == "+" || op == "-"); Adding or subtracting a [`Duration`](#Duration) to/from a MonoTime results in a MonoTime which is adjusted by that amount. const pure nothrow @nogc @property long **ticks**(); The number of ticks in the monotonic time. Most programs should not use this directly, but it's exposed for those few programs that need it. The main reasons that a program might need to use ticks directly is if the system clock has higher precision than hnsecs, and the program needs that higher precision, or if the program needs to avoid the rounding errors caused by converting to hnsecs. static pure nothrow @nogc @property long **ticksPerSecond**(); The number of ticks that MonoTime has per second - i.e. the resolution or frequency of the system's monotonic clock. e.g. if the system clock had a resolution of microseconds, then ticksPerSecond would be `1_000_000`. const pure nothrow string **toString**(); pure nothrow @nogc @safe long **convClockFreq**(long ticks, long srcTicksPerSecond, long dstTicksPerSecond); Converts the given time from one clock frequency/resolution to another. See Also: [`ticksToNSecs`](#ticksToNSecs) Examples: ``` // one tick is one second -> one tick is a hecto-nanosecond assert(convClockFreq(45, 1, 10_000_000) == 450_000_000); // one tick is one microsecond -> one tick is a millisecond assert(convClockFreq(9029, 1_000_000, 1_000) == 9); // one tick is 1/3_515_654 of a second -> 1/1_001_010 of a second assert(convClockFreq(912_319, 3_515_654, 1_001_010) == 259_764); // one tick is 1/MonoTime.ticksPerSecond -> one tick is a nanosecond // Equivalent to ticksToNSecs auto nsecs = convClockFreq(1982, MonoTime.ticksPerSecond, 1_000_000_000); ``` pure nothrow @nogc @safe long **ticksToNSecs**(long ticks); Convenience wrapper around [`convClockFreq`](#convClockFreq) which converts ticks at a clock frequency of `MonoTime.ticksPerSecond` to nanoseconds. It's primarily of use when `MonoTime.ticksPerSecond` is greater than hecto-nanosecond resolution, and an application needs a higher precision than hecto-nanoceconds. See Also: [`convClockFreq`](#convClockFreq) Examples: ``` auto before = MonoTime.currTime; // do stuff auto after = MonoTime.currTime; auto diffInTicks = after.ticks - before.ticks; auto diffInNSecs = ticksToNSecs(diffInTicks); assert(diffInNSecs == convClockFreq(diffInTicks, MonoTime.ticksPerSecond, 1_000_000_000)); ``` pure nothrow @nogc @safe long **nsecsToTicks**(long ticks); The reverse of [`ticksToNSecs`](#ticksToNSecs). struct **TickDuration**; Warning: TickDuration will be deprecated in the near future (once all uses of it in Phobos have been deprecated). Please use [`MonoTime`](#MonoTime) for the cases where a monotonic timestamp is needed and [`Duration`](#Duration) when a duration is needed, rather than using TickDuration. It has been decided that TickDuration is too confusing (e.g. it conflates a monotonic timestamp and a duration in monotonic clock ticks) and that having multiple duration types is too awkward and confusing. Represents a duration of time in system clock ticks. The system clock ticks are the ticks of the system clock at the highest precision that the system provides. static immutable long **ticksPerSec**; The number of ticks that the system clock has in one second. If `ticksPerSec` is `0`, then then `TickDuration` failed to get the value of `ticksPerSec` on the current system, and `TickDuration` is not going to work. That would be highly abnormal though. static immutable TickDuration **appOrigin**; The tick of the system clock (as a `TickDuration`) when the application started. static pure nothrow @nogc @property @safe TickDuration **zero**(); It's the same as `TickDuration(0)`, but it's provided to be consistent with `Duration`, which provides a `zero` property. static pure nothrow @nogc @property @safe TickDuration **max**(); Largest `TickDuration` possible. static pure nothrow @nogc @property @safe TickDuration **min**(); Most negative `TickDuration` possible. long **length**; The number of system ticks in this `TickDuration`. You can convert this `length` into the number of seconds by dividing it by `ticksPerSec` (or using one the appropriate property function to do it). const pure nothrow @nogc @property @safe long **seconds**(); Returns the total number of seconds in this `TickDuration`. const pure nothrow @nogc @property @safe long **msecs**(); Returns the total number of milliseconds in this `TickDuration`. const pure nothrow @nogc @property @safe long **usecs**(); Returns the total number of microseconds in this `TickDuration`. const pure nothrow @nogc @property @safe long **hnsecs**(); Returns the total number of hecto-nanoseconds in this `TickDuration`. const pure nothrow @nogc @property @safe long **nsecs**(); Returns the total number of nanoseconds in this `TickDuration`. pure nothrow @nogc @safe TickDuration **from**(string units)(long length) Constraints: if (units == "seconds" || units == "msecs" || units == "usecs" || units == "hnsecs" || units == "nsecs"); This allows you to construct a `TickDuration` from the given time units with the given length. Parameters: | | | | --- | --- | | units | The time units of the `TickDuration` (e.g. `"msecs"`). | | long `length` | The number of units in the `TickDuration`. | const pure nothrow @nogc @safe Duration **opCast**(T)() Constraints: if (is(immutable(T) == immutable(Duration))); Returns a [`Duration`](#Duration) with the same number of hnsecs as this `TickDuration`. Note that the conventional way to convert between `TickDuration` and `Duration` is using [`std.conv.to`](std_conv#to), e.g.: `tickDuration.to!Duration()` pure nothrow @nogc ref @safe TickDuration **opOpAssign**(string op)(TickDuration rhs) Constraints: if (op == "+" || op == "-"); Adds or subtracts two `TickDuration`s as well as assigning the result to this `TickDuration`. The legal types of arithmetic for `TickDuration` using this operator are | | | | | | | --- | --- | --- | --- | --- | | TickDuration | += | TickDuration | --> | TickDuration | | TickDuration | -= | TickDuration | --> | TickDuration | Parameters: | | | | --- | --- | | TickDuration `rhs` | The `TickDuration` to add to or subtract from this `TickDuration`. | const pure nothrow @nogc @safe TickDuration **opBinary**(string op)(TickDuration rhs) Constraints: if (op == "+" || op == "-"); Adds or subtracts two `TickDuration`s. The legal types of arithmetic for `TickDuration` using this operator are | | | | | | | --- | --- | --- | --- | --- | | TickDuration | + | TickDuration | --> | TickDuration | | TickDuration | - | TickDuration | --> | TickDuration | Parameters: | | | | --- | --- | | TickDuration `rhs` | The `TickDuration` to add to or subtract from this `TickDuration`. | const pure nothrow @nogc @safe TickDuration **opUnary**(string op)() Constraints: if (op == "-"); Returns the negation of this `TickDuration`. const pure nothrow @nogc @safe int **opCmp**(TickDuration rhs); operator overloading "<, >, <=, >=" pure nothrow @nogc @safe void **opOpAssign**(string op, T)(T value) Constraints: if (op == "\*" && (\_\_traits(isIntegral, T) || \_\_traits(isFloating, T))); The legal types of arithmetic for `TickDuration` using this operator overload are | | | | | | | --- | --- | --- | --- | --- | | TickDuration | \* | long | --> | TickDuration | | TickDuration | \* | floating point | --> | TickDuration | Parameters: | | | | --- | --- | | T `value` | The value to divide from this duration. | pure @safe void **opOpAssign**(string op, T)(T value) Constraints: if (op == "/" && (\_\_traits(isIntegral, T) || \_\_traits(isFloating, T))); The legal types of arithmetic for `TickDuration` using this operator overload are | | | | | | | --- | --- | --- | --- | --- | | TickDuration | / | long | --> | TickDuration | | TickDuration | / | floating point | --> | TickDuration | Parameters: | | | | --- | --- | | T `value` | The value to divide from this `TickDuration`. | Throws: `TimeException` if an attempt to divide by `0` is made. const pure nothrow @nogc @safe TickDuration **opBinary**(string op, T)(T value) Constraints: if (op == "\*" && (\_\_traits(isIntegral, T) || \_\_traits(isFloating, T))); The legal types of arithmetic for `TickDuration` using this operator overload are | | | | | | | --- | --- | --- | --- | --- | | TickDuration | \* | long | --> | TickDuration | | TickDuration | \* | floating point | --> | TickDuration | Parameters: | | | | --- | --- | | T `value` | The value to divide from this `TickDuration`. | const pure @safe TickDuration **opBinary**(string op, T)(T value) Constraints: if (op == "/" && (\_\_traits(isIntegral, T) || \_\_traits(isFloating, T))); The legal types of arithmetic for `TickDuration` using this operator overload are | | | | | | | --- | --- | --- | --- | --- | | TickDuration | / | long | --> | TickDuration | | TickDuration | / | floating point | --> | TickDuration | Parameters: | | | | --- | --- | | T `value` | The value to divide from this `TickDuration`. | Throws: `TimeException` if an attempt to divide by `0` is made. pure nothrow @nogc @safe this(long ticks); Parameters: | | | | --- | --- | | long `ticks` | The number of ticks in the TickDuration. | static nothrow @nogc @property @trusted TickDuration **currSystemTick**(); The current system tick. The number of ticks per second varies from system to system. `currSystemTick` uses a monotonic clock, so it's intended for precision timing by comparing relative time values, not for getting the current system time. On Windows, `QueryPerformanceCounter` is used. On Mac OS X, `mach_absolute_time` is used, while on other Posix systems, `clock_gettime` is used. If `mach_absolute_time` or `clock_gettime` is unavailable, then Posix systems use `gettimeofday` (the decision is made when `TickDuration` is compiled), which unfortunately, is not monotonic, but if `mach_absolute_time` and `clock_gettime` aren't available, then `gettimeofday` is the the best that there is. Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock could be off if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or on Linux. Throws: `TimeException` if it fails to get the time. pure nothrow @nogc @safe long **convert**(string from, string to)(long value) Constraints: if ((from == "weeks" || from == "days" || from == "hours" || from == "minutes" || from == "seconds" || from == "msecs" || from == "usecs" || from == "hnsecs" || from == "nsecs") && (to == "weeks" || to == "days" || to == "hours" || to == "minutes" || to == "seconds" || to == "msecs" || to == "usecs" || to == "hnsecs" || to == "nsecs") || (from == "years" || from == "months") && (to == "years" || to == "months")); Generic way of converting between two time units. Conversions to smaller units use truncating division. Years and months can be converted to each other, small units can be converted to each other, but years and months cannot be converted to or from smaller units (due to the varying number of days in a month or year). Parameters: | | | | --- | --- | | from | The units of time to convert from. | | to | The units of time to convert to. | | long `value` | The value to convert. | Examples: ``` assert(convert!("years", "months")(1) == 12); assert(convert!("months", "years")(12) == 1); assert(convert!("weeks", "days")(1) == 7); assert(convert!("hours", "seconds")(1) == 3600); assert(convert!("seconds", "days")(1) == 0); assert(convert!("seconds", "days")(86_400) == 1); assert(convert!("nsecs", "nsecs")(1) == 1); assert(convert!("nsecs", "hnsecs")(1) == 0); assert(convert!("hnsecs", "nsecs")(1) == 100); assert(convert!("nsecs", "seconds")(1) == 0); assert(convert!("seconds", "nsecs")(1) == 1_000_000_000); ``` class **TimeException**: object.Exception; Exception type used by core.time. pure nothrow @safe this(string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null); Parameters: | | | | --- | --- | | string `msg` | The message for the exception. | | string `file` | The file where the exception occurred. | | size\_t `line` | The line number where the exception occurred. | | Throwable `next` | The previous exception in the chain of exceptions, if any. | pure nothrow @safe this(string msg, Throwable next, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_); Parameters: | | | | --- | --- | | string `msg` | The message for the exception. | | Throwable `next` | The previous exception in the chain of exceptions. | | string `file` | The file where the exception occurred. | | size\_t `line` | The line number where the exception occurred. | pure nothrow @nogc @safe Duration **abs**(Duration duration); pure nothrow @nogc @safe TickDuration **abs**(TickDuration duration); Returns the absolute value of a duration.
programming_docs
d std.container.array std.container.array =================== This module provides an `Array` type with deterministic memory usage not reliant on the GC, as an alternative to the built-in arrays. This module is a submodule of [`std.container`](std_container). Source [std/container/array.d](https://github.com/dlang/phobos/blob/master/std/container/array.d) License: Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE\_1\_0.txt or copy at [boost.org/LICENSE\_1\_0.txt](http://%20boost.org/LICENSE_1_0.txt)). Authors: [Andrei Alexandrescu](http://erdani.com) Examples: ``` auto arr = Array!int(0, 2, 3); writeln(arr[0]); // 0 writeln(arr.front); // 0 writeln(arr.back); // 3 // reserve space arr.reserve(1000); writeln(arr.length); // 3 assert(arr.capacity >= 1000); // insertion arr.insertBefore(arr[1..$], 1); writeln(arr.front); // 0 writeln(arr.length); // 4 arr.insertBack(4); writeln(arr.back); // 4 writeln(arr.length); // 5 // set elements arr[1] *= 42; writeln(arr[1]); // 42 ``` Examples: ``` import std.algorithm.comparison : equal; auto arr = Array!int(1, 2, 3); // concat auto b = Array!int(11, 12, 13); arr ~= b; writeln(arr.length); // 6 // slicing assert(arr[1 .. 3].equal([2, 3])); // remove arr.linearRemove(arr[1 .. 3]); assert(arr[0 .. 2].equal([1, 11])); ``` Examples: `Array!bool` packs together values efficiently by allocating one bit per element ``` Array!bool arr; arr.insert([true, true, false, true, false]); writeln(arr.length); // 5 ``` struct **Array**(T) if (!is(immutable(T) == immutable(bool))); Array type with deterministic control of memory. The memory allocated for the array is reclaimed as soon as possible; there is no reliance on the garbage collector. `Array` uses `malloc`, `realloc` and `free` for managing its own memory. This means that pointers to elements of an `Array` will become dangling as soon as the element is removed from the `Array`. On the other hand the memory allocated by an `Array` will be scanned by the GC and GC managed objects referenced from an `Array` will be kept alive. Note When using `Array` with range-based functions like those in `std.algorithm`, `Array` must be sliced to get a range (for example, use `array[].map!` instead of `array.map!`). The container itself is not a range. Examples: typeof may give wrong result in case of classes defining `opCall` operator <https://issues.dlang.org/show_bug.cgi?id=20589> destructor std.container.array.Array!(MyClass).Array.~this is @system so the unittest is @system too ``` class MyClass { T opCall(T)(T p) { return p; } } Array!MyClass arr; ``` this(U)(U[] values...) Constraints: if (isImplicitlyConvertible!(U, T)); Constructor taking a number of items. this(Range)(Range r) Constraints: if (isInputRange!Range && isImplicitlyConvertible!(ElementType!Range, T) && !is(Range == T[])); Constructor taking an [input range](std_range_primitives#isInputRange) const bool **opEquals**(const Array rhs); const bool **opEquals**(ref const Array rhs); Comparison for equality. alias **Range** = RangeT!Array; alias **ConstRange** = RangeT!(const(Array)); alias **ImmutableRange** = RangeT!(immutable(Array)); Defines the array's primary range, which is a random-access range. `ConstRange` is a variant with `const` elements. `ImmutableRange` is a variant with `immutable` elements. @property Array **dup**(); Duplicates the array. The elements themselves are not transitively duplicated. Complexity Ο(`length`). const @property bool **empty**(); Returns: `true` if and only if the array has no elements. Complexity Ο(`1`) const @property size\_t **length**(); const size\_t **opDollar**(); Returns: The number of elements in the array. Complexity Ο(`1`). @property size\_t **capacity**(); Returns: The maximum number of elements the array can store without reallocating memory and invalidating iterators upon insertion. Complexity Ο(`1`) void **reserve**(size\_t elements); Ensures sufficient capacity to accommodate `e` elements. If `e < capacity`, this method does nothing. Postcondition `capacity >= e` Note If the capacity is increased, one should assume that all iterators to the elements are invalidated. Complexity at most Ο(`length`) if `e > capacity`, otherwise Ο(`1`). Range **opSlice**(); Returns: A range that iterates over elements of the array in forward order. Complexity Ο(`1`) Range **opSlice**(size\_t i, size\_t j); Returns: A range that iterates over elements of the array from index `i` up to (excluding) index `j`. Precondition `i <= j && j <= length` Complexity Ο(`1`) inout @property ref inout(T) **front**(); Returns: The first element of the array. Precondition `empty == false` Complexity Ο(`1`) inout @property ref inout(T) **back**(); Returns: The last element of the array. Precondition `empty == false` Complexity Ο(`1`) inout ref inout(T) **opIndex**(size\_t i); Returns: The element or a reference to the element at the specified index. Precondition `i < length` Complexity Ο(`1`) void **opSliceAssign**(T value); void **opSliceAssign**(T value, size\_t i, size\_t j); void **opSliceUnary**(string op)() Constraints: if (op == "++" || op == "--"); void **opSliceUnary**(string op)(size\_t i, size\_t j) Constraints: if (op == "++" || op == "--"); void **opSliceOpAssign**(string op)(T value); void **opSliceOpAssign**(string op)(T value, size\_t i, size\_t j); Slicing operators executing the specified operation on the entire slice. Precondition `i < j && j < length` Complexity Ο(`slice.length`) Array **opBinary**(string op, Stuff)(Stuff stuff) Constraints: if (op == "~"); Returns: A new array which is a concatenation of `this` and its argument. Complexity Ο(`length + m`), where `m` is the number of elements in `stuff`. void **opOpAssign**(string op, Stuff)(auto ref Stuff stuff) Constraints: if (op == "~"); Forwards to `insertBack`. void **clear**(); Removes all the elements from the array and releases allocated memory. Postcondition `empty == true && capacity == 0` Complexity Ο(`length`) @property void **length**(size\_t newLength); Sets the number of elements in the array to `newLength`. If `newLength` is greater than `length`, the new elements are added to the end of the array and initialized with `T.init`. Complexity Guaranteed Ο(`abs(length - newLength)`) if `capacity >= newLength`. If `capacity < newLength` the worst case is Ο(`newLength`). Postcondition `length == newLength` T **removeAny**(); alias **stableRemoveAny** = removeAny; Removes the last element from the array and returns it. Both stable and non-stable versions behave the same and guarantee that ranges iterating over the array are never invalidated. Precondition `empty == false` Returns: The element removed. Complexity Ο(`1`). Throws: `Exception` if the array is empty. size\_t **insertBack**(Stuff)(Stuff stuff) Constraints: if (isImplicitlyConvertible!(Stuff, T) || isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T)); alias **insert** = insertBack; Inserts the specified elements at the back of the array. `stuff` can be a value convertible to `T` or a range of objects convertible to `T`. Returns: The number of elements inserted. Complexity Ο(`length + m`) if reallocation takes place, otherwise Ο(`m`), where `m` is the number of elements in `stuff`. void **removeBack**(); alias **stableRemoveBack** = removeBack; Removes the value from the back of the array. Both stable and non-stable versions behave the same and guarantee that ranges iterating over the array are never invalidated. Precondition `empty == false` Complexity Ο(`1`). Throws: `Exception` if the array is empty. size\_t **removeBack**(size\_t howMany); alias **stableRemoveBack** = removeBack; Removes `howMany` values from the back of the array. Unlike the unparameterized versions above, these functions do not throw if they could not remove `howMany` elements. Instead, if `howMany > n`, all elements are removed. The returned value is the effective number of elements removed. Both stable and non-stable versions behave the same and guarantee that ranges iterating over the array are never invalidated. Returns: The number of elements removed. Complexity Ο(`howMany`). size\_t **insertBefore**(Stuff)(Range r, Stuff stuff) Constraints: if (isImplicitlyConvertible!(Stuff, T)); size\_t **insertBefore**(Stuff)(Range r, Stuff stuff) Constraints: if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T)); alias **stableInsertBefore** = insertBefore; size\_t **insertAfter**(Stuff)(Range r, Stuff stuff); size\_t **replace**(Stuff)(Range r, Stuff stuff) Constraints: if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T)); size\_t **replace**(Stuff)(Range r, Stuff stuff) Constraints: if (isImplicitlyConvertible!(Stuff, T)); Inserts `stuff` before, after, or instead range `r`, which must be a valid range previously extracted from this array. `stuff` can be a value convertible to `T` or a range of objects convertible to `T`. Both stable and non-stable version behave the same and guarantee that ranges iterating over the array are never invalidated. Returns: The number of values inserted. Complexity Ο(`length + m`), where `m` is the length of `stuff`. Throws: `Exception` if `r` is not a range extracted from this array. Range **linearRemove**(Range r); Removes all elements belonging to `r`, which must be a range obtained originally from this array. Returns: A range spanning the remaining elements in the array that initially were right after `r`. Complexity Ο(`length`) Throws: `Exception` if `r` is not a valid range extracted from this array. struct **Array**(T) if (is(immutable(T) == immutable(bool))); Array specialized for `bool`. Packs together values efficiently by allocating one bit per element. struct **Range**; Defines the array's primary range. @property Range **save**(); @property bool **empty**(); @property T **front**(); @property void **front**(bool value); T **moveFront**(); void **popFront**(); @property T **back**(); @property void **back**(bool value); T **moveBack**(); void **popBack**(); T **opIndex**(size\_t i); void **opIndexAssign**(T value, size\_t i); T **moveAt**(size\_t i); const @property size\_t **length**(); Range **opSlice**(size\_t low, size\_t high); Range primitives @property bool **empty**(); Property returning `true` if and only if the array has no elements. Complexity Ο(`1`) @property Array **dup**(); Returns: A duplicate of the array. Complexity Ο(`length`). const @property size\_t **length**(); Returns the number of elements in the array. Complexity Ο(`1`). @property size\_t **capacity**(); Returns: The maximum number of elements the array can store without reallocating memory and invalidating iterators upon insertion. Complexity Ο(`1`). void **reserve**(size\_t e); Ensures sufficient capacity to accommodate `e` elements. If `e < capacity`, this method does nothing. Postcondition `capacity >= e` Note If the capacity is increased, one should assume that all iterators to the elements are invalidated. Complexity at most Ο(`length`) if `e > capacity`, otherwise Ο(`1`). Range **opSlice**(); Returns: A range that iterates over all elements of the array in forward order. Complexity Ο(`1`) Range **opSlice**(size\_t a, size\_t b); Returns: A range that iterates the array between two specified positions. Complexity Ο(`1`) @property bool **front**(); @property void **front**(bool value); Returns: The first element of the array. Precondition `empty == false` Complexity Ο(`1`) Throws: `Exception` if the array is empty. @property bool **back**(); @property void **back**(bool value); Returns: The last element of the array. Precondition `empty == false` Complexity Ο(`1`) Throws: `Exception` if the array is empty. bool **opIndex**(size\_t i); void **opIndexAssign**(bool value, size\_t i); void **opIndexOpAssign**(string op)(bool value, size\_t i); T **moveAt**(size\_t i); Indexing operators yielding or modifyng the value at the specified index. Precondition `i < length` Complexity Ο(`1`) Array!bool **opBinary**(string op, Stuff)(Stuff rhs) Constraints: if (op == "~"); Returns: A new array which is a concatenation of `this` and its argument. Complexity Ο(`length + m`), where `m` is the number of elements in `stuff`. Array!bool **opOpAssign**(string op, Stuff)(Stuff stuff) Constraints: if (op == "~"); Forwards to `insertBack`. void **clear**(); Removes all the elements from the array and releases allocated memory. Postcondition `empty == true && capacity == 0` Complexity Ο(`length`) @property void **length**(size\_t newLength); Sets the number of elements in the array to `newLength`. If `newLength` is greater than `length`, the new elements are added to the end of the array and initialized with `false`. Complexity Guaranteed Ο(`abs(length - newLength)`) if `capacity >= newLength`. If `capacity < newLength` the worst case is Ο(`newLength`). Postcondition `length == newLength` T **removeAny**(); alias **stableRemoveAny** = removeAny; Removes the last element from the array and returns it. Both stable and non-stable versions behave the same and guarantee that ranges iterating over the array are never invalidated. Precondition `empty == false` Returns: The element removed. Complexity Ο(`1`). Throws: `Exception` if the array is empty. size\_t **insertBack**(Stuff)(Stuff stuff) Constraints: if (is(Stuff : bool)); size\_t **insertBack**(Stuff)(Stuff stuff) Constraints: if (isInputRange!Stuff && is(ElementType!Stuff : bool)); alias **stableInsertBack** = insertBack; alias **insert** = insertBack; alias **stableInsert** = insertBack; alias **linearInsert** = insertBack; alias **stableLinearInsert** = insertBack; Inserts the specified elements at the back of the array. `stuff` can be a value convertible to `bool` or a range of objects convertible to `bool`. Returns: The number of elements inserted. Complexity Ο(`length + m`) if reallocation takes place, otherwise Ο(`m`), where `m` is the number of elements in `stuff`. void **removeBack**(); alias **stableRemoveBack** = removeBack; Removes the value from the back of the array. Both stable and non-stable versions behave the same and guarantee that ranges iterating over the array are never invalidated. Precondition `empty == false` Complexity Ο(`1`). Throws: `Exception` if the array is empty. size\_t **removeBack**(size\_t howMany); alias **stableRemoveBack** = removeBack; Removes `howMany` values from the back of the array. Unlike the unparameterized versions above, these functions do not throw if they could not remove `howMany` elements. Instead, if `howMany > n`, all elements are removed. The returned value is the effective number of elements removed. Both stable and non-stable versions behave the same and guarantee that ranges iterating over the array are never invalidated. Returns: The number of elements removed. Complexity Ο(`howMany`). size\_t **insertBefore**(Stuff)(Range r, Stuff stuff); alias **stableInsertBefore** = insertBefore; size\_t **insertAfter**(Stuff)(Range r, Stuff stuff); alias **stableInsertAfter** = insertAfter; size\_t **replace**(Stuff)(Range r, Stuff stuff) Constraints: if (is(Stuff : bool)); alias **stableReplace** = replace; Inserts `stuff` before, after, or instead range `r`, which must be a valid range previously extracted from this array. `stuff` can be a value convertible to `bool` or a range of objects convertible to `bool`. Both stable and non-stable version behave the same and guarantee that ranges iterating over the array are never invalidated. Returns: The number of values inserted. Complexity Ο(`length + m`), where `m` is the length of `stuff`. Range **linearRemove**(Range r); Removes all elements belonging to `r`, which must be a range obtained originally from this array. Returns: A range spanning the remaining elements in the array that initially were right after `r`. Complexity Ο(`length`) d std.algorithm.searching std.algorithm.searching ======================= This is a submodule of [`std.algorithm`](std_algorithm). It contains generic searching algorithms. Cheat Sheet| Function Name | Description | | [`all`](#all) | `all!"a > 0"([1, 2, 3, 4])` returns `true` because all elements are positive | | [`any`](#any) | `any!"a > 0"([1, 2, -3, -4])` returns `true` because at least one element is positive | | [`balancedParens`](#balancedParens) | `balancedParens("((1 + 1) / 2)")` returns `true` because the string has balanced parentheses. | | [`boyerMooreFinder`](#boyerMooreFinder) | `find("hello world", boyerMooreFinder("or"))` returns `"orld"` using the [Boyer-Moore algorithm](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm). | | [`canFind`](#canFind) | `canFind("hello world", "or")` returns `true`. | | [`count`](#count) | Counts elements that are equal to a specified value or satisfy a predicate. `count([1, 2, 1], 1)` returns `2` and `count!"a < 0"([1, -3, 0])` returns `1`. | | [`countUntil`](#countUntil) | `countUntil(a, b)` returns the number of steps taken in `a` to reach `b`; for example, `countUntil("hello!", "o")` returns `4`. | | [`commonPrefix`](#commonPrefix) | `commonPrefix("parakeet", "parachute")` returns `"para"`. | | [`endsWith`](#endsWith) | `endsWith("rocks", "ks")` returns `true`. | | [`find`](#find) | `find("hello world", "or")` returns `"orld"` using linear search. (For binary search refer to [`std.range.SortedRange`](std_range#SortedRange).) | | [`findAdjacent`](#findAdjacent) | `findAdjacent([1, 2, 3, 3, 4])` returns the subrange starting with two equal adjacent elements, i.e. `[3, 3, 4]`. | | [`findAmong`](#findAmong) | `findAmong("abcd", "qcx")` returns `"cd"` because `'c'` is among `"qcx"`. | | [`findSkip`](#findSkip) | If `a = "abcde"`, then `findSkip(a, "x")` returns `false` and leaves `a` unchanged, whereas `findSkip(a, "c")` advances `a` to `"de"` and returns `true`. | | [`findSplit`](#findSplit) | `findSplit("abcdefg", "de")` returns the three ranges `"abc"`, `"de"`, and `"fg"`. | | [`findSplitAfter`](#findSplitAfter) | `findSplitAfter("abcdefg", "de")` returns the two ranges `"abcde"` and `"fg"`. | | [`findSplitBefore`](#findSplitBefore) | `findSplitBefore("abcdefg", "de")` returns the two ranges `"abc"` and `"defg"`. | | [`minCount`](#minCount) | `minCount([2, 1, 1, 4, 1])` returns `tuple(1, 3)`. | | [`maxCount`](#maxCount) | `maxCount([2, 4, 1, 4, 1])` returns `tuple(4, 2)`. | | [`minElement`](#minElement) | Selects the minimal element of a range. `minElement([3, 4, 1, 2])` returns `1`. | | [`maxElement`](#maxElement) | Selects the maximal element of a range. `maxElement([3, 4, 1, 2])` returns `4`. | | [`minIndex`](#minIndex) | Index of the minimal element of a range. `minElement([3, 4, 1, 2])` returns `2`. | | [`maxIndex`](#maxIndex) | Index of the maximal element of a range. `maxElement([3, 4, 1, 2])` returns `1`. | | [`minPos`](#minPos) | `minPos([2, 3, 1, 3, 4, 1])` returns the subrange `[1, 3, 4, 1]`, i.e., positions the range at the first occurrence of its minimal element. | | [`maxPos`](#maxPos) | `maxPos([2, 3, 1, 3, 4, 1])` returns the subrange `[4, 1]`, i.e., positions the range at the first occurrence of its maximal element. | | [`skipOver`](#skipOver) | Assume `a = "blah"`. Then `skipOver(a, "bi")` leaves `a` unchanged and returns `false`, whereas `skipOver(a, "bl")` advances `a` to refer to `"ah"` and returns `true`. | | [`startsWith`](#startsWith) | `startsWith("hello, world", "hello")` returns `true`. | | [`until`](#until) | Lazily iterates a range until a specific value is found. | License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: [Andrei Alexandrescu](http://erdani.com) Source [std/algorithm/searching.d](https://github.com/dlang/phobos/blob/master/std/algorithm/searching.d) template **all**(alias pred = "a") Checks if *all* of the elements verify `pred`. Examples: ``` assert( all!"a & 1"([1, 3, 5, 7, 9])); assert(!all!"a & 1"([1, 2, 3, 5, 7, 9])); ``` Examples: `all` can also be used without a predicate, if its items can be evaluated to true or false in a conditional statement. This can be a convenient way to quickly evaluate that *all* of the elements of a range are true. ``` int[3] vals = [5, 3, 18]; assert( all(vals[])); ``` bool **all**(Range)(Range range) Constraints: if (isInputRange!Range); Returns `true` if and only if *all* values `v` found in the input range `range` satisfy the predicate `pred`. Performs (at most) Ο(`range.length`) evaluations of `pred`. template **any**(alias pred = "a") Checks if *any* of the elements verifies `pred`. `!any` can be used to verify that *none* of the elements verify `pred`. This is sometimes called `exists` in other languages. Examples: ``` import std.ascii : isWhite; assert( all!(any!isWhite)(["a a", "b b"])); assert(!any!(all!isWhite)(["a a", "b b"])); ``` Examples: `any` can also be used without a predicate, if its items can be evaluated to true or false in a conditional statement. `!any` can be a convenient way to quickly test that *none* of the elements of a range evaluate to true. ``` int[3] vals1 = [0, 0, 0]; assert(!any(vals1[])); //none of vals1 evaluate to true int[3] vals2 = [2, 0, 2]; assert( any(vals2[])); assert(!all(vals2[])); int[3] vals3 = [3, 3, 3]; assert( any(vals3[])); assert( all(vals3[])); ``` bool **any**(Range)(Range range) Constraints: if (isInputRange!Range && is(typeof(unaryFun!pred(range.front)))); Returns `true` if and only if *any* value `v` found in the input range `range` satisfies the predicate `pred`. Performs (at most) Ο(`range.length`) evaluations of `pred`. bool **balancedParens**(Range, E)(Range r, E lPar, E rPar, size\_t maxNestingLevel = size\_t.max) Constraints: if (isInputRange!Range && is(typeof(r.front == lPar))); Checks whether `r` has "balanced parentheses", i.e. all instances of `lPar` are closed by corresponding instances of `rPar`. The parameter `maxNestingLevel` controls the nesting level allowed. The most common uses are the default or `0`. In the latter case, no nesting is allowed. Parameters: | | | | --- | --- | | Range `r` | The range to check. | | E `lPar` | The element corresponding with a left (opening) parenthesis. | | E `rPar` | The element corresponding with a right (closing) parenthesis. | | size\_t `maxNestingLevel` | The maximum allowed nesting level. | Returns: true if the given range has balanced parenthesis within the given maximum nesting level; false otherwise. Examples: ``` auto s = "1 + (2 * (3 + 1 / 2)"; assert(!balancedParens(s, '(', ')')); s = "1 + (2 * (3 + 1) / 2)"; assert(balancedParens(s, '(', ')')); s = "1 + (2 * (3 + 1) / 2)"; assert(!balancedParens(s, '(', ')', 0)); s = "1 + (2 * 3 + 1) / (2 - 5)"; assert(balancedParens(s, '(', ')', 0)); s = "f(x) = ⌈x⌉"; assert(balancedParens(s, '⌈', '⌉')); ``` struct **BoyerMooreFinder**(alias pred, Range); BoyerMooreFinder!(binaryFun!pred, Range) **boyerMooreFinder**(alias pred = "a == b", Range)(Range needle) Constraints: if (isRandomAccessRange!Range && hasSlicing!Range || isSomeString!Range); Sets up Boyer-Moore matching for use with `find` below. By default, elements are compared for equality. `BoyerMooreFinder` allocates GC memory. Parameters: | | | | --- | --- | | pred | Predicate used to compare elements. | | Range `needle` | A random-access range with length and slicing. | Returns: An instance of `BoyerMooreFinder` that can be used with `find()` to invoke the Boyer-Moore matching algorithm for finding of `needle` in a given haystack. Examples: ``` auto bmFinder = boyerMooreFinder("TG"); string r = "TAGTGCCTGA"; // search for the first match in the haystack r r = bmFinder.beFound(r); writeln(r); // "TGCCTGA" // continue search in haystack r = bmFinder.beFound(r[2 .. $]); writeln(r); // "TGA" ``` this(Range needle); scope Range **beFound**(Range haystack); @property size\_t **length**(); alias **opDollar** = length; auto **commonPrefix**(alias pred = "a == b", R1, R2)(R1 r1, R2 r2) Constraints: if (isForwardRange!R1 && isInputRange!R2 && !isNarrowString!R1 && is(typeof(binaryFun!pred(r1.front, r2.front)))); auto **commonPrefix**(alias pred, R1, R2)(R1 r1, R2 r2) Constraints: if (isNarrowString!R1 && isInputRange!R2 && is(typeof(binaryFun!pred(r1.front, r2.front)))); auto **commonPrefix**(R1, R2)(R1 r1, R2 r2) Constraints: if (isNarrowString!R1 && isInputRange!R2 && !isNarrowString!R2 && is(typeof(r1.front == r2.front))); auto **commonPrefix**(R1, R2)(R1 r1, R2 r2) Constraints: if (isNarrowString!R1 && isNarrowString!R2); Returns the common prefix of two ranges. Parameters: | | | | --- | --- | | pred | The predicate to use in comparing elements for commonality. Defaults to equality `"a == b"`. | | R1 `r1` | A [forward range](std_range_primitives#isForwardRange) of elements. | | R2 `r2` | An [input range](std_range_primitives#isInputRange) of elements. | Returns: A slice of `r1` which contains the characters that both ranges start with, if the first argument is a string; otherwise, the same as the result of `takeExactly(r1, n)`, where `n` is the number of elements in the common prefix of both ranges. See Also: [`std.range.takeExactly`](std_range#takeExactly) Examples: ``` writeln(commonPrefix("hello, world", "hello, there")); // "hello, " ``` size\_t **count**(alias pred = "a == b", Range, E)(Range haystack, E needle) Constraints: if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(haystack.front, needle)) : bool)); size\_t **count**(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle) Constraints: if (isForwardRange!R1 && !isInfinite!R1 && isForwardRange!R2 && is(typeof(binaryFun!pred(haystack.front, needle.front)) : bool)); size\_t **count**(alias pred, R)(R haystack) Constraints: if (isInputRange!R && !isInfinite!R && is(typeof(unaryFun!pred(haystack.front)) : bool)); size\_t **count**(R)(R haystack) Constraints: if (isInputRange!R && !isInfinite!R); The first version counts the number of elements `x` in `r` for which `pred(x, value)` is `true`. `pred` defaults to equality. Performs Ο(`haystack.length`) evaluations of `pred`. The second version returns the number of times `needle` occurs in `haystack`. Throws an exception if `needle.empty`, as the count of the empty range in any range would be infinite. Overlapped counts are not considered, for example `count("aaa", "aa")` is `1`, not `2`. The third version counts the elements for which `pred(x)` is `true`. Performs Ο(`haystack.length`) evaluations of `pred`. The fourth version counts the number of elements in a range. It is an optimization for the third version: if the given range has the `length` property the count is returned right away, otherwise performs Ο(`haystack.length`) to walk the range. Note Regardless of the overload, `count` will not accept infinite ranges for `haystack`. Parameters: | | | | --- | --- | | pred | The predicate to evaluate. | | Range `haystack` | The range to count. | | E `needle` | The element or sub-range to count in the `haystack`. | Returns: The number of positions in the `haystack` for which `pred` returned true. Examples: ``` import std.uni : toLower; // count elements in range int[] a = [ 1, 2, 4, 3, 2, 5, 3, 2, 4 ]; writeln(count(a)); // 9 writeln(count(a, 2)); // 3 writeln(count!("a > b")(a, 2)); // 5 // count range in range writeln(count("abcadfabf", "ab")); // 2 writeln(count("ababab", "abab")); // 1 writeln(count("ababab", "abx")); // 0 // fuzzy count range in range writeln(count!((a, b) => toLower(a) == toLower(b))("AbcAdFaBf", "ab")); // 2 // count predicate in range writeln(count!("a > 1")(a)); // 8 ``` ptrdiff\_t **countUntil**(alias pred = "a == b", R, Rs...)(R haystack, Rs needles) Constraints: if (isForwardRange!R && (Rs.length > 0) && (isForwardRange!(Rs[0]) == isInputRange!(Rs[0])) && is(typeof(startsWith!pred(haystack, needles[0]))) && (Rs.length == 1 || is(typeof(countUntil!pred(haystack, needles[1..$]))))); ptrdiff\_t **countUntil**(alias pred = "a == b", R, N)(R haystack, N needle) Constraints: if (isInputRange!R && is(typeof(binaryFun!pred(haystack.front, needle)) : bool)); ptrdiff\_t **countUntil**(alias pred, R)(R haystack) Constraints: if (isInputRange!R && is(typeof(unaryFun!pred(haystack.front)) : bool)); Counts elements in the given [forward range](std_range_primitives#isForwardRange) until the given predicate is true for one of the given `needles`. Parameters: | | | | --- | --- | | pred | The predicate for determining when to stop counting. | | R `haystack` | The [input range](std_range_primitives#isInputRange) to be counted. | | Rs `needles` | Either a single element, or a [forward range](std_range_primitives#isForwardRange) of elements, to be evaluated in turn against each element in `haystack` under the given predicate. | Returns: The number of elements which must be popped from the front of `haystack` before reaching an element for which `startsWith!pred(haystack, needles)` is `true`. If `startsWith!pred(haystack, needles)` is not `true` for any element in `haystack`, then `-1` is returned. If only `pred` is provided, `pred(haystack)` is tested for each element. See Also: [`std.string.indexOf`](std_string#indexOf) Examples: ``` writeln(countUntil("hello world", "world")); // 6 writeln(countUntil("hello world", 'r')); // 8 writeln(countUntil("hello world", "programming")); // -1 writeln(countUntil("日本語", "本語")); // 1 writeln(countUntil("日本語", '語')); // 2 writeln(countUntil("日本語", "五")); // -1 writeln(countUntil("日本語", '五')); // -1 writeln(countUntil([0, 7, 12, 22, 9], [12, 22])); // 2 writeln(countUntil([0, 7, 12, 22, 9], 9)); // 4 writeln(countUntil!"a > b"([0, 7, 12, 22, 9], 20)); // 3 ``` Examples: ``` import std.ascii : isDigit; import std.uni : isWhite; writeln(countUntil!(std.uni.isWhite)("hello world")); // 5 writeln(countUntil!(std.ascii.isDigit)("hello world")); // -1 writeln(countUntil!"a > 20"([0, 7, 12, 22, 9])); // 3 ``` uint **endsWith**(alias pred = "a == b", Range, Needles...)(Range doesThisEnd, Needles withOneOfThese) Constraints: if (isBidirectionalRange!Range && (Needles.length > 1) && is(typeof(.endsWith!pred(doesThisEnd, withOneOfThese[0])) : bool) && is(typeof(.endsWith!pred(doesThisEnd, withOneOfThese[1..$])) : uint)); bool **endsWith**(alias pred = "a == b", R1, R2)(R1 doesThisEnd, R2 withThis) Constraints: if (isBidirectionalRange!R1 && isBidirectionalRange!R2 && is(typeof(binaryFun!pred(doesThisEnd.back, withThis.back)) : bool)); bool **endsWith**(alias pred = "a == b", R, E)(R doesThisEnd, E withThis) Constraints: if (isBidirectionalRange!R && is(typeof(binaryFun!pred(doesThisEnd.back, withThis)) : bool)); bool **endsWith**(alias pred, R)(R doesThisEnd) Constraints: if (isInputRange!R && ifTestable!(typeof(doesThisEnd.front), unaryFun!pred)); Checks if the given range ends with (one of) the given needle(s). The reciprocal of `startsWith`. Parameters: | | | | --- | --- | | pred | The predicate to use for comparing elements between the range and the needle(s). | | Range `doesThisEnd` | The [bidirectional range](std_range_primitives#isBidirectionalRange) to check. | | Needles `withOneOfThese` | The needles to check against, which may be single elements, or bidirectional ranges of elements. | | R2 `withThis` | The single element to check. | Returns: 0 if the needle(s) do not occur at the end of the given range; otherwise the position of the matching needle, that is, 1 if the range ends with `withOneOfThese[0]`, 2 if it ends with `withOneOfThese[1]`, and so on. In the case when no needle parameters are given, return `true` iff back of `doesThisStart` fulfils predicate `pred`. Examples: ``` import std.ascii : isAlpha; assert("abc".endsWith!(a => a.isAlpha)); assert("abc".endsWith!isAlpha); assert(!"ab1".endsWith!(a => a.isAlpha)); assert(!"ab1".endsWith!isAlpha); assert(!"".endsWith!(a => a.isAlpha)); import std.algorithm.comparison : among; assert("abc".endsWith!(a => a.among('c', 'd') != 0)); assert(!"abc".endsWith!(a => a.among('a', 'b') != 0)); assert(endsWith("abc", "")); assert(!endsWith("abc", "b")); writeln(endsWith("abc", "a", 'c')); // 2 writeln(endsWith("abc", "c", "a")); // 1 writeln(endsWith("abc", "c", "c")); // 1 writeln(endsWith("abc", "bc", "c")); // 2 writeln(endsWith("abc", "x", "c", "b")); // 2 writeln(endsWith("abc", "x", "aa", "bc")); // 3 writeln(endsWith("abc", "x", "aaa", "sab")); // 0 writeln(endsWith("abc", "x", "aaa", 'c', "sab")); // 3 ``` InputRange **find**(alias pred = "a == b", InputRange, Element)(InputRange haystack, scope Element needle) Constraints: if (isInputRange!InputRange && is(typeof(binaryFun!pred(haystack.front, needle)) : bool) && !is(typeof(binaryFun!pred(haystack.front, needle.front)) : bool)); InputRange **find**(alias pred, InputRange)(InputRange haystack) Constraints: if (isInputRange!InputRange); R1 **find**(alias pred = "a == b", R1, R2)(R1 haystack, scope R2 needle) Constraints: if (isForwardRange!R1 && isForwardRange!R2 && is(typeof(binaryFun!pred(haystack.front, needle.front)) : bool)); Finds an individual element in an [input range](std_range_primitives#isInputRange). Elements of `haystack` are compared with `needle` by using predicate `pred` with `pred(haystack.front, needle)`. `find` performs Ο(`walkLength(haystack)`) evaluations of `pred`. The predicate is passed to [`std.functional.binaryFun`](std_functional#binaryFun), and can either accept a string, or any callable that can be executed via `pred(element, element)`. To find the last occurrence of `needle` in a [bidirectional](std_range_primitives#isBidirectionalRange) `haystack`, call `find(retro(haystack), needle)`. See [`std.range.retro`](std_range#retro). If no `needle` is provided, `pred(haystack.front)` will be evaluated on each element of the input range. If `input` is a [forward range](std_range_primitives#isForwardRange), `needle` can be a [forward range](std_range_primitives#isForwardRange) too. In this case `startsWith!pred(haystack, needle)` is evaluated on each evaluation. Note `find` behaves similar to `dropWhile` in other languages. Complexity `find` performs Ο(`walkLength(haystack)`) evaluations of `pred`. There are specializations that improve performance by taking advantage of [bidirectional](std_range_primitives#isBidirectionalRange) or [random access](std_range_primitives#isRandomAccess) ranges (where possible). Parameters: | | | | --- | --- | | pred | The predicate for comparing each element with the needle, defaulting to equality `"a == b"`. The negated predicate `"a != b"` can be used to search instead for the first element *not* matching the needle. | | InputRange `haystack` | The [input range](std_range_primitives#isInputRange) searched in. | | Element `needle` | The element searched for. | Returns: `haystack` advanced such that the front element is the one searched for; that is, until `binaryFun!pred(haystack.front, needle)` is `true`. If no such position exists, returns an empty `haystack`. See Also: [`findAdjacent`](#findAdjacent), [`findAmong`](#findAmong), [`findSkip`](#findSkip), [`findSplit`](#findSplit), [`startsWith`](#startsWith) Examples: ``` import std.range.primitives; auto arr = [1, 2, 4, 4, 4, 4, 5, 6, 9]; writeln(arr.find(4)); // [4, 4, 4, 4, 5, 6, 9] writeln(arr.find(1)); // arr writeln(arr.find(9)); // [9] writeln(arr.find!((a, b) => a > b)(4)); // [5, 6, 9] writeln(arr.find!((a, b) => a < b)(4)); // arr assert(arr.find(0).empty); assert(arr.find(10).empty); assert(arr.find(8).empty); writeln(find("hello, world", ',')); // ", world" ``` Examples: Case-insensitive find of a string ``` import std.range.primitives; import std.uni : toLower; string[] s = ["Hello", "world", "!"]; writeln(s.find!((a, b) => toLower(a) == b)("hello")); // s ``` Examples: ``` auto arr = [ 1, 2, 3, 4, 1 ]; writeln(find!("a > 2")(arr)); // [3, 4, 1] // with predicate alias bool pred(int x) { return x + 1 > 1.5; } writeln(find!(pred)(arr)); // arr ``` Examples: ``` import std.container : SList; import std.range.primitives : empty; import std.typecons : Tuple; assert(find("hello, world", "World").empty); writeln(find("hello, world", "wo")); // "world" writeln([1, 2, 3, 4].find(SList!int(2, 3)[])); // [2, 3, 4] alias C = Tuple!(int, "x", int, "y"); auto a = [C(1,0), C(2,0), C(3,1), C(4,0)]; writeln(a.find!"a.x == b"([2, 3])); // [C(2, 0), C(3, 1), C(4, 0)] writeln(a[1 .. $].find!"a.x == b"([2, 3])); // [C(2, 0), C(3, 1), C(4, 0)] ``` Tuple!(Range, size\_t) **find**(alias pred = "a == b", Range, Ranges...)(Range haystack, Ranges needles) Constraints: if (Ranges.length > 1 && is(typeof(startsWith!pred(haystack, needles)))); Finds two or more `needles` into a `haystack`. The predicate `pred` is used throughout to compare elements. By default, elements are compared for equality. Parameters: | | | | --- | --- | | pred | The predicate to use for comparing elements. | | Range `haystack` | The target of the search. Must be an input range. If any of `needles` is a range with elements comparable to elements in `haystack`, then `haystack` must be a [forward range](std_range_primitives#isForwardRange) such that the search can backtrack. | | Ranges `needles` | One or more items to search for. Each of `needles` must be either comparable to one element in `haystack`, or be itself a forward range with elements comparable with elements in `haystack`. | Returns: A tuple containing `haystack` positioned to match one of the needles and also the 1-based index of the matching element in `needles` (0 if none of `needles` matched, 1 if `needles[0]` matched, 2 if `needles[1]` matched...). The first needle to be found will be the one that matches. If multiple needles are found at the same spot in the range, then the shortest one is the one which matches (if multiple needles of the same length are found at the same spot (e.g `"a"` and `'a'`), then the left-most of them in the argument list matches). The relationship between `haystack` and `needles` simply means that one can e.g. search for individual `int`s or arrays of `int`s in an array of `int`s. In addition, if elements are individually comparable, searches of heterogeneous types are allowed as well: a `double[]` can be searched for an `int` or a `short[]`, and conversely a `long` can be searched for a `float` or a `double[]`. This makes for efficient searches without the need to coerce one side of the comparison into the other's side type. The complexity of the search is Ο(`haystack.length * max(needles.length)`). (For needles that are individual items, length is considered to be 1.) The strategy used in searching several subranges at once maximizes cache usage by moving in `haystack` as few times as possible. Examples: ``` import std.typecons : tuple; int[] a = [ 1, 4, 2, 3 ]; writeln(find(a, 4)); // [4, 2, 3] writeln(find(a, [1, 4])); // [1, 4, 2, 3] writeln(find(a, [1, 3], 4)); // tuple([4, 2, 3], 2) // Mixed types allowed if comparable writeln(find(a, 5, [1.2, 3.5], 2.0)); // tuple([2, 3], 3) ``` RandomAccessRange **find**(RandomAccessRange, alias pred, InputRange)(RandomAccessRange haystack, scope BoyerMooreFinder!(pred, InputRange) needle); Finds `needle` in `haystack` efficiently using the [Boyer-Moore](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm) method. Parameters: | | | | --- | --- | | RandomAccessRange `haystack` | A random-access range with length and slicing. | | BoyerMooreFinder!(pred, InputRange) `needle` | A [`BoyerMooreFinder`](#BoyerMooreFinder). | Returns: `haystack` advanced such that `needle` is a prefix of it (if no such position exists, returns `haystack` advanced to termination). Examples: ``` import std.range.primitives : empty; int[] a = [ -1, 0, 1, 2, 3, 4, 5 ]; int[] b = [ 1, 2, 3 ]; writeln(find(a, boyerMooreFinder(b))); // [1, 2, 3, 4, 5] assert(find(b, boyerMooreFinder(a)).empty); ``` template **canFind**(alias pred = "a == b") Convenience function. Like find, but only returns whether or not the search was successful. See Also: [`std.algorithm.comparison.among`](std_algorithm_comparison#among) for checking a value against multiple possibilities. Examples: ``` writeln(canFind([0, 1, 2, 3], 2)); // true assert(canFind([0, 1, 2, 3], [1, 2], [2, 3])); writeln(canFind([0, 1, 2, 3], [1, 2], [2, 3])); // 1 assert(canFind([0, 1, 2, 3], [1, 7], [2, 3])); writeln(canFind([0, 1, 2, 3], [1, 7], [2, 3])); // 2 writeln(canFind([0, 1, 2, 3], 4)); // false assert(!canFind([0, 1, 2, 3], [1, 3], [2, 4])); writeln(canFind([0, 1, 2, 3], [1, 3], [2, 4])); // 0 ``` Examples: Example using a custom predicate. Note that the needle appears as the second argument of the predicate. ``` auto words = [ "apple", "beeswax", "cardboard" ]; assert(!canFind(words, "bees")); assert( canFind!((string a, string b) => a.startsWith(b))(words, "bees")); ``` Examples: Search for mutliple items in an array of items (search for needles in an array of hay stacks) ``` string s1 = "aaa111aaa"; string s2 = "aaa222aaa"; string s3 = "aaa333aaa"; string s4 = "aaa444aaa"; const hay = [s1, s2, s3, s4]; assert(hay.canFind!(e => (e.canFind("111", "222")))); ``` bool **canFind**(Range)(Range haystack) Constraints: if (is(typeof(find!pred(haystack)))); Returns `true` if and only if any value `v` found in the input range `range` satisfies the predicate `pred`. Performs (at most) Ο(`haystack.length`) evaluations of `pred`. bool **canFind**(Range, Element)(Range haystack, scope Element needle) Constraints: if (is(typeof(find!pred(haystack, needle)))); Returns `true` if and only if `needle` can be found in `range`. Performs Ο(`haystack.length`) evaluations of `pred`. size\_t **canFind**(Range, Ranges...)(Range haystack, scope Ranges needles) Constraints: if (Ranges.length > 1 && allSatisfy!(isForwardRange, Ranges) && is(typeof(find!pred(haystack, needles)))); Returns the 1-based index of the first needle found in `haystack`. If no needle is found, then `0` is returned. So, if used directly in the condition of an if statement or loop, the result will be `true` if one of the needles is found and `false` if none are found, whereas if the result is used elsewhere, it can either be cast to `bool` for the same effect or used to get which needle was found first without having to deal with the tuple that `LREF find` returns for the same operation. Range **findAdjacent**(alias pred = "a == b", Range)(Range r) Constraints: if (isForwardRange!Range); Advances `r` until it finds the first two adjacent elements `a`, `b` that satisfy `pred(a, b)`. Performs Ο(`r.length`) evaluations of `pred`. Parameters: | | | | --- | --- | | pred | The predicate to satisfy. | | Range `r` | A [forward range](std_range_primitives#isForwardRange) to search in. | Returns: `r` advanced to the first occurrence of two adjacent elements that satisfy the given predicate. If there are no such two elements, returns `r` advanced until empty. See Also: [STL's `adjacent_find`](http://en.cppreference.com/w/cpp/algorithm/adjacent_find) Examples: ``` int[] a = [ 11, 10, 10, 9, 8, 8, 7, 8, 9 ]; auto r = findAdjacent(a); writeln(r); // [10, 10, 9, 8, 8, 7, 8, 9] auto p = findAdjacent!("a < b")(a); writeln(p); // [7, 8, 9] ``` InputRange **findAmong**(alias pred = "a == b", InputRange, ForwardRange)(InputRange seq, ForwardRange choices) Constraints: if (isInputRange!InputRange && isForwardRange!ForwardRange); Searches the given range for an element that matches one of the given choices. Advances `seq` by calling `seq.popFront` until either `find!(pred)(choices, seq.front)` is `true`, or `seq` becomes empty. Performs Ο(`seq.length * choices.length`) evaluations of `pred`. Parameters: | | | | --- | --- | | pred | The predicate to use for determining a match. | | InputRange `seq` | The [input range](std_range_primitives#isInputRange) to search. | | ForwardRange `choices` | A [forward range](std_range_primitives#isForwardRange) of possible choices. | Returns: `seq` advanced to the first matching element, or until empty if there are no matching elements. See Also: [`find`](#find), [`algorithm.comparison.among.std`](algorithm_comparison_among#std) Examples: ``` int[] a = [ -1, 0, 1, 2, 3, 4, 5 ]; int[] b = [ 3, 1, 2 ]; writeln(findAmong(a, b)); // a[2 .. &dollar;] ``` bool **findSkip**(alias pred = "a == b", R1, R2)(ref R1 haystack, R2 needle) Constraints: if (isForwardRange!R1 && isForwardRange!R2 && is(typeof(binaryFun!pred(haystack.front, needle.front)))); size\_t **findSkip**(alias pred, R1)(ref R1 haystack) Constraints: if (isForwardRange!R1 && ifTestable!(typeof(haystack.front), unaryFun!pred)); Finds `needle` in `haystack` and positions `haystack` right after the first occurrence of `needle`. If no needle is provided, the `haystack` is advanced as long as `pred` evaluates to `true`. Similarly, the haystack is positioned so as `pred` evaluates to `false` for `haystack.front`. Parameters: | | | | --- | --- | | R1 `haystack` | The [forward range](std_range_primitives#isForwardRange) to search in. | | R2 `needle` | The [forward range](std_range_primitives#isForwardRange) to search for. | | pred | Custom predicate for comparison of haystack and needle | Returns: `true` if the needle was found, in which case `haystack` is positioned after the end of the first occurrence of `needle`; otherwise `false`, leaving `haystack` untouched. If no needle is provided, it returns the number of times `pred(haystack.front)` returned true. See Also: [`find`](#find) Examples: ``` import std.range.primitives : empty; // Needle is found; s is replaced by the substring following the first // occurrence of the needle. string s = "abcdef"; assert(findSkip(s, "cd") && s == "ef"); // Needle is not found; s is left untouched. s = "abcdef"; assert(!findSkip(s, "cxd") && s == "abcdef"); // If the needle occurs at the end of the range, the range is left empty. s = "abcdef"; assert(findSkip(s, "def") && s.empty); ``` Examples: ``` import std.ascii : isWhite; string s = " abc"; assert(findSkip!isWhite(s) && s == "abc"); assert(!findSkip!isWhite(s) && s == "abc"); s = " "; writeln(findSkip!isWhite(s)); // 2 ``` auto **findSplit**(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle) Constraints: if (isForwardRange!R1 && isForwardRange!R2); auto **findSplitBefore**(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle) Constraints: if (isForwardRange!R1 && isForwardRange!R2); auto **findSplitAfter**(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle) Constraints: if (isForwardRange!R1 && isForwardRange!R2); These functions find the first occurrence of `needle` in `haystack` and then split `haystack` as follows. `findSplit` returns a tuple `result` containing *three* ranges. `result[0]` is the portion of `haystack` before `needle`, `result[1]` is the portion of `haystack` that matches `needle`, and `result[2]` is the portion of `haystack` after the match. If `needle` was not found, `result[0]` comprehends `haystack` entirely and `result[1]` and `result[2]` are empty. `findSplitBefore` returns a tuple `result` containing two ranges. `result[0]` is the portion of `haystack` before `needle`, and `result[1]` is the balance of `haystack` starting with the match. If `needle` was not found, `result[0]` comprehends `haystack` entirely and `result[1]` is empty. `findSplitAfter` returns a tuple `result` containing two ranges. `result[0]` is the portion of `haystack` up to and including the match, and `result[1]` is the balance of `haystack` starting after the match. If `needle` was not found, `result[0]` is empty and `result[1]` is `haystack`. In all cases, the concatenation of the returned ranges spans the entire `haystack`. If `haystack` is a random-access range, all three components of the tuple have the same type as `haystack`. Otherwise, `haystack` must be a [forward range](std_range_primitives#isForwardRange) and the type of `result[0]` and `result[1]` is the same as [`std.range.takeExactly`](std_range#takeExactly). Parameters: | | | | --- | --- | | pred | Predicate to use for comparing needle against haystack. | | R1 `haystack` | The range to search. | | R2 `needle` | What to look for. | Returns: A sub-type of `Tuple!()` of the split portions of `haystack` (see above for details). This sub-type of `Tuple!()` has `opCast` defined for `bool`. This `opCast` returns `true` when the separating `needle` was found and `false` otherwise. See Also: [`find`](#find) Examples: Returning a subtype of [`std.typecons.Tuple`](std_typecons#Tuple) enables the following convenient idiom: ``` // findSplit returns a triplet if (auto split = "dlang-rocks".findSplit("-")) { writeln(split[0]); // "dlang" writeln(split[1]); // "-" writeln(split[2]); // "rocks" } else assert(0); // works with const aswell if (const split = "dlang-rocks".findSplit("-")) { writeln(split[0]); // "dlang" writeln(split[1]); // "-" writeln(split[2]); // "rocks" } else assert(0); ``` Examples: ``` import std.range.primitives : empty; auto a = "Carl Sagan Memorial Station"; auto r = findSplit(a, "Velikovsky"); import std.typecons : isTuple; static assert(isTuple!(typeof(r.asTuple))); static assert(isTuple!(typeof(r))); assert(!r); writeln(r[0]); // a assert(r[1].empty); assert(r[2].empty); r = findSplit(a, " "); writeln(r[0]); // "Carl" writeln(r[1]); // " " writeln(r[2]); // "Sagan Memorial Station" if (const r1 = findSplitBefore(a, "Sagan")) { assert(r1); writeln(r1[0]); // "Carl " writeln(r1[1]); // "Sagan Memorial Station" } if (const r2 = findSplitAfter(a, "Sagan")) { assert(r2); writeln(r2[0]); // "Carl Sagan" writeln(r2[1]); // " Memorial Station" } ``` Examples: Use [`std.range.only`](std_range#only) to find single elements: ``` import std.range : only; writeln([1, 2, 3, 4].findSplitBefore(only(3))[0]); // [1, 2] ``` Tuple!(ElementType!Range, size\_t) **minCount**(alias pred = "a < b", Range)(Range range) Constraints: if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front, range.front)))); Tuple!(ElementType!Range, size\_t) **maxCount**(alias pred = "a < b", Range)(Range range) Constraints: if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front, range.front)))); Computes the minimum (respectively maximum) of `range` along with its number of occurrences. Formally, the minimum is a value `x` in `range` such that `pred(a, x)` is `false` for all values `a` in `range`. Conversely, the maximum is a value `x` in `range` such that `pred(x, a)` is `false` for all values `a` in `range` (note the swapped arguments to `pred`). These functions may be used for computing arbitrary extrema by choosing `pred` appropriately. For corrrect functioning, `pred` must be a strict partial order, i.e. transitive (if `pred(a, b) && pred(b, c)` then `pred(a, c)`) and irreflexive (`pred(a, a)` is `false`). The [trichotomy property of inequality](#) is not required: these algorithms consider elements `a` and `b` equal (for the purpose of counting) if `pred` puts them in the same equivalence class, i.e. `!pred(a, b) && !pred(b, a)`. Parameters: | | | | --- | --- | | pred | The ordering predicate to use to determine the extremum (minimum or maximum). | | Range `range` | The [input range](std_range_primitives#isInputRange) to count. | Returns: The minimum, respectively maximum element of a range together with the number it occurs in the range. Limitations If at least one of the arguments is NaN, the result is an unspecified value. See [`std.algorithm.searching.maxElement`](std_algorithm_searching#maxElement) for examples on how to cope with NaNs. Throws: `Exception` if `range.empty`. See Also: [`std.algorithm.comparison.min`](std_algorithm_comparison#min), [`minIndex`](#minIndex), [`minElement`](#minElement), [`minPos`](#minPos) Examples: ``` import std.conv : text; import std.typecons : tuple; int[] a = [ 2, 3, 4, 1, 2, 4, 1, 1, 2 ]; // Minimum is 1 and occurs 3 times writeln(a.minCount); // tuple(1, 3) // Maximum is 4 and occurs 2 times writeln(a.maxCount); // tuple(4, 2) ``` auto **minElement**(alias map = (a) => a, Range)(Range r) Constraints: if (isInputRange!Range && !isInfinite!Range); auto **minElement**(alias map = (a) => a, Range, RangeElementType = ElementType!Range)(Range r, RangeElementType seed) Constraints: if (isInputRange!Range && !isInfinite!Range && !is(CommonType!(ElementType!Range, RangeElementType) == void)); Iterates the passed range and returns the minimal element. A custom mapping function can be passed to `map`. In other languages this is sometimes called `argmin`. Complexity O(n) Exactly `n - 1` comparisons are needed. Parameters: | | | | --- | --- | | map | custom accessor for the comparison key | | Range `r` | range from which the minimal element will be selected | | RangeElementType `seed` | custom seed to use as initial element | Returns: The minimal element of the passed-in range. Note If at least one of the arguments is NaN, the result is an unspecified value. If you want to ignore NaNs, you can use [`std.algorithm.iteration.filter`](std_algorithm_iteration#filter) and [`std.math.isNaN`](std_math#isNaN) to remove them, before applying minElement. Add a suitable seed, to avoid error messages if all elements are NaNs: ``` <range>.filter!(a=>!a.isNaN).minElement(<seed>); ``` If you want to get NaN as a result if a NaN is present in the range, you can use [`std.algorithm.iteration.fold`](std_algorithm_iteration#fold) and [`std.math.isNaN`](std_math#isNaN): ``` <range>.fold!((a,b)=>a.isNaN || b.isNaN ? real.nan : a < b ? a : b); ``` See Also: [`maxElement`](#maxElement), [`std.algorithm.comparison.min`](std_algorithm_comparison#min), [`minCount`](#minCount), [`minIndex`](#minIndex), [`minPos`](#minPos) Examples: ``` import std.range : enumerate; import std.typecons : tuple; writeln([2, 7, 1, 3].minElement); // 1 // allows to get the index of an element too writeln([5, 3, 7, 9].enumerate.minElement!"a.value"); // tuple(1, 3) // any custom accessor can be passed writeln([[0, 4], [1, 2]].minElement!"a[1]"); // [1, 2] // can be seeded int[] arr; writeln(arr.minElement(1)); // 1 ``` auto **maxElement**(alias map = (a) => a, Range)(Range r) Constraints: if (isInputRange!Range && !isInfinite!Range); auto **maxElement**(alias map = (a) => a, Range, RangeElementType = ElementType!Range)(Range r, RangeElementType seed) Constraints: if (isInputRange!Range && !isInfinite!Range && !is(CommonType!(ElementType!Range, RangeElementType) == void)); Iterates the passed range and returns the maximal element. A custom mapping function can be passed to `map`. In other languages this is sometimes called `argmax`. Complexity O(n) Exactly `n - 1` comparisons are needed. Parameters: | | | | --- | --- | | map | custom accessor for the comparison key | | Range `r` | range from which the maximum element will be selected | | RangeElementType `seed` | custom seed to use as initial element | Returns: The maximal element of the passed-in range. Note If at least one of the arguments is NaN, the result is an unspecified value. See [`std.algorithm.searching.minElement`](std_algorithm_searching#minElement) for examples on how to cope with NaNs. See Also: [`minElement`](#minElement), [`std.algorithm.comparison.max`](std_algorithm_comparison#max), [`maxCount`](#maxCount), [`maxIndex`](#maxIndex), [`maxPos`](#maxPos) Examples: ``` import std.range : enumerate; import std.typecons : tuple; writeln([2, 1, 4, 3].maxElement); // 4 // allows to get the index of an element too writeln([2, 1, 4, 3].enumerate.maxElement!"a.value"); // tuple(2, 4) // any custom accessor can be passed writeln([[0, 4], [1, 2]].maxElement!"a[1]"); // [0, 4] // can be seeded int[] arr; writeln(arr.minElement(1)); // 1 ``` Range **minPos**(alias pred = "a < b", Range)(Range range) Constraints: if (isForwardRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front, range.front)))); Range **maxPos**(alias pred = "a < b", Range)(Range range) Constraints: if (isForwardRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front, range.front)))); Computes a subrange of `range` starting at the first occurrence of `range`'s minimum (respectively maximum) and with the same ending as `range`, or the empty range if `range` itself is empty. Formally, the minimum is a value `x` in `range` such that `pred(a, x)` is `false` for all values `a` in `range`. Conversely, the maximum is a value `x` in `range` such that `pred(x, a)` is `false` for all values `a` in `range` (note the swapped arguments to `pred`). These functions may be used for computing arbitrary extrema by choosing `pred` appropriately. For corrrect functioning, `pred` must be a strict partial order, i.e. transitive (if `pred(a, b) && pred(b, c)` then `pred(a, c)`) and irreflexive (`pred(a, a)` is `false`). Parameters: | | | | --- | --- | | pred | The ordering predicate to use to determine the extremum (minimum or maximum) element. | | Range `range` | The [forward range](std_range_primitives#isForwardRange) to search. | Returns: The position of the minimum (respectively maximum) element of forward range `range`, i.e. a subrange of `range` starting at the position of its smallest (respectively largest) element and with the same ending as `range`. Limitations If at least one of the arguments is NaN, the result is an unspecified value. See [`std.algorithm.searching.maxElement`](std_algorithm_searching#maxElement) for examples on how to cope with NaNs. See Also: [`std.algorithm.comparison.max`](std_algorithm_comparison#max), [`minCount`](#minCount), [`minIndex`](#minIndex), [`minElement`](#minElement) Examples: ``` int[] a = [ 2, 3, 4, 1, 2, 4, 1, 1, 2 ]; // Minimum is 1 and first occurs in position 3 writeln(a.minPos); // [1, 2, 4, 1, 1, 2] // Maximum is 4 and first occurs in position 2 writeln(a.maxPos); // [4, 1, 2, 4, 1, 1, 2] ``` ptrdiff\_t **minIndex**(alias pred = "a < b", Range)(Range range) Constraints: if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front, range.front)))); Computes the index of the first occurrence of `range`'s minimum element. Parameters: | | | | --- | --- | | pred | The ordering predicate to use to determine the minimum element. | | Range `range` | The [input range](std_range_primitives#isInputRange) to search. | Complexity Ο(`range.length`) Exactly `range.length - 1` comparisons are needed. Returns: The index of the first encounter of the minimum element in `range`. If the `range` is empty, -1 is returned. Limitations If at least one of the arguments is NaN, the result is an unspecified value. See [`std.algorithm.searching.maxElement`](std_algorithm_searching#maxElement) for examples on how to cope with NaNs. See Also: [`maxIndex`](#maxIndex), [`std.algorithm.comparison.min`](std_algorithm_comparison#min), [`minCount`](#minCount), [`minElement`](#minElement), [`minPos`](#minPos) Examples: ``` int[] a = [2, 3, 4, 1, 2, 4, 1, 1, 2]; // Minimum is 1 and first occurs in position 3 writeln(a.minIndex); // 3 // Get maximum index with minIndex writeln(a.minIndex!"a > b"); // 2 // Range is empty, so return value is -1 int[] b; writeln(b.minIndex); // -1 // Works with more custom types struct Dog { int age; } Dog[] dogs = [Dog(10), Dog(5), Dog(15)]; writeln(dogs.minIndex!"a.age < b.age"); // 1 ``` ptrdiff\_t **maxIndex**(alias pred = "a < b", Range)(Range range) Constraints: if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front, range.front)))); Computes the index of the first occurrence of `range`'s maximum element. Complexity Ο(`range`) Exactly `range.length - 1` comparisons are needed. Parameters: | | | | --- | --- | | pred | The ordering predicate to use to determine the maximum element. | | Range `range` | The [input range](std_range_primitives#isInputRange) to search. | Returns: The index of the first encounter of the maximum in `range`. If the `range` is empty, -1 is returned. Limitations If at least one of the arguments is NaN, the result is an unspecified value. See [`std.algorithm.searching.maxElement`](std_algorithm_searching#maxElement) for examples on how to cope with NaNs. See Also: [`minIndex`](#minIndex), [`std.algorithm.comparison.max`](std_algorithm_comparison#max), [`maxCount`](#maxCount), [`maxElement`](#maxElement), [`maxPos`](#maxPos) Examples: ``` // Maximum is 4 and first occurs in position 2 int[] a = [2, 3, 4, 1, 2, 4, 1, 1, 2]; writeln(a.maxIndex); // 2 // Empty range int[] b; writeln(b.maxIndex); // -1 // Works with more custom types struct Dog { int age; } Dog[] dogs = [Dog(10), Dog(15), Dog(5)]; writeln(dogs.maxIndex!"a.age < b.age"); // 1 ``` template **skipOver**(alias pred = (a, b) => a == b) Skip over the initial portion of the first given range (`haystack`) that matches any of the additionally given ranges (`needles`) fully, or if no second range is given skip over the elements that fulfill pred. Do nothing if there is no match. Parameters: | | | | --- | --- | | pred | The predicate that determines whether elements from each respective range match. Defaults to equality `"a == b"`. | Examples: ``` import std.algorithm.comparison : equal; auto s1 = "Hello world"; assert(!skipOver(s1, "Ha")); writeln(s1); // "Hello world" assert(skipOver(s1, "Hell") && s1 == "o world", s1); string[] r1 = ["abc", "def", "hij"]; dstring[] r2 = ["abc"d]; assert(!skipOver!((a, b) => a.equal(b))(r1, ["def"d]), r1[0]); writeln(r1); // ["abc", "def", "hij"] assert(skipOver!((a, b) => a.equal(b))(r1, r2)); writeln(r1); // ["def", "hij"] ``` Examples: ``` import std.ascii : isWhite; import std.range.primitives : empty; auto s2 = "\t\tvalue"; auto s3 = ""; auto s4 = "\t\t\t"; assert(s2.skipOver!isWhite && s2 == "value"); assert(!s3.skipOver!isWhite); assert(s4.skipOver!isWhite && s3.empty); ``` Examples: Variadic skipOver ``` auto s = "Hello world"; assert(!skipOver(s, "hello", "HellO")); writeln(s); // "Hello world" // the range is skipped over the longest matching needle is skipped assert(skipOver(s, "foo", "hell", "Hello ")); writeln(s); // "world" ``` Examples: ``` import std.algorithm.comparison : equal; auto s1 = "Hello world"; assert(!skipOver(s1, 'a')); writeln(s1); // "Hello world" assert(skipOver(s1, 'H') && s1 == "ello world"); string[] r = ["abc", "def", "hij"]; dstring e = "abc"d; assert(!skipOver!((a, b) => a.equal(b))(r, "def"d)); writeln(r); // ["abc", "def", "hij"] assert(skipOver!((a, b) => a.equal(b))(r, e)); writeln(r); // ["def", "hij"] auto s2 = ""; assert(!s2.skipOver('a')); ``` Examples: Partial instantiation ``` import std.ascii : isWhite; import std.range.primitives : empty; alias whitespaceSkiper = skipOver!isWhite; auto s2 = "\t\tvalue"; auto s3 = ""; auto s4 = "\t\t\t"; assert(whitespaceSkiper(s2) && s2 == "value"); assert(!whitespaceSkiper(s2)); assert(whitespaceSkiper(s4) && s3.empty); ``` bool **skipOver**(Haystack, Needles...)(ref Haystack haystack, Needles needles) Constraints: if (is(typeof(binaryFun!pred(haystack.front, needles[0].front))) && isForwardRange!Haystack && allSatisfy!(isInputRange, Needles) && !is(CommonType!(staticMap!(ElementType, staticMap!(Unqual, Needles))) == void)); bool **skipOver**(R)(ref R r1) Constraints: if (isForwardRange!R && ifTestable!(typeof(r1.front), unaryFun!pred)); bool **skipOver**(R, Es...)(ref R r, Es es) Constraints: if (isInputRange!R && is(typeof(binaryFun!pred(r.front, es[0])))); Parameters: | | | | --- | --- | | Haystack `haystack` | The [forward range](std_range_primitives#isForwardRange) to move forward. | | Needles `needles` | The [input ranges](std_range_primitives#isInputRange) representing the prefix of `r1` to skip over. | | Es `es` | The element to match. | Returns: `true` if the prefix of `haystack` matches any range of `needles` fully or `pred` evaluates to true, and `haystack` has been advanced to the point past this segment; otherwise false, and `haystack` is left in its original position. Note By definition, empty ranges are matched fully and if `needles` contains an empty range, `skipOver` will return `true`. uint **startsWith**(alias pred = (a, b) => a == b, Range, Needles...)(Range doesThisStart, Needles withOneOfThese) Constraints: if (isInputRange!Range && (Needles.length > 1) && is(typeof(.startsWith!pred(doesThisStart, withOneOfThese[0])) : bool) && is(typeof(.startsWith!pred(doesThisStart, withOneOfThese[1..$])) : uint)); bool **startsWith**(alias pred = "a == b", R1, R2)(R1 doesThisStart, R2 withThis) Constraints: if (isInputRange!R1 && isInputRange!R2 && is(typeof(binaryFun!pred(doesThisStart.front, withThis.front)) : bool)); bool **startsWith**(alias pred = "a == b", R, E)(R doesThisStart, E withThis) Constraints: if (isInputRange!R && is(typeof(binaryFun!pred(doesThisStart.front, withThis)) : bool)); bool **startsWith**(alias pred, R)(R doesThisStart) Constraints: if (isInputRange!R && ifTestable!(typeof(doesThisStart.front), unaryFun!pred)); Checks whether the given [input range](std_range_primitives#isInputRange) starts with (one of) the given needle(s) or, if no needles are given, if its front element fulfils predicate `pred`. Parameters: | | | | --- | --- | | pred | Predicate to use in comparing the elements of the haystack and the needle(s). Mandatory if no needles are given. | | Range `doesThisStart` | The input range to check. | | Needles `withOneOfThese` | The needles against which the range is to be checked, which may be individual elements or input ranges of elements. | | R2 `withThis` | The single needle to check, which may be either a single element or an input range of elements. | Returns: 0 if the needle(s) do not occur at the beginning of the given range; otherwise the position of the matching needle, that is, 1 if the range starts with `withOneOfThese[0]`, 2 if it starts with `withOneOfThese[1]`, and so on. In the case where `doesThisStart` starts with multiple of the ranges or elements in `withOneOfThese`, then the shortest one matches (if there are two which match which are of the same length (e.g. `"a"` and `'a'`), then the left-most of them in the argument list matches). In the case when no needle parameters are given, return `true` iff front of `doesThisStart` fulfils predicate `pred`. Examples: ``` import std.ascii : isAlpha; assert("abc".startsWith!(a => a.isAlpha)); assert("abc".startsWith!isAlpha); assert(!"1ab".startsWith!(a => a.isAlpha)); assert(!"".startsWith!(a => a.isAlpha)); import std.algorithm.comparison : among; assert("abc".startsWith!(a => a.among('a', 'b') != 0)); assert(!"abc".startsWith!(a => a.among('b', 'c') != 0)); assert(startsWith("abc", "")); assert(startsWith("abc", "a")); assert(!startsWith("abc", "b")); writeln(startsWith("abc", 'a', "b")); // 1 writeln(startsWith("abc", "b", "a")); // 2 writeln(startsWith("abc", "a", "a")); // 1 writeln(startsWith("abc", "ab", "a")); // 2 writeln(startsWith("abc", "x", "a", "b")); // 2 writeln(startsWith("abc", "x", "aa", "ab")); // 3 writeln(startsWith("abc", "x", "aaa", "sab")); // 0 writeln(startsWith("abc", "x", "aaa", "a", "sab")); // 3 import std.typecons : Tuple; alias C = Tuple!(int, "x", int, "y"); assert(startsWith!"a.x == b"([ C(1,1), C(1,2), C(2,2) ], [1, 1])); writeln(startsWith!"a.x == b"([C(1, 1), C(2, 1), C(2, 2)], [1, 1], [1, 2], [1, 3])); // 2 ``` alias **OpenRight** = std.typecons.Flag!"openRight".Flag; Interval option specifier for `until` (below) and others. If set to `OpenRight.yes`, then the interval is open to the right (last element is not included). Otherwise if set to `OpenRight.no`, then the interval is closed to the right (last element included). Until!(pred, Range, Sentinel) **until**(alias pred = "a == b", Range, Sentinel)(Range range, Sentinel sentinel, OpenRight openRight = Yes.openRight) Constraints: if (!is(Sentinel == OpenRight)); Until!(pred, Range, void) **until**(alias pred, Range)(Range range, OpenRight openRight = Yes.openRight); struct **Until**(alias pred, Range, Sentinel) if (isInputRange!Range); Lazily iterates `range` until the element `e` for which `pred(e, sentinel)` is true. This is similar to `takeWhile` in other languages. Parameters: | | | | --- | --- | | pred | Predicate to determine when to stop. | | Range `range` | The [input range](std_range_primitives#isInputRange) to iterate over. | | Sentinel `sentinel` | The element to stop at. | | OpenRight `openRight` | Determines whether the element for which the given predicate is true should be included in the resulting range (`No.openRight`), or not (`Yes.openRight`). | Returns: An [input range](std_range_primitives#isInputRange) that iterates over the original range's elements, but ends when the specified predicate becomes true. If the original range is a [forward range](std_range_primitives#isForwardRange) or higher, this range will be a forward range. Examples: ``` import std.algorithm.comparison : equal; import std.typecons : No; int[] a = [ 1, 2, 4, 7, 7, 2, 4, 7, 3, 5]; assert(equal(a.until(7), [1, 2, 4])); assert(equal(a.until(7, No.openRight), [1, 2, 4, 7])); ```
programming_docs
d rt.util.typeinfo rt.util.typeinfo ================ This module contains utilities for TypeInfo implementation. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Kenji Hara class **TypeInfo\_v**: rt.util.typeinfo.TypeInfoGeneric!(ubyte, ubyte).TypeInfoGeneric; d std.experimental.checkedint std.experimental.checkedint =========================== This module defines facilities for efficient checking of integral operations against overflow, casting with loss of precision, unexpected change of sign, etc. The checking (and possibly correction) can be done at operation level, for example [`opChecked`](#opChecked)`!"+"(x, y, overflow)` adds two integrals `x` and `y` and sets `overflow` to `true` if an overflow occurred. The flag `overflow` (a `bool` passed by reference) is not touched if the operation succeeded, so the same flag can be reused for a sequence of operations and tested at the end. Issuing individual checked operations is flexible and efficient but often tedious. The [`Checked`](#Checked) facility offers encapsulated integral wrappers that do all checking internally and have configurable behavior upon erroneous results. For example, `Checked!int` is a type that behaves like `int` but aborts execution immediately whenever involved in an operation that produces the arithmetically wrong result. The accompanying convenience function [`checked`](#checked) uses type deduction to convert a value `x` of integral type `T` to `Checked!T` by means of `checked(x)`. For example: ``` void main() { import std.experimental.checkedint, std.stdio; writeln((checked(5) + 7).get); // 12 writeln((checked(10) * 1000 * 1000 * 1000).get); // Overflow } ``` Similarly, `checked(-1) > uint(0)` aborts execution (even though the built-in comparison `int(-1) > uint(0)` is surprisingly true due to language's conversion rules modeled after C). Thus, `Checked!int` is a virtually drop-in replacement for `int` useable in debug builds, to be replaced by `int` in release mode if efficiency demands it. `Checked` has customizable behavior with the help of a second type parameter, `Hook`. Depending on what methods `Hook` defines, core operations on the underlying integral may be verified for overflow or completely redefined. If `Hook` defines no method at all and carries no state, there is no change in behavior, i.e. `Checked!(int, void)` is a wrapper around `int` that adds no customization at all. This module provides a few predefined hooks (below) that add useful behavior to `Checked`: | | | | --- | --- | | [`Abort`](#Abort) | fails every incorrect operation with a message to [`std.stdio. stderr`](std_stdio#%20%20%20%20%20%20%20%20stderr) followed by a call to `assert(0)`. It is the default second parameter, i.e. `Checked!short` is the same as `Checked!(short, Abort)`. | | [`Throw`](#Throw) | fails every incorrect operation by throwing an exception. | | [`Warn`](#Warn) | prints incorrect operations to [`std.stdio.stderr`](std_stdio#stderr) but otherwise preserves the built-in behavior. | | [`ProperCompare`](#ProperCompare) | fixes the comparison operators `==`, `!=`, `<`, `<=`, `>`, and `>=` to return correct results in all circumstances, at a slight cost in efficiency. For example, `Checked!(uint, ProperCompare)(1) > -1` is `true`, which is not the case for the built-in comparison. Also, comparing numbers for equality with floating-point numbers only passes if the integral can be converted to the floating-point number precisely, so as to preserve transitivity of equality. | | [`WithNaN`](#WithNaN) | reserves a special "Not a Number" (NaN) value akin to the homonym value reserved for floating-point values. Once a `Checked!(X, WithNaN)` gets this special value, it preserves and propagates it until reassigned. [`isNaN`](#isNaN) can be used to query whether the object is not a number. | | [`Saturate`](#Saturate) | implements saturating arithmetic, i.e. `Checked!(int, Saturate)` "stops" at `int.max` for all operations that would cause an `int` to overflow toward infinity, and at `int.min` for all operations that would correspondingly overflow toward negative infinity. | These policies may be used alone, e.g. `Checked!(uint, WithNaN)` defines a `uint`-like type that reaches a stable NaN state for all erroneous operations. They may also be "stacked" on top of each other, owing to the property that a checked integral emulates an actual integral, which means another checked integral can be built on top of it. Some combinations of interest include: | | | --- | | `Checked!(Checked!int, ProperCompare)` | | defines an `int` with fixed comparison operators that will fail with `assert(0)` upon overflow. (Recall that `Abort` is the default policy.) The order in which policies are combined is important because the outermost policy (`ProperCompare` in this case) has the first crack at intercepting an operator. The converse combination `Checked!(Checked!(int, ProperCompare))` is meaningless because `Abort` will intercept comparison and will fail without giving `ProperCompare` a chance to intervene. | | | | `Checked!(Checked!(int, ProperCompare), WithNaN)` | | defines an `int`-like type that supports a NaN value. For values that are not NaN, comparison works properly. Again the composition order is important; `Checked!(Checked!(int, WithNaN), ProperCompare)` does not have good semantics because `ProperCompare` intercepts comparisons before the numbers involved are tested for NaN. | The hook's members are looked up statically in a Design by Introspection manner and are all optional. The table below illustrates the members that a hook type may define and their influence over the behavior of the `Checked` type using it. In the table, `hook` is an alias for `Hook` if the type `Hook` does not introduce any state, or an object of type `Hook` otherwise. | `Hook` member | Semantics in `Checked!(T, Hook)` | | --- | --- | | `defaultValue` | If defined, `Hook.defaultValue!T` is used as the default initializer of the payload. | | `min` | If defined, `Hook.min!T` is used as the minimum value of the payload. | | `max` | If defined, `Hook.max!T` is used as the maximum value of the payload. | | `hookOpCast` | If defined, `hook.hookOpCast!U(get)` is forwarded to unconditionally when the payload is to be cast to type `U`. | | `onBadCast` | If defined and `hookOpCast` is *not* defined, `onBadCast!U(get)` is forwarded to when the payload is to be cast to type `U` and the cast would lose information or force a change of sign. | | `hookOpEquals` | If defined, `hook.hookOpEquals(get, rhs)` is forwarded to unconditionally when the payload is compared for equality against value `rhs` of integral, floating point, or Boolean type. | | `hookOpCmp` | If defined, `hook.hookOpCmp(get, rhs)` is forwarded to unconditionally when the payload is compared for ordering against value `rhs` of integral, floating point, or Boolean type. | | `hookOpUnary` | If defined, `hook.hookOpUnary!op(get)` (where `op` is the operator symbol) is forwarded to for unary operators `-` and `~`. In addition, for unary operators `++` and `--`, `hook.hookOpUnary!op(payload)` is called, where `payload` is a reference to the value wrapped by `Checked` so the hook can change it. | | `hookOpBinary` | If defined, `hook.hookOpBinary!op(get, rhs)` (where `op` is the operator symbol and `rhs` is the right-hand side operand) is forwarded to unconditionally for binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>`. | | `hookOpBinaryRight` | If defined, `hook.hookOpBinaryRight!op(lhs, get)` (where `op` is the operator symbol and `lhs` is the left-hand side operand) is forwarded to unconditionally for binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>`. | | `onOverflow` | If defined, `hook.onOverflow!op(get)` is forwarded to for unary operators that overflow but only if `hookOpUnary` is not defined. Unary `~` does not overflow; unary `-` overflows only when the most negative value of a signed type is negated, and the result of the hook call is returned. When the increment or decrement operators overflow, the payload is assigned the result of `hook.onOverflow!op(get)`. When a binary operator overflows, the result of `hook.onOverflow!op(get, rhs)` is returned, but only if `Hook` does not define `hookOpBinary`. | | `hookOpOpAssign` | If defined, `hook.hookOpOpAssign!op(payload, rhs)` (where `op` is the operator symbol and `rhs` is the right-hand side operand) is forwarded to unconditionally for binary operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=`. | | `onLowerBound` | If defined, `hook.onLowerBound(value, bound)` (where `value` is the value being assigned) is forwarded to when the result of binary operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=` is smaller than the smallest value representable by `T`. | | `onUpperBound` | If defined, `hook.onUpperBound(value, bound)` (where `value` is the value being assigned) is forwarded to when the result of binary operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=` is larger than the largest value representable by `T`. | | `hookToHash` | If defined, `hook.hookToHash(payload)` (where `payload` is a reference to the value wrapped by Checked) is forwarded to when `toHash` is called on a Checked type. Custom hashing can be implemented in a `Hook`, otherwise the built-in hashing is used. | Source [std/experimental/checkedint.d](https://github.com/dlang/phobos/blob/master/std/experimental/checkedint.d) Examples: ``` int[] concatAndAdd(int[] a, int[] b, int offset) { // Aborts on overflow on size computation auto r = new int[(checked(a.length) + b.length).get]; // Aborts on overflow on element computation foreach (i; 0 .. a.length) r[i] = (a[i] + checked(offset)).get; foreach (i; 0 .. b.length) r[i + a.length] = (b[i] + checked(offset)).get; return r; } writeln(concatAndAdd([1, 2, 3], [4, 5], -1)); // [0, 1, 2, 3, 4] ``` Examples: `Saturate` stops at an overflow ``` auto x = (cast(byte) 127).checked!Saturate; writeln(x); // 127 x++; writeln(x); // 127 ``` Examples: `WithNaN` has a special "Not a Number" (NaN) value akin to the homonym value reserved for floating-point values ``` auto x = 100.checked!WithNaN; writeln(x); // 100 x /= 0; assert(x.isNaN); ``` Examples: `ProperCompare` fixes the comparison operators ==, !=, <, <=, >, and >= to return correct results ``` uint x = 1; auto y = x.checked!ProperCompare; assert(x < -1); // built-in comparison assert(y > -1); // ProperCompare ``` Examples: `Throw` fails every incorrect operation by throwing an exception ``` import std.exception : assertThrown; auto x = -1.checked!Throw; assertThrown(x / 0); assertThrown(x + int.min); assertThrown(x == uint.max); ``` struct **Checked**(T, Hook = Abort) if (isIntegral!T || is(T == **Checked**!(U, H), U, H)); Checked integral type wraps an integral `T` and customizes its behavior with the help of a `Hook` type. The type wrapped must be one of the predefined integrals (unqualified), or another instance of `Checked`. alias **Representation** = T; The type of the integral subject to checking. Hook **hook**; `hook` is a member variable if it has state, or an alias for `Hook` otherwise. inout auto **get**(); Returns a copy of the underlying value. Examples: ``` auto x = checked(ubyte(42)); static assert(is(typeof(x.get()) == ubyte)); writeln(x.get); // 42 const y = checked(ubyte(42)); static assert(is(typeof(y.get()) == const ubyte)); writeln(y.get); // 42 ``` enum Checked!(T, Hook) **min**; enum Checked!(T, Hook) **max**; Defines the minimum and maximum. These values are hookable by defining `Hook.min` and/or `Hook.max`. Examples: Defines the minimum and maximum. These values are hookable by defining `Hook.min` and/or `Hook.max`. ``` writeln(Checked!short.min); // -32768 writeln(Checked!(short, WithNaN).min); // -32767 writeln(Checked!(uint, WithNaN).max); // uint.max - 1 ``` this(U)(U rhs) Constraints: if (valueConvertible!(U, T) || !isIntegral!T && is(typeof(T(rhs))) || is(U == Checked!(V, W), V, W) && is(typeof(Checked!(T, Hook)(rhs.get)))); Constructor taking a value properly convertible to the underlying type. `U` may be either an integral that can be converted to `T` without a loss, or another `Checked` instance whose representation may be in turn converted to `T` without a loss. Examples: ``` auto a = checked(42L); writeln(a); // 42 auto b = Checked!long(4242); // convert 4242 to long writeln(b); // 4242 ``` ref Checked **opAssign**(U)(U rhs) return Constraints: if (is(typeof(Checked!(T, Hook)(rhs)))); Assignment operator. Has the same constraints as the constructor. Examples: ``` Checked!long a; a = 42L; writeln(a); // 42 a = 4242; writeln(a); // 4242 ``` Examples: ``` Checked!long a, b; a = b = 3; assert(a == 3 && b == 3); ``` U **opCast**(U, this \_)() Constraints: if (isIntegral!U || isFloatingPoint!U || is(U == bool)); Casting operator to integral, `bool`, or floating point type. If `Hook` defines `hookOpCast`, the call immediately returns `hook.hookOpCast!U(get)`. Otherwise, casting to `bool` yields `get != 0` and casting to another integral that can represent all values of `T` returns `get` promoted to `U`. If a cast to a floating-point type is requested and `Hook` defines `onBadCast`, the cast is verified by ensuring `get == cast(T) U(get)`. If that is not `true`, `hook.onBadCast!U(get)` is returned. If a cast to an integral type is requested and `Hook` defines `onBadCast`, the cast is verified by ensuring `get` and `cast(U) get` are the same arithmetic number. (Note that `int(-1)` and `uint(1)` are different values arithmetically although they have the same bitwise representation and compare equal by language rules.) If the numbers are not arithmetically equal, `hook.onBadCast!U(get)` is returned. Examples: ``` writeln(cast(uint)checked(42)); // 42 writeln(cast(uint)checked!WithNaN(-42)); // uint.max ``` bool **opEquals**(U, this \_)(U rhs) Constraints: if (isIntegral!U || isFloatingPoint!U || is(U == bool) || is(U == Checked!(V, W), V, W) && is(typeof(this == rhs.payload))); Compares `this` against `rhs` for equality. If `Hook` defines `hookOpEquals`, the function forwards to `hook.hookOpEquals(get, rhs)`. Otherwise, the result of the built-in operation `get == rhs` is returned. If `U` is also an instance of `Checked`, both hooks (left- and right-hand side) are introspected for the method `hookOpEquals`. If both define it, priority is given to the left-hand side. Examples: ``` import std.traits : isUnsigned; static struct MyHook { static bool thereWereErrors; static bool hookOpEquals(L, R)(L lhs, R rhs) { if (lhs != rhs) return false; static if (isUnsigned!L && !isUnsigned!R) { if (lhs > 0 && rhs < 0) thereWereErrors = true; } else static if (isUnsigned!R && !isUnsigned!L) if (lhs < 0 && rhs > 0) thereWereErrors = true; // Preserve built-in behavior. return true; } } auto a = checked!MyHook(-42); writeln(a); // uint(-42) assert(MyHook.thereWereErrors); MyHook.thereWereErrors = false; writeln(checked!MyHook(uint(-42))); // -42 assert(MyHook.thereWereErrors); static struct MyHook2 { static bool hookOpEquals(L, R)(L lhs, R rhs) { return lhs == rhs; } } MyHook.thereWereErrors = false; writeln(checked!MyHook2(uint(-42))); // a // Hook on left hand side takes precedence, so no errors assert(!MyHook.thereWereErrors); ``` const nothrow @safe size\_t **toHash**(); Generates a hash for `this`. If `Hook` defines `hookToHash`, the call immediately returns `hook.hookToHash(payload)`. If `Hook` does not implement `hookToHash`, but it has state, a hash will be generated for the `Hook` using the built-in function and it will be xored with the hash of the `payload`. auto **opCmp**(U, this \_)(const U rhs) Constraints: if (isIntegral!U || isFloatingPoint!U || is(U == bool)); auto **opCmp**(U, Hook1, this \_)(Checked!(U, Hook1) rhs); Compares `this` against `rhs` for ordering. If `Hook` defines `hookOpCmp`, the function forwards to `hook.hookOpCmp(get, rhs)`. Otherwise, the result of the built-in comparison operation is returned. If `U` is also an instance of `Checked`, both hooks (left- and right-hand side) are introspected for the method `hookOpCmp`. If both define it, priority is given to the left-hand side. Examples: ``` import std.traits : isUnsigned; static struct MyHook { static bool thereWereErrors; static int hookOpCmp(L, R)(L lhs, R rhs) { static if (isUnsigned!L && !isUnsigned!R) { if (rhs < 0 && rhs >= lhs) thereWereErrors = true; } else static if (isUnsigned!R && !isUnsigned!L) { if (lhs < 0 && lhs >= rhs) thereWereErrors = true; } // Preserve built-in behavior. return lhs < rhs ? -1 : lhs > rhs; } } auto a = checked!MyHook(-42); assert(a > uint(42)); assert(MyHook.thereWereErrors); static struct MyHook2 { static int hookOpCmp(L, R)(L lhs, R rhs) { // Default behavior return lhs < rhs ? -1 : lhs > rhs; } } MyHook.thereWereErrors = false; assert(Checked!(uint, MyHook2)(uint(-42)) <= a); //assert(Checked!(uint, MyHook2)(uint(-42)) >= a); // Hook on left hand side takes precedence, so no errors assert(!MyHook.thereWereErrors); assert(a <= Checked!(uint, MyHook2)(uint(-42))); assert(MyHook.thereWereErrors); ``` auto **opUnary**(string op, this \_)() Constraints: if (op == "+" || op == "-" || op == "~"); ref Checked **opUnary**(string op)() return Constraints: if (op == "++" || op == "--"); Defines unary operators `+`, `-`, `~`, `++`, and `--`. Unary `+` is not overridable and always has built-in behavior (returns `this`). For the others, if `Hook` defines `hookOpUnary`, `opUnary` forwards to `Checked!(typeof(hook.hookOpUnary!op(get)), Hook)(hook.hookOpUnary!op(get))`. If `Hook` does not define `hookOpUnary` but defines `onOverflow`, `opUnary` forwards to `hook.onOverflow!op(get)` in case an overflow occurs. For `++` and `--`, the payload is assigned from the result of the call to `onOverflow`. Note that unary `-` is considered to overflow if `T` is a signed integral of 32 or 64 bits and is equal to the most negative value. This is because that value has no positive negation. Examples: ``` static struct MyHook { static bool thereWereErrors; static L hookOpUnary(string x, L)(L lhs) { if (x == "-" && lhs == -lhs) thereWereErrors = true; return -lhs; } } auto a = checked!MyHook(long.min); writeln(a); // -a assert(MyHook.thereWereErrors); auto b = checked!void(42); writeln(++b); // 43 ``` auto **opBinary**(string op, Rhs)(const Rhs rhs) Constraints: if (isIntegral!Rhs || isFloatingPoint!Rhs || is(Rhs == bool)); const auto **opBinary**(string op, Rhs)(const Rhs rhs) Constraints: if (isIntegral!Rhs || isFloatingPoint!Rhs || is(Rhs == bool)); auto **opBinary**(string op, U, Hook1)(Checked!(U, Hook1) rhs); const auto **opBinary**(string op, U, Hook1)(Checked!(U, Hook1) rhs); Defines binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>`. If `Hook` defines `hookOpBinary`, `opBinary` forwards to `Checked!(typeof(hook.hookOpBinary!op(get, rhs)), Hook)(hook.hookOpBinary!op(get, rhs))`. If `Hook` does not define `hookOpBinary` but defines `onOverflow`, `opBinary` forwards to `hook.onOverflow!op(get, rhs)` in case an overflow occurs. If two `Checked` instances are involved in a binary operation and both define `hookOpBinary`, the left-hand side hook has priority. If both define `onOverflow`, a compile-time error occurs. auto **opBinaryRight**(string op, Lhs)(const Lhs lhs) Constraints: if (isIntegral!Lhs || isFloatingPoint!Lhs || is(Lhs == bool)); const auto **opBinaryRight**(string op, Lhs)(const Lhs lhs) Constraints: if (isIntegral!Lhs || isFloatingPoint!Lhs || is(Lhs == bool)); Defines binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>` for the case when a built-in numeric or Boolean type is on the left-hand side, and a `Checked` instance is on the right-hand side. ref Checked **opOpAssign**(string op, Rhs)(const Rhs rhs) return Constraints: if (isIntegral!Rhs || isFloatingPoint!Rhs || is(Rhs == bool)); ref Checked **opOpAssign**(string op, Rhs)(const Rhs rhs) return Constraints: if (is(Rhs == Checked!(RhsT, RhsHook), RhsT, RhsHook)); Defines operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=`. If `Hook` defines `hookOpOpAssign`, `opOpAssign` forwards to `hook.hookOpOpAssign!op(payload, rhs)`, where `payload` is a reference to the internally held data so the hook can change it. Otherwise, the operator first evaluates `auto result = opBinary!op(payload, rhs).payload`, which is subject to the hooks in `opBinary`. Then, if `result` is less than `Checked!(T, Hook).min` and if `Hook` defines `onLowerBound`, the payload is assigned from `hook.onLowerBound(result, min)`. If `result` is greater than `Checked!(T, Hook).max` and if `Hook` defines `onUpperBound`, the payload is assigned from `hook.onUpperBound(result, min)`. If the right-hand side is also a Checked but with a different hook or underlying type, the hook and underlying type of this Checked takes precedence. In all other cases, the built-in behavior is carried out. Parameters: | | | | --- | --- | | op | The operator involved (without the `"="`, e.g. `"+"` for `"+="` etc) | | Rhs `rhs` | The right-hand side of the operator (left-hand side is `this`) | Returns: A reference to `this`. Examples: ``` static struct MyHook { static bool thereWereErrors; static T onLowerBound(Rhs, T)(Rhs rhs, T bound) { thereWereErrors = true; return bound; } static T onUpperBound(Rhs, T)(Rhs rhs, T bound) { thereWereErrors = true; return bound; } } auto x = checked!MyHook(byte.min); x -= 1; assert(MyHook.thereWereErrors); MyHook.thereWereErrors = false; x = byte.max; x += 1; assert(MyHook.thereWereErrors); ``` Checked!(T, Hook) **checked**(Hook = Abort, T)(const T value) Constraints: if (is(typeof(Checked!(T, Hook)(value)))); Convenience function that turns an integral into the corresponding `Checked` instance by using template argument deduction. The hook type may be specified (by default `Abort`). Examples: ``` static assert(is(typeof(checked(42)) == Checked!int)); writeln(checked(42)); // Checked!int(42) static assert(is(typeof(checked!WithNaN(42)) == Checked!(int, WithNaN))); writeln(checked!WithNaN(42)); // Checked!(int, WithNaN)(42) ``` struct **Abort**; Force all integral errors to fail by printing an error message to `stderr` and then abort the program. `Abort` is the default second argument for `Checked`. Dst **onBadCast**(Dst, Src)(Src src); Called automatically upon a bad cast (one that loses precision or attempts to convert a negative value to an unsigned type). The source type is `Src` and the destination type is `Dst`. Parameters: | | | | --- | --- | | Src `src` | The source of the cast | Returns: Nominally the result is the desired value of the cast operation, which will be forwarded as the result of the cast. For `Abort`, the function never returns because it aborts the program. T **onLowerBound**(Rhs, T)(Rhs rhs, T bound); T **onUpperBound**(Rhs, T)(Rhs rhs, T bound); Called automatically upon a bounds error. Parameters: | | | | --- | --- | | Rhs `rhs` | The right-hand side value in the assignment, after the operator has been evaluated | | T `bound` | The value of the bound being violated | Returns: Nominally the result is the desired value of the operator, which will be forwarded as result. For `Abort`, the function never returns because it aborts the program. bool **hookOpEquals**(Lhs, Rhs)(Lhs lhs, Rhs rhs); Called automatically upon a comparison for equality. In case of a erroneous comparison (one that would make a signed negative value appear equal to an unsigned positive value), this hook issues `assert(0)` which terminates the application. Parameters: | | | | --- | --- | | Lhs `lhs` | The first argument of `Checked`, e.g. `int` if the left-hand side of the operator is `Checked!int` | | Rhs `rhs` | The right-hand side type involved in the operator | Returns: Upon a correct comparison, returns the result of the comparison. Otherwise, the function terminates the application so it never returns. int **hookOpCmp**(Lhs, Rhs)(Lhs lhs, Rhs rhs); Called automatically upon a comparison for ordering using one of the operators `<`, `<=`, `>`, or `>=`. In case the comparison is erroneous (i.e. it would make a signed negative value appear greater than or equal to an unsigned positive value), then application is terminated with `assert(0)`. Otherwise, the three-state result is returned (positive if `lhs > rhs`, negative if `lhs < rhs`, `0` otherwise). Parameters: | | | | --- | --- | | Lhs `lhs` | The first argument of `Checked`, e.g. `int` if the left-hand side of the operator is `Checked!int` | | Rhs `rhs` | The right-hand side type involved in the operator | Returns: For correct comparisons, returns a positive integer if `lhs > rhs`, a negative integer if `lhs < rhs`, `0` if the two are equal. Upon a mistaken comparison such as `int(-1) < uint(0)`, the function never returns because it aborts the program. typeof(~Lhs()) **onOverflow**(string x, Lhs)(Lhs lhs); typeof(Lhs() + Rhs()) **onOverflow**(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs); Called automatically upon an overflow during a unary or binary operation. Parameters: | | | | --- | --- | | x | The operator, e.g. `-` | | Lhs `lhs` | The left-hand side (or sole) argument | | Rhs `rhs` | The right-hand side type involved in the operator | Returns: Nominally the result is the desired value of the operator, which will be forwarded as result. For `Abort`, the function never returns because it aborts the program. struct **Throw**; Force all integral errors to fail by throwing an exception of type `Throw.CheckFailure`. The message coming with the error is similar to the one printed by `Warn`. Examples: ``` void test(T)() { Checked!(int, Throw) x; x = 42; auto x1 = cast(T) x; writeln(x1); // 42 x = T.max + 1; import std.exception : assertThrown, assertNotThrown; assertThrown(cast(T) x); x = x.max; assertThrown(x += 42); assertThrown(x += 42L); x = x.min; assertThrown(-x); assertThrown(x -= 42); assertThrown(x -= 42L); x = -1; assertNotThrown(x == -1); assertThrown(x == uint(-1)); assertNotThrown(x <= -1); assertThrown(x <= uint(-1)); } test!short; test!(const short); test!(immutable short); ``` class **CheckFailure**: object.Exception; Exception type thrown upon any failure. Dst **onBadCast**(Dst, Src)(Src src); Called automatically upon a bad cast (one that loses precision or attempts to convert a negative value to an unsigned type). The source type is `Src` and the destination type is `Dst`. Parameters: | | | | --- | --- | | Src `src` | The source of the cast | Returns: Nominally the result is the desired value of the cast operation, which will be forwarded as the result of the cast. For `Throw`, the function never returns because it throws an exception. T **onLowerBound**(Rhs, T)(Rhs rhs, T bound); T **onUpperBound**(Rhs, T)(Rhs rhs, T bound); Called automatically upon a bounds error. Parameters: | | | | --- | --- | | Rhs `rhs` | The right-hand side value in the assignment, after the operator has been evaluated | | T `bound` | The value of the bound being violated | Returns: Nominally the result is the desired value of the operator, which will be forwarded as result. For `Throw`, the function never returns because it throws. bool **hookOpEquals**(L, R)(L lhs, R rhs); Called automatically upon a comparison for equality. Throws upon an erroneous comparison (one that would make a signed negative value appear equal to an unsigned positive value). Parameters: | | | | --- | --- | | L `lhs` | The first argument of `Checked`, e.g. `int` if the left-hand side of the operator is `Checked!int` | | R `rhs` | The right-hand side type involved in the operator | Returns: The result of the comparison. Throws: `CheckFailure` if the comparison is mathematically erroneous. int **hookOpCmp**(Lhs, Rhs)(Lhs lhs, Rhs rhs); Called automatically upon a comparison for ordering using one of the operators `<`, `<=`, `>`, or `>=`. In case the comparison is erroneous (i.e. it would make a signed negative value appear greater than or equal to an unsigned positive value), throws a `Throw.CheckFailure` exception. Otherwise, the three-state result is returned (positive if `lhs > rhs`, negative if `lhs < rhs`, `0` otherwise). Parameters: | | | | --- | --- | | Lhs `lhs` | The first argument of `Checked`, e.g. `int` if the left-hand side of the operator is `Checked!int` | | Rhs `rhs` | The right-hand side type involved in the operator | Returns: For correct comparisons, returns a positive integer if `lhs > rhs`, a negative integer if `lhs < rhs`, `0` if the two are equal. Throws: Upon a mistaken comparison such as `int(-1) < uint(0)`, the function never returns because it throws a `Throw.CheckedFailure` exception. typeof(~Lhs()) **onOverflow**(string x, Lhs)(Lhs lhs); typeof(Lhs() + Rhs()) **onOverflow**(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs); Called automatically upon an overflow during a unary or binary operation. Parameters: | | | | --- | --- | | x | The operator, e.g. `-` | | Lhs `lhs` | The left-hand side (or sole) argument | | Rhs `rhs` | The right-hand side type involved in the operator | Returns: Nominally the result is the desired value of the operator, which will be forwarded as result. For `Throw`, the function never returns because it throws an exception. struct **Warn**; Hook that prints to `stderr` a trace of all integral errors, without affecting default behavior. Examples: ``` auto x = checked!Warn(42); short x1 = cast(short) x; //x += long(int.max); auto y = checked!Warn(cast(const int) 42); short y1 = cast(const byte) y; ``` Dst **onBadCast**(Dst, Src)(Src src); Called automatically upon a bad cast from `src` to type `Dst` (one that loses precision or attempts to convert a negative value to an unsigned type). Parameters: | | | | --- | --- | | Src `src` | The source of the cast | | Dst | The target type of the cast | Returns: `cast(Dst) src` Lhs **onLowerBound**(Rhs, T)(Rhs rhs, T bound); T **onUpperBound**(Rhs, T)(Rhs rhs, T bound); Called automatically upon a bad `opOpAssign` call (one that loses precision or attempts to convert a negative value to an unsigned type). Parameters: | | | | --- | --- | | Rhs `rhs` | The right-hand side value in the assignment, after the operator has been evaluated | | T `bound` | The bound being violated | Returns: `cast(Lhs) rhs` bool **hookOpEquals**(Lhs, Rhs)(Lhs lhs, Rhs rhs); Called automatically upon a comparison for equality. In case of an Erroneous comparison (one that would make a signed negative value appear equal to an unsigned positive value), writes a warning message to `stderr` as a side effect. Parameters: | | | | --- | --- | | Lhs `lhs` | The first argument of `Checked`, e.g. `int` if the left-hand side of the operator is `Checked!int` | | Rhs `rhs` | The right-hand side type involved in the operator | Returns: In all cases the function returns the built-in result of `lhs == rhs`. Examples: ``` auto x = checked!Warn(-42); // Passes writeln(x); // -42 // Passes but prints a warning // assert(x == uint(-42)); ``` int **hookOpCmp**(Lhs, Rhs)(Lhs lhs, Rhs rhs); Called automatically upon a comparison for ordering using one of the operators `<`, `<=`, `>`, or `>=`. In case the comparison is erroneous (i.e. it would make a signed negative value appear greater than or equal to an unsigned positive value), then a warning message is printed to `stderr`. Parameters: | | | | --- | --- | | Lhs `lhs` | The first argument of `Checked`, e.g. `int` if the left-hand side of the operator is `Checked!int` | | Rhs `rhs` | The right-hand side type involved in the operator | Returns: In all cases, returns `lhs < rhs ? -1 : lhs > rhs`. The result is not autocorrected in case of an erroneous comparison. Examples: ``` auto x = checked!Warn(-42); // Passes assert(x <= -42); // Passes but prints a warning // assert(x <= uint(-42)); ``` typeof(~Lhs()) **onOverflow**(string x, Lhs)(ref Lhs lhs); typeof(Lhs() + Rhs()) **onOverflow**(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs); Called automatically upon an overflow during a unary or binary operation. Parameters: | | | | --- | --- | | x | The operator involved | | Lhs | The first argument of `Checked`, e.g. `int` if the left-hand side of the operator is `Checked!int` | | Rhs | The right-hand side type involved in the operator | Returns: `mixin(x ~ "lhs")` for unary, `mixin("lhs" ~ x ~ "rhs")` for binary struct **ProperCompare**; Hook that provides arithmetically correct comparisons for equality and ordering. Comparing an object of type `Checked!(X, ProperCompare)` against another integral (for equality or ordering) ensures that no surprising conversions from signed to unsigned integral occur before the comparison. Using `Checked!(X, ProperCompare)` on either side of a comparison for equality against a floating-point number makes sure the integral can be properly converted to the floating point type, thus making sure equality is transitive. Examples: ``` alias opEqualsProper = ProperCompare.hookOpEquals; assert(opEqualsProper(42, 42)); assert(opEqualsProper(42.0, 42.0)); assert(opEqualsProper(42u, 42)); assert(opEqualsProper(42, 42u)); writeln(-1); // 4294967295u assert(!opEqualsProper(-1, 4294967295u)); assert(!opEqualsProper(const uint(-1), -1)); assert(!opEqualsProper(uint(-1), -1.0)); writeln(3_000_000_000U); // -1_294_967_296 assert(!opEqualsProper(3_000_000_000U, -1_294_967_296)); ``` bool **hookOpEquals**(L, R)(L lhs, R rhs); Hook for `==` and `!=` that ensures comparison against integral values has the behavior expected by the usual arithmetic rules. The built-in semantics yield surprising behavior when comparing signed values against unsigned values for equality, for example `uint.max == -1` or `-1_294_967_296 == 3_000_000_000u`. The call `hookOpEquals(x, y)` returns `true` if and only if `x` and `y` represent the same arithmetic number. If one of the numbers is an integral and the other is a floating-point number, `hookOpEquals(x, y)` returns `true` if and only if the integral can be converted exactly (without approximation) to the floating-point number. This is in order to preserve transitivity of equality: if `hookOpEquals(x, y)` and `hookOpEquals(y, z)` then `hookOpEquals(y, z)`, in case `x`, `y`, and `z` are a mix of integral and floating-point numbers. Parameters: | | | | --- | --- | | L `lhs` | The left-hand side of the comparison for equality | | R `rhs` | The right-hand side of the comparison for equality | Returns: The result of the comparison, `true` if the values are equal auto **hookOpCmp**(L, R)(L lhs, R rhs); Hook for `<`, `<=`, `>`, and `>=` that ensures comparison against integral values has the behavior expected by the usual arithmetic rules. The built-in semantics yield surprising behavior when comparing signed values against unsigned values, for example `0u < -1`. The call `hookOpCmp(x, y)` returns `-1` if and only if `x` is smaller than `y` in abstract arithmetic sense. If one of the numbers is an integral and the other is a floating-point number, `hookOpEquals(x, y)` returns a floating-point number that is `-1` if `x < y`, `0` if `x == y`, `1` if `x > y`, and `NaN` if the floating-point number is `NaN`. Parameters: | | | | --- | --- | | L `lhs` | The left-hand side of the comparison for ordering | | R `rhs` | The right-hand side of the comparison for ordering | Returns: The result of the comparison (negative if `lhs < rhs`, positive if `lhs > rhs`, `0` if the values are equal) struct **WithNaN**; Hook that reserves a special value as a "Not a Number" representative. For signed integrals, the reserved value is `T.min`. For signed integrals, the reserved value is `T.max`. The default value of a `Checked!(X, WithNaN)` is its NaN value, so care must be taken that all variables are explicitly initialized. Any arithmetic and logic operation involving at least on NaN becomes NaN itself. All of `a == b`, `a < b`, `a > b`, `a <= b`, `a >= b` yield `false` if at least one of `a` and `b` is NaN. Examples: ``` auto x1 = Checked!(int, WithNaN)(); assert(x1.isNaN); writeln(x1.get); // int.min assert(x1 != x1); assert(!(x1 < x1)); assert(!(x1 > x1)); assert(!(x1 == x1)); ++x1; assert(x1.isNaN); writeln(x1.get); // int.min --x1; assert(x1.isNaN); writeln(x1.get); // int.min x1 = 42; assert(!x1.isNaN); writeln(x1); // x1 assert(x1 <= x1); assert(x1 >= x1); static assert(x1.min == int.min + 1); x1 += long(int.max); ``` enum T **defaultValue**(T); The default value used for values not explicitly initialized. It is the NaN value, i.e. `T.min` for signed integrals and `T.max` for unsigned integrals. enum T **max**(T); enum T **min**(T); The maximum value representable is `T.max` for signed integrals, `T.max - 1` for unsigned integrals. The minimum value representable is `T.min + 1` for signed integrals, `0` for unsigned integrals. Lhs **hookOpCast**(Lhs, Rhs)(Rhs rhs); If `rhs` is `WithNaN.defaultValue!Rhs`, returns `WithNaN.defaultValue!Lhs`. Otherwise, returns `cast(Lhs) rhs`. Parameters: | | | | --- | --- | | Rhs `rhs` | the value being cast (`Rhs` is the first argument to `Checked`) | | Lhs | the target type of the cast | Returns: The result of the cast operation. Examples: ``` auto x = checked!WithNaN(422); writeln((cast(ubyte)x)); // 255 x = checked!WithNaN(-422); writeln((cast(byte)x)); // -128 writeln(cast(short)x); // -422 assert(cast(bool) x); x = x.init; // set back to NaN assert(x != true); assert(x != false); ``` bool **hookOpEquals**(Lhs, Rhs)(Lhs lhs, Rhs rhs); Returns `false` if `lhs == WithNaN.defaultValue!Lhs`, `lhs == rhs` otherwise. Parameters: | | | | --- | --- | | Lhs `lhs` | The left-hand side of the comparison (`Lhs` is the first argument to `Checked`) | | Rhs `rhs` | The right-hand side of the comparison | Returns: `lhs != WithNaN.defaultValue!Lhs && lhs == rhs` double **hookOpCmp**(Lhs, Rhs)(Lhs lhs, Rhs rhs); If `lhs == WithNaN.defaultValue!Lhs`, returns `double.init`. Otherwise, has the same semantics as the default comparison. Parameters: | | | | --- | --- | | Lhs `lhs` | The left-hand side of the comparison (`Lhs` is the first argument to `Checked`) | | Rhs `rhs` | The right-hand side of the comparison | Returns: `double.init` if `lhs == WitnNaN.defaultValue!Lhs`, `-1.0` if `lhs < rhs`, `0.0` if `lhs == rhs`, `1.0` if `lhs > rhs`. Examples: ``` Checked!(int, WithNaN) x; assert(!(x < 0) && !(x > 0) && !(x == 0)); x = 1; assert(x > 0 && !(x < 0) && !(x == 0)); ``` auto **hookOpUnary**(string x, T)(ref T v); Defines hooks for unary operators `-`, `~`, `++`, and `--`. For `-` and `~`, if `v == WithNaN.defaultValue!T`, returns `WithNaN.defaultValue!T`. Otherwise, the semantics is the same as for the built-in operator. For `++` and `--`, if `v == WithNaN.defaultValue!Lhs` or the operation would result in an overflow, sets `v` to `WithNaN.defaultValue!T`. Otherwise, the semantics is the same as for the built-in operator. Parameters: | | | | --- | --- | | x | The operator symbol | | T `v` | The left-hand side of the comparison (`T` is the first argument to `Checked`) | Returns: * For `x == "-" || x == "~"`: If `v == WithNaN.defaultValue!T`, the function returns `WithNaN.defaultValue!T`. Otherwise it returns the normal result of the operator. * For `x == "++" || x == "--"`: The function returns `void`. Examples: ``` Checked!(int, WithNaN) x; ++x; assert(x.isNaN); x = 1; assert(!x.isNaN); x = -x; ++x; assert(!x.isNaN); ``` auto **hookOpBinary**(string x, L, R)(L lhs, R rhs); Defines hooks for binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>` for cases where a `Checked` object is the left-hand side operand. If `lhs == WithNaN.defaultValue!Lhs`, returns `WithNaN.defaultValue!(typeof(lhs + rhs))` without evaluating the operand. Otherwise, evaluates the operand. If evaluation does not overflow, returns the result. Otherwise, returns `WithNaN.defaultValue!(typeof(lhs + rhs))`. Parameters: | | | | --- | --- | | x | The operator symbol | | L `lhs` | The left-hand side operand (`Lhs` is the first argument to `Checked`) | | R `rhs` | The right-hand side operand | Returns: If `lhs != WithNaN.defaultValue!Lhs` and the operator does not overflow, the function returns the same result as the built-in operator. In all other cases, returns `WithNaN.defaultValue!(typeof(lhs + rhs))`. Examples: ``` Checked!(int, WithNaN) x; assert((x + 1).isNaN); x = 100; assert(!(x + 1).isNaN); ``` auto **hookOpBinaryRight**(string x, L, R)(L lhs, R rhs); Defines hooks for binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>` for cases where a `Checked` object is the right-hand side operand. If `rhs == WithNaN.defaultValue!Rhs`, returns `WithNaN.defaultValue!(typeof(lhs + rhs))` without evaluating the operand. Otherwise, evaluates the operand. If evaluation does not overflow, returns the result. Otherwise, returns `WithNaN.defaultValue!(typeof(lhs + rhs))`. Parameters: | | | | --- | --- | | x | The operator symbol | | L `lhs` | The left-hand side operand | | R `rhs` | The right-hand side operand (`Rhs` is the first argument to `Checked`) | Returns: If `rhs != WithNaN.defaultValue!Rhs` and the operator does not overflow, the function returns the same result as the built-in operator. In all other cases, returns `WithNaN.defaultValue!(typeof(lhs + rhs))`. Examples: ``` Checked!(int, WithNaN) x; assert((1 + x).isNaN); x = 100; assert(!(1 + x).isNaN); ``` void **hookOpOpAssign**(string x, L, R)(ref L lhs, R rhs); Defines hooks for binary operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=` for cases where a `Checked` object is the left-hand side operand. If `lhs == WithNaN.defaultValue!Lhs`, no action is carried. Otherwise, evaluates the operand. If evaluation does not overflow and fits in `Lhs` without loss of information or change of sign, sets `lhs` to the result. Otherwise, sets `lhs` to `WithNaN.defaultValue!Lhs`. Parameters: | | | | --- | --- | | x | The operator symbol (without the `=`) | | L `lhs` | The left-hand side operand (`Lhs` is the first argument to `Checked`) | | R `rhs` | The right-hand side operand | Returns: `void` Examples: ``` Checked!(int, WithNaN) x; x += 4; assert(x.isNaN); x = 0; x += 4; assert(!x.isNaN); x += int.max; assert(x.isNaN); ``` bool **isNaN**(T)(const Checked!(T, WithNaN) x); Queries whether a `Checked!(T, WithNaN)` object is not a number (NaN). Parameters: | | | | --- | --- | | Checked!(T, WithNaN) `x` | the `Checked` instance queried | Returns: `true` if `x` is a NaN, `false` otherwise Examples: ``` auto x1 = Checked!(int, WithNaN)(); assert(x1.isNaN); x1 = 1; assert(!x1.isNaN); x1 = x1.init; assert(x1.isNaN); ``` struct **Saturate**; Hook that implements *saturation*, i.e. any arithmetic operation that would overflow leaves the result at its extreme value (`min` or `max` depending on the direction of the overflow). Saturation is not sticky; if a value reaches its saturation value, another operation may take it back to normal range. Examples: ``` auto x = checked!Saturate(int.max); ++x; writeln(x); // int.max --x; writeln(x); // int.max - 1 x = int.min; writeln(-x); // int.max x -= 42; writeln(x); // int.min writeln(x * -2); // int.max ``` T **onLowerBound**(Rhs, T)(Rhs rhs, T bound); T **onUpperBound**(Rhs, T)(Rhs rhs, T bound); Implements saturation for operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=`. This hook is called if the result of the binary operation does not fit in `Lhs` without loss of information or a change in sign. Parameters: | | | | --- | --- | | Rhs | The right-hand side type in the assignment, after the operation has been computed | | T `bound` | The bound being violated | Returns: `Lhs.max` if `rhs >= 0`, `Lhs.min` otherwise. Examples: ``` auto x = checked!Saturate(short(100)); x += 33000; writeln(x); // short.max x -= 70000; writeln(x); // short.min ``` auto **onOverflow**(string x, Lhs)(Lhs lhs); typeof(Lhs() + Rhs()) **onOverflow**(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs); Implements saturation for operators `+`, `-` (unary and binary), `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>`. For unary `-`, `onOverflow` is called if `lhs == Lhs.min` and `Lhs` is a signed type. The function returns `Lhs.max`. For binary operators, the result is as follows: * `Lhs.max` if the result overflows in the positive direction, on division by `0`, or on shifting right by a negative value * `Lhs.min` if the result overflows in the negative direction * `0` if `lhs` is being shifted left by a negative value, or shifted right by a large positive value Parameters: | | | | --- | --- | | x | The operator involved in the `opAssign` operation | | Lhs | The left-hand side of the operator (`Lhs` is the first argument to `Checked`) | | Rhs | The right-hand side type in the operator | Returns: The saturated result of the operator. Examples: ``` writeln(checked!Saturate(int.max) + 1); // int.max writeln(checked!Saturate(100)^^10); // int.max writeln(checked!Saturate(-100)^^10); // int.max writeln(checked!Saturate(100) / 0); // int.max writeln(checked!Saturate(100) << -1); // 0 writeln(checked!Saturate(100) << 33); // int.max writeln(checked!Saturate(100) >> -1); // int.max writeln(checked!Saturate(100) >> 33); // 0 ``` typeof(mixin(x == "cmp" ? "0" : "L() " ~ x ~ " R()")) **opChecked**(string x, L, R)(const L lhs, const R rhs, ref bool overflow) Constraints: if (isIntegral!L && isIntegral!R); Defines binary operations with overflow checking for any two integral types. The result type obeys the language rules (even when they may be counterintuitive), and `overflow` is set if an overflow occurs (including inadvertent change of signedness, e.g. `-1` is converted to `uint`). Conceptually the behavior is: 1. Perform the operation in infinite precision 2. If the infinite-precision result fits in the result type, return it and do not touch `overflow` 3. Otherwise, set `overflow` to `true` and return an unspecified value The implementation exploits properties of types and operations to minimize additional work. Parameters: | | | | --- | --- | | x | The binary operator involved, e.g. `/` | | L `lhs` | The left-hand side of the operator | | R `rhs` | The right-hand side of the operator | | bool `overflow` | The overflow indicator (assigned `true` in case there's an error) | Returns: The result of the operation, which is the same as the built-in operator Examples: ``` bool overflow; assert(opChecked!"+"(const short(1), short(1), overflow) == 2 && !overflow); assert(opChecked!"+"(1, 1, overflow) == 2 && !overflow); assert(opChecked!"+"(1, 1u, overflow) == 2 && !overflow); assert(opChecked!"+"(-1, 1u, overflow) == 0 && !overflow); assert(opChecked!"+"(1u, -1, overflow) == 0 && !overflow); ``` Examples: ``` bool overflow; assert(opChecked!"-"(1, 1, overflow) == 0 && !overflow); assert(opChecked!"-"(1, 1u, overflow) == 0 && !overflow); assert(opChecked!"-"(1u, -1, overflow) == 2 && !overflow); assert(opChecked!"-"(-1, 1u, overflow) == 0 && overflow); ```
programming_docs
d Garbage Collection Garbage Collection ================== **Contents** 1. [How Garbage Collection Works](#how_gc_works) 2. [Interfacing Garbage Collected Objects With Foreign Code](#gc_foreign_obj) 3. [Pointers and the Garbage Collector](#pointers_and_gc) 4. [Working with the Garbage Collector](#working_with_the_gc) 5. [Object Pinning and a Moving Garbage Collector](#obj_pinning_and_gc) 6. [Configuring the Garbage Collector](#gc_config) 7. [Precise Heap Scanning](#precise_gc) 8. [Precise Scanning of the DATA and TLS segment](#precise_dataseg) 9. [Parallel marking](#gc_parallel) 10. [Adding your own Garbage Collector](#gc_registry) 11. [References](#references) D is a systems programming language with support for garbage collection. Usually it is not necessary to free memory explicitly. Just allocate as needed, and the garbage collector will periodically return all unused memory to the pool of available memory. D also provides the mechanisms to write code where the garbage collector is **not involved**. More information is provided below. Programmers accustomed to explicitly managing memory allocation and deallocation will likely be skeptical of the benefits and efficacy of garbage collection. Experience both with new projects written with garbage collection in mind, and converting existing projects to garbage collection shows that: * Garbage collected programs are often faster. This is counterintuitive, but the reasons are: + Reference counting is a common solution to solve explicit memory allocation problems. The code to implement the increment and decrement operations whenever assignments are made is one source of slowdown. Hiding it behind smart pointer classes doesn't help the speed. (Reference counting methods are not a general solution anyway, as circular references never get deleted.) + Destructors are used to deallocate resources acquired by an object. For most classes, this resource is allocated memory. With garbage collection, most destructors then become empty and can be discarded entirely. + All those destructors freeing memory can become significant when objects are allocated on the stack. For each one, some mechanism must be established so that if an exception happens, the destructors all get called in each frame to release any memory they hold. If the destructors become irrelevant, then there's no need to set up special stack frames to handle exceptions, and the code runs faster. + Garbage collection kicks in only when memory gets tight. When memory is not tight, the program runs at full speed and does not spend any time tracing and freeing memory. + Garbage collected programs do not suffer from gradual deterioration due to an accumulation of memory leaks. * Garbage collectors reclaim unused memory, therefore they do not suffer from "memory leaks" which can cause long running applications to gradually consume more and more memory until they bring down the system. GC programs have longer term stability. * Garbage collected programs have fewer hard-to-find pointer bugs. This is because there are no dangling references to freed memory. There is no code to explicitly manage memory, hence no bugs in such code. * Garbage collected programs are faster to develop and debug, because there's no need for developing, debugging, testing, or maintaining the explicit deallocation code. Garbage collection is not a panacea. There are some downsides: * It is not always obvious when the GC allocates memory, which in turn can trigger a collection, so the program can pause unexpectedly. * The time it takes for a collection to complete is not bounded. While in practice it is very quick, this cannot normally be guaranteed. * Normally, all threads other than the collector thread must be halted while the collection is in progress. * Garbage collectors can keep around some memory that an explicit deallocator would not. * Garbage collection should be implemented as a basic operating system kernel service. But since it is not, garbage collecting programs must carry around with them the garbage collection implementation. While this can be a shared library, it is still there. These constraints are addressed by techniques outlined in [Memory Management](https://wiki.dlang.org/Memory_Management), including the mechanisms provided by D to control allocations outside the GC heap. There is currently work in progress to make the runtime library free of GC heap allocations, to allow its use in scenarios where the use of GC infrastructure is not possible. How Garbage Collection Works ---------------------------- The GC works by: 1. Stopping all other threads than the thread currently trying to allocate GC memory. 2. ‘Hijacking’ the current thread for GC work. 3. Scanning all ‘root’ memory ranges for pointers into GC allocated memory. 4. Recursively scanning all allocated memory pointed to by roots looking for more pointers into GC allocated memory. 5. Freeing all GC allocated memory that has no active pointers to it and do not need destructors to run. 6. Queueing all unreachable memory that needs destructors to run. 7. Resuming all other threads. 8. Running destructors for all queued memory. 9. Freeing any remaining unreachable memory. 10. Returning the current thread to whatever work it was doing. Interfacing Garbage Collected Objects With Foreign Code ------------------------------------------------------- The garbage collector looks for roots in: 1. the static data segment 2. the stacks and register contents of each thread 3. the TLS (thread-local storage) areas of each thread 4. any roots added by core.memory.GC.addRoot() or core.memory.GC.addRange() If the only pointer to an object is held outside of these areas, then the collector will miss it and free the memory. To avoid this from happening, either * maintain a pointer to the object in an area the collector does scan for pointers; * add a root where a pointer to the object is stored using core.memory.GC.addRoot() or core.memory.GC.addRange(). * reallocate and copy the object using the foreign code's storage allocator or using the C runtime library's malloc/free. Pointers and the Garbage Collector ---------------------------------- Pointers in D can be broadly divided into two categories: Those that point to garbage collected memory, and those that do not. Examples of the latter are pointers created by calls to C's malloc(), pointers received from C library routines, pointers to static data, pointers to objects on the stack, etc. For those pointers, anything that is legal in C can be done with them. For garbage collected pointers and references, however, there are some restrictions. These restrictions are minor, but they are intended to enable the maximum flexibility in garbage collector design. **Undefined Behavior:** * Do not xor pointers with other values, like the xor pointer linked list trick used in C. * Do not use the xor trick to swap two pointer values. * Do not store pointers into non-pointer variables using casts and other tricks. ``` void* p; ... int x = cast(int)p; // error: undefined behavior ``` The garbage collector does not scan non-pointer fields for GC pointers. * Do not take advantage of alignment of pointers to store bit flags in the low order bits: ``` p = cast(void*)(cast(int)p | 1); // error: undefined behavior ``` * Do not store into pointers values that may point into the garbage collected heap: ``` p = cast(void*)12345678; // error: undefined behavior ``` A copying garbage collector may change this value. * Do not store magic values into pointers, other than `null`. * Do not write pointer values out to disk and read them back in again. * Do not use pointer values to compute a hash function. A copying garbage collector can arbitrarily move objects around in memory, thus invalidating the computed hash value. * Do not depend on the ordering of pointers: ``` if (p1 < p2) // error: undefined behavior ... ``` since, again, the garbage collector can move objects around in memory. * Do not add or subtract an offset to a pointer such that the result points outside of the bounds of the garbage collected object originally allocated. ``` char* p = new char[10]; char* q = p + 6; // ok q = p + 11; // error: undefined behavior q = p - 1; // error: undefined behavior ``` * Do not misalign pointers if those pointers may point into the GC heap, such as: ``` struct Foo { align (1): byte b; char* p; // misaligned pointer } ``` Misaligned pointers may be used if the underlying hardware supports them **and** the pointer is never used to point into the GC heap. * Do not use byte-by-byte memory copies to copy pointer values. This may result in intermediate conditions where there is not a valid pointer, and if the gc pauses the thread in such a condition, it can corrupt memory. Most implementations of `memcpy()` will work since the internal implementation of it does the copy in aligned chunks greater than or equal to the pointer size, but since this kind of implementation is not guaranteed by the C standard, use `memcpy()` only with extreme caution. * Do not have pointers in a struct instance that point back to the same instance. The trouble with this is if the instance gets moved in memory, the pointer will point back to where it came from, with likely disastrous results. Things that are reliable and can be done: * Use a union to share storage with a pointer: ``` union U { void* ptr; int value } ``` * A pointer to the start of a garbage collected object need not be maintained if a pointer to the interior of the object exists. ``` char[] p = new char[10]; char[] q = p[3..6]; // q is enough to hold on to the object, don't need to keep // p as well. ``` One can avoid using pointers anyway for most tasks. D provides features rendering most explicit pointer uses obsolete, such as reference objects, dynamic arrays, and garbage collection. Pointers are provided in order to interface successfully with C APIs and for some low level work. Working with the Garbage Collector ---------------------------------- Garbage collection doesn't solve every memory deallocation problem. For example, if a pointer to a large data structure is kept, the garbage collector cannot reclaim it, even if it is never referred to again. To eliminate this problem, it is good practice to set a reference or pointer to an object to null when no longer needed. This advice applies only to static references or references embedded inside other objects. There is not much point for such stored on the stack to be nulled because new stack frames are initialized anyway. Object Pinning and a Moving Garbage Collector --------------------------------------------- Although D does not currently use a moving garbage collector, by following the rules listed above one can be implemented. No special action is required to pin objects. A moving collector will only move objects for which there are no ambiguous references, and for which it can update those references. All other objects will be automatically pinned. D Operations That Involve the Garbage Collector ----------------------------------------------- Some sections of code may need to avoid using the garbage collector. The following constructs may allocate memory using the garbage collector: * [*NewExpression*](expression#NewExpression) * Array appending * Array concatenation * Array literals (except when used to initialize static data) * Associative array literals * Any insertion, removal, or lookups in an associative array * Extracting keys or values from an associative array * Taking the address of (i.e. making a delegate to) a nested function that accesses variables in an outer scope * A function literal that accesses variables in an outer scope * An [*AssertExpression*](expression#AssertExpression) that fails its condition Configuring the Garbage Collector --------------------------------- Since version 2.067, The garbage collector can now be configured through the command line, the environment or by options embedded into the executable. By default, GC options can only be passed on the command line of the program to run, e.g. ``` app "--DRT-gcopt=profile:1 minPoolSize:16" arguments to app ``` Available GC options are: * disable:0|1 - start disabled * profile:0|1 - enable profiling with summary when terminating program * gc:conservative|precise|manual - select gc implementation (default = conservative) * initReserve:N - initial memory to reserve in MB * minPoolSize:N - initial and minimum pool size in MB * maxPoolSize:N - maximum pool size in MB * incPoolSize:N - pool size increment MB * parallel:N - number of additional threads for marking * heapSizeFactor:N - targeted heap size to used memory ratio * cleanup:none|collect|finalize - how to treat live objects when terminating + collect: run a collection (the default for backward compatibility) + none: do nothing + finalize: all live objects are finalized unconditionally In addition, --DRT-gcopt=help will show the list of options and their current settings. Command line options starting with "--DRT-" are filtered out before calling main, so the program will not see them. They are still available via `rt_args`. Configuration via the command line can be disabled by declaring a variable for the linker to pick up before using its default from the runtime: ``` extern(C) __gshared bool rt_cmdline_enabled = false; ``` Likewise, declare a boolean `rt_envvars_enabled` to enable configuration via the environment variable `DRT_GCOPT`: ``` extern(C) __gshared bool rt_envvars_enabled = true; ``` Setting default configuration properties in the executable can be done by specifying an array of options named `rt_options`: ``` extern(C) __gshared string[] rt_options = [ "gcopt=initReserve:100 profile:1" ]; ``` Evaluation order of options is `rt_options`, then environment variables, then command line arguments, i.e. if command line arguments are not disabled, they can override options specified through the environment or embedded in the executable. Precise Heap Scanning --------------------- Selecting `precise` as the garbage collector via the options above means type information will be used to identify actual or possible pointers or references within heap allocated data objects. Non-pointer data will not be interpreted as a reference to other memory as a "false pointer". The collector has to make pessimistic assumptions if a memory slot can contain both a pointer or an integer value, it will still be scanned (e.g. in a `union`). To use the GC memory functions from `core.memory` for data with a mixture of pointers and non-pointer data, pass the TypeInfo of the allocated struct, class, or type as the optional parameter. The default `null` is interpreted as memory that might contain pointers everywhere. ``` struct S { size_t hash; Data* data; } S* s = cast(S*)GC.malloc(S.sizeof, 0, typeid(S)); ``` Attention: Enabling precise scanning needs slightly more caution with type declarations. For example, when reserving a buffer as part of a struct and later emplacing an object instance with references to other allocations into this memory, do not use basic integer types to reserve the space. Doing so will cause the garbage collector not to detect the references. Instead, use an array type that will scan this area conservatively. Using `void*` is usually the best option as it also ensures proper alignment for pointers being scanned by the GC. Precise Scanning of the DATA and TLS segment -------------------------------------------- **Windows only:** As of version 2.075, the DATA (global shared data) and TLS segment (thread local data) of an executable or DLL can be configured to be scanned precisely by the garbage collector instead of conservatively. This takes advantage of information emitted by the compiler to identify possible mutable pointers inside these segments. Immutable pointers [with initializers](const3#immutable_storage_class) are excluded from scanning, too, as they can only point to preallocated memory. Precise scanning can be enabled with the D runtime option "scanDataSeg". Possible option values are "conservative" (default) and "precise". As with the GC options, it can be specified on the command line, in the environment or embedded into the executable, e.g. ``` extern(C) __gshared string[] rt_options = [ "scanDataSeg=precise" ]; ``` Attention: Enabling precise scanning needs slightly more caution typing global memory. For example, to pre-allocate memory in the DATA/TLS segment and later emplace an object instance with references to other allocations into this memory, do not use basic integer types to reserve the space. Doing so will cause the garbage collector not to detect the references. Instead, use an array type that will scan this area conservatively. Using `void*` is usually the best option as it also ensures proper alignment for pointers being scanned by the GC. ``` class Singleton { void[] mem; } void*[(__traits(classInstanceSize, Singleton) - 1) / (void*).sizeof + 1] singleton_store; static this() { emplace!Singleton(singleton_store).mem = allocateMem(); } Singleton singleton() { return cast(Singleton)singleton_store.ptr; } ``` For precise typing of that area, let the compiler generate the class instance into the DATA segment: ``` class Singleton { void[] mem; } shared(Singleton) singleton = new Singleton; shared static this() { singleton.mem = allocateSharedMem(); } ``` This doesn't work for TLS memory, though. Parallel marking ---------------- By default the garbage collector uses all available CPU cores to mark the heap. This might affect your application if it has threads that are not suspended during the mark phase of the collection. Configure the number of additional threads used for marking by GC option `parallel`, e.g. by passing `--DRT-gcopt=parallel:2` on the command line or embedding the option into the binary via `rt_options`. The number of threads actually created is limited to [`core.cpuid.threadsPerCPU-1`](https://dlang.org/library/core/cpuid/threads_per_cpu.html). A value of `0` disables parallel marking completely. Adding your own Garbage Collector --------------------------------- GC implementations are added to a registry that allows to supply more implementations by just linking them into the binary. To do so add a function that is executed before the D runtime initialization using `pragma(crt_constructor)`: ``` import core.gc.gcinterface, core.gc.registry; extern (C) pragma(crt_constructor) void registerMyGC() { registerGCFactory("mygc", &createMyGC); } GC createMyGC() { __gshared instance = new MyGC; instance.initialize(); return instance; } class MyGC : GC { /*...*/ } ``` [The GC modules defining the interface (gc.interface) and registration (gc.registry) are currently not public and are subject to change from version to version. Add an import search path to the druntime/src path to compile the example.] The new GC is added to the list of available garbage collectors that can be selected via the usual configuration options, e.g. by embedding `rt_options` into the binary: ``` extern (C) __gshared string[] rt_options = ["gcopt=gc:mygc"]; ``` The standard GC implementation from a statically linked binary can be removed by redefining the function `extern(C) void* register_default_gcs()`. If no custom garbage collector has been registered all attempts to allocate GC managed memory will terminate the application with an appropriate message. References ---------- * [Wikipedia](https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29) * [GC FAQ](http://www.iecc.com/gclist/GC-faq.html) * [Uniprocessor Garbage Collector Techniques](ftp://ftp.cs.utexas.edu/pub/garbage/gcsurvey.ps) * [Garbage Collection: Algorithms for Automatic Dynamic Memory Management](http://amazon.com/exec/obidos/ASIN/0471941484/classicempire)
programming_docs
d rt.sections_elf_shared rt.sections\_elf\_shared ======================== Written in the D programming language. This module provides ELF-specific support for sections with shared libraries. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Martin Nowak Source [rt/sections\_linux.d](https://github.com/dlang/druntime/blob/master/src/rt/sections_linux.d) bool **\_isRuntimeInitialized**; Boolean flag set to true while the runtime is initialized. nothrow @nogc void **initSections**(); Gets called on program startup just before GC is initialized. nothrow @nogc void **finiSections**(); Gets called on program shutdown just after GC is terminated. nothrow @nogc Array!(void[])\* **initTLSRanges**(); Called once per thread; returns array of thread local storage ranges d rt.dwarfeh rt.dwarfeh ========== Exception handling support for Dwarf-style portable exceptions. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright Source [rt/dwarfeh.d](https://github.com/dlang/druntime/blob/master/src/rt/dwarfeh.d) struct **ExceptionHeader**; Wrap the unwinder's data with our own compiler specific struct with our own data. static @nogc ExceptionHeader\* **create**(Throwable o); Allocate and initialize an ExceptionHeader. Parameters: | | | | --- | --- | | Throwable `o` | thrown object | Returns: allocated and initalized ExceptionHeader static void **free**(ExceptionHeader\* eh); Free ExceptionHeader that was created by create(). Parameters: | | | | --- | --- | | ExceptionHeader\* `eh` | ExceptionHeader to free | void **push**(); Push this onto stack of chained exceptions. static ExceptionHeader\* **pop**(); Pop and return top of chained exception stack. static ExceptionHeader\* **toExceptionHeader**(\_Unwind\_Exception\* eo); Convert from pointer to exception\_object to pointer to ExceptionHeader that it is embedded inside of. Parameters: | | | | --- | --- | | \_Unwind\_Exception\* `eo` | pointer to exception\_object field | Returns: pointer to ExceptionHeader that eo points into. Throwable **\_\_dmd\_begin\_catch**(\_Unwind\_Exception\* exceptionObject); The first thing a catch handler does is call this. Parameters: | | | | --- | --- | | \_Unwind\_Exception\* `exceptionObject` | value passed to catch handler by unwinder | Returns: object that was caught nothrow @nogc void\* **\_d\_eh\_swapContextDwarf**(void\* newContext); Called when fibers switch contexts. Parameters: | | | | --- | --- | | void\* `newContext` | stack to switch to | Returns: previous value of stack void **\_d\_throwdwarf**(Throwable o); Called by D code to throw an exception via ``` throw o; ``` Parameters: | | | | --- | --- | | Throwable `o` | Object to throw | Returns: doesn't return \_Unwind\_Reason\_Code **\_\_dmd\_personality\_v0**(int ver, \_Unwind\_Action actions, \_Unwind\_Exception\_Class exceptionClass, \_Unwind\_Exception\* exceptionObject, \_Unwind\_Context\* context); "personality" function, specific to each language. This one, of course, is specific to DMD. Parameters: | | | | --- | --- | | int `ver` | version must be 1 | | \_Unwind\_Action `actions` | bitwise OR of the 4 actions UA\_xxx. UA\_SEARCH\_PHASE means return URC\_HANDLER\_FOUND if current frame has a handler, URC\_CONTINUE\_UNWIND if not. Cannot be used with UA\_CLEANUP\_PHASE. UA\_CLEANUP\_PHASE means perform cleanup for current frame by calling nested functions and returning URC\_CONTINUE\_UNWIND. Or, set up registers and IP for Landing Pad and return URC\_INSTALL\_CONTEXT. UA\_HANDLER\_FRAME means this frame was the one with the handler in Phase 1, and now it is Phase 2 and the handler must be run. UA\_FORCE\_UNWIND means unwinding the stack for longjmp or thread cancellation. Run finally clauses, not catch clauses, finallys must end with call to Uwind\_Resume(). | | \_Unwind\_Exception\_Class `exceptionClass` | 8 byte value indicating type of thrown exception. If the low 4 bytes are "C++\0", it's a C++ exception. | | \_Unwind\_Exception\* `exceptionObject` | language specific exception information | | \_Unwind\_Context\* `context` | opaque type of unwinder state information | Returns: reason code See Also: <http://www.ucw.cz/~hubicka/papers/abi/node25.html> ClassInfo **getClassInfo**(\_Unwind\_Exception\* exceptionObject, const(ubyte)\* currentLsd); Look at the chain of inflight exceptions and pick the class type that'll be looked for in catch clauses. Parameters: | | | | --- | --- | | \_Unwind\_Exception\* `exceptionObject` | language specific exception information | | const(ubyte)\* `currentLsd` | pointer to LSDA table | Returns: class type to look for \_uleb128\_t **uLEB128**(const(ubyte)\*\* p); Decode Unsigned LEB128. Parameters: | | | | --- | --- | | const(ubyte)\*\* `p` | pointer to data pointer, \*p is updated to point past decoded value | Returns: decoded value See Also: <https://en.wikipedia.org/wiki/LEB128> \_sleb128\_t **sLEB128**(const(ubyte)\*\* p); Decode Signed LEB128. Parameters: | | | | --- | --- | | const(ubyte)\*\* `p` | pointer to data pointer, \*p is updated to point past decoded value | Returns: decoded value See Also: <https://en.wikipedia.org/wiki/LEB128> LsdaResult **scanLSDA**(const(ubyte)\* lsda, \_Unwind\_Ptr ip, \_Unwind\_Exception\_Class exceptionClass, bool cleanupsOnly, bool preferHandler, \_Unwind\_Exception\* exceptionObject, out \_Unwind\_Ptr landingPad, out int handler); Read and extract information from the LSDA (aka gcc\_except\_table section). The dmd Call Site Table is structurally different from other implementations. It is organized as nested ranges, and one ip can map to multiple ranges. The most nested candidate is selected when searched. Other implementations have one candidate per ip. Parameters: | | | | --- | --- | | const(ubyte)\* `lsda` | pointer to LSDA table | | \_Unwind\_Ptr `ip` | offset from start of function at which exception happened | | \_Unwind\_Exception\_Class `exceptionClass` | which language threw the exception | | bool `cleanupsOnly` | only look for cleanups | | bool `preferHandler` | if a handler encloses a cleanup, prefer the handler | | \_Unwind\_Exception\* `exceptionObject` | language specific exception information | | \_Unwind\_Ptr `landingPad` | set to landing pad | | int `handler` | set to index of which catch clause was matched | Returns: LsdaResult See Also: <http://reverseengineering.stackexchange.com/questions/6311/how-to-recover-the-exception-info-from-gcc-except-table-and-eh-handle-sections> <http://www.airs.com/blog/archives/464> <https://anarcheuz.github.io/2015/02/15/ELF%20internals%20part%202%20-%20exception%20handling/> int **actionTableLookup**(\_Unwind\_Exception\* exceptionObject, uint actionRecordPtr, const(ubyte)\* pActionTable, const(ubyte)\* tt, ubyte TType, \_Unwind\_Exception\_Class exceptionClass, const(ubyte)\* lsda); Look up classType in Action Table. Parameters: | | | | --- | --- | | \_Unwind\_Exception\* `exceptionObject` | language specific exception information | | uint `actionRecordPtr` | starting index in Action Table + 1 | | const(ubyte)\* `pActionTable` | pointer to start of Action Table | | const(ubyte)\* `tt` | pointer past end of Type Table | | ubyte `TType` | encoding of entries in Type Table | | \_Unwind\_Exception\_Class `exceptionClass` | which language threw the exception | | const(ubyte)\* `lsda` | pointer to LSDA table | Returns: * >=1 means the handler index of the classType * 0 means classType is not in the Action Table * <0 means corrupt enum \_Unwind\_Exception\_Class **cppExceptionClass**; C++ Support void\* **getCppPtrToThrownObject**(\_Unwind\_Exception\* exceptionObject, CppTypeInfo sti); Get Pointer to Thrown Object if type of thrown object is implicitly convertible to the catch type. Parameters: | | | | --- | --- | | \_Unwind\_Exception\* `exceptionObject` | language specific exception information | | CppTypeInfo `sti` | type of catch clause | Returns: null if not caught, pointer to thrown object if caught interface **CppTypeInfo**; Access C++ std::type\_info's virtual functions from D, being careful to not require linking with libstd++ or interfere with core.stdcpp.typeinfo. So, give it a different name. struct **CppExceptionHeader**; The C++ version of D's ExceptionHeader wrapper static CppExceptionHeader\* **toExceptionHeader**(\_Unwind\_Exception\* eo); Convert from pointer to exception\_object field to pointer to CppExceptionHeader that it is embedded inside of. Parameters: | | | | --- | --- | | \_Unwind\_Exception\* `eo` | pointer to exception\_object field | Returns: pointer to CppExceptionHeader that eo points into. d core.stdcpp.array core.stdcpp.array ================= D header file for interaction with C++ std::array. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Manu Evans Source [core/stdcpp/array.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/array.d) struct **array**(T, size\_t N); D language counterpart to C++ std::array. C++ reference: alias **size\_type** = size\_t; alias **difference\_type** = ptrdiff\_t; alias **value\_type** = T; alias **pointer** = T\*; alias **const\_pointer** = const(T)\*; this(T[N] args...); Variadic constructor void **fill**()(auto ref const(T) value); const @safe size\_type **size**(); alias **length** = size; alias **opDollar** = length; const @safe size\_type **max\_size**(); const @safe bool **empty**(); inout ref @safe inout(T) **front**(); inout ref @safe inout(T) **back**(); inout @safe inout(T)\* **data**(); inout ref @safe inout(T)[N] **as\_array**(); inout ref @safe inout(T) **at**(size\_type i); d rt.sections_solaris rt.sections\_solaris ==================== Written in the D programming language. This module provides Solaris-specific support for sections. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Martin Nowak Source [rt/sections\_solaris.d](https://github.com/dlang/druntime/blob/master/src/rt/sections_solaris.d) d std.experimental.allocator.building_blocks.ascending_page_allocator std.experimental.allocator.building\_blocks.ascending\_page\_allocator ====================================================================== Source [std/experimental/allocator/building\_blocks/ascending\_page\_allocator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/ascending_page_allocator.d) struct **AscendingPageAllocator**; `AscendingPageAllocator` is a fast and safe allocator that rounds all allocations to multiples of the system's page size. It reserves a range of virtual addresses (using `mmap` on Posix and `VirtualAlloc` on Windows) and allocates memory at consecutive virtual addresses. When a chunk of memory is requested, the allocator finds a range of virtual pages that satisfy the requested size, changing their protection to read/write using OS primitives (`mprotect` and `VirtualProtect`, respectively). The physical memory is allocated on demand, when the pages are accessed. Deallocation removes any read/write permissions from the target pages and notifies the OS to reclaim the physical memory, while keeping the virtual memory. Because the allocator does not reuse memory, any dangling references to deallocated memory will always result in deterministically crashing the process. See Also: [Simple Fast and Safe Manual Memory Management](https://microsoft.com/en-us/research/wp-content/uploads/2017/03/kedia2017mem.pdf) for the general approach. Examples: ``` import core.memory : pageSize; size_t numPages = 100; void[] buf; void[] prevBuf = null; AscendingPageAllocator a = AscendingPageAllocator(numPages * pageSize); foreach (i; 0 .. numPages) { // Allocation is rounded up to page size buf = a.allocate(pageSize - 100); writeln(buf.length); // pageSize - 100 // Allocations are served at increasing addresses if (prevBuf) writeln(prevBuf.ptr + pageSize); // buf.ptr assert(a.deallocate(buf)); prevBuf = buf; } ``` nothrow @nogc this(size\_t n); Rounds the mapping size to the next multiple of the page size and calls the OS primitive responsible for creating memory mappings: `mmap` on POSIX and `VirtualAlloc` on Windows. Parameters: | | | | --- | --- | | size\_t `n` | mapping size in bytes | nothrow @nogc size\_t **goodAllocSize**(size\_t n); Rounds the requested size to the next multiple of the page size. nothrow @nogc void **deallocate**(void[] b); Decommit all physical memory associated with the buffer given as parameter, but keep the range of virtual addresses. On POSIX systems `deallocate` calls `mmap` with `MAP\_FIXED' a second time to decommit the memory. On Windows, it uses `VirtualFree` with `MEM_DECOMMIT`. nothrow @nogc Ternary **owns**(void[] buf); Returns `Ternary.yes` if the passed buffer is inside the range of virtual adresses. Does not guarantee that the passed buffer is still valid. nothrow @nogc bool **deallocateAll**(); Removes the memory mapping causing all physical memory to be decommited and the virtual address space to be reclaimed. nothrow @nogc size\_t **getAvailableSize**(); Returns the available size for further allocations in bytes. nothrow @nogc void[] **allocate**(size\_t n); Rounds the allocation size to the next multiple of the page size. The allocation only reserves a range of virtual pages but the actual physical memory is allocated on demand, when accessing the memory. Parameters: | | | | --- | --- | | size\_t `n` | Bytes to allocate | Returns: `null` on failure or if the requested size exceeds the remaining capacity. nothrow @nogc void[] **alignedAllocate**(size\_t n, uint a); Rounds the allocation size to the next multiple of the page size. The allocation only reserves a range of virtual pages but the actual physical memory is allocated on demand, when accessing the memory. The allocated memory is aligned to the specified alignment `a`. Parameters: | | | | --- | --- | | size\_t `n` | Bytes to allocate | | uint `a` | Alignment | Returns: `null` on failure or if the requested size exceeds the remaining capacity. nothrow @nogc bool **expand**(ref void[] b, size\_t delta); If the passed buffer is not the last allocation, then `delta` can be at most the number of bytes left on the last page. Otherwise, we can expand the last allocation until the end of the virtual address range. nothrow @nogc Ternary **empty**(); Returns `Ternary.yes` if the allocator does not contain any alive objects and `Ternary.no` otherwise. struct **SharedAscendingPageAllocator**; `SharedAscendingPageAllocator` is the threadsafe version of `AscendingPageAllocator`. Examples: ``` import core.memory : pageSize; import core.thread : ThreadGroup; enum numThreads = 100; shared SharedAscendingPageAllocator a = SharedAscendingPageAllocator(pageSize * numThreads); void fun() { void[] b = a.allocate(pageSize); writeln(b.length); // pageSize assert(a.deallocate(b)); } auto tg = new ThreadGroup; foreach (i; 0 .. numThreads) { tg.create(&fun); } tg.joinAll(); ``` shared nothrow @nogc this(size\_t n); Rounds the mapping size to the next multiple of the page size and calls the OS primitive responsible for creating memory mappings: `mmap` on POSIX and `VirtualAlloc` on Windows. Parameters: | | | | --- | --- | | size\_t `n` | mapping size in bytes | shared nothrow @nogc size\_t **goodAllocSize**(size\_t n); Rounds the requested size to the next multiple of the page size. shared nothrow @nogc void **deallocate**(void[] b); Decommit all physical memory associated with the buffer given as parameter, but keep the range of virtual addresses. On POSIX systems `deallocate` calls `mmap` with `MAP\_FIXED' a second time to decommit the memory. On Windows, it uses `VirtualFree` with `MEM_DECOMMIT`. shared nothrow @nogc Ternary **owns**(void[] buf); Returns `Ternary.yes` if the passed buffer is inside the range of virtual adresses. Does not guarantee that the passed buffer is still valid. shared nothrow @nogc bool **deallocateAll**(); Removes the memory mapping causing all physical memory to be decommited and the virtual address space to be reclaimed. shared nothrow @nogc size\_t **getAvailableSize**(); Returns the available size for further allocations in bytes. shared nothrow @nogc void[] **allocate**(size\_t n); Rounds the allocation size to the next multiple of the page size. The allocation only reserves a range of virtual pages but the actual physical memory is allocated on demand, when accessing the memory. Parameters: | | | | --- | --- | | size\_t `n` | Bytes to allocate | Returns: `null` on failure or if the requested size exceeds the remaining capacity. shared nothrow @nogc void[] **alignedAllocate**(size\_t n, uint a); Rounds the allocation size to the next multiple of the page size. The allocation only reserves a range of virtual pages but the actual physical memory is allocated on demand, when accessing the memory. The allocated memory is aligned to the specified alignment `a`. Parameters: | | | | --- | --- | | size\_t `n` | Bytes to allocate | | uint `a` | Alignment | Returns: `null` on failure or if the requested size exceeds the remaining capacity. shared nothrow @nogc bool **expand**(ref void[] b, size\_t delta); If the passed buffer is not the last allocation, then `delta` can be at most the number of bytes left on the last page. Otherwise, we can expand the last allocation until the end of the virtual address range. d rt.aApply rt.aApply ========= This code handles decoding UTF strings for foreach loops. There are 6 combinations of conversions between char, wchar, and dchar, and 2 of each of those. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Walter Bright Source [rt/aApply.d](https://github.com/dlang/druntime/blob/master/src/rt/aApply.d) alias **dg\_t** = int delegate(void\*); int **\_aApplywd1**(in wchar[] aa, dg\_t dg); int **\_aApplycw1**(in char[] aa, dg\_t dg); int **\_aApplywc1**(in wchar[] aa, dg\_t dg); int **\_aApplydc1**(in dchar[] aa, dg\_t dg); int **\_aApplydw1**(in dchar[] aa, dg\_t dg); alias **dg2\_t** = int delegate(void\*, void\*); int **\_aApplywd2**(in wchar[] aa, dg2\_t dg); int **\_aApplycw2**(in char[] aa, dg2\_t dg); int **\_aApplywc2**(in wchar[] aa, dg2\_t dg); int **\_aApplydc2**(in dchar[] aa, dg2\_t dg); int **\_aApplydw2**(in dchar[] aa, dg2\_t dg); d std.compiler std.compiler ============ Identify the compiler used and its various features. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com), Alex Rønne Petersen Source [std/compiler.d](https://github.com/dlang/phobos/blob/master/std/compiler.d) immutable string **name**; Vendor specific string naming the compiler, for example: "Digital Mars D". enum **Vendor**: int; Master list of D compiler vendors. **unknown** Compiler vendor could not be detected **digitalMars** Digital Mars D (DMD) **gnu** GNU D Compiler (GDC) **llvm** LLVM D Compiler (LDC) **dotNET** D.NET **sdc** Stupid D Compiler (SDC) immutable Vendor **vendor**; Which vendor produced this compiler. immutable uint **version\_major**; immutable uint **version\_minor**; The vendor specific version number, as in version\_major.version\_minor immutable uint **D\_major**; The version of the D Programming Language Specification supported by the compiler.
programming_docs
d rt.memory rt.memory ========= This module tells the garbage collector about the static data and bss segments, so the GC can scan them for roots. It does not deal with thread local static data. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright, Sean Kelly Source [rt/memory.d](https://github.com/dlang/druntime/blob/master/src/rt/memory.d) d core.stdc.limits core.stdc.limits ================ D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<limits.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/limits.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly Source [core/stdc/limits.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/limits.d) Standards: ISO/IEC 9899:1999 (E) enum int **CHAR\_BIT**; enum byte **SCHAR\_MIN**; enum byte **SCHAR\_MAX**; enum ubyte **UCHAR\_MAX**; enum char **CHAR\_MIN**; enum char **CHAR\_MAX**; enum int **MB\_LEN\_MAX**; enum short **SHRT\_MIN**; enum short **SHRT\_MAX**; enum ushort **USHRT\_MAX**; enum int **INT\_MIN**; enum int **INT\_MAX**; enum uint **UINT\_MAX**; enum long **LONG\_MIN**; enum long **LONG\_MAX**; enum ulong **ULONG\_MAX**; enum long **LLONG\_MIN**; enum long **LLONG\_MAX**; enum ulong **ULLONG\_MAX**; enum int **MAX\_CANON**; enum int **MAX\_INPUT**; enum int **NAME\_MAX**; enum int **PATH\_MAX**; enum int **PIPE\_BUF**; d std.typecons std.typecons ============ This module implements a variety of type constructors, i.e., templates that allow construction of new, useful general-purpose types. | Category | Functions | | --- | --- | | Tuple | [`isTuple`](#isTuple) [`Tuple`](#Tuple) [`tuple`](#tuple) [`reverse`](#reverse) | | Flags | [`BitFlags`](#BitFlags) [`isBitFlagEnum`](#isBitFlagEnum) [`Flag`](#Flag) [`No`](#No) [`Yes`](#Yes) | | Memory allocation | [`RefCounted`](#RefCounted) [`refCounted`](#refCounted) [`RefCountedAutoInitialize`](#RefCountedAutoInitialize) [`scoped`](#scoped) [`Unique`](#Unique) | | Code generation | [`AutoImplement`](#AutoImplement) [`BlackHole`](#BlackHole) [`generateAssertTrap`](#generateAssertTrap) [`generateEmptyFunction`](#generateEmptyFunction) [`WhiteHole`](#WhiteHole) | | Nullable | [`Nullable`](#Nullable) [`nullable`](#nullable) [`NullableRef`](#NullableRef) [`nullableRef`](#nullableRef) | | Proxies | [`Proxy`](#Proxy) [`rebindable`](#rebindable) [`Rebindable`](#Rebindable) [`ReplaceType`](#ReplaceType) [`unwrap`](#unwrap) [`wrap`](#wrap) | | Types | [`alignForSize`](#alignForSize) [`Ternary`](#Ternary) [`Typedef`](#Typedef) [`TypedefType`](#TypedefType) [`UnqualRef`](#UnqualRef) | License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Source [std/typecons.d](https://github.com/dlang/phobos/blob/master/std/typecons.d) Authors: [Andrei Alexandrescu](http://erdani.org), [Bartosz Milewski](http://bartoszmilewski.wordpress.com), Don Clugston, Shin Fujishiro, Kenji Hara Examples: ``` // value tuples alias Coord = Tuple!(int, "x", int, "y", int, "z"); Coord c; c[1] = 1; // access by index c.z = 1; // access by given name writeln(c); // Coord(0, 1, 1) // names can be omitted alias DicEntry = Tuple!(string, string); // tuples can also be constructed on instantiation writeln(tuple(2, 3, 4)[1]); // 3 // construction on instantiation works with names too writeln(tuple!("x", "y", "z")(2, 3, 4).y); // 3 // Rebindable references to const and immutable objects { class Widget { void foo() const @safe {} } const w1 = new Widget, w2 = new Widget; w1.foo(); // w1 = w2 would not work; can't rebind const object auto r = Rebindable!(const Widget)(w1); // invoke method as if r were a Widget object r.foo(); // rebind r to refer to another object r = w2; } ``` struct **Unique**(T); Encapsulates unique ownership of a resource. When a `Unique!T` goes out of scope it will call `destroy` on the resource `T` that it manages, unless it is transferred. One important consequence of `destroy` is that it will call the destructor of the resource `T`. GC-managed references are not guaranteed to be valid during a destructor call, but other members of `T`, such as file handles or pointers to `malloc` memory, will still be valid during the destructor call. This allows the resource `T` to deallocate or clean up any non-GC resources. If it is desirable to persist a `Unique!T` outside of its original scope, then it can be transferred. The transfer can be explicit, by calling `release`, or implicit, when returning Unique from a function. The resource `T` can be a polymorphic class object or instance of an interface, in which case Unique behaves polymorphically too. If `T` is a value type, then `Unique!T` will be implemented as a reference to a `T`. Examples: ``` static struct S { int i; this(int i){this.i = i;} } Unique!S produce() { // Construct a unique instance of S on the heap Unique!S ut = new S(5); // Implicit transfer of ownership return ut; } // Borrow a unique resource by ref void increment(ref Unique!S ur) { ur.i++; } void consume(Unique!S u2) { writeln(u2.i); // 6 // Resource automatically deleted here } Unique!S u1; assert(u1.isEmpty); u1 = produce(); increment(u1); writeln(u1.i); // 6 //consume(u1); // Error: u1 is not copyable // Transfer ownership of the resource consume(u1.release); assert(u1.isEmpty); ``` alias **RefT** = T; Represents a reference to `T`. Resolves to `T*` if `T` is a value type. Unique!T **create**(A...)(auto ref A args) Constraints: if (\_\_traits(compiles, new T(args))); Allows safe construction of `Unique`. It creates the resource and guarantees unique ownership of it (unless `T` publishes aliases of `this`). Note Nested structs/classes cannot be created. Parameters: | | | | --- | --- | | A `args` | Arguments to pass to `T`'s constructor. ``` static class C {} auto u = Unique!(C).create(); ``` | this(RefT p); Constructor that takes an rvalue. It will ensure uniqueness, as long as the rvalue isn't just a view on an lvalue (e.g., a cast). Typical usage: ``` Unique!Foo f = new Foo; ``` this(ref RefT p); Constructor that takes an lvalue. It nulls its source. The nulling will ensure uniqueness as long as there are no previous aliases to the source. this(U)(Unique!U u) Constraints: if (is(u.RefT : RefT)); Constructor that takes a `Unique` of a type that is convertible to our type. Typically used to transfer a `Unique` rvalue of derived type to a `Unique` of base type. Example ``` class C : Object {} Unique!C uc = new C; Unique!Object uo = uc.release; ``` void **opAssign**(U)(Unique!U u) Constraints: if (is(u.RefT : RefT)); Transfer ownership from a `Unique` of a type that is convertible to our type. const @property bool **isEmpty**(); Returns whether the resource exists. Unique **release**(); Transfer ownership to a `Unique` rvalue. Nullifies the current contents. Same as calling std.algorithm.move on it. struct **Tuple**(Specs...) if (distinctFieldNames!Specs); Tuple of values, for example `Tuple!(int, string)` is a record that stores an `int` and a `string`. `Tuple` can be used to bundle values together, notably when returning multiple values from a function. If `obj` is a `Tuple`, the individual members are accessible with the syntax `obj[0]` for the first field, `obj[1]` for the second, and so on. See Also: [`tuple`](#tuple). Parameters: | | | | --- | --- | | Specs | A list of types (and optionally, member names) that the `Tuple` contains. | Examples: ``` Tuple!(int, int) point; // assign coordinates point[0] = 5; point[1] = 6; // read coordinates auto x = point[0]; auto y = point[1]; ``` Examples: `Tuple` members can be named. It is legal to mix named and unnamed members. The method above is still applicable to all fields. ``` alias Entry = Tuple!(int, "index", string, "value"); Entry e; e.index = 4; e.value = "Hello"; writeln(e[1]); // "Hello" writeln(e[0]); // 4 ``` Examples: A `Tuple` with named fields is a distinct type from a `Tuple` with unnamed fields, i.e. each naming imparts a separate type for the `Tuple`. Two `Tuple`s differing in naming only are still distinct, even though they might have the same structure. ``` Tuple!(int, "x", int, "y") point1; Tuple!(int, int) point2; assert(!is(typeof(point1) == typeof(point2))); ``` Examples: Use tuples as ranges ``` import std.algorithm.iteration : sum; import std.range : only; auto t = tuple(1, 2); writeln(t.expand.only.sum); // 3 ``` Examples: Concatenate tuples ``` import std.meta : AliasSeq; auto t = tuple(1, "2") ~ tuple(ushort(42), true); static assert(is(t.Types == AliasSeq!(int, string, ushort, bool))); writeln(t[1]); // "2" writeln(t[2]); // 42 writeln(t[3]); // true ``` alias **Types** = staticMap!(extractType, fieldSpecs); The types of the `Tuple`'s components. alias **fieldNames** = staticMap!(extractName, fieldSpecs); The names of the `Tuple`'s components. Unnamed fields have empty names. Examples: ``` import std.meta : AliasSeq; alias Fields = Tuple!(int, "id", string, float); static assert(Fields.fieldNames == AliasSeq!("id", "", "")); ``` Types **expand**; Use `t.expand` for a `Tuple` `t` to expand it into its components. The result of `expand` acts as if the `Tuple`'s components were listed as a list of values. (Ordinarily, a `Tuple` acts as a single value.) Examples: ``` auto t1 = tuple(1, " hello ", 'a'); writeln(t1.toString()); // `Tuple!(int, string, char)(1, " hello ", 'a')` void takeSeveralTypes(int n, string s, bool b) { assert(n == 4 && s == "test" && b == false); } auto t2 = tuple(4, "test", false); //t.expand acting as a list of values takeSeveralTypes(t2.expand); ``` this(Types values); Constructor taking one value for each field. Parameters: | | | | --- | --- | | Types `values` | A list of values that are either the same types as those given by the `Types` field of this `Tuple`, or can implicitly convert to those types. They must be in the same order as they appear in `Types`. | Examples: ``` alias ISD = Tuple!(int, string, double); auto tup = ISD(1, "test", 3.2); writeln(tup.toString()); // `Tuple!(int, string, double)(1, "test", 3.2)` ``` this(U, size\_t n)(U[n] values) Constraints: if (n == Types.length && allSatisfy!(isBuildableFrom!U, Types)); Constructor taking a compatible array. Parameters: | | | | --- | --- | | U[n] `values` | A compatible static array to build the `Tuple` from. Array slices are not supported. | Examples: ``` int[2] ints; Tuple!(int, int) t = ints; ``` this(U)(U another) Constraints: if (areBuildCompatibleTuples!(typeof(this), U)); Constructor taking a compatible `Tuple`. Two `Tuple`s are compatible **iff** they are both of the same length, and, for each type `T` on the left-hand side, the corresponding type `U` on the right-hand side can implicitly convert to `T`. Parameters: | | | | --- | --- | | U `another` | A compatible `Tuple` to build from. Its type must be compatible with the target `Tuple`'s type. | Examples: ``` alias IntVec = Tuple!(int, int, int); alias DubVec = Tuple!(double, double, double); IntVec iv = tuple(1, 1, 1); //Ok, int can implicitly convert to double DubVec dv = iv; //Error: double cannot implicitly convert to int //IntVec iv2 = dv; ``` bool **opEquals**(R)(R rhs) Constraints: if (areCompatibleTuples!(typeof(this), R, "==")); const bool **opEquals**(R)(R rhs) Constraints: if (areCompatibleTuples!(typeof(this), R, "==")); bool **opEquals**(R...)(auto ref R rhs) Constraints: if (R.length > 1 && areCompatibleTuples!(typeof(this), Tuple!R, "==")); Comparison for equality. Two `Tuple`s are considered equal **iff** they fulfill the following criteria: * Each `Tuple` is the same length. * For each type `T` on the left-hand side and each type `U` on the right-hand side, values of type `T` can be compared with values of type `U`. * For each value `v1` on the left-hand side and each value `v2` on the right-hand side, the expression `v1 == v2` is true. Parameters: | | | | --- | --- | | R `rhs` | The `Tuple` to compare against. It must meeting the criteria for comparison between `Tuple`s. | Returns: true if both `Tuple`s are equal, otherwise false. Examples: ``` Tuple!(int, string) t1 = tuple(1, "test"); Tuple!(double, string) t2 = tuple(1.0, "test"); //Ok, int can be compared with double and //both have a value of 1 writeln(t1); // t2 ``` int **opCmp**(R)(R rhs) Constraints: if (areCompatibleTuples!(typeof(this), R, "<")); const int **opCmp**(R)(R rhs) Constraints: if (areCompatibleTuples!(typeof(this), R, "<")); Comparison for ordering. Parameters: | | | | --- | --- | | R `rhs` | The `Tuple` to compare against. It must meet the criteria for comparison between `Tuple`s. | Returns: For any values `v1` on the right-hand side and `v2` on the left-hand side: * A negative integer if the expression `v1 < v2` is true. * A positive integer if the expression `v1 > v2` is true. * 0 if the expression `v1 == v2` is true. Examples: The first `v1` for which `v1 > v2` is true determines the result. This could lead to unexpected behaviour. ``` auto tup1 = tuple(1, 1, 1); auto tup2 = tuple(1, 100, 100); assert(tup1 < tup2); //Only the first result matters for comparison tup1[0] = 2; assert(tup1 > tup2); ``` auto **opBinary**(string op, T)(auto ref T t) Constraints: if (op == "~" && !(is(T : U[], U) && isTuple!U)); auto **opBinaryRight**(string op, T)(auto ref T t) Constraints: if (op == "~" && !(is(T : U[], U) && isTuple!U)); Concatenate Tuples. Tuple concatenation is only allowed if all named fields are distinct (no named field of this tuple occurs in `t` and no named field of `t` occurs in this tuple). Parameters: | | | | --- | --- | | T `t` | The `Tuple` to concatenate with | Returns: A concatenation of this tuple and `t` ref Tuple **opAssign**(R)(auto ref R rhs) Constraints: if (areCompatibleTuples!(typeof(this), R, "=")); Assignment from another `Tuple`. Parameters: | | | | --- | --- | | R `rhs` | The source `Tuple` to assign from. Each element of the source `Tuple` must be implicitly assignable to each respective element of the target `Tuple`. | inout ref auto **rename**(names...)() return Constraints: if (names.length == 0 || allSatisfy!(isSomeString, typeof(names))); Renames the elements of a [`Tuple`](#Tuple). `rename` uses the passed `names` and returns a new [`Tuple`](#Tuple) using these names, with the content unchanged. If fewer names are passed than there are members of the [`Tuple`](#Tuple) then those trailing members are unchanged. An empty string will remove the name for that member. It is an compile-time error to pass more names than there are members of the [`Tuple`](#Tuple). Examples: ``` auto t0 = tuple(4, "hello"); auto t0Named = t0.rename!("val", "tag"); writeln(t0Named.val); // 4 writeln(t0Named.tag); // "hello" Tuple!(float, "dat", size_t[2], "pos") t1; t1.pos = [2, 1]; auto t1Named = t1.rename!"height"; t1Named.height = 3.4f; writeln(t1Named.height); // 3.4f writeln(t1Named.pos); // [2, 1] t1Named.rename!"altitude".altitude = 5; writeln(t1Named.height); // 5 Tuple!(int, "a", int, int, "c") t2; t2 = tuple(3,4,5); auto t2Named = t2.rename!("", "b"); // "a" no longer has a name static assert(!__traits(hasMember, typeof(t2Named), "a")); writeln(t2Named[0]); // 3 writeln(t2Named.b); // 4 writeln(t2Named.c); // 5 // not allowed to specify more names than the tuple has members static assert(!__traits(compiles, t2.rename!("a","b","c","d"))); // use it in a range pipeline import std.range : iota, zip; import std.algorithm.iteration : map, sum; auto res = zip(iota(1, 4), iota(10, 13)) .map!(t => t.rename!("a", "b")) .map!(t => t.a * t.b) .sum; writeln(res); // 68 const tup = Tuple!(int, "a", int, "b")(2, 3); const renamed = tup.rename!("c", "d"); writeln(renamed.c + renamed.d); // 5 ``` inout ref auto **rename**(alias translate)() Constraints: if (is(typeof(translate) : V[K], V, K) && isSomeString!V && (isSomeString!K || is(K : size\_t))); Overload of [`rename`](#rename) that takes an associative array `translate` as a template parameter, where the keys are either the names or indices of the members to be changed and the new names are the corresponding values. Every key in `translate` must be the name of a member of the [`tuple`](#tuple). The same rules for empty strings apply as for the variadic template overload of [`rename`](#rename). Examples: ``` //replacing names by their current name Tuple!(float, "dat", size_t[2], "pos") t1; t1.pos = [2, 1]; auto t1Named = t1.rename!(["dat": "height"]); t1Named.height = 3.4; writeln(t1Named.pos); // [2, 1] t1Named.rename!(["height": "altitude"]).altitude = 5; writeln(t1Named.height); // 5 Tuple!(int, "a", int, "b") t2; t2 = tuple(3, 4); auto t2Named = t2.rename!(["a": "b", "b": "c"]); writeln(t2Named.b); // 3 writeln(t2Named.c); // 4 const t3 = Tuple!(int, "a", int, "b")(3, 4); const t3Named = t3.rename!(["a": "b", "b": "c"]); writeln(t3Named.b); // 3 writeln(t3Named.c); // 4 ``` Examples: ``` //replace names by their position Tuple!(float, "dat", size_t[2], "pos") t1; t1.pos = [2, 1]; auto t1Named = t1.rename!([0: "height"]); t1Named.height = 3.4; writeln(t1Named.pos); // [2, 1] t1Named.rename!([0: "altitude"]).altitude = 5; writeln(t1Named.height); // 5 Tuple!(int, "a", int, "b", int, "c") t2; t2 = tuple(3, 4, 5); auto t2Named = t2.rename!([0: "c", 2: "a"]); writeln(t2Named.a); // 5 writeln(t2Named.b); // 4 writeln(t2Named.c); // 3 ``` inout @property ref @trusted inout(Tuple!(sliceSpecs!(from, to))) **slice**(size\_t from, size\_t to)() Constraints: if (from <= to && (to <= Types.length)); Takes a slice by-reference of this `Tuple`. Parameters: | | | | --- | --- | | from | A `size_t` designating the starting position of the slice. | | to | A `size_t` designating the ending position (exclusive) of the slice. | Returns: A new `Tuple` that is a slice from `[from, to)` of the original. It has the same types and values as the range `[from, to)` in the original. Examples: ``` Tuple!(int, string, float, double) a; a[1] = "abc"; a[2] = 4.5; auto s = a.slice!(1, 3); static assert(is(typeof(s) == Tuple!(string, float))); assert(s[0] == "abc" && s[1] == 4.5); // https://issues.dlang.org/show_bug.cgi?id=15645 Tuple!(int, short, bool, double) b; static assert(!__traits(compiles, b.slice!(2, 4))); ``` const nothrow @safe size\_t **toHash**(); Creates a hash of this `Tuple`. Returns: A `size_t` representing the hash of this `Tuple`. const string **toString**()(); Converts to string. Returns: The string representation of this `Tuple`. const void **toString**(DG)(scope DG sink); const void **toString**(DG, Char)(scope DG sink, ref scope const FormatSpec!Char fmt); Formats `Tuple` with either `%s`, `%(inner%)` or `%(inner%|sep%)`. Formats supported by Tuple| **Format** | **Description** | | `%s` | Format like `Tuple!(types)(elements formatted with %s each)`. | | `%(inner%)` | The format `inner` is applied the expanded `Tuple`, so it may contain as many formats as the `Tuple` has fields. | | `%(inner%|sep%)` | The format `inner` is one format, that is applied on all fields of the `Tuple`. The inner format must be compatible to all of them. | Parameters: | | | | --- | --- | | DG `sink` | A `char` accepting delegate | | FormatSpec!Char `fmt` | A [`std.format.FormatSpec`](std_format#FormatSpec) | Examples: ``` import std.format : format; Tuple!(int, double)[3] tupList = [ tuple(1, 1.0), tuple(2, 4.0), tuple(3, 9.0) ]; // Default format writeln(format("%s", tuple("a", 1))); // `Tuple!(string, int)("a", 1)` // One Format for each individual component writeln(format("%(%#x v %.4f w %#x%)", tuple(1, 1.0, 10))); // `0x1 v 1.0000 w 0xa` writeln(format("%#x v %.4f w %#x", tuple(1, 1.0, 10).expand)); // `0x1 v 1.0000 w 0xa` // One Format for all components // `>abc< & >1< & >2.3< & >[4, 5]<` writeln(format("%(>%s<%| & %)", tuple("abc", 1, 2.3, [4, 5]))); // Array of Tuples writeln(format("%(%(f(%d) = %.1f%); %)", tupList)); // `f(1) = 1.0; f(2) = 4.0; f(3) = 9.0` ``` Examples: ``` import std.exception : assertThrown; import std.format : format, FormatException; // Error: %( %) missing. assertThrown!FormatException( format("%d, %f", tuple(1, 2.0)) == `1, 2.0` ); // Error: %( %| %) missing. assertThrown!FormatException( format("%d", tuple(1, 2)) == `1, 2` ); // Error: %d inadequate for double assertThrown!FormatException( format("%(%d%|, %)", tuple(1, 2.0)) == `1, 2.0` ); ``` auto **reverse**(T)(T t) Constraints: if (isTuple!T); Creates a copy of a [`Tuple`](#Tuple) with its fields in reverse order. Parameters: | | | | --- | --- | | T `t` | The `Tuple` to copy. | Returns: A new `Tuple`. Examples: ``` auto tup = tuple(1, "2"); writeln(tup.reverse); // tuple("2", 1) ``` template **tuple**(Names...) Constructs a [`Tuple`](#Tuple) object instantiated and initialized according to the given arguments. Parameters: | | | | --- | --- | | Names | An optional list of strings naming each successive field of the `Tuple` or a list of types that the elements are being casted to. For a list of names, each name matches up with the corresponding field given by `Args`. A name does not have to be provided for every field, but as the names must proceed in order, it is not possible to skip one field and name the next after it. For a list of types, there must be exactly as many types as parameters. | Examples: ``` auto value = tuple(5, 6.7, "hello"); writeln(value[0]); // 5 writeln(value[1]); // 6.7 writeln(value[2]); // "hello" // Field names can be provided. auto entry = tuple!("index", "value")(4, "Hello"); writeln(entry.index); // 4 writeln(entry.value); // "Hello" ``` auto **tuple**(Args...)(Args args); Parameters: | | | | --- | --- | | Args `args` | Values to initialize the `Tuple` with. The `Tuple`'s type will be inferred from the types of the values given. | Returns: A new `Tuple` with its type inferred from the arguments given. enum auto **isTuple**(T); Returns `true` if and only if `T` is an instance of `std.typecons.Tuple`. Parameters: | | | | --- | --- | | T | The type to check. | Returns: true if `T` is a `Tuple` type, false otherwise. Examples: ``` static assert(isTuple!(Tuple!())); static assert(isTuple!(Tuple!(int))); static assert(isTuple!(Tuple!(int, real, string))); static assert(isTuple!(Tuple!(int, "x", real, "y"))); static assert(isTuple!(Tuple!(int, Tuple!(real), string))); ``` template **Rebindable**(T) if (is(T == class) || is(T == interface) || isDynamicArray!T || isAssociativeArray!T) `Rebindable!(T)` is a simple, efficient wrapper that behaves just like an object of type `T`, except that you can reassign it to refer to another object. For completeness, `Rebindable!(T)` aliases itself away to `T` if `T` is a non-const object type. You may want to use `Rebindable` when you want to have mutable storage referring to `const` objects, for example an array of references that must be sorted in place. `Rebindable` does not break the soundness of D's type system and does not incur any of the risks usually associated with `cast`. Parameters: | | | | --- | --- | | T | An object, interface, array slice type, or associative array type. | Examples: Regular `const` object references cannot be reassigned. ``` class Widget { int x; int y() @safe const { return x; } } const a = new Widget; // Fine a.y(); // error! can't modify const a // a.x = 5; // error! can't modify const a // a = new Widget; ``` Examples: However, `Rebindable!(Widget)` does allow reassignment, while otherwise behaving exactly like a `const Widget`. ``` class Widget { int x; int y() const @safe { return x; } } auto a = Rebindable!(const Widget)(new Widget); // Fine a.y(); // error! can't modify const a // a.x = 5; // Fine a = new Widget; ``` Rebindable!T **rebindable**(T)(T obj) Constraints: if (is(T == class) || is(T == interface) || isDynamicArray!T || isAssociativeArray!T); Convenience function for creating a `Rebindable` using automatic type inference. Parameters: | | | | --- | --- | | T `obj` | A reference to an object, interface, associative array, or an array slice to initialize the `Rebindable` with. | Returns: A newly constructed `Rebindable` initialized with the given reference. Examples: ``` class C { int payload; this(int p) { payload = p; } } const c = new C(1); auto c2 = c.rebindable; writeln(c2.payload); // 1 // passing Rebindable to rebindable c2 = c2.rebindable; c2 = new C(2); writeln(c2.payload); // 2 const c3 = c2.get; writeln(c3.payload); // 2 ``` Rebindable!T **rebindable**(T)(Rebindable!T obj); This function simply returns the `Rebindable` object passed in. It's useful in generic programming cases when a given object may be either a regular `class` or a `Rebindable`. Parameters: | | | | --- | --- | | Rebindable!T `obj` | An instance of Rebindable!T. | Returns: `obj` without any modification. Examples: ``` class C { int payload; this(int p) { payload = p; } } const c = new C(1); auto c2 = c.rebindable; writeln(c2.payload); // 1 // passing Rebindable to rebindable c2 = c2.rebindable; writeln(c2.payload); // 1 ``` template **UnqualRef**(T) if (is(T == class) || is(T == interface)) Similar to `Rebindable!(T)` but strips all qualifiers from the reference as opposed to just constness / immutability. Primary intended use case is with shared (having thread-local reference to shared class data) Parameters: | | | | --- | --- | | T | A class or interface type. | Examples: ``` class Data {} static shared(Data) a; static UnqualRef!(shared Data) b; import core.thread; auto thread = new core.thread.Thread({ a = new shared Data(); b = new shared Data(); }); thread.start(); thread.join(); assert(a !is null); assert(b is null); ``` string **alignForSize**(E...)(const char[][] names...); Order the provided members to minimize size while preserving alignment. Alignment is not always optimal for 80-bit reals, nor for structs declared as align(1). Parameters: | | | | --- | --- | | E | A list of the types to be aligned, representing fields of an aggregate such as a `struct` or `class`. | | char[][] `names` | The names of the fields that are to be aligned. | Returns: A string to be mixed in to an aggregate, such as a `struct` or `class`. Examples: ``` struct Banner { mixin(alignForSize!(byte[6], double)(["name", "height"])); } ``` struct **Nullable**(T); auto **nullable**(T)(T t); Defines a value paired with a distinctive "null" state that denotes the absence of a value. If default constructed, a `Nullable!T` object starts in the null state. Assigning it renders it non-null. Calling `nullify` can nullify it again. Practically `Nullable!T` stores a `T` and a `bool`. Examples: ``` struct CustomerRecord { string name; string address; int customerNum; } Nullable!CustomerRecord getByName(string name) { //A bunch of hairy stuff return Nullable!CustomerRecord.init; } auto queryResult = getByName("Doe, John"); if (!queryResult.isNull) { //Process Mr. Doe's customer record auto address = queryResult.get.address; auto customerNum = queryResult.get.customerNum; //Do some things with this customer's info } else { //Add the customer to the database } ``` Examples: ``` import std.exception : assertThrown; auto a = 42.nullable; assert(!a.isNull); writeln(a.get); // 42 a.nullify(); assert(a.isNull); assertThrown!Throwable(a.get); ``` inout this(inout T value); Constructor initializing `this` with `value`. Parameters: | | | | --- | --- | | T `value` | The value to initialize this `Nullable` with. | const bool **opEquals**()(auto ref const(typeof(this)) rhs); const bool **opEquals**(U)(auto ref const(U) rhs) Constraints: if (!is(U : typeof(this)) && is(typeof(this.get == rhs))); If they are both null, then they are equal. If one is null and the other is not, then they are not equal. If they are both non-null, then they are equal if their values are equal. Examples: ``` Nullable!int empty; Nullable!int a = 42; Nullable!int b = 42; Nullable!int c = 27; writeln(empty); // empty writeln(empty); // Nullable!int.init assert(empty != a); assert(empty != b); assert(empty != c); writeln(a); // b assert(a != c); assert(empty != 42); writeln(a); // 42 assert(c != 42); ``` string **toString**(); const string **toString**(); void **toString**(W)(ref W writer, ref scope const FormatSpec!char fmt) Constraints: if (isOutputRange!(W, char)); const void **toString**(W)(ref W writer, ref scope const FormatSpec!char fmt) Constraints: if (isOutputRange!(W, char)); Gives the string `"Nullable.null"` if `isNull` is `true`. Otherwise, the result is equivalent to calling [`std.format.formattedWrite`](std_format#formattedWrite) on the underlying value. Parameters: | | | | --- | --- | | W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) | | FormatSpec!char `fmt` | A [`std.format.FormatSpec`](std_format#FormatSpec) which is used to represent the value if this Nullable is not null | Returns: A `string` if `writer` and `fmt` are not set; `void` otherwise. const pure nothrow @property @safe bool **isNull**(); Check if `this` is in the null state. Returns: true **iff** `this` is in the null state, otherwise false. Examples: ``` Nullable!int ni; assert(ni.isNull); ni = 0; assert(!ni.isNull); ``` void **nullify**()(); Forces `this` to the null state. Examples: ``` Nullable!int ni = 0; assert(!ni.isNull); ni.nullify(); assert(ni.isNull); ``` void **opAssign**()(T value); Assigns `value` to the internally-held state. If the assignment succeeds, `this` becomes non-null. Parameters: | | | | --- | --- | | T `value` | A value of type `T` to assign to this `Nullable`. | void **opAssign**()(Nullable!T value); If value is null, sets this to null, otherwise assigns `value.get` to the internally-held state. If the assignment succeeds, `this` becomes non-null. Parameters: | | | | --- | --- | | Nullable!T `value` | A value of type `Nullable!T` to assign to this `Nullable`. | Examples: If this `Nullable` wraps a type that already has a null value (such as a pointer), then assigning the null value to this `Nullable` is no different than assigning any other value of type `T`, and the resulting code will look very strange. It is strongly recommended that this be avoided by instead using the version of `Nullable` that takes an additional `nullValue` template argument. ``` //Passes Nullable!(int*) npi; assert(npi.isNull); //Passes?! npi = null; assert(!npi.isNull); ``` inout pure nothrow @property ref @safe inout(T) **get**(); inout pure nothrow @property @safe inout(T) **get**()(inout(T) fallback); inout pure nothrow @property @safe auto **get**(U)(inout(U) fallback); Gets the value if not null. If `this` is in the null state, and the optional parameter `fallback` was provided, it will be returned. Without `fallback`, calling `get` with a null state is invalid. When the fallback type is different from the Nullable type, `get(T)` returns the common type. Parameters: | | | | --- | --- | | inout(T) `fallback` | the value to return in case the `Nullable` is null. | Returns: The value held internally by this `Nullable`. struct **Nullable**(T, T nullValue); auto **nullable**(alias nullValue, T)(T t) Constraints: if (is(typeof(nullValue) == T)); Just like `Nullable!T`, except that the null state is defined as a particular value. For example, `Nullable!(uint, uint.max)` is an `uint` that sets aside the value `uint.max` to denote a null state. `Nullable!(T, nullValue)` is more storage-efficient than `Nullable!T` because it does not need to store an extra `bool`. Parameters: | | | | --- | --- | | T | The wrapped type for which Nullable provides a null value. | | nullValue | The null value which denotes the null state of this `Nullable`. Must be of type `T`. | Examples: ``` Nullable!(size_t, size_t.max) indexOf(string[] haystack, string needle) { //Find the needle, returning -1 if not found return Nullable!(size_t, size_t.max).init; } void sendLunchInvite(string name) { } //It's safer than C... auto coworkers = ["Jane", "Jim", "Marry", "Fred"]; auto pos = indexOf(coworkers, "Bob"); if (!pos.isNull) { //Send Bob an invitation to lunch sendLunchInvite(coworkers[pos]); } else { //Bob not found; report the error } //And there's no overhead static assert(Nullable!(size_t, size_t.max).sizeof == size_t.sizeof); ``` Examples: ``` import std.exception : assertThrown; Nullable!(int, int.min) a; assert(a.isNull); assertThrown!Throwable(a.get); a = 5; assert(!a.isNull); writeln(a); // 5 static assert(a.sizeof == int.sizeof); ``` Examples: ``` auto a = nullable!(int.min)(8); writeln(a); // 8 a.nullify(); assert(a.isNull); ``` this(T value); Constructor initializing `this` with `value`. Parameters: | | | | --- | --- | | T `value` | The value to initialize this `Nullable` with. | const @property bool **isNull**(); Check if `this` is in the null state. Returns: true **iff** `this` is in the null state, otherwise false. Examples: ``` Nullable!(int, -1) ni; //Initialized to "null" state assert(ni.isNull); ni = 0; assert(!ni.isNull); ``` void **nullify**()(); Forces `this` to the null state. Examples: ``` Nullable!(int, -1) ni = 0; assert(!ni.isNull); ni = -1; assert(ni.isNull); ``` void **opAssign**()(T value); Assigns `value` to the internally-held state. If the assignment succeeds, `this` becomes non-null. No null checks are made. Note that the assignment may leave `this` in the null state. Parameters: | | | | --- | --- | | T `value` | A value of type `T` to assign to this `Nullable`. If it is `nullvalue`, then the internal state of this `Nullable` will be set to null. | Examples: If this `Nullable` wraps a type that already has a null value (such as a pointer), and that null value is not given for `nullValue`, then assigning the null value to this `Nullable` is no different than assigning any other value of type `T`, and the resulting code will look very strange. It is strongly recommended that this be avoided by using `T`'s "built in" null value for `nullValue`. ``` //Passes enum nullVal = cast(int*) 0xCAFEBABE; Nullable!(int*, nullVal) npi; assert(npi.isNull); //Passes?! npi = null; assert(!npi.isNull); ``` inout @property ref inout(T) **get**(); Gets the value. `this` must not be in the null state. This function is also called for the implicit conversion to `T`. Preconditions `isNull` must be `false`. Returns: The value held internally by this `Nullable`. Examples: ``` import std.exception : assertThrown, assertNotThrown; Nullable!(int, -1) ni; //`get` is implicitly called. Will throw //an error in non-release mode assertThrown!Throwable(ni == 0); ni = 0; assertNotThrown!Throwable(ni == 0); ``` template **apply**(alias fun) Unpacks the content of a `Nullable`, performs an operation and packs it again. Does nothing if isNull. When called on a `Nullable`, `apply` will unpack the value contained in the `Nullable`, pass it to the function you provide and wrap the result in another `Nullable` (if necessary). If the `Nullable` is null, `apply` will return null itself. Parameters: | | | | --- | --- | | T t | a `Nullable` | | fun | a function operating on the content of the nullable | Returns: `fun(t.get).nullable` if `!t.isNull`, else `Nullable.init`. See also: [The `Maybe` monad](https://en.wikipedia.org/wiki/Monad_(functional_programming)#The_Maybe_monad) Examples: ``` alias toFloat = i => cast(float) i; Nullable!int sample; // apply(null) results in a null `Nullable` of the function's return type. Nullable!float f = sample.apply!toFloat; assert(sample.isNull && f.isNull); sample = 3; // apply(non-null) calls the function and wraps the result in a `Nullable`. f = sample.apply!toFloat; assert(!sample.isNull && !f.isNull); writeln(f.get); // 3.0f ``` Examples: ``` alias greaterThree = i => (i > 3) ? i.nullable : Nullable!(typeof(i)).init; Nullable!int sample; // when the function already returns a `Nullable`, that `Nullable` is not wrapped. auto result = sample.apply!greaterThree; assert(sample.isNull && result.isNull); // The function may decide to return a null `Nullable`. sample = 3; result = sample.apply!greaterThree; assert(!sample.isNull && result.isNull); // Or it may return a value already wrapped in a `Nullable`. sample = 4; result = sample.apply!greaterThree; assert(!sample.isNull && !result.isNull); writeln(result.get); // 4 ``` struct **NullableRef**(T); auto **nullableRef**(T)(T\* t); Just like `Nullable!T`, except that the object refers to a value sitting elsewhere in memory. This makes assignments overwrite the initially assigned value. Internally `NullableRef!T` only stores a pointer to `T` (i.e., `Nullable!T.sizeof == (T*).sizeof`). Examples: ``` import std.exception : assertThrown; int x = 5, y = 7; auto a = nullableRef(&x); assert(!a.isNull); writeln(a); // 5 writeln(x); // 5 a = 42; writeln(x); // 42 assert(!a.isNull); writeln(a); // 42 a.nullify(); writeln(x); // 42 assert(a.isNull); assertThrown!Throwable(a.get); assertThrown!Throwable(a = 71); a.bind(&y); writeln(a); // 7 y = 135; writeln(a); // 135 ``` pure nothrow @safe this(T\* value); Constructor binding `this` to `value`. Parameters: | | | | --- | --- | | T\* `value` | The value to bind to. | pure nothrow @safe void **bind**(T\* value); Binds the internal state to `value`. Parameters: | | | | --- | --- | | T\* `value` | A pointer to a value of type `T` to bind this `NullableRef` to. | Examples: ``` NullableRef!int nr = new int(42); writeln(nr); // 42 int* n = new int(1); nr.bind(n); writeln(nr); // 1 ``` const pure nothrow @property @safe bool **isNull**(); Returns `true` if and only if `this` is in the null state. Returns: true if `this` is in the null state, otherwise false. Examples: ``` NullableRef!int nr; assert(nr.isNull); int* n = new int(42); nr.bind(n); assert(!nr.isNull && nr == 42); ``` pure nothrow @safe void **nullify**(); Forces `this` to the null state. Examples: ``` NullableRef!int nr = new int(42); assert(!nr.isNull); nr.nullify(); assert(nr.isNull); ``` void **opAssign**()(T value) Constraints: if (isAssignable!T); Assigns `value` to the internally-held state. Parameters: | | | | --- | --- | | T `value` | A value of type `T` to assign to this `NullableRef`. If the internal state of this `NullableRef` has not been initialized, an error will be thrown in non-release mode. | Examples: ``` import std.exception : assertThrown, assertNotThrown; NullableRef!int nr; assert(nr.isNull); assertThrown!Throwable(nr = 42); nr.bind(new int(0)); assert(!nr.isNull); assertNotThrown!Throwable(nr = 42); writeln(nr); // 42 ``` inout pure nothrow @property ref @safe inout(T) **get**(); Gets the value. `this` must not be in the null state. This function is also called for the implicit conversion to `T`. Examples: ``` import std.exception : assertThrown, assertNotThrown; NullableRef!int nr; //`get` is implicitly called. Will throw //an error in non-release mode assertThrown!Throwable(nr == 0); nr.bind(new int(0)); assertNotThrown!Throwable(nr == 0); ``` template **BlackHole**(Base) `BlackHole!Base` is a subclass of `Base` which automatically implements all abstract member functions in `Base` as do-nothing functions. Each auto-implemented function just returns the default value of the return type without doing anything. The name came from [Class::BlackHole](http://search.cpan.org/~sburke/Class-BlackHole-0.04/lib/Class/BlackHole.pm) Perl module by Sean M. Burke. Parameters: | | | | --- | --- | | Base | A non-final class for `BlackHole` to inherit from. | See Also: [`AutoImplement`](#AutoImplement), [`generateEmptyFunction`](#generateEmptyFunction) Examples: ``` import std.math : isNaN; static abstract class C { int m_value; this(int v) { m_value = v; } int value() @property { return m_value; } abstract real realValue() @property; abstract void doSomething(); } auto c = new BlackHole!C(42); writeln(c.value); // 42 // Returns real.init which is NaN assert(c.realValue.isNaN); // Abstract functions are implemented as do-nothing c.doSomething(); ``` template **WhiteHole**(Base) `WhiteHole!Base` is a subclass of `Base` which automatically implements all abstract member functions as functions that always fail. These functions simply throw an `Error` and never return. `Whitehole` is useful for trapping the use of class member functions that haven't been implemented. The name came from [Class::WhiteHole](http://search.cpan.org/~mschwern/Class-WhiteHole-0.04/lib/Class/WhiteHole.pm) Perl module by Michael G Schwern. Parameters: | | | | --- | --- | | Base | A non-final class for `WhiteHole` to inherit from. | See Also: [`AutoImplement`](#AutoImplement), [`generateAssertTrap`](#generateAssertTrap) Examples: ``` import std.exception : assertThrown; static class C { abstract void notYetImplemented(); } auto c = new WhiteHole!C; assertThrown!NotImplementedError(c.notYetImplemented()); // throws an Error ``` class **AutoImplement**(Base, alias how, alias what = isAbstractFunction) if (!is(how == class)): Base; class **AutoImplement**(Interface, BaseClass, alias how, alias what = isAbstractFunction) if (is(Interface == interface) && is(BaseClass == class)): BaseClass, Interface; `AutoImplement` automatically implements (by default) all abstract member functions in the class or interface `Base` in specified way. The second version of `AutoImplement` automatically implements `Interface`, while deriving from `BaseClass`. Parameters: | | | | --- | --- | | how | template which specifies how functions will be implemented/overridden. Two arguments are passed to `how`: the type `Base` and an alias to an implemented function. Then `how` must return an implemented function body as a string. The generated function body can use these keywords: * `a0`, `a1`, …: arguments passed to the function; * `args`: a tuple of the arguments; * `self`: an alias to the function itself; * `parent`: an alias to the overridden function (if any). You may want to use templated property functions (instead of Implicit Template Properties) to generate complex functions: ``` // Prints log messages for each call to overridden functions. string generateLogger(C, alias fun)() @property { import std.traits; enum qname = C.stringof ~ "." ~ __traits(identifier, fun); string stmt; stmt ~= q{ struct Importer { import std.stdio; } }; stmt ~= `Importer.writeln("Log: ` ~ qname ~ `(", args, ")");`; static if (!__traits(isAbstractFunction, fun)) { static if (is(ReturnType!fun == void)) stmt ~= q{ parent(args); }; else stmt ~= q{ auto r = parent(args); Importer.writeln("--> ", r); return r; }; } return stmt; } ``` | | what | template which determines what functions should be implemented/overridden. An argument is passed to `what`: an alias to a non-final member function in `Base`. Then `what` must return a boolean value. Return `true` to indicate that the passed function should be implemented/overridden. ``` // Sees if fun returns something. enum bool hasValue(alias fun) = !is(ReturnType!(fun) == void); ``` | Note Generated code is inserted in the scope of `std.typecons` module. Thus, any useful functions outside `std.typecons` cannot be used in the generated code. To workaround this problem, you may `import` necessary things in a local struct, as done in the `generateLogger()` template in the above example. Bugs: * Variadic arguments to constructors are not forwarded to super. * Deep interface inheritance causes compile error with messages like "Error: function std.typecons.AutoImplement!(Foo).AutoImplement.bar does not override any function". [[Bugzilla 2525](https://issues.dlang.org/show_bug.cgi?id=2525)] * The `parent` keyword is actually a delegate to the super class' corresponding member function. [[Bugzilla 2540](https://issues.dlang.org/show_bug.cgi?id=2540)] * Using alias template parameter in `how` and/or `what` may cause strange compile error. Use template tuple parameter instead to workaround this problem. [[Bugzilla 4217](https://issues.dlang.org/show_bug.cgi?id=4217)] Examples: ``` interface PackageSupplier { int foo(); int bar(); } static abstract class AbstractFallbackPackageSupplier : PackageSupplier { protected PackageSupplier default_, fallback; this(PackageSupplier default_, PackageSupplier fallback) { this.default_ = default_; this.fallback = fallback; } abstract int foo(); abstract int bar(); } template fallback(T, alias func) { import std.format : format; // for all implemented methods: // - try default first // - only on a failure run & return fallback enum fallback = q{ scope (failure) return fallback.%1&dollar;s(args); return default_.%1&dollar;s(args); }.format(__traits(identifier, func)); } // combines two classes and use the second one as fallback alias FallbackPackageSupplier = AutoImplement!(AbstractFallbackPackageSupplier, fallback); class FailingPackageSupplier : PackageSupplier { int foo(){ throw new Exception("failure"); } int bar(){ return 2;} } class BackupPackageSupplier : PackageSupplier { int foo(){ return -1; } int bar(){ return -1;} } auto registry = new FallbackPackageSupplier(new FailingPackageSupplier(), new BackupPackageSupplier()); writeln(registry.foo()); // -1 writeln(registry.bar()); // 2 ``` template **generateEmptyFunction**(C, func...) enum string **generateAssertTrap**(C, func...); Predefined how-policies for `AutoImplement`. These templates are also used by `BlackHole` and `WhiteHole`, respectively. Examples: ``` alias BlackHole(Base) = AutoImplement!(Base, generateEmptyFunction); interface I { int foo(); string bar(); } auto i = new BlackHole!I(); // generateEmptyFunction returns the default value of the return type without doing anything writeln(i.foo); // 0 assert(i.bar is null); ``` Examples: ``` import std.exception : assertThrown; alias WhiteHole(Base) = AutoImplement!(Base, generateAssertTrap); interface I { int foo(); string bar(); } auto i = new WhiteHole!I(); // generateAssertTrap throws an exception for every unimplemented function of the interface assertThrown!NotImplementedError(i.foo); assertThrown!NotImplementedError(i.bar); ``` template **wrap**(Targets...) if (Targets.length >= 1 && allSatisfy!(isMutable, Targets)) template **wrap**(Targets...) if (Targets.length >= 1 && !allSatisfy!(isMutable, Targets)) template **unwrap**(Target) if (isMutable!Target) template **unwrap**(Target) if (!isMutable!Target) Supports structural based typesafe conversion. If `Source` has structural conformance with the `interface` `Targets`, wrap creates an internal wrapper class which inherits `Targets` and wraps the `src` object, then returns it. `unwrap` can be used to extract objects which have been wrapped by `wrap`. Examples: ``` interface Quack { int quack(); @property int height(); } interface Flyer { @property int height(); } class Duck : Quack { int quack() { return 1; } @property int height() { return 10; } } class Human { int quack() { return 2; } @property int height() { return 20; } } Duck d1 = new Duck(); Human h1 = new Human(); interface Refleshable { int reflesh(); } // does not have structural conformance static assert(!__traits(compiles, d1.wrap!Refleshable)); static assert(!__traits(compiles, h1.wrap!Refleshable)); // strict upcast Quack qd = d1.wrap!Quack; assert(qd is d1); assert(qd.quack() == 1); // calls Duck.quack // strict downcast Duck d2 = qd.unwrap!Duck; assert(d2 is d1); // structural upcast Quack qh = h1.wrap!Quack; assert(qh.quack() == 2); // calls Human.quack // structural downcast Human h2 = qh.unwrap!Human; assert(h2 is h1); // structural upcast (two steps) Quack qx = h1.wrap!Quack; // Human -> Quack Flyer fx = qx.wrap!Flyer; // Quack -> Flyer assert(fx.height == 20); // calls Human.height // structural downcast (two steps) Quack qy = fx.unwrap!Quack; // Flyer -> Quack Human hy = qy.unwrap!Human; // Quack -> Human assert(hy is h1); // structural downcast (one step) Human hz = fx.unwrap!Human; // Flyer -> Human assert(hz is h1); ``` Examples: ``` import std.traits : FunctionAttribute, functionAttributes; interface A { int run(); } interface B { int stop(); @property int status(); } class X { int run() { return 1; } int stop() { return 2; } @property int status() { return 3; } } auto x = new X(); auto ab = x.wrap!(A, B); A a = ab; B b = ab; writeln(a.run()); // 1 writeln(b.stop()); // 2 writeln(b.status); // 3 static assert(functionAttributes!(typeof(ab).status) & FunctionAttribute.property); ``` enum **RefCountedAutoInitialize**: int; Options regarding auto-initialization of a `RefCounted` object (see the definition of `RefCounted` below). Examples: ``` import core.exception : AssertError; import std.exception : assertThrown; struct Foo { int a = 42; } RefCounted!(Foo, RefCountedAutoInitialize.yes) rcAuto; RefCounted!(Foo, RefCountedAutoInitialize.no) rcNoAuto; writeln(rcAuto.refCountedPayload.a); // 42 assertThrown!AssertError(rcNoAuto.refCountedPayload); rcNoAuto.refCountedStore.ensureInitialized; writeln(rcNoAuto.refCountedPayload.a); // 42 ``` **no** Do not auto-initialize the object **yes** Auto-initialize the object struct **RefCounted**(T, RefCountedAutoInitialize autoInit = RefCountedAutoInitialize.yes) if (!is(T == class) && !is(T == interface)); Defines a reference-counted object containing a `T` value as payload. An instance of `RefCounted` is a reference to a structure, which is referred to as the *store*, or *storage implementation struct* in this documentation. The store contains a reference count and the `T` payload. `RefCounted` uses `malloc` to allocate the store. As instances of `RefCounted` are copied or go out of scope, they will automatically increment or decrement the reference count. When the reference count goes down to zero, `RefCounted` will call `destroy` against the payload and call `free` to deallocate the store. If the `T` payload contains any references to GC-allocated memory, then `RefCounted` will add it to the GC memory that is scanned for pointers, and remove it from GC scanning before `free` is called on the store. One important consequence of `destroy` is that it will call the destructor of the `T` payload. GC-managed references are not guaranteed to be valid during a destructor call, but other members of `T`, such as file handles or pointers to `malloc` memory, will still be valid during the destructor call. This allows the `T` to deallocate or clean up any non-GC resources immediately after the reference count has reached zero. `RefCounted` is unsafe and should be used with care. No references to the payload should be escaped outside the `RefCounted` object. The `autoInit` option makes the object ensure the store is automatically initialized. Leaving `autoInit == RefCountedAutoInitialize.yes` (the default option) is convenient but has the cost of a test whenever the payload is accessed. If `autoInit == RefCountedAutoInitialize.no`, user code must call either `refCountedStore.isInitialized` or `refCountedStore.ensureInitialized` before attempting to access the payload. Not doing so results in null pointer dereference. Examples: ``` // A pair of an `int` and a `size_t` - the latter being the // reference count - will be dynamically allocated auto rc1 = RefCounted!int(5); writeln(rc1); // 5 // No more allocation, add just one extra reference count auto rc2 = rc1; // Reference semantics rc2 = 42; writeln(rc1); // 42 // the pair will be freed when rc1 and rc2 go out of scope ``` struct **RefCountedStore**; `RefCounted` storage implementation. const pure nothrow @nogc @property @safe bool **isInitialized**(); Returns `true` if and only if the underlying store has been allocated and initialized. const pure nothrow @nogc @property @safe size\_t **refCount**(); Returns underlying reference count if it is allocated and initialized (a positive integer), and `0` otherwise. void **ensureInitialized**(); Makes sure the payload was properly initialized. Such a call is typically inserted before using the payload. inout nothrow @property ref @safe inout(RefCountedStore) **refCountedStore**(); Returns storage implementation struct. this(A...)(auto ref A args) Constraints: if (A.length > 0); this(T val); Constructor that initializes the payload. Postcondition `refCountedStore.isInitialized` void **opAssign**(typeof(this) rhs); void **opAssign**(T rhs); Assignment operators @property ref @trusted T **refCountedPayload**() return; inout pure nothrow @nogc @property ref @safe inout(T) **refCountedPayload**() return; Returns a reference to the payload. If (autoInit == RefCountedAutoInitialize.yes), calls `refCountedStore.ensureInitialized`. Otherwise, just issues `assert(refCountedStore.isInitialized)`. Used with `alias refCountedPayload this;`, so callers can just use the `RefCounted` object as a `T`. The first overload exists only if `autoInit == RefCountedAutoInitialize.yes`. So if `autoInit == RefCountedAutoInitialize.no` or called for a constant or immutable object, then `refCountedPayload` will also be qualified as safe and nothrow (but will still assert if not initialized). RefCounted!(T, RefCountedAutoInitialize.no) **refCounted**(T)(T val); Initializes a `RefCounted` with `val`. The template parameter `T` of `RefCounted` is inferred from `val`. This function can be used to move non-copyable values to the heap. It also disables the `autoInit` option of `RefCounted`. Parameters: | | | | --- | --- | | T `val` | The value to be reference counted | Returns: An initialized `RefCounted` containing `val`. See Also: [C++'s make\_shared](http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared) Examples: ``` static struct File { string name; @disable this(this); // not copyable ~this() { name = null; } } auto file = File("name"); writeln(file.name); // "name" // file cannot be copied and has unique ownership static assert(!__traits(compiles, {auto file2 = file;})); // make the file refcounted to share ownership import std.algorithm.mutation : move; auto rcFile = refCounted(move(file)); writeln(rcFile.name); // "name" writeln(file.name); // null auto rcFile2 = rcFile; writeln(rcFile.refCountedStore.refCount); // 2 // file gets properly closed when last reference is dropped ``` template **Proxy**(alias a) Creates a proxy for the value `a` that will forward all operations while disabling implicit conversions. The aliased item `a` must be an **lvalue**. This is useful for creating a new type from the "base" type (though this is **not** a subtype-supertype relationship; the new type is not related to the old type in any way, by design). The new type supports all operations that the underlying type does, including all operators such as `+`, `--`, `<`, `[]`, etc. Parameters: | | | | --- | --- | | a | The value to act as a proxy for all operations. It must be an lvalue. | Examples: ``` struct MyInt { private int value; mixin Proxy!value; this(int n){ value = n; } } MyInt n = 10; // Enable operations that original type has. ++n; writeln(n); // 11 writeln(n * 2); // 22 void func(int n) { } // Disable implicit conversions to original type. //int x = n; //func(n); ``` Examples: The proxied value must be an **lvalue**. ``` struct NewIntType { //Won't work; the literal '1' //is an rvalue, not an lvalue //mixin Proxy!1; //Okay, n is an lvalue int n; mixin Proxy!n; this(int n) { this.n = n; } } NewIntType nit = 0; nit++; writeln(nit); // 1 struct NewObjectType { Object obj; //Ok, obj is an lvalue mixin Proxy!obj; this (Object o) { obj = o; } } NewObjectType not = new Object(); assert(__traits(compiles, not.toHash())); ``` Examples: There is one exception to the fact that the new type is not related to the old type. [Pseudo-member](https://dlang.org/spec/function.html#pseudo-member) functions are usable with the new type; they will be forwarded on to the proxied value. ``` import std.math; float f = 1.0; assert(!f.isInfinity); struct NewFloat { float _; mixin Proxy!_; this(float f) { _ = f; } } NewFloat nf = 1.0f; assert(!nf.isInfinity); ``` struct **Typedef**(T, T init = T.init, string cookie = null); **Typedef** allows the creation of a unique type which is based on an existing type. Unlike the `alias` feature, **Typedef** ensures the two types are not considered as equals. Parameters: | | | | --- | --- | | init | Optional initial value for the new type. | | cookie | Optional, used to create multiple unique types which are based on the same origin type `T` | Note If a library routine cannot handle the Typedef type, you can use the `TypedefType` template to extract the type which the Typedef wraps. Examples: ``` alias MyInt = Typedef!int; MyInt foo = 10; foo++; writeln(foo); // 11 ``` Examples: custom initialization values ``` alias MyIntInit = Typedef!(int, 42); static assert(is(TypedefType!MyIntInit == int)); static assert(MyIntInit() == 42); ``` Examples: Typedef creates a new type ``` alias MyInt = Typedef!int; static void takeInt(int) {} static void takeMyInt(MyInt) {} int i; takeInt(i); // ok static assert(!__traits(compiles, takeMyInt(i))); MyInt myInt; static assert(!__traits(compiles, takeInt(myInt))); takeMyInt(myInt); // ok ``` Examples: Use the optional `cookie` argument to create different types of the same base type ``` alias TypeInt1 = Typedef!int; alias TypeInt2 = Typedef!int; // The two Typedefs are the same type. static assert(is(TypeInt1 == TypeInt2)); alias MoneyEuros = Typedef!(float, float.init, "euros"); alias MoneyDollars = Typedef!(float, float.init, "dollars"); // The two Typedefs are _not_ the same type. static assert(!is(MoneyEuros == MoneyDollars)); ``` string **toString**(this T)(); void **toString**(this T, W)(ref W writer, ref scope const FormatSpec!char fmt) Constraints: if (isOutputRange!(W, char)); Convert wrapped value to a human readable string Examples: ``` import std.conv : to; int i = 123; auto td = Typedef!int(i); writeln(i.to!string); // td.to!string ``` template **TypedefType**(T) Get the underlying type which a `Typedef` wraps. If `T` is not a `Typedef` it will alias itself to `T`. Examples: ``` import std.conv : to; alias MyInt = Typedef!int; static assert(is(TypedefType!MyInt == int)); /// Instantiating with a non-Typedef will return that type static assert(is(TypedefType!int == int)); string num = "5"; // extract the needed type MyInt myInt = MyInt( num.to!(TypedefType!MyInt) ); writeln(myInt); // 5 // cast to the underlying type to get the value that's being wrapped int x = cast(TypedefType!MyInt) myInt; alias MyIntInit = Typedef!(int, 42); static assert(is(TypedefType!MyIntInit == int)); static assert(MyIntInit() == 42); ``` template **scoped**(T) if (is(T == class)) Allocates a `class` object right inside the current scope, therefore avoiding the overhead of `new`. This facility is unsafe; it is the responsibility of the user to not escape a reference to the object outside the scope. The class destructor will be called when the result of `scoped()` is itself destroyed. Scoped class instances can be embedded in a parent `class` or `struct`, just like a child struct instance. Scoped member variables must have type `typeof(scoped!Class(args))`, and be initialized with a call to scoped. See below for an example. Note It's illegal to move a class instance even if you are sure there are no pointers to it. As such, it is illegal to move a scoped object. Examples: ``` class A { int x; this() {x = 0;} this(int i){x = i;} ~this() {} } // Standard usage, constructing A on the stack auto a1 = scoped!A(); a1.x = 42; // Result of `scoped` call implicitly converts to a class reference A aRef = a1; writeln(aRef.x); // 42 // Scoped destruction { auto a2 = scoped!A(1); writeln(a2.x); // 1 aRef = a2; // a2 is destroyed here, calling A's destructor } // aRef is now an invalid reference // Here the temporary scoped A is immediately destroyed. // This means the reference is then invalid. version (Bug) { // Wrong, should use `auto` A invalid = scoped!A(); } // Restrictions version (Bug) { import std.algorithm.mutation : move; auto invalid = a1.move; // illegal, scoped objects can't be moved } static assert(!is(typeof({ auto e1 = a1; // illegal, scoped objects can't be copied assert([a1][0].x == 42); // ditto }))); static assert(!is(typeof({ alias ScopedObject = typeof(a1); auto e2 = ScopedObject(); // illegal, must be built via scoped!A auto e3 = ScopedObject(1); // ditto }))); // Use with alias alias makeScopedA = scoped!A; auto a3 = makeScopedA(); auto a4 = makeScopedA(1); // Use as member variable struct B { typeof(scoped!A()) a; // note the trailing parentheses this(int i) { // construct member a = scoped!A(i); } } // Stack-allocate auto b1 = B(5); aRef = b1.a; writeln(aRef.x); // 5 destroy(b1); // calls A's destructor for b1.a // aRef is now an invalid reference // Heap-allocate auto b2 = new B(6); writeln(b2.a.x); // 6 destroy(*b2); // calls A's destructor for b2.a ``` @system auto **scoped**(Args...)(auto ref Args args); Returns the scoped object. Parameters: | | | | --- | --- | | Args `args` | Arguments to pass to `T`'s constructor. | template **Flag**(string name) Defines a simple, self-documenting yes/no flag. This makes it easy for APIs to define functions accepting flags without resorting to `bool`, which is opaque in calls, and without needing to define an enumerated type separately. Using `Flag!"Name"` instead of `bool` makes the flag's meaning visible in calls. Each yes/no flag has its own type, which makes confusions and mix-ups impossible. Example Code calling `getLine` (usually far away from its definition) can't be understood without looking at the documentation, even by users familiar with the API: ``` string getLine(bool keepTerminator) { ... if (keepTerminator) ... ... } ... auto line = getLine(false); ``` Assuming the reverse meaning (i.e. "ignoreTerminator") and inserting the wrong code compiles and runs with erroneous results. After replacing the boolean parameter with an instantiation of `Flag`, code calling `getLine` can be easily read and understood even by people not fluent with the API: ``` string getLine(Flag!"keepTerminator" keepTerminator) { ... if (keepTerminator) ... ... } ... auto line = getLine(Yes.keepTerminator); ``` The structs `Yes` and `No` are provided as shorthand for `Flag!"Name".yes` and `Flag!"Name".no` and are preferred for brevity and readability. These convenience structs mean it is usually unnecessary and counterproductive to create an alias of a `Flag` as a way of avoiding typing out the full type while specifying the affirmative or negative options. Passing categorical data by means of unstructured `bool` parameters is classified under "simple-data coupling" by Steve McConnell in the [Code Complete](https://google.com/search?btnI=I%27m+Feeling+Lucky&ie=UTF-8&oe=UTF-8&q=Code%20Complete) book, along with three other kinds of coupling. The author argues citing several studies that coupling has a negative effect on code quality. `Flag` offers a simple structuring method for passing yes/no flags to APIs. Examples: ``` Flag!"abc" flag; writeln(flag); // Flag!"abc".no writeln(flag); // No.abc assert(!flag); if (flag) assert(0); ``` Examples: ``` auto flag = Yes.abc; assert(flag); writeln(flag); // Yes.abc if (!flag) assert(0); if (flag) {} else assert(0); ``` enum **Flag**: bool; **no** When creating a value of type `Flag!"Name"`, use `Flag!"Name".no` for the negative option. When using a value of type `Flag!"Name"`, compare it against `Flag!"Name".no` or just `false` or `0`. **yes** When creating a value of type `Flag!"Name"`, use `Flag!"Name".yes` for the affirmative option. When using a value of type `Flag!"Name"`, compare it against `Flag!"Name".yes`. struct **Yes**; struct **No**; Convenience names that allow using e.g. `Yes.encryption` instead of `Flag!"encryption".yes` and `No.encryption` instead of `Flag!"encryption".no`. Examples: ``` Flag!"abc" flag; writeln(flag); // Flag!"abc".no writeln(flag); // No.abc assert(!flag); if (flag) assert(0); ``` Examples: ``` auto flag = Yes.abc; assert(flag); writeln(flag); // Yes.abc if (!flag) assert(0); if (flag) {} else assert(0); ``` template **isBitFlagEnum**(E) Detect whether an enum is of integral type and has only "flag" values (i.e. values with a bit count of exactly 1). Additionally, a zero value is allowed for compatibility with enums including a "None" value. Examples: ``` enum A { None, A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, } static assert(isBitFlagEnum!A); ``` Examples: Test an enum with default (consecutive) values ``` enum B { A, B, C, D // D == 3 } static assert(!isBitFlagEnum!B); ``` Examples: Test an enum with non-integral values ``` enum C: double { A = 1 << 0, B = 1 << 1 } static assert(!isBitFlagEnum!C); ``` struct **BitFlags**(E, Flag!"unsafe" unsafe = No.unsafe) if (unsafe || isBitFlagEnum!E); A typesafe structure for storing combinations of enum values. This template defines a simple struct to represent bitwise OR combinations of enum values. It can be used if all the enum values are integral constants with a bit count of at most 1, or if the `unsafe` parameter is explicitly set to Yes. This is much safer than using the enum itself to store the OR combination, which can produce surprising effects like this: ``` enum E { A = 1 << 0, B = 1 << 1 } E e = E.A | E.B; // will throw SwitchError final switch (e) { case E.A: return; case E.B: return; } ``` Examples: Set values with the | operator and test with & ``` enum Enum { A = 1 << 0, } // A default constructed BitFlags has no value set immutable BitFlags!Enum flags_empty; assert(!flags_empty.A); // Value can be set with the | operator immutable flags_A = flags_empty | Enum.A; // and tested using property access assert(flags_A.A); // or the & operator assert(flags_A & Enum.A); // which commutes. assert(Enum.A & flags_A); ``` Examples: A default constructed BitFlags has no value set ``` enum Enum { None, A = 1 << 0, B = 1 << 1, C = 1 << 2 } immutable BitFlags!Enum flags_empty; assert(!(flags_empty & (Enum.A | Enum.B | Enum.C))); assert(!(flags_empty & Enum.A) && !(flags_empty & Enum.B) && !(flags_empty & Enum.C)); ``` Examples: Binary operations: subtracting and intersecting flags ``` enum Enum { A = 1 << 0, B = 1 << 1, C = 1 << 2, } immutable BitFlags!Enum flags_AB = BitFlags!Enum(Enum.A, Enum.B); immutable BitFlags!Enum flags_BC = BitFlags!Enum(Enum.B, Enum.C); // Use the ~ operator for subtracting flags immutable BitFlags!Enum flags_B = flags_AB & ~BitFlags!Enum(Enum.A); assert(!flags_B.A && flags_B.B && !flags_B.C); // use & between BitFlags for intersection writeln(flags_B); // (flags_BC & flags_AB) ``` Examples: All the binary operators work in their assignment version ``` enum Enum { A = 1 << 0, B = 1 << 1, } BitFlags!Enum flags_empty, temp, flags_AB; flags_AB = Enum.A | Enum.B; temp |= flags_AB; writeln(temp); // (flags_empty | flags_AB) temp = flags_empty; temp |= Enum.B; writeln(temp); // (flags_empty | Enum.B) temp = flags_empty; temp &= flags_AB; writeln(temp); // (flags_empty & flags_AB) temp = flags_empty; temp &= Enum.A; writeln(temp); // (flags_empty & Enum.A) ``` Examples: Conversion to bool and int ``` enum Enum { A = 1 << 0, B = 1 << 1, } BitFlags!Enum flags; // BitFlags with no value set evaluate to false assert(!flags); // BitFlags with at least one value set evaluate to true flags |= Enum.A; assert(flags); // This can be useful to check intersection between BitFlags BitFlags!Enum flags_AB = Enum.A | Enum.B; assert(flags & flags_AB); assert(flags & Enum.A); // You can of course get you raw value out of flags auto value = cast(int) flags; writeln(value); // Enum.A ``` Examples: You need to specify the `unsafe` parameter for enums with custom values ``` enum UnsafeEnum { A = 1, B = 2, C = 4, BC = B|C } static assert(!__traits(compiles, { BitFlags!UnsafeEnum flags; })); BitFlags!(UnsafeEnum, Yes.unsafe) flags; // property access tests for exact match of unsafe enums flags.B = true; assert(!flags.BC); // only B flags.C = true; assert(flags.BC); // both B and C flags.B = false; assert(!flags.BC); // only C // property access sets all bits of unsafe enum group flags = flags.init; flags.BC = true; assert(!flags.A && flags.B && flags.C); flags.A = true; flags.BC = false; assert(flags.A && !flags.B && !flags.C); ``` template **ReplaceType**(From, To, T...) Replaces all occurrences of `From` into `To`, in one or more types `T`. For example, `ReplaceType!(int, uint, Tuple!(int, float)[string])` yields `Tuple!(uint, float)[string]`. The types in which replacement is performed may be arbitrarily complex, including qualifiers, built-in type constructors (pointers, arrays, associative arrays, functions, and delegates), and template instantiations; replacement proceeds transitively through the type definition. However, member types in `struct`s or `class`es are not replaced because there are no ways to express the types resulting after replacement. This is an advanced type manipulation necessary e.g. for replacing the placeholder type `This` in [`std.variant.Algebraic`](std_variant#Algebraic). Returns: `ReplaceType` aliases itself to the type(s) that result after replacement. Examples: ``` static assert( is(ReplaceType!(int, string, int[]) == string[]) && is(ReplaceType!(int, string, int[int]) == string[string]) && is(ReplaceType!(int, string, const(int)[]) == const(string)[]) && is(ReplaceType!(int, string, Tuple!(int[], float)) == Tuple!(string[], float)) ); ``` template **ReplaceTypeUnless**(alias pred, From, To, T...) Like [`ReplaceType`](#ReplaceType), but does not perform replacement in types for which `pred` evaluates to `true`. Examples: ``` import std.traits : isArray; static assert( is(ReplaceTypeUnless!(isArray, int, string, int*) == string*) && is(ReplaceTypeUnless!(isArray, int, string, int[]) == int[]) && is(ReplaceTypeUnless!(isArray, int, string, Tuple!(int, int[])) == Tuple!(string, int[])) ); ``` struct **Ternary**; Ternary type with three truth values: * `Ternary.yes` for `true` * `Ternary.no` for `false` * `Ternary.unknown` as an unknown state Also known as trinary, trivalent, or trilean. See Also: [Three Valued Logic on Wikipedia](http://en.wikipedia.org/wiki/Three-valued_logic) Examples: ``` Ternary a; writeln(a); // Ternary.unknown writeln(~Ternary.yes); // Ternary.no writeln(~Ternary.no); // Ternary.yes writeln(~Ternary.unknown); // Ternary.unknown ``` enum Ternary **no**; enum Ternary **yes**; enum Ternary **unknown**; The possible states of the `Ternary` pure nothrow @nogc @safe this(bool b); pure nothrow @nogc @safe void **opAssign**(bool b); Construct and assign from a `bool`, receiving `no` for `false` and `yes` for `true`. pure nothrow @nogc @safe this(const Ternary b); Construct a ternary value from another ternary value Ternary **opUnary**(string s)() Constraints: if (s == "~"); Ternary **opBinary**(string s)(Ternary rhs) Constraints: if (s == "|"); Ternary **opBinary**(string s)(Ternary rhs) Constraints: if (s == "&"); Ternary **opBinary**(string s)(Ternary rhs) Constraints: if (s == "^"); Ternary **opBinary**(string s)(bool rhs) Constraints: if (s == "|" || s == "&" || s == "^"); Truth table for logical operations| `a` | `b` | `˜a` | `a | b` | `a & b` | `a ^ b` | | `no` | `no` | `yes` | `no` | `no` | `no` | | `no` | `yes` | | `yes` | `no` | `yes` | | `no` | `unknown` | | `unknown` | `no` | `unknown` | | `yes` | `no` | `no` | `yes` | `no` | `yes` | | `yes` | `yes` | | `yes` | `yes` | `no` | | `yes` | `unknown` | | `yes` | `unknown` | `unknown` | | `unknown` | `no` | `unknown` | `unknown` | `no` | `unknown` | | `unknown` | `yes` | | `yes` | `unknown` | `unknown` | | `unknown` | `unknown` | | `unknown` | `unknown` | `unknown` |
programming_docs
d std.experimental.allocator.building_blocks std.experimental.allocator.building\_blocks =========================================== Assembling Your Own Allocator ----------------------------- This package also implements untyped composable memory allocators. They are *untyped* because they deal exclusively in `void[]` and have no notion of what type the memory allocated would be destined for. They are *composable* because the included allocators are building blocks that can be assembled in complex nontrivial allocators. Unlike the allocators for the C and C++ programming languages, which manage the allocated size internally, these allocators require that the client maintains (or knows *a priori*) the allocation size for each piece of memory allocated. Put simply, the client must pass the allocated size upon deallocation. Storing the size in the allocator has significant negative performance implications, and is virtually always redundant because client code needs knowledge of the allocated size in order to avoid buffer overruns. (See more discussion in a [proposal](#) for sized deallocation in C++.) For this reason, allocators herein traffic in `void[]` as opposed to `void*`. In order to be usable as an allocator, a type should implement the following methods with their respective semantics. Only `alignment` and `allocate` are required. If any of the other methods is missing, the allocator is assumed to not have that capability (for example some allocators do not offer manual deallocation of memory). Allocators should NOT implement unsupported methods to always fail. For example, an allocator that lacks the capability to implement `alignedAllocate` should not define it at all (as opposed to defining it to always return `null` or throw an exception). The missing implementation statically informs other components about the allocator's capabilities and allows them to make design decisions accordingly. | Method name | Semantics | | --- | --- | | `uint alignment;`*Post:* `*result* > 0` | Returns the minimum alignment of all data returned by the allocator. An allocator may implement `alignment` as a statically-known `enum` value only. Applications that need dynamically-chosen alignment values should use the `alignedAllocate` and `alignedReallocate` APIs. | | `size\_t goodAllocSize(size\_t n);`*Post:* `*result* >= n` | Allocators customarily allocate memory in discretely-sized chunks. Therefore, a request for `n` bytes may result in a larger allocation. The extra memory allocated goes unused and adds to the so-called [internal fragmentation](http://goo.gl/YoKffF). The function `goodAllocSize(n)` returns the actual number of bytes that would be allocated upon a request for `n` bytes. This module defines a default implementation that returns `n` rounded up to a multiple of the allocator's alignment. | | `void[] allocate(size\_t s);`*Post:* `*result* is null || *result*.length == s` | If `s == 0`, the call may return any empty slice (including `null`). Otherwise, the call allocates `s` bytes of memory and returns the allocated block, or `null` if the request could not be satisfied. | | `void[] alignedAllocate(size\_t s, uint a);`*Post:* `*result* is null || *result*.length == s` | Similar to `allocate`, with the additional guarantee that the memory returned is aligned to at least `a` bytes. `a` must be a power of 2. | | `void[] allocateAll();` | Offers all of allocator's memory to the caller, so it's usually defined by fixed-size allocators. If the allocator is currently NOT managing any memory, then `allocateAll()` shall allocate and return all memory available to the allocator, and subsequent calls to all allocation primitives should not succeed (e.g. `allocate` shall return `null` etc). Otherwise, `allocateAll` only works on a best-effort basis, and the allocator is allowed to return `null` even if does have available memory. Memory allocated with `allocateAll` is not otherwise special (e.g. can be reallocated or deallocated with the usual primitives, if defined). | | `bool expand(ref void[] b, size\_t delta);`*Post:* `!*result* || b.length == *old*(b).length + delta` | Expands `b` by `delta` bytes. If `delta == 0`, succeeds without changing `b`. If `b is null`, returns `false` (the null pointer cannot be expanded in place). Otherwise, `b` must be a buffer previously allocated with the same allocator. If expansion was successful, `expand` changes `b`'s length to `b.length + delta` and returns `true`. Upon failure, the call effects no change upon the allocator object, leaves `b` unchanged, and returns `false`. | | `bool reallocate(ref void[] b, size\_t s);`*Post:* `!*result* || b.length == s` | Reallocates `b` to size `s`, possibly moving memory around. `b` must be `null` or a buffer allocated with the same allocator. If reallocation was successful, `reallocate` changes `b` appropriately and returns `true`. Upon failure, the call effects no change upon the allocator object, leaves `b` unchanged, and returns `false`. An allocator should implement `reallocate` if it can derive some advantage from doing so; otherwise, this module defines a `reallocate` free function implemented in terms of `expand`, `allocate`, and `deallocate`. | | `bool alignedReallocate(ref void[] b, size\_t s, uint a);`*Post:* `!*result* || b.length == s` | Similar to `reallocate`, but guarantees the reallocated memory is aligned at `a` bytes. The buffer must have been originated with a call to `alignedAllocate`. `a` must be a power of 2 greater than `(void*).sizeof`. An allocator should implement `alignedReallocate` if it can derive some advantage from doing so; otherwise, this module defines a `alignedReallocate` free function implemented in terms of `expand`, `alignedAllocate`, and `deallocate`. | | `Ternary owns(void[] b);` | Returns `Ternary.yes` if `b` has been allocated with this allocator. An allocator should define this method only if it can decide on ownership precisely and fast (in constant time, logarithmic time, or linear time with a low multiplication factor). Traditional allocators such as the C heap do not define such functionality. If `b is null`, the allocator shall return `Ternary.no`, i.e. no allocator owns the `null` slice. | | `Ternary resolveInternalPointer(void\* p, ref void[] result);` | If `p` is a pointer somewhere inside a block allocated with this allocator, `result` holds a pointer to the beginning of the allocated block and returns `Ternary.yes`. Otherwise, `result` holds `null` and returns `Ternary.no`. If the pointer points immediately after an allocated block, the result is implementation defined. | | `bool deallocate(void[] b);` | If `b is null`, does nothing and returns `true`. Otherwise, deallocates memory previously allocated with this allocator and returns `true` if successful, `false` otherwise. An implementation that would not support deallocation (i.e. would always return `false` should not define this primitive at all.) | | `bool deallocateAll();`*Post:* `empty` | Deallocates all memory allocated with this allocator. If an allocator implements this method, it must specify whether its destructor calls it, too. | | `Ternary empty();` | Returns `Ternary.yes` if and only if the allocator holds no memory (i.e. no allocation has occurred, or all allocations have been deallocated). | | `static Allocator instance;`*Post:* `instance *is a valid* Allocator *object*` | Some allocators are *monostate*, i.e. have only an instance and hold only global state. (Notable examples are C's own `malloc`-based allocator and D's garbage-collected heap.) Such allocators must define a static `instance` instance that serves as the symbolic placeholder for the global instance of the allocator. An allocator should not hold state and define `instance` simultaneously. Depending on whether the allocator is thread-safe or not, this instance may be `shared`. | Sample Assembly --------------- The example below features an allocator modeled after [jemalloc](http://goo.gl/m7329l), which uses a battery of free-list allocators spaced so as to keep internal fragmentation to a minimum. The `FList` definitions specify no bounds for the freelist because the `Segregator` does all size selection in advance. Sizes through 3584 bytes are handled via freelists of staggered sizes. Sizes from 3585 bytes through 4072 KB are handled by a `BitmappedBlock` with a block size of 4 KB. Sizes above that are passed direct to the `GCAllocator`. ``` alias FList = FreeList!(GCAllocator, 0, unbounded); alias A = Segregator!( 8, FreeList!(GCAllocator, 0, 8), 128, Bucketizer!(FList, 1, 128, 16), 256, Bucketizer!(FList, 129, 256, 32), 512, Bucketizer!(FList, 257, 512, 64), 1024, Bucketizer!(FList, 513, 1024, 128), 2048, Bucketizer!(FList, 1025, 2048, 256), 3584, Bucketizer!(FList, 2049, 3584, 512), 4072 * 1024, AllocatorList!( () => BitmappedBlock!(GCAllocator, 4096)(4072 * 1024)), GCAllocator ); A tuMalloc; auto b = tuMalloc.allocate(500); assert(b.length == 500); auto c = tuMalloc.allocate(113); assert(c.length == 113); assert(tuMalloc.expand(c, 14)); tuMalloc.deallocate(b); tuMalloc.deallocate(c); ``` Allocating memory for sharing across threads -------------------------------------------- One allocation pattern used in multithreaded applications is to share memory across threads, and to deallocate blocks in a different thread than the one that allocated it. All allocators in this module accept and return `void[]` (as opposed to `shared void[]`). This is because at the time of allocation, deallocation, or reallocation, the memory is effectively not `shared` (if it were, it would reveal a bug at the application level). The issue remains of calling `a.deallocate(b)` from a different thread than the one that allocated `b`. It follows that both threads must have access to the same instance `a` of the respective allocator type. By definition of D, this is possible only if `a` has the `shared` qualifier. It follows that the allocator type must implement `allocate` and `deallocate` as `shared` methods. That way, the allocator commits to allowing usable `shared` instances. Conversely, allocating memory with one non-`shared` allocator, passing it across threads (by casting the obtained buffer to `shared`), and later deallocating it in a different thread (either with a different allocator object or with the same allocator object after casting it to `shared`) is illegal. Building Blocks --------------- The table below gives a synopsis of predefined allocator building blocks, with their respective modules. Either `import` the needed modules individually, or `import` `std.experimental.building_blocks`, which imports them all `public`ly. The building blocks can be assembled in unbounded ways and also combined with your own. For a collection of typical and useful preassembled allocators and for inspiration in defining more such assemblies, refer to [`std.experimental.allocator.showcase`](std_experimental_allocator_showcase). | Allocator | Description | | --- | --- | | `[NullAllocator](std_experimental_allocator_building_blocks_null_allocator#NullAllocator)``std.experimental.allocator.building\_blocks.null\_allocator` | Very good at doing absolutely nothing. A good starting point for defining other allocators or for studying the API. | | `[GCAllocator](std_experimental_allocator_gc_allocator#GCAllocator)``std.experimental.allocator.gc\_allocator` | The system-provided garbage-collector allocator. This should be the default fallback allocator tapping into system memory. It offers manual `free` and dutifully collects litter. | | `[Mallocator](std_experimental_allocator_mallocator#Mallocator)``std.experimental.allocator.mallocator` | The C heap allocator, a.k.a. `malloc`/`realloc`/`free`. Use sparingly and only for code that is unlikely to leak. | | `[AlignedMallocator](std_experimental_allocator_mallocator#AlignedMallocator)``std.experimental.allocator.mallocator` | Interface to OS-specific allocators that support specifying alignment: [`posix_memalign`](http://man7.org/linux/man-pages/man3/posix_memalign.3.html) on Posix and [`__aligned_xxx`](http://msdn.microsoft.com/en-us/library/fs9stz4e(v=vs.80).aspx) on Windows. | | `[AlignedBlockList](std_experimental_allocator_building_blocks_aligned_block_list#AlignedBlockList)``std.experimental.allocator.building\_blocks.aligned\_block\_list` | A wrapper around a list of allocators which allow for very fast deallocations. | | `[AffixAllocator](std_experimental_allocator_building_blocks_affix_allocator#AffixAllocator)``std.experimental.allocator.building\_blocks.affix\_allocator` | Allocator that allows and manages allocating extra prefix and/or a suffix bytes for each block allocated. | | `[BitmappedBlock](std_experimental_allocator_building_blocks_bitmapped_block#BitmappedBlock)``std.experimental.allocator.building\_blocks.bitmapped\_block` | Organizes one contiguous chunk of memory in equal-size blocks and tracks allocation status at the cost of one bit per block. | | `[FallbackAllocator](std_experimental_allocator_building_blocks_fallback_allocator#FallbackAllocator)``std.experimental.allocator.building\_blocks.fallback\_allocator` | Allocator that combines two other allocators - primary and fallback. Allocation requests are first tried with primary, and upon failure are passed to the fallback. Useful for small and fast allocators fronting general-purpose ones. | | `[FreeList](std_experimental_allocator_building_blocks_free_list#FreeList)``std.experimental.allocator.building\_blocks.free\_list` | Allocator that implements a [free list](http://wikipedia.org/wiki/Free_list) on top of any other allocator. The preferred size, tolerance, and maximum elements are configurable at compile- and run time. | | `[SharedFreeList](std_experimental_allocator_building_blocks_free_list#SharedFreeList)``std.experimental.allocator.building\_blocks.free\_list` | Same features as `FreeList`, but packaged as a `shared` structure that is accessible to several threads. | | `[FreeTree](std_experimental_allocator_building_blocks_free_tree#FreeTree)``std.experimental.allocator.building\_blocks.free\_tree` | Allocator similar to `FreeList` that uses a binary search tree to adaptively store not one, but many free lists. | | `[Region](std_experimental_allocator_building_blocks_region#Region)``std.experimental.allocator.building\_blocks.region` | Region allocator organizes a chunk of memory as a simple bump-the-pointer allocator. | | `[InSituRegion](std_experimental_allocator_building_blocks_region#InSituRegion)``std.experimental.allocator.building\_blocks.region` | Region holding its own allocation, most often on the stack. Has statically-determined size. | | `[SbrkRegion](std_experimental_allocator_building_blocks_region#SbrkRegion)``std.experimental.allocator.building\_blocks.region` | Region using `[sbrk](https://en.wikipedia.org/wiki/Sbrk)` for allocating memory. | | `[MmapAllocator](std_experimental_allocator_mmap_allocator#MmapAllocator)``std.experimental.allocator.mmap\_allocator` | Allocator using `[mmap](https://en.wikipedia.org/wiki/Mmap)` directly. | | `[StatsCollector](std_experimental_allocator_building_blocks_stats_collector#StatsCollector)``std.experimental.allocator.building\_blocks.stats\_collector` | Collect statistics about any other allocator. | | `[Quantizer](std_experimental_allocator_building_blocks_quantizer#Quantizer)``std.experimental.allocator.building\_blocks.quantizer` | Allocates in coarse-grained quantas, thus improving performance of reallocations by often reallocating in place. The drawback is higher memory consumption because of allocated and unused memory. | | `[AllocatorList](std_experimental_allocator_building_blocks_allocator_list#AllocatorList)``std.experimental.allocator.building\_blocks.allocator\_list` | Given an allocator factory, lazily creates as many allocators as needed to satisfy allocation requests. The allocators are stored in a linked list. Requests for allocation are satisfied by searching the list in a linear manner. | | `[Segregator](std_experimental_allocator_building_blocks_segregator#Segregator)``std.experimental.allocator.building\_blocks.segregator` | Segregates allocation requests by size and dispatches them to distinct allocators. | | `[Bucketizer](std_experimental_allocator_building_blocks_bucketizer#Bucketizer)``std.experimental.allocator.building\_blocks.bucketizer` | Divides allocation sizes in discrete buckets and uses an array of allocators, one per bucket, to satisfy requests. | | `[AscendingPageAllocator](std_experimental_allocator_building_blocks_ascending_page_allocator#AscendingPageAllocator)``std.experimental.allocator.building\_blocks.ascending\_page\_allocator` | A memory safe allocator where sizes are rounded to a multiple of the page size and allocations are satisfied at increasing addresses. | Source [std/experimental/allocator/building\_blocks/package.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/package.d) d std.experimental.allocator.mmap_allocator std.experimental.allocator.mmap\_allocator ========================================== Source [std/experimental/allocator/mmap\_allocator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/mmap_allocator.d) struct **MmapAllocator**; Allocator (currently defined only for Posix and Windows) using `[mmap](https://en.wikipedia.org/wiki/Mmap)` and `[munmap](https://google.com/search?btnI=I%27m+Feeling+Lucky&ie=UTF-8&oe=UTF-8&q=munmap)` directly (or their Windows equivalents). There is no additional structure: each call to `allocate(s)` issues a call to `mmap(null, s, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)`, and each call to `deallocate(b)` issues `munmap(b.ptr, b.length)`. So `MmapAllocator` is usually intended for allocating large chunks to be managed by fine-granular allocators. static shared const MmapAllocator **instance**; The one shared instance. enum size\_t **alignment**; Alignment is page-size and hardcoded to 4096 (even though on certain systems it could be larger). shared const pure nothrow @nogc @safe void[] **allocate**(size\_t bytes); shared const pure nothrow @nogc bool **deallocate**(void[] b); Allocator API. d std.random std.random ========== Facilities for random number generation. | Category | Functions | | --- | --- | | Uniform sampling | [`uniform`](#uniform) [`uniform01`](#uniform01) [`uniformDistribution`](#uniformDistribution) | | Element sampling | [`choice`](#choice) [`dice`](#dice) | | Range sampling | [`randomCover`](#randomCover) [`randomSample`](#randomSample) | | Default Random Engines | [`rndGen`](#rndGen) [`Random`](#Random) [`unpredictableSeed`](#unpredictableSeed) | | Linear Congruential Engines | [`MinstdRand`](#MinstdRand) [`MinstdRand0`](#MinstdRand0) [`LinearCongruentialEngine`](#LinearCongruentialEngine) | | Mersenne Twister Engines | [`Mt19937`](#Mt19937) [`Mt19937_64`](#Mt19937_64) [`MersenneTwisterEngine`](#MersenneTwisterEngine) | | Xorshift Engines | [`Xorshift`](#Xorshift) [`XorshiftEngine`](#XorshiftEngine) [`Xorshift32`](#Xorshift32) [`Xorshift64`](#Xorshift64) [`Xorshift96`](#Xorshift96) [`Xorshift128`](#Xorshift128) [`Xorshift160`](#Xorshift160) [`Xorshift192`](#Xorshift192) | | Shuffle | [`partialShuffle`](#partialShuffle) [`randomShuffle`](#randomShuffle) | | Traits | [`isSeedable`](#isSeedable) [`isUniformRNG`](#isUniformRNG) | Disclaimer: The random number generators and API provided in this module are not designed to be cryptographically secure, and are therefore unsuitable for cryptographic or security-related purposes such as generating authentication tokens or network sequence numbers. For such needs, please use a reputable cryptographic library instead. The new-style generator objects hold their own state so they are immune of threading issues. The generators feature a number of well-known and well-documented methods of generating random numbers. An overall fast and reliable means to generate random numbers is the Mt19937 generator, which derives its name from "[Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_Twister) with a period of 2 to the power of 19937". In memory-constrained situations, [linear congruential generators](https://en.wikipedia.org/wiki/Linear_congruential_generator) such as `MinstdRand0` and `MinstdRand` might be useful. The standard library provides an alias Random for whichever generator it considers the most fit for the target environment. In addition to random number generators, this module features distributions, which skew a generator's output statistical distribution in various ways. So far the uniform distribution for integers and real numbers have been implemented. Source [std/random.d](https://github.com/dlang/phobos/blob/master/std/random.d) License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Andrei Alexandrescu](http://erdani.org) Masahiro Nakagawa (Xorshift random generator) [Joseph Rushton Wakeling](http://braingam.es) (Algorithm D for random sampling) Ilya Yaroshenko (Mersenne Twister implementation, adapted from [mir-random](https://github.com/libmir/mir-random)) Credits The entire random number library architecture is derived from the excellent [C++0X](http://open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf) random number facility proposed by Jens Maurer and contributed to by researchers at the Fermi laboratory (excluding Xorshift). enum bool **isUniformRNG**(Rng, ElementType); enum bool **isUniformRNG**(Rng); Test if Rng is a random-number generator. The overload taking a ElementType also makes sure that the Rng generates values of that type. A random-number generator has at least the following features: * it's an InputRange * it has a 'bool isUniformRandom' field readable in CTFE Examples: ``` struct NoRng { @property uint front() {return 0;} @property bool empty() {return false;} void popFront() {} } static assert(!isUniformRNG!(NoRng)); struct validRng { @property uint front() {return 0;} @property bool empty() {return false;} void popFront() {} enum isUniformRandom = true; } static assert(isUniformRNG!(validRng, uint)); static assert(isUniformRNG!(validRng)); ``` enum bool **isSeedable**(Rng, SeedType); enum bool **isSeedable**(Rng); Test if Rng is seedable. The overload taking a SeedType also makes sure that the Rng can be seeded with SeedType. A seedable random-number generator has the following additional features: * it has a 'seed(ElementType)' function Examples: ``` struct validRng { @property uint front() {return 0;} @property bool empty() {return false;} void popFront() {} enum isUniformRandom = true; } static assert(!isSeedable!(validRng, uint)); static assert(!isSeedable!(validRng)); struct seedRng { @property uint front() {return 0;} @property bool empty() {return false;} void popFront() {} void seed(uint val){} enum isUniformRandom = true; } static assert(isSeedable!(seedRng, uint)); static assert(!isSeedable!(seedRng, ulong)); static assert(isSeedable!(seedRng)); ``` struct **LinearCongruentialEngine**(UIntType, UIntType a, UIntType c, UIntType m) if (isUnsigned!UIntType); Linear Congruential generator. Examples: Declare your own linear congruential engine ``` alias CPP11LCG = LinearCongruentialEngine!(uint, 48271, 0, 2_147_483_647); // seed with a constant auto rnd = CPP11LCG(42); auto n = rnd.front; // same for each run writeln(n); // 2027382 ``` Examples: Declare your own linear congruential engine ``` // glibc's LCG alias GLibcLCG = LinearCongruentialEngine!(uint, 1103515245, 12345, 2_147_483_648); // Seed with an unpredictable value auto rnd = GLibcLCG(unpredictableSeed); auto n = rnd.front; // different across runs ``` enum bool **isUniformRandom**; Mark this as a Rng enum bool **hasFixedRange**; Does this generator have a fixed range? (true). enum UIntType **min**; Lowest generated value (`1` if `c == 0`, `0` otherwise). enum UIntType **max**; Highest generated value (`modulus - 1`). enum UIntType **multiplier**; enum UIntType **increment**; enum UIntType **modulus**; The parameters of this distribution. The random number is x = (x \* multipler + increment) % modulus. pure nothrow @nogc @safe this(UIntType x0); Constructs a LinearCongruentialEngine generator seeded with `x0`. pure nothrow @nogc @safe void **seed**(UIntType x0 = 1); (Re)seeds the generator. pure nothrow @nogc @safe void **popFront**(); Advances the random sequence. const pure nothrow @nogc @property @safe UIntType **front**(); Returns the current number in the random sequence. const pure nothrow @nogc @property @safe typeof(this) **save**(); enum bool **empty**; Always `false` (random generators are infinite ranges). alias **MinstdRand0** = LinearCongruentialEngine!(uint, 16807u, 0u, 2147483647u).LinearCongruentialEngine; alias **MinstdRand** = LinearCongruentialEngine!(uint, 48271u, 0u, 2147483647u).LinearCongruentialEngine; Define LinearCongruentialEngine generators with well-chosen parameters. `MinstdRand0` implements Park and Miller's "minimal standard" [generator](http://wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator) that uses 16807 for the multiplier. `MinstdRand` implements a variant that has slightly better spectral behavior by using the multiplier 48271. Both generators are rather simplistic. Examples: ``` // seed with a constant auto rnd0 = MinstdRand0(1); auto n = rnd0.front; // same for each run writeln(n); // 16807 // Seed with an unpredictable value rnd0.seed(unpredictableSeed); n = rnd0.front; // different across runs ``` struct **MersenneTwisterEngine**(UIntType, size\_t w, size\_t n, size\_t m, size\_t r, UIntType a, size\_t u, UIntType d, size\_t s, UIntType b, size\_t t, UIntType c, size\_t l, UIntType f) if (isUnsigned!UIntType); The [Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_Twister) generator. Examples: ``` // seed with a constant Mt19937 gen; auto n = gen.front; // same for each run writeln(n); // 3499211612 // Seed with an unpredictable value gen.seed(unpredictableSeed); n = gen.front; // different across runs ``` enum bool **isUniformRandom**; Mark this as a Rng enum size\_t **wordSize**; enum size\_t **stateSize**; enum size\_t **shiftSize**; enum size\_t **maskBits**; enum UIntType **xorMask**; enum size\_t **temperingU**; enum UIntType **temperingD**; enum size\_t **temperingS**; enum UIntType **temperingB**; enum size\_t **temperingT**; enum UIntType **temperingC**; enum size\_t **temperingL**; enum UIntType **initializationMultiplier**; Parameters for the generator. enum UIntType **min**; Smallest generated value (0). enum UIntType **max**; Largest generated value. enum UIntType **defaultSeed**; The default seed value. pure nothrow @nogc @safe this(UIntType value); Constructs a MersenneTwisterEngine object. pure nothrow @nogc @safe void **seed**()(UIntType value = defaultSeed); Seeds a MersenneTwisterEngine object. Note This seed function gives 2^w starting points (the lowest w bits of the value provided will be used). To allow the RNG to be started in any one of its internal states use the seed overload taking an InputRange. void **seed**(T)(T range) Constraints: if (isInputRange!T && is(immutable(ElementType!T) == immutable(UIntType))); Seeds a MersenneTwisterEngine object using an InputRange. Throws: `Exception` if the InputRange didn't provide enough elements to seed the generator. The number of elements required is the 'n' template parameter of the MersenneTwisterEngine struct. pure nothrow @nogc @safe void **popFront**(); Advances the generator. const pure nothrow @nogc @property @safe UIntType **front**(); Returns the current random value. const pure nothrow @nogc @property @safe typeof(this) **save**(); enum bool **empty**; Always `false`. alias **Mt19937** = MersenneTwisterEngine!(uint, 32LU, 624LU, 397LU, 31LU, 2567483615u, 11LU, 4294967295u, 7LU, 2636928640u, 15LU, 4022730752u, 18LU, 1812433253u).MersenneTwisterEngine; A `MersenneTwisterEngine` instantiated with the parameters of the original engine [MT19937](http://math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html), generating uniformly-distributed 32-bit numbers with a period of 2 to the power of 19937. Recommended for random number generation unless memory is severely restricted, in which case a [`LinearCongruentialEngine`](#LinearCongruentialEngine) would be the generator of choice. Examples: ``` // seed with a constant Mt19937 gen; auto n = gen.front; // same for each run writeln(n); // 3499211612 // Seed with an unpredictable value gen.seed(unpredictableSeed); n = gen.front; // different across runs ``` alias **Mt19937\_64** = MersenneTwisterEngine!(ulong, 64LU, 312LU, 156LU, 31LU, 13043109905998158313LU, 29LU, 6148914691236517205LU, 17LU, 8202884508482404352LU, 37LU, 18444473444759240704LU, 43LU, 6364136223846793005LU).MersenneTwisterEngine; A `MersenneTwisterEngine` instantiated with the parameters of the original engine [MT19937-64](http://en.wikipedia.org/wiki/Mersenne_Twister), generating uniformly-distributed 64-bit numbers with a period of 2 to the power of 19937. Examples: ``` // Seed with a constant auto gen = Mt19937_64(12345); auto n = gen.front; // same for each run writeln(n); // 6597103971274460346 // Seed with an unpredictable value gen.seed(unpredictableSeed!ulong); n = gen.front; // different across runs ``` struct **XorshiftEngine**(UIntType, uint nbits, int sa, int sb, int sc) if (isUnsigned!UIntType && !(sa > 0 && (sb > 0) && (sc > 0))); template **XorshiftEngine**(UIntType, int bits, int a, int b, int c) if (isUnsigned!UIntType && (a > 0) && (b > 0) && (c > 0)) Xorshift generator. Implemented according to [Xorshift RNGs](http://www.jstatsoft.org/v08/i14/paper) (Marsaglia, 2003) when the size is small. For larger sizes the generator uses Sebastino Vigna's optimization of using an index to avoid needing to rotate the internal array. Period is `2 ^^ nbits - 1` except for a legacy 192-bit uint version (see note below). Parameters: | | | | --- | --- | | UIntType | Word size of this xorshift generator and the return type of `opCall`. | | nbits | The number of bits of state of this generator. This must be a positive multiple of the size in bits of UIntType. If nbits is large this struct may occupy slightly more memory than this so it can use a circular counter instead of shifting the entire array. | | sa | The direction and magnitude of the 1st shift. Positive means left, negative means right. | | sb | The direction and magnitude of the 2nd shift. Positive means left, negative means right. | | sc | The direction and magnitude of the 3rd shift. Positive means left, negative means right. | Note For historical compatibility when `nbits == 192` and `UIntType` is `uint` a legacy hybrid PRNG is used consisting of a 160-bit xorshift combined with a 32-bit counter. This combined generator has period equal to the least common multiple of `2^^160 - 1` and `2^^32`. Previous versions of `XorshiftEngine` did not provide any mechanism to specify the directions of the shifts, taking each shift as an unsigned magnitude. For backwards compatibility, because three shifts in the same direction cannot result in a full-period XorshiftEngine, when all three of `sa`, `sb`, `sc, are positive` XorshiftEngine` treats them as unsigned magnitudes and uses shift directions to match the old behavior of `XorshiftEngine`. Not every set of shifts results in a full-period xorshift generator. The template does not currently at compile-time perform a full check for maximum period but in a future version might reject parameters resulting in shorter periods. Examples: ``` alias Xorshift96 = XorshiftEngine!(uint, 96, 10, 5, 26); auto rnd = Xorshift96(42); auto num = rnd.front; // same for each run writeln(num); // 2704588748 ``` enum bool **isUniformRandom**; Mark this as a Rng enum auto **empty**; Always `false` (random generators are infinite ranges). enum UIntType **min**; Smallest generated value. enum UIntType **max**; Largest generated value. pure nothrow @nogc @safe this()(UIntType x0); Constructs a `XorshiftEngine` generator seeded with x0. Parameters: | | | | --- | --- | | UIntType `x0` | value used to deterministically initialize internal state | pure nothrow @nogc @safe void **seed**()(UIntType x0); (Re)seeds the generator. Parameters: | | | | --- | --- | | UIntType `x0` | value used to deterministically initialize internal state | const pure nothrow @nogc @property @safe UIntType **front**(); Returns the current number in the random sequence. pure nothrow @nogc @safe void **popFront**(); Advances the random sequence. const pure nothrow @nogc @property @safe typeof(this) **save**(); Captures a range state. alias **Xorshift32** = XorshiftEngine!(uint, 32u, 13, -17, 15).XorshiftEngine; alias **Xorshift64** = XorshiftEngine!(uint, 64u, 10, -13, -10).XorshiftEngine; alias **Xorshift96** = XorshiftEngine!(uint, 96u, 10, -5, -26).XorshiftEngine; alias **Xorshift128** = XorshiftEngine!(uint, 128u, 11, -8, -19).XorshiftEngine; alias **Xorshift160** = XorshiftEngine!(uint, 160u, 2, -1, -4).XorshiftEngine; alias **Xorshift192** = XorshiftEngine!(uint, 192u, -2, 1, 4).XorshiftEngine; alias **Xorshift** = XorshiftEngine!(uint, 128u, 11, -8, -19).XorshiftEngine; Define `XorshiftEngine` generators with well-chosen parameters. See each bits examples of "Xorshift RNGs". `Xorshift` is a Xorshift128's alias because 128bits implementation is mostly used. Examples: ``` // Seed with a constant auto rnd = Xorshift(1); auto num = rnd.front; // same for each run writeln(num); // 1405313047 // Seed with an unpredictable value rnd.seed(unpredictableSeed); num = rnd.front; // different across rnd ``` nothrow @nogc @property @trusted uint **unpredictableSeed**(); template **unpredictableSeed**(UIntType) if (isUnsigned!UIntType) A "good" seed for initializing random number engines. Initializing with unpredictableSeed makes engines generate different random number sequences every run. Returns: A single unsigned integer seed value, different on each successive call Note In general periodically 'reseeding' a PRNG does not improve its quality and in some cases may harm it. For an extreme example the Mersenne Twister has `2 ^^ 19937 - 1` distinct states but after `seed(uint)` is called it can only be in one of `2 ^^ 32` distinct states regardless of how excellent the source of entropy is. Examples: ``` auto rnd = Random(unpredictableSeed); auto n = rnd.front; static assert(is(typeof(n) == uint)); ``` alias **Random** = MersenneTwisterEngine!(uint, 32LU, 624LU, 397LU, 31LU, 2567483615u, 11LU, 4294967295u, 7LU, 2636928640u, 15LU, 4022730752u, 18LU, 1812433253u).MersenneTwisterEngine; The "default", "favorite", "suggested" random number generator type on the current platform. It is an alias for one of the previously-defined generators. You may want to use it if (1) you need to generate some nice random numbers, and (2) you don't care for the minutiae of the method being used. nothrow @nogc @property ref @safe Random **rndGen**(); Global random number generator used by various functions in this module whenever no generator is specified. It is allocated per-thread and initialized to an unpredictable value for each thread. Returns: A singleton instance of the default random number generator Examples: ``` import std.algorithm.iteration : sum; import std.range : take; auto rnd = rndGen; assert(rnd.take(3).sum > 0); ``` auto **uniform**(string boundaries = "[)", T1, T2)(T1 a, T2 b) Constraints: if (!is(CommonType!(T1, T2) == void)); auto **uniform**(string boundaries = "[)", T1, T2, UniformRandomNumberGenerator)(T1 a, T2 b, ref UniformRandomNumberGenerator urng) Constraints: if (isFloatingPoint!(CommonType!(T1, T2)) && isUniformRNG!UniformRandomNumberGenerator); Generates a number between `a` and `b`. The `boundaries` parameter controls the shape of the interval (open vs. closed on either side). Valid values for `boundaries` are `"[]"`, `"(]"`, `"[)"`, and `"()"`. The default interval is closed to the left and open to the right. The version that does not take `urng` uses the default generator `rndGen`. Parameters: | | | | --- | --- | | T1 `a` | lower bound of the uniform distribution | | T2 `b` | upper bound of the uniform distribution | | UniformRandomNumberGenerator `urng` | (optional) random number generator to use; if not specified, defaults to `rndGen` | Returns: A single random variate drawn from the uniform distribution between `a` and `b`, whose type is the common type of these parameters Examples: ``` auto rnd = Random(unpredictableSeed); // Generate an integer in [0, 1023] auto a = uniform(0, 1024, rnd); assert(0 <= a && a < 1024); // Generate a float in [0, 1) auto b = uniform(0.0f, 1.0f, rnd); assert(0 <= b && b < 1); // Generate a float in [0, 1] b = uniform!"[]"(0.0f, 1.0f, rnd); assert(0 <= b && b <= 1); // Generate a float in (0, 1) b = uniform!"()"(0.0f, 1.0f, rnd); assert(0 < b && b < 1); ``` Examples: Create an array of random numbers using range functions and UFCS ``` import std.array : array; import std.range : generate, takeExactly; int[] arr = generate!(() => uniform(0, 100)).takeExactly(10).array; writeln(arr.length); // 10 assert(arr[0] >= 0 && arr[0] < 100); ``` auto **uniform**(T, UniformRandomNumberGenerator)(ref UniformRandomNumberGenerator urng) Constraints: if (!is(T == enum) && (isIntegral!T || isSomeChar!T) && isUniformRNG!UniformRandomNumberGenerator); auto **uniform**(T)() Constraints: if (!is(T == enum) && (isIntegral!T || isSomeChar!T)); auto **uniform**(E, UniformRandomNumberGenerator)(ref UniformRandomNumberGenerator urng) Constraints: if (is(E == enum) && isUniformRNG!UniformRandomNumberGenerator); auto **uniform**(E)() Constraints: if (is(E == enum)); Generates a uniformly-distributed number in the range `[T.min, T.max]` for any integral or character type `T`. If no random number generator is passed, uses the default `rndGen`. If an `enum` is used as type, the random variate is drawn with equal probability from any of the possible values of the enum `E`. Parameters: | | | | --- | --- | | UniformRandomNumberGenerator `urng` | (optional) random number generator to use; if not specified, defaults to `rndGen` | Returns: Random variate drawn from the uniform distribution across all possible values of the integral, character or enum type `T`. Examples: ``` auto rnd = MinstdRand0(42); writeln(rnd.uniform!ubyte); // 102 writeln(rnd.uniform!ulong); // 4838462006927449017 enum Fruit { apple, mango, pear } version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147 writeln(rnd.uniform!Fruit); // Fruit.mango ``` T **uniform01**(T = double)() Constraints: if (isFloatingPoint!T); T **uniform01**(T = double, UniformRNG)(ref UniformRNG rng) Constraints: if (isFloatingPoint!T && isUniformRNG!UniformRNG); Generates a uniformly-distributed floating point number of type `T` in the range [0, 1). If no random number generator is specified, the default RNG `rndGen` will be used as the source of randomness. `uniform01` offers a faster generation of random variates than the equivalent `uniform!"[)"(0.0, 1.0)` and so may be preferred for some applications. Parameters: | | | | --- | --- | | UniformRNG `rng` | (optional) random number generator to use; if not specified, defaults to `rndGen` | Returns: Floating-point random variate of type `T` drawn from the uniform distribution across the half-open interval [0, 1). Examples: ``` import std.math : feqrel; auto rnd = MinstdRand0(42); // Generate random numbers in the range in the range [0, 1) auto u1 = uniform01(rnd); assert(u1 >= 0 && u1 < 1); auto u2 = rnd.uniform01!float; assert(u2 >= 0 && u2 < 1); // Confirm that the random values with the initial seed 42 are 0.000328707 and 0.524587 assert(u1.feqrel(0.000328707) > 20); assert(u2.feqrel(0.524587) > 20); ``` F[] **uniformDistribution**(F = double)(size\_t n, F[] useThis = null) Constraints: if (isFloatingPoint!F); Generates a uniform probability distribution of size `n`, i.e., an array of size `n` of positive numbers of type `F` that sum to `1`. If `useThis` is provided, it is used as storage. Examples: ``` import std.algorithm.iteration : reduce; import std.math : approxEqual; auto a = uniformDistribution(5); writeln(a.length); // 5 assert(approxEqual(reduce!"a + b"(a), 1)); a = uniformDistribution(10, a); writeln(a.length); // 10 assert(approxEqual(reduce!"a + b"(a), 1)); ``` ref auto **choice**(Range, RandomGen = Random)(auto ref Range range, ref RandomGen urng) Constraints: if (isRandomAccessRange!Range && hasLength!Range && isUniformRNG!RandomGen); ref auto **choice**(Range)(auto ref Range range); Returns a random, uniformly chosen, element `e` from the supplied `Range range`. If no random number generator is passed, the default `rndGen` is used. Parameters: | | | | --- | --- | | Range `range` | a random access range that has the `length` property defined | | RandomGen `urng` | (optional) random number generator to use; if not specified, defaults to `rndGen` | Returns: A single random element drawn from the `range`. If it can, it will return a `ref` to the `range element`, otherwise it will return a copy. Examples: ``` auto rnd = MinstdRand0(42); auto elem = [1, 2, 3, 4, 5].choice(rnd); version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147 writeln(elem); // 3 ``` Range **randomShuffle**(Range, RandomGen)(Range r, ref RandomGen gen) Constraints: if (isRandomAccessRange!Range && isUniformRNG!RandomGen); Range **randomShuffle**(Range)(Range r) Constraints: if (isRandomAccessRange!Range); Shuffles elements of `r` using `gen` as a shuffler. `r` must be a random-access range with length. If no RNG is specified, `rndGen` will be used. Parameters: | | | | --- | --- | | Range `r` | random-access range whose elements are to be shuffled | | RandomGen `gen` | (optional) random number generator to use; if not specified, defaults to `rndGen` | Returns: The shuffled random-access range. Examples: ``` auto rnd = MinstdRand0(42); auto arr = [1, 2, 3, 4, 5].randomShuffle(rnd); version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147 writeln(arr); // [3, 5, 2, 4, 1] ``` Range **partialShuffle**(Range, RandomGen)(Range r, in size\_t n, ref RandomGen gen) Constraints: if (isRandomAccessRange!Range && isUniformRNG!RandomGen); Range **partialShuffle**(Range)(Range r, in size\_t n) Constraints: if (isRandomAccessRange!Range); Partially shuffles the elements of `r` such that upon returning `r[0 .. n]` is a random subset of `r` and is randomly ordered. `r[n .. r.length]` will contain the elements not in `r[0 .. n]`. These will be in an undefined order, but will not be random in the sense that their order after `partialShuffle` returns will not be independent of their order before `partialShuffle` was called. `r` must be a random-access range with length. `n` must be less than or equal to `r.length`. If no RNG is specified, `rndGen` will be used. Parameters: | | | | --- | --- | | Range `r` | random-access range whose elements are to be shuffled | | size\_t `n` | number of elements of `r` to shuffle (counting from the beginning); must be less than `r.length` | | RandomGen `gen` | (optional) random number generator to use; if not specified, defaults to `rndGen` | Returns: The shuffled random-access range. Examples: ``` auto rnd = MinstdRand0(42); auto arr = [1, 2, 3, 4, 5, 6]; arr = arr.dup.partialShuffle(1, rnd); version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147 assert(arr == [2, 1, 3, 4, 5, 6]); // 1<->2 arr = arr.dup.partialShuffle(2, rnd); version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147 assert(arr == [1, 4, 3, 2, 5, 6]); // 1<->2, 2<->4 arr = arr.dup.partialShuffle(3, rnd); version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147 assert(arr == [5, 4, 6, 2, 1, 3]); // 1<->5, 2<->4, 3<->6 ``` size\_t **dice**(Rng, Num)(ref Rng rnd, Num[] proportions...) Constraints: if (isNumeric!Num && isForwardRange!Rng); size\_t **dice**(R, Range)(ref R rnd, Range proportions) Constraints: if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range); size\_t **dice**(Range)(Range proportions) Constraints: if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range); size\_t **dice**(Num)(Num[] proportions...) Constraints: if (isNumeric!Num); Rolls a dice with relative probabilities stored in `proportions`. Returns the index in `proportions` that was chosen. Parameters: | | | | --- | --- | | Rng `rnd` | (optional) random number generator to use; if not specified, defaults to `rndGen` | | Num[] `proportions` | forward range or list of individual values whose elements correspond to the probabilities with which to choose the corresponding index value | Returns: Random variate drawn from the index values [0, ... `proportions.length` - 1], with the probability of getting an individual index value `i` being proportional to `proportions[i]`. Examples: ``` auto x = dice(0.5, 0.5); // x is 0 or 1 in equal proportions auto y = dice(50, 50); // y is 0 or 1 in equal proportions auto z = dice(70, 20, 10); // z is 0 70% of the time, 1 20% of the time, // and 2 10% of the time ``` Examples: ``` auto rnd = MinstdRand0(42); auto z = rnd.dice(70, 20, 10); writeln(z); // 0 z = rnd.dice(30, 20, 40, 10); writeln(z); // 2 ``` struct **RandomCover**(Range, UniformRNG = void) if (isRandomAccessRange!Range && (isUniformRNG!UniformRNG || is(UniformRNG == void))); auto **randomCover**(Range, UniformRNG)(Range r, auto ref UniformRNG rng) Constraints: if (isRandomAccessRange!Range && isUniformRNG!UniformRNG); auto **randomCover**(Range)(Range r) Constraints: if (isRandomAccessRange!Range); Covers a given range `r` in a random manner, i.e. goes through each element of `r` once and only once, just in a random order. `r` must be a random-access range with length. If no random number generator is passed to `randomCover`, the thread-global RNG rndGen will be used internally. Parameters: | | | | --- | --- | | Range `r` | random-access range to cover | | UniformRNG `rng` | (optional) random number generator to use; if not specified, defaults to `rndGen` | Returns: Range whose elements consist of the elements of `r`, in random order. Will be a forward range if both `r` and `rng` are forward ranges, an [input range](std_range_primitives#isInputRange) otherwise. Examples: ``` import std.algorithm.comparison : equal; import std.range : iota; auto rnd = MinstdRand0(42); version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147 assert(10.iota.randomCover(rnd).equal([7, 4, 2, 0, 1, 6, 8, 3, 9, 5])); ``` struct **RandomSample**(Range, UniformRNG = void) if (isInputRange!Range && (isUniformRNG!UniformRNG || is(UniformRNG == void))); auto **randomSample**(Range)(Range r, size\_t n, size\_t total) Constraints: if (isInputRange!Range); auto **randomSample**(Range)(Range r, size\_t n) Constraints: if (isInputRange!Range && hasLength!Range); auto **randomSample**(Range, UniformRNG)(Range r, size\_t n, size\_t total, auto ref UniformRNG rng) Constraints: if (isInputRange!Range && isUniformRNG!UniformRNG); auto **randomSample**(Range, UniformRNG)(Range r, size\_t n, auto ref UniformRNG rng) Constraints: if (isInputRange!Range && hasLength!Range && isUniformRNG!UniformRNG); Selects a random subsample out of `r`, containing exactly `n` elements. The order of elements is the same as in the original range. The total length of `r` must be known. If `total` is passed in, the total number of sample is considered to be `total`. Otherwise, `RandomSample` uses `r.length`. Parameters: | | | | --- | --- | | Range `r` | range to sample from | | size\_t `n` | number of elements to include in the sample; must be less than or equal to the total number of elements in `r` and/or the parameter `total` (if provided) | | size\_t `total` | (semi-optional) number of elements of `r` from which to select the sample (counting from the beginning); must be less than or equal to the total number of elements in `r` itself. May be omitted if `r` has the `.length` property and the sample is to be drawn from all elements of `r`. | | UniformRNG `rng` | (optional) random number generator to use; if not specified, defaults to `rndGen` | Returns: Range whose elements consist of a randomly selected subset of the elements of `r`, in the same order as these elements appear in `r` itself. Will be a forward range if both `r` and `rng` are forward ranges, an input range otherwise. `RandomSample` implements Jeffrey Scott Vitter's Algorithm D (see Vitter [1984](http://dx.doi.org/10.1145/358105.893), [1987](http://dx.doi.org/10.1145/23002.23003)), which selects a sample of size `n` in O(n) steps and requiring O(n) random variates, regardless of the size of the data being sampled. The exception to this is if traversing k elements on the input range is itself an O(k) operation (e.g. when sampling lines from an input file), in which case the sampling calculation will inevitably be of O(total). RandomSample will throw an exception if `total` is verifiably less than the total number of elements available in the input, or if `n > total`. If no random number generator is passed to `randomSample`, the thread-global RNG rndGen will be used internally. Examples: ``` import std.algorithm.comparison : equal; import std.range : iota; auto rnd = MinstdRand0(42); assert(10.iota.randomSample(3, rnd).equal([7, 8, 9])); ``` const @property bool **empty**(); @property ref auto **front**(); void **popFront**(); const @property typeof(this) **save**(); const @property size\_t **length**(); Range primitives. @property size\_t **index**(); Returns the index of the visited record.
programming_docs
d rt.config rt.config ========= Configuration options for druntime. The default way to configure the runtime is by passing command line arguments starting with `--DRT-` and followed by the option name, e.g. `--DRT-gcopt` to configure the GC. When command line parsing is enabled, command line options starting with `--DRT-` are filtered out before calling main, so the program will not see them. They are still available via `rt_args()`. Configuration via the command line can be disabled by declaring a variable for the linker to pick up before using it's default from the runtime: ``` extern(C) __gshared bool rt_cmdline_enabled = false; ``` Likewise, declare a boolean rt\_envvars\_enabled to enable configuration via the environment variable `DRT_` followed by the option name, e.g. `DRT_GCOPT`: ``` extern(C) __gshared bool rt_envvars_enabled = true; ``` Setting default configuration properties in the executable can be done by specifying an array of options named `rt_options`: ``` extern(C) __gshared string[] rt_options = [ "gcopt=precise:1 profile:1"]; ``` Evaluation order of options is `rt_options`, then environment variables, then command line arguments, i.e. if command line arguments are not disabled, they can override options specified through the environment or embedded in the executable. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Rainer Schuetze Source [rt/config.d](https://github.com/dlang/druntime/blob/master/src/rt/config.d) nothrow @nogc string **rt\_configOption**(string opt, scope rt\_configCallBack dg = null, bool reverse = false); get a druntime config option using standard configuration options opt name of the option to retrieve dg if non-null, passes the option through this delegate and only returns its return value if non-null reverse reverse the default processing order cmdline/envvar/rt\_options to allow overwriting settings in the delegate with values from higher priority returns the options' value if * set on the command line as "--DRT-=value" (rt\_cmdline\_enabled enabled) * the environment variable "DRT\_" is set (rt\_envvars\_enabled enabled) * rt\_options[] contains an entry "=value" * null otherwise d core.sync.barrier core.sync.barrier ================= The barrier module provides a primitive for synchronizing the progress of a group of threads. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) Authors: Sean Kelly Source [core/sync/barrier.d](https://github.com/dlang/druntime/blob/master/src/core/sync/barrier.d) class **Barrier**; This class represents a barrier across which threads may only travel in groups of a specific size. Examples: ``` import core.thread; int numThreads = 10; auto barrier = new Barrier( numThreads ); auto synInfo = new Object; int numReady = 0; int numPassed = 0; void threadFn() { synchronized( synInfo ) { ++numReady; } barrier.wait(); synchronized( synInfo ) { ++numPassed; } } auto group = new ThreadGroup; for ( int i = 0; i < numThreads; ++i ) { group.create( &threadFn ); } group.joinAll(); assert( numReady == numThreads && numPassed == numThreads ); ``` this(uint limit); Initializes a barrier object which releases threads in groups of limit in size. Parameters: | | | | --- | --- | | uint `limit` | The number of waiting threads to release in unison. | Throws: SyncError on error. void **wait**(); Wait for the pre-determined number of threads and then proceed. Throws: SyncError on error. d core.checkedint core.checkedint =============== This module implements integral arithmetic primitives that check for out-of-range results. Integral arithmetic operators operate on fixed width types. Results that are not representable in those fixed widths are silently truncated to fit. This module offers integral arithmetic primitives that produce the same results, but set an 'overflow' flag when such truncation occurs. The setting is sticky, meaning that numerous operations can be cascaded and then the flag need only be checked at the end. Whether the operation is signed or unsigned is indicated by an 's' or 'u' suffix, respectively. While this could be achieved without such suffixes by using overloading on the signedness of the types, the suffix makes it clear which is happening without needing to examine the types. While the generic versions of these functions are computationally expensive relative to the cost of the operation itself, compiler implementations are free to recognize them and generate equivalent and faster code. References [Fast Integer Overflow Checks](http://blog.regehr.org/archives/1139) License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) Authors: Walter Bright Source [core/checkedint.d](https://github.com/dlang/druntime/blob/master/src/core/checkedint.d) int **adds**()(int x, int y, ref bool overflow); long **adds**()(long x, long y, ref bool overflow); Add two signed integers, checking for overflow. The overflow is sticky, meaning a sequence of operations can be done and overflow need only be checked at the end. Parameters: | | | | --- | --- | | int `x` | left operand | | int `y` | right operand | | bool `overflow` | set if an overflow occurs, is not affected otherwise | Returns: the sum uint **addu**()(uint x, uint y, ref bool overflow); ulong **addu**()(ulong x, ulong y, ref bool overflow); Add two unsigned integers, checking for overflow (aka carry). The overflow is sticky, meaning a sequence of operations can be done and overflow need only be checked at the end. Parameters: | | | | --- | --- | | uint `x` | left operand | | uint `y` | right operand | | bool `overflow` | set if an overflow occurs, is not affected otherwise | Returns: the sum int **subs**()(int x, int y, ref bool overflow); long **subs**()(long x, long y, ref bool overflow); Subtract two signed integers, checking for overflow. The overflow is sticky, meaning a sequence of operations can be done and overflow need only be checked at the end. Parameters: | | | | --- | --- | | int `x` | left operand | | int `y` | right operand | | bool `overflow` | set if an overflow occurs, is not affected otherwise | Returns: the difference uint **subu**()(uint x, uint y, ref bool overflow); ulong **subu**()(ulong x, ulong y, ref bool overflow); Subtract two unsigned integers, checking for overflow (aka borrow). The overflow is sticky, meaning a sequence of operations can be done and overflow need only be checked at the end. Parameters: | | | | --- | --- | | uint `x` | left operand | | uint `y` | right operand | | bool `overflow` | set if an overflow occurs, is not affected otherwise | Returns: the difference int **negs**()(int x, ref bool overflow); long **negs**()(long x, ref bool overflow); Negate an integer. Parameters: | | | | --- | --- | | int `x` | operand | | bool `overflow` | set if x cannot be negated, is not affected otherwise | Returns: the negation of x int **muls**()(int x, int y, ref bool overflow); long **muls**()(long x, long y, ref bool overflow); Multiply two signed integers, checking for overflow. The overflow is sticky, meaning a sequence of operations can be done and overflow need only be checked at the end. Parameters: | | | | --- | --- | | int `x` | left operand | | int `y` | right operand | | bool `overflow` | set if an overflow occurs, is not affected otherwise | Returns: the product uint **mulu**()(uint x, uint y, ref bool overflow); ulong **mulu**()(ulong x, uint y, ref bool overflow); ulong **mulu**()(ulong x, ulong y, ref bool overflow); Multiply two unsigned integers, checking for overflow (aka carry). The overflow is sticky, meaning a sequence of operations can be done and overflow need only be checked at the end. Parameters: | | | | --- | --- | | uint `x` | left operand | | uint `y` | right operand | | bool `overflow` | set if an overflow occurs, is not affected otherwise | Returns: the product d std.utf std.utf ======= Encode and decode UTF-8, UTF-16 and UTF-32 strings. UTF character support is restricted to `'\u0000' <= character <= '\U0010FFFF'`. | Category | Functions | | --- | --- | | Decode | [`decode`](#decode) [`decodeFront`](#decodeFront) | | Lazy decode | [`byCodeUnit`](#byCodeUnit) [`byChar`](#byChar) [`byWchar`](#byWchar) [`byDchar`](#byDchar) [`byUTF`](#byUTF) | | Encode | [`encode`](#encode) [`toUTF8`](#toUTF8) [`toUTF16`](#toUTF16) [`toUTF32`](#toUTF32) [`toUTFz`](#toUTFz) [`toUTF16z`](#toUTF16z) | | Length | [`codeLength`](#codeLength) [`count`](#count) [`stride`](#stride) [`strideBack`](#strideBack) | | Index | [`toUCSindex`](#toUCSindex) [`toUTFindex`](#toUTFindex) | | Validation | [`isValidDchar`](#isValidDchar) [`validate`](#validate) | | Miscellaneous | [`replacementDchar`](#replacementDchar) [`UseReplacementDchar`](#UseReplacementDchar) [`UTFException`](#UTFException) | See Also: [Wikipedia](http://en.wikipedia.org/wiki/Unicode) <http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8> <http://anubis.dkuug.dk/JTC1/SC2/WG2/docs/n1335> License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com) and [Jonathan M Davis](http://jmdavisprog.com) Source [std/utf.d](https://github.com/dlang/phobos/blob/master/std/utf.d) class **UTFException**: core.exception.UnicodeException; Exception thrown on errors in std.utf functions. Examples: ``` import std.exception : assertThrown; char[4] buf; assertThrown!UTFException(encode(buf, cast(dchar) 0xD800)); assertThrown!UTFException(encode(buf, cast(dchar) 0xDBFF)); assertThrown!UTFException(encode(buf, cast(dchar) 0xDC00)); assertThrown!UTFException(encode(buf, cast(dchar) 0xDFFF)); assertThrown!UTFException(encode(buf, cast(dchar) 0x110000)); ``` pure nothrow @nogc @safe this(string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null); pure nothrow @safe this(string msg, size\_t index, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null); Standard exception constructors. const string **toString**(); Returns: A `string` detailing the invalid UTF sequence. pure nothrow @nogc @safe bool **isValidDchar**(dchar c); Check whether the given Unicode code point is valid. Parameters: | | | | --- | --- | | dchar `c` | code point to check | Returns: `true` if and only if `c` is a valid Unicode code point Note `'\uFFFE'` and `'\uFFFF'` are considered valid by `isValidDchar`, as they are permitted for internal use by an application, but they are not allowed for interchange by the Unicode standard. Examples: ``` assert( isValidDchar(cast(dchar) 0x41)); assert( isValidDchar(cast(dchar) 0x00)); assert(!isValidDchar(cast(dchar) 0xD800)); assert(!isValidDchar(cast(dchar) 0x11FFFF)); ``` uint **stride**(S)(auto ref S str, size\_t index) Constraints: if (is(S : const(char[])) || isRandomAccessRange!S && is(immutable(ElementType!S) == immutable(char))); uint **stride**(S)(auto ref S str) Constraints: if (is(S : const(char[])) || isInputRange!S && is(immutable(ElementType!S) == immutable(char))); uint **stride**(S)(auto ref S str, size\_t index) Constraints: if (is(S : const(wchar[])) || isRandomAccessRange!S && is(immutable(ElementType!S) == immutable(wchar))); pure @safe uint **stride**(S)(auto ref S str) Constraints: if (is(S : const(wchar[]))); uint **stride**(S)(auto ref S str) Constraints: if (isInputRange!S && is(immutable(ElementType!S) == immutable(wchar)) && !is(S : const(wchar[]))); uint **stride**(S)(auto ref S str, size\_t index = 0) Constraints: if (is(S : const(dchar[])) || isInputRange!S && is(immutable(ElementEncodingType!S) == immutable(dchar))); Calculate the length of the UTF sequence starting at `index` in `str`. Parameters: | | | | --- | --- | | S `str` | [input range](std_range_primitives#isInputRange) of UTF code units. Must be random access if `index` is passed | | size\_t `index` | starting index of UTF sequence (default: `0`) | Returns: The number of code units in the UTF sequence. For UTF-8, this is a value between 1 and 4 (as per [RFC 3629, section 3](http://tools.ietf.org/html/rfc3629#section-3)). For UTF-16, it is either 1 or 2. For UTF-32, it is always 1. Throws: May throw a `UTFException` if `str[index]` is not the start of a valid UTF sequence. Note `stride` will only analyze the first `str[index]` element. It will not fully verify the validity of the UTF sequence, nor even verify the presence of the sequence: it will not actually guarantee that `index + stride(str, index) <= str.length`. Examples: ``` writeln("a".stride); // 1 writeln("λ".stride); // 2 writeln("aλ".stride); // 1 writeln("aλ".stride(1)); // 2 writeln("𐐷".stride); // 4 ``` uint **strideBack**(S)(auto ref S str, size\_t index) Constraints: if (is(S : const(char[])) || isRandomAccessRange!S && is(immutable(ElementType!S) == immutable(char))); uint **strideBack**(S)(auto ref S str) Constraints: if (is(S : const(char[])) || isRandomAccessRange!S && hasLength!S && is(immutable(ElementType!S) == immutable(char))); uint **strideBack**(S)(auto ref S str) Constraints: if (isBidirectionalRange!S && is(immutable(ElementType!S) == immutable(char)) && !isRandomAccessRange!S); uint **strideBack**(S)(auto ref S str, size\_t index) Constraints: if (is(S : const(wchar[])) || isRandomAccessRange!S && is(immutable(ElementType!S) == immutable(wchar))); uint **strideBack**(S)(auto ref S str) Constraints: if (is(S : const(wchar[])) || isBidirectionalRange!S && is(immutable(ElementType!S) == immutable(wchar))); uint **strideBack**(S)(auto ref S str, size\_t index) Constraints: if (isRandomAccessRange!S && is(immutable(ElementEncodingType!S) == immutable(dchar))); uint **strideBack**(S)(auto ref S str) Constraints: if (isBidirectionalRange!S && is(immutable(ElementEncodingType!S) == immutable(dchar))); Calculate the length of the UTF sequence ending one code unit before `index` in `str`. Parameters: | | | | --- | --- | | S `str` | bidirectional range of UTF code units. Must be random access if `index` is passed | | size\_t `index` | index one past end of UTF sequence (default: `str.length`) | Returns: The number of code units in the UTF sequence. For UTF-8, this is a value between 1 and 4 (as per [RFC 3629, section 3](http://tools.ietf.org/html/rfc3629#section-3)). For UTF-16, it is either 1 or 2. For UTF-32, it is always 1. Throws: May throw a `UTFException` if `str[index]` is not one past the end of a valid UTF sequence. Note `strideBack` will only analyze the element at `str[index - 1]` element. It will not fully verify the validity of the UTF sequence, nor even verify the presence of the sequence: it will not actually guarantee that `strideBack(str, index) <= index`. Examples: ``` writeln("a".strideBack); // 1 writeln("λ".strideBack); // 2 writeln("aλ".strideBack); // 2 writeln("aλ".strideBack(1)); // 1 writeln("𐐷".strideBack); // 4 ``` pure @safe size\_t **toUCSindex**(C)(const(C)[] str, size\_t index) Constraints: if (isSomeChar!C); Given `index` into `str` and assuming that `index` is at the start of a UTF sequence, `toUCSindex` determines the number of UCS characters up to `index`. So, `index` is the index of a code unit at the beginning of a code point, and the return value is how many code points into the string that that code point is. Examples: ``` writeln(toUCSindex(`hello world`, 7)); // 7 writeln(toUCSindex(`hello world`w, 7)); // 7 writeln(toUCSindex(`hello world`d, 7)); // 7 writeln(toUCSindex(`Ma Chérie`, 7)); // 6 writeln(toUCSindex(`Ma Chérie`w, 7)); // 7 writeln(toUCSindex(`Ma Chérie`d, 7)); // 7 writeln(toUCSindex(`さいごの果実 / ミツバチと科学者`, 9)); // 3 writeln(toUCSindex(`さいごの果実 / ミツバチと科学者`w, 9)); // 9 writeln(toUCSindex(`さいごの果実 / ミツバチと科学者`d, 9)); // 9 ``` pure @safe size\_t **toUTFindex**(C)(const(C)[] str, size\_t n) Constraints: if (isSomeChar!C); Given a UCS index `n` into `str`, returns the UTF index. So, `n` is how many code points into the string the code point is, and the array index of the code unit is returned. Examples: ``` writeln(toUTFindex(`hello world`, 7)); // 7 writeln(toUTFindex(`hello world`w, 7)); // 7 writeln(toUTFindex(`hello world`d, 7)); // 7 writeln(toUTFindex(`Ma Chérie`, 6)); // 7 writeln(toUTFindex(`Ma Chérie`w, 7)); // 7 writeln(toUTFindex(`Ma Chérie`d, 7)); // 7 writeln(toUTFindex(`さいごの果実 / ミツバチと科学者`, 3)); // 9 writeln(toUTFindex(`さいごの果実 / ミツバチと科学者`w, 9)); // 9 writeln(toUTFindex(`さいごの果実 / ミツバチと科学者`d, 9)); // 9 ``` alias **UseReplacementDchar** = std.typecons.Flag!"useReplacementDchar".Flag; Whether or not to replace invalid UTF with [`replacementDchar`](#replacementDchar) dchar **decode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(auto ref S str, ref size\_t index) Constraints: if (!isSomeString!S && isRandomAccessRange!S && hasSlicing!S && hasLength!S && isSomeChar!(ElementType!S)); pure @trusted dchar **decode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(auto ref S str, ref size\_t index) Constraints: if (isSomeString!S); Decodes and returns the code point starting at `str[index]`. `index` is advanced to one past the decoded code point. If the code point is not well-formed, then a `UTFException` is thrown and `index` remains unchanged. decode will only work with strings and random access ranges of code units with length and slicing, whereas [`decodeFront`](#decodeFront) will work with any input range of code units. Parameters: | | | | --- | --- | | useReplacementDchar | if invalid UTF, return replacementDchar rather than throwing | | S `str` | input string or indexable Range | | size\_t `index` | starting index into s[]; incremented by number of code units processed | Returns: decoded character Throws: [`UTFException`](#UTFException) if `str[index]` is not the start of a valid UTF sequence and useReplacementDchar is `No.useReplacementDchar` Examples: ``` size_t i; assert("a".decode(i) == 'a' && i == 1); i = 0; assert("å".decode(i) == 'å' && i == 2); i = 1; assert("aå".decode(i) == 'å' && i == 3); i = 0; assert("å"w.decode(i) == 'å' && i == 1); // ë as a multi-code point grapheme i = 0; assert("e\u0308".decode(i) == 'e' && i == 1); // ë as a single code point grapheme i = 0; assert("ë".decode(i) == 'ë' && i == 2); i = 0; assert("ë"w.decode(i) == 'ë' && i == 1); ``` dchar **decodeFront**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(ref S str, out size\_t numCodeUnits) Constraints: if (!isSomeString!S && isInputRange!S && isSomeChar!(ElementType!S)); pure @trusted dchar **decodeFront**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(ref S str, out size\_t numCodeUnits) Constraints: if (isSomeString!S); dchar **decodeFront**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(ref S str) Constraints: if (isInputRange!S && isSomeChar!(ElementType!S)); `decodeFront` is a variant of [`decode`](#decode) which specifically decodes the first code point. Unlike [`decode`](#decode), `decodeFront` accepts any [input range](std_range_primitives#isInputRange) of code units (rather than just a string or random access range). It also takes the range by `ref` and pops off the elements as it decodes them. If `numCodeUnits` is passed in, it gets set to the number of code units which were in the code point which was decoded. Parameters: | | | | --- | --- | | useReplacementDchar | if invalid UTF, return replacementDchar rather than throwing | | S `str` | input string or indexable Range | | size\_t `numCodeUnits` | set to number of code units processed | Returns: decoded character Throws: [`UTFException`](#UTFException) if `str.front` is not the start of a valid UTF sequence. If an exception is thrown, then there is no guarantee as to the number of code units which were popped off, as it depends on the type of range being used and how many code units had to be popped off before the code point was determined to be invalid. Examples: ``` import std.range.primitives; string str = "Hello, World!"; assert(str.decodeFront == 'H' && str == "ello, World!"); str = "å"; assert(str.decodeFront == 'å' && str.empty); str = "å"; size_t i; assert(str.decodeFront(i) == 'å' && i == 2 && str.empty); ``` dchar **decodeBack**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(ref S str, out size\_t numCodeUnits) Constraints: if (isSomeString!S); dchar **decodeBack**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(ref S str, out size\_t numCodeUnits) Constraints: if (!isSomeString!S && isSomeChar!(ElementType!S) && isBidirectionalRange!S && (isRandomAccessRange!S && hasLength!S || !isRandomAccessRange!S)); dchar **decodeBack**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(ref S str) Constraints: if (isSomeString!S || isRandomAccessRange!S && hasLength!S && isSomeChar!(ElementType!S) || !isRandomAccessRange!S && isBidirectionalRange!S && isSomeChar!(ElementType!S)); `decodeBack` is a variant of [`decode`](#decode) which specifically decodes the last code point. Unlike [`decode`](#decode), `decodeBack` accepts any bidirectional range of code units (rather than just a string or random access range). It also takes the range by `ref` and pops off the elements as it decodes them. If `numCodeUnits` is passed in, it gets set to the number of code units which were in the code point which was decoded. Parameters: | | | | --- | --- | | useReplacementDchar | if invalid UTF, return `replacementDchar` rather than throwing | | S `str` | input string or bidirectional Range | | size\_t `numCodeUnits` | gives the number of code units processed | Returns: A decoded UTF character. Throws: [`UTFException`](#UTFException) if `str.back` is not the end of a valid UTF sequence. If an exception is thrown, the `str` itself remains unchanged, but there is no guarantee as to the value of `numCodeUnits` (when passed). Examples: ``` import std.range.primitives; string str = "Hello, World!"; assert(str.decodeBack == '!' && str == "Hello, World"); str = "å"; assert(str.decodeBack == 'å' && str.empty); str = "å"; size_t i; assert(str.decodeBack(i) == 'å' && i == 2 && str.empty); ``` pure @safe size\_t **encode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar)(out char[4] buf, dchar c); pure @safe size\_t **encode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar)(out wchar[2] buf, dchar c); pure @safe size\_t **encode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar)(out dchar[1] buf, dchar c); Encodes `c` into the static array, `buf`, and returns the actual length of the encoded character (a number between `1` and `4` for `char[4]` buffers and a number between `1` and `2` for `wchar[2]` buffers). Throws: `UTFException` if `c` is not a valid UTF code point. Examples: ``` import std.exception : assertThrown; import std.typecons : Yes; char[4] buf; assert(encode(buf, '\u0000') == 1 && buf[0 .. 1] == "\u0000"); assert(encode(buf, '\u007F') == 1 && buf[0 .. 1] == "\u007F"); assert(encode(buf, '\u0080') == 2 && buf[0 .. 2] == "\u0080"); assert(encode(buf, '\uE000') == 3 && buf[0 .. 3] == "\uE000"); assert(encode(buf, 0xFFFE) == 3 && buf[0 .. 3] == "\xEF\xBF\xBE"); assertThrown!UTFException(encode(buf, cast(dchar) 0x110000)); encode!(Yes.useReplacementDchar)(buf, cast(dchar) 0x110000); auto slice = buf[]; writeln(slice.decodeFront); // replacementDchar ``` Examples: ``` import std.exception : assertThrown; import std.typecons : Yes; wchar[2] buf; assert(encode(buf, '\u0000') == 1 && buf[0 .. 1] == "\u0000"); assert(encode(buf, '\uD7FF') == 1 && buf[0 .. 1] == "\uD7FF"); assert(encode(buf, '\uE000') == 1 && buf[0 .. 1] == "\uE000"); assert(encode(buf, '\U00010000') == 2 && buf[0 .. 2] == "\U00010000"); assert(encode(buf, '\U0010FFFF') == 2 && buf[0 .. 2] == "\U0010FFFF"); assertThrown!UTFException(encode(buf, cast(dchar) 0xD800)); encode!(Yes.useReplacementDchar)(buf, cast(dchar) 0x110000); auto slice = buf[]; writeln(slice.decodeFront); // replacementDchar ``` Examples: ``` import std.exception : assertThrown; import std.typecons : Yes; dchar[1] buf; assert(encode(buf, '\u0000') == 1 && buf[0] == '\u0000'); assert(encode(buf, '\uD7FF') == 1 && buf[0] == '\uD7FF'); assert(encode(buf, '\uE000') == 1 && buf[0] == '\uE000'); assert(encode(buf, '\U0010FFFF') == 1 && buf[0] == '\U0010FFFF'); assertThrown!UTFException(encode(buf, cast(dchar) 0xD800)); encode!(Yes.useReplacementDchar)(buf, cast(dchar) 0x110000); writeln(buf[0]); // replacementDchar ``` pure @safe void **encode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar)(ref char[] str, dchar c); pure @safe void **encode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar)(ref wchar[] str, dchar c); pure @safe void **encode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar)(ref dchar[] str, dchar c); Encodes `c` in `str`'s encoding and appends it to `str`. Throws: `UTFException` if `c` is not a valid UTF code point. Examples: ``` char[] s = "abcd".dup; dchar d1 = 'a'; dchar d2 = 'ø'; encode(s, d1); writeln(s.length); // 5 writeln(s); // "abcda" encode(s, d2); writeln(s.length); // 7 writeln(s); // "abcdaø" ``` pure nothrow @nogc @safe ubyte **codeLength**(C)(dchar c) Constraints: if (isSomeChar!C); Returns the number of code units that are required to encode the code point `c` when `C` is the character type used to encode it. Examples: ``` writeln(codeLength!char('a')); // 1 writeln(codeLength!wchar('a')); // 1 writeln(codeLength!dchar('a')); // 1 writeln(codeLength!char('\U0010FFFF')); // 4 writeln(codeLength!wchar('\U0010FFFF')); // 2 writeln(codeLength!dchar('\U0010FFFF')); // 1 ``` size\_t **codeLength**(C, InputRange)(InputRange input) Constraints: if (isInputRange!InputRange && !isInfinite!InputRange && isSomeChar!(ElementType!InputRange)); Returns the number of code units that are required to encode `str` in a string whose character type is `C`. This is particularly useful when slicing one string with the length of another and the two string types use different character types. Parameters: | | | | --- | --- | | C | the character type to get the encoding length for | | InputRange `input` | the [input range](std_range_primitives#isInputRange) to calculate the encoding length from | Returns: The number of code units in `input` when encoded to `C` Examples: ``` assert(codeLength!char("hello world") == "hello world".length); assert(codeLength!wchar("hello world") == "hello world"w.length); assert(codeLength!dchar("hello world") == "hello world"d.length); assert(codeLength!char(`プログラミング`) == `プログラミング`.length); assert(codeLength!wchar(`プログラミング`) == `プログラミング`w.length); assert(codeLength!dchar(`プログラミング`) == `プログラミング`d.length); string haystack = `Être sans la verité, ça, ce ne serait pas bien.`; wstring needle = `Être sans la verité`; assert(haystack[codeLength!char(needle) .. $] == `, ça, ce ne serait pas bien.`); ``` pure @safe void **validate**(S)(in S str) Constraints: if (isSomeString!S); Checks to see if `str` is well-formed unicode or not. Throws: `UTFException` if `str` is not well-formed. Examples: ``` import std.exception : assertThrown; char[] a = [167, 133, 175]; assertThrown!UTFException(validate(a)); ``` string **toUTF8**(S)(S s) Constraints: if (isInputRange!S && !isInfinite!S && isSomeChar!(ElementEncodingType!S)); Encodes the elements of `s` to UTF-8 and returns a newly allocated string of the elements. Parameters: | | | | --- | --- | | S `s` | the string to encode | Returns: A UTF-8 string See Also: For a lazy, non-allocating version of these functions, see [`byUTF`](#byUTF). Examples: ``` import std.algorithm.comparison : equal; // The ö is represented by two UTF-8 code units assert("Hellø"w.toUTF8.equal(['H', 'e', 'l', 'l', 0xC3, 0xB8])); // 𐐷 is four code units in UTF-8 assert("𐐷"d.toUTF8.equal([0xF0, 0x90, 0x90, 0xB7])); ``` wstring **toUTF16**(S)(S s) Constraints: if (isInputRange!S && !isInfinite!S && isSomeChar!(ElementEncodingType!S)); Encodes the elements of `s` to UTF-16 and returns a newly GC allocated `wstring` of the elements. Parameters: | | | | --- | --- | | S `s` | the range to encode | Returns: A UTF-16 string See Also: For a lazy, non-allocating version of these functions, see [`byUTF`](#byUTF). Examples: ``` import std.algorithm.comparison : equal; // these graphemes are two code units in UTF-16 and one in UTF-32 writeln("𤭢"d.length); // 1 writeln("𐐷"d.length); // 1 assert("𤭢"d.toUTF16.equal([0xD852, 0xDF62])); assert("𐐷"d.toUTF16.equal([0xD801, 0xDC37])); ``` dstring **toUTF32**(S)(S s) Constraints: if (isInputRange!S && !isInfinite!S && isSomeChar!(ElementEncodingType!S)); Encodes the elements of `s` to UTF-32 and returns a newly GC allocated `dstring` of the elements. Parameters: | | | | --- | --- | | S `s` | the range to encode | Returns: A UTF-32 string See Also: For a lazy, non-allocating version of these functions, see [`byUTF`](#byUTF). Examples: ``` import std.algorithm.comparison : equal; // these graphemes are two code units in UTF-16 and one in UTF-32 writeln("𤭢"w.length); // 2 writeln("𐐷"w.length); // 2 assert("𤭢"w.toUTF32.equal([0x00024B62])); assert("𐐷"w.toUTF32.equal([0x00010437])); ``` template **toUTFz**(P) if (isPointer!P && isSomeChar!(typeof(\*P.init))) Returns a C-style zero-terminated string equivalent to `str`. `str` must not contain embedded `'\0'`'s as any C function will treat the first `'\0'` that it sees as the end of the string. If `str.empty` is `true`, then a string containing only `'\0'` is returned. `toUTFz` accepts any type of string and is templated on the type of character pointer that you wish to convert to. It will avoid allocating a new string if it can, but there's a decent chance that it will end up having to allocate a new string - particularly when dealing with character types other than `char`. Warning 1: If the result of `toUTFz` equals `str.ptr`, then if anything alters the character one past the end of `str` (which is the `'\0'` character terminating the string), then the string won't be zero-terminated anymore. The most likely scenarios for that are if you append to `str` and no reallocation takes place or when `str` is a slice of a larger array, and you alter the character in the larger array which is one character past the end of `str`. Another case where it could occur would be if you had a mutable character array immediately after `str` in memory (for example, if they're member variables in a user-defined type with one declared right after the other) and that character array happened to start with `'\0'`. Such scenarios will never occur if you immediately use the zero-terminated string after calling `toUTFz` and the C function using it doesn't keep a reference to it. Also, they are unlikely to occur even if you save the zero-terminated string (the cases above would be among the few examples of where it could happen). However, if you save the zero-terminate string and want to be absolutely certain that the string stays zero-terminated, then simply append a `'\0'` to the string and use its `ptr` property rather than calling `toUTFz`. Warning 2: When passing a character pointer to a C function, and the C function keeps it around for any reason, make sure that you keep a reference to it in your D code. Otherwise, it may go away during a garbage collection cycle and cause a nasty bug when the C code tries to use it. Examples: ``` auto p1 = toUTFz!(char*)("hello world"); auto p2 = toUTFz!(const(char)*)("hello world"); auto p3 = toUTFz!(immutable(char)*)("hello world"); auto p4 = toUTFz!(char*)("hello world"d); auto p5 = toUTFz!(const(wchar)*)("hello world"); auto p6 = toUTFz!(immutable(dchar)*)("hello world"w); ``` pure @safe const(wchar)\* **toUTF16z**(C)(const(C)[] str) Constraints: if (isSomeChar!C); `toUTF16z` is a convenience function for `toUTFz!(const(wchar)*)`. Encodes string `s` into UTF-16 and returns the encoded string. `toUTF16z` is suitable for calling the 'W' functions in the Win32 API that take an `LPCWSTR` argument. Examples: ``` string str = "Hello, World!"; const(wchar)* p = str.toUTF16z; writeln(p[str.length]); // '\0' ``` pure nothrow @nogc @safe size\_t **count**(C)(const(C)[] str) Constraints: if (isSomeChar!C); Returns the total number of code points encoded in `str`. Supercedes This function supercedes [`toUCSindex`](#toUCSindex). Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Throws: `UTFException` if `str` is not well-formed. Examples: ``` writeln(count("")); // 0 writeln(count("a")); // 1 writeln(count("abc")); // 3 writeln(count("\u20AC100")); // 4 ``` enum dchar **replacementDchar**; Inserted in place of invalid UTF sequences. References <http://en.wikipedia.org/wiki/Replacement_character#Replacement_character> auto **byCodeUnit**(R)(R r) Constraints: if (isConvertibleToString!R && !isStaticArray!R || isInputRange!R && isSomeChar!(ElementEncodingType!R)); Iterate a range of char, wchar, or dchars by code unit. The purpose is to bypass the special case decoding that [`std.range.primitives.front`](std_range_primitives#front) does to character arrays. As a result, using ranges with `byCodeUnit` can be `nothrow` while [`std.range.primitives.front`](std_range_primitives#front) throws when it encounters invalid Unicode sequences. A code unit is a building block of the UTF encodings. Generally, an individual code unit does not represent what's perceived as a full character (a.k.a. a grapheme cluster in Unicode terminology). Many characters are encoded with multiple code units. For example, the UTF-8 code units for `ø` are `0xC3 0xB8`. That means, an individual element of `byCodeUnit` often does not form a character on its own. Attempting to treat it as one while iterating over the resulting range will give nonsensical results. Parameters: | | | | --- | --- | | R `r` | an [input range](std_range_primitives#isInputRange) of characters (including strings) or a type that implicitly converts to a string type. | Returns: If `r` is not an auto-decodable string (i.e. a narrow string or a user-defined type that implicits converts to a string type), then `r` is returned. Otherwise, `r` is converted to its corresponding string type (if it's not already a string) and wrapped in a random-access range where the element encoding type of the string (its code unit) is the element type of the range, and that range returned. The range has slicing. If `r` is quirky enough to be a struct or class which is an input range of characters on its own (i.e. it has the input range API as member functions), *and* it's implicitly convertible to a string type, then `r` is returned, and no implicit conversion takes place. If `r` is wrapped in a new range, then that range has a `source` property for returning the string that's currently contained within that range. See Also: Refer to the [`std.uni`](std_uni) docs for a reference on Unicode terminology. For a range that iterates by grapheme cluster (written character) see [`std.uni.byGrapheme`](std_uni#byGrapheme). Examples: ``` import std.range.primitives; import std.traits : isAutodecodableString; auto r = "Hello, World!".byCodeUnit(); static assert(hasLength!(typeof(r))); static assert(hasSlicing!(typeof(r))); static assert(isRandomAccessRange!(typeof(r))); static assert(is(ElementType!(typeof(r)) == immutable char)); // contrast with the range capabilities of standard strings (with or // without autodecoding enabled). auto s = "Hello, World!"; static assert(isBidirectionalRange!(typeof(r))); static if (isAutodecodableString!(typeof(s))) { // with autodecoding enabled, strings are non-random-access ranges of // dchar. static assert(is(ElementType!(typeof(s)) == dchar)); static assert(!isRandomAccessRange!(typeof(s))); static assert(!hasSlicing!(typeof(s))); static assert(!hasLength!(typeof(s))); } else { // without autodecoding, strings are normal arrays. static assert(is(ElementType!(typeof(s)) == immutable char)); static assert(isRandomAccessRange!(typeof(s))); static assert(hasSlicing!(typeof(s))); static assert(hasLength!(typeof(s))); } ``` Examples: `byCodeUnit` does no Unicode decoding ``` string noel1 = "noe\u0308l"; // noël using e + combining diaeresis assert(noel1.byCodeUnit[2] != 'ë'); writeln(noel1.byCodeUnit[2]); // 'e' string noel2 = "no\u00EBl"; // noël using a precomposed ë character // Because string is UTF-8, the code unit at index 2 is just // the first of a sequence that encodes 'ë' assert(noel2.byCodeUnit[2] != 'ë'); ``` Examples: `byCodeUnit` exposes a `source` property when wrapping narrow strings. ``` import std.algorithm.comparison : equal; import std.range : popFrontN; import std.traits : isAutodecodableString; { auto range = byCodeUnit("hello world"); range.popFrontN(3); assert(equal(range.save, "lo world")); static if (isAutodecodableString!string) // only enabled with autodecoding { string str = range.source; writeln(str); // "lo world" } } // source only exists if the range was wrapped { auto range = byCodeUnit("hello world"d); static assert(!__traits(compiles, range.source)); } ``` alias **byChar** = byUTF!(char, Flag.yes).byUTF(R)(R r) if (isAutodecodableString!R && isInputRange!R && isSomeChar!(ElementEncodingType!R)); alias **byWchar** = byUTF!(wchar, Flag.yes).byUTF(R)(R r) if (isAutodecodableString!R && isInputRange!R && isSomeChar!(ElementEncodingType!R)); alias **byDchar** = byUTF!(dchar, Flag.yes).byUTF(R)(R r) if (isAutodecodableString!R && isInputRange!R && isSomeChar!(ElementEncodingType!R)); Iterate an [input range](std_range_primitives#isInputRange) of characters by char, wchar, or dchar. These aliases simply forward to [`byUTF`](#byUTF) with the corresponding C argument. Parameters: | | | | --- | --- | | R r | input range of characters, or array of characters | template **byUTF**(C, UseReplacementDchar useReplacementDchar = Yes.useReplacementDchar) if (isSomeChar!C) Iterate an [input range](std_range_primitives#isInputRange) of characters by char type `C` by encoding the elements of the range. UTF sequences that cannot be converted to the specified encoding are either replaced by U+FFFD per "5.22 Best Practice for U+FFFD Substitution" of the Unicode Standard 6.2 or result in a thrown UTFException. Hence byUTF is not symmetric. This algorithm is lazy, and does not allocate memory. `@nogc`, `pure`-ity, `nothrow`, and `@safe`-ty are inferred from the `r` parameter. Parameters: | | | | --- | --- | | C | `char`, `wchar`, or `dchar` | | useReplacementDchar | UseReplacementDchar.yes means replace invalid UTF with `replacementDchar`, UseReplacementDchar.no means throw `UTFException` for invalid UTF | Throws: `UTFException` if invalid UTF sequence and `useReplacementDchar` is set to `UseReplacementDchar.yes` GC Does not use GC if `useReplacementDchar` is set to `UseReplacementDchar.no` Returns: A forward range if `R` is a range and not auto-decodable, as defined by [`std.traits.isAutodecodableString`](std_traits#isAutodecodableString), and if the base range is also a forward range. Or, if `R` is a range and it is auto-decodable and `is(ElementEncodingType!typeof(r) == C)`, then the range is passed to [`byCodeUnit`](#byCodeUnit). Otherwise, an input range of characters. Examples: ``` import std.algorithm.comparison : equal; // hellö as a range of `char`s, which are UTF-8 assert("hell\u00F6".byUTF!char().equal(['h', 'e', 'l', 'l', 0xC3, 0xB6])); // `wchar`s are able to hold the ö in a single element (UTF-16 code unit) assert("hell\u00F6".byUTF!wchar().equal(['h', 'e', 'l', 'l', 'ö'])); // 𐐷 is four code units in UTF-8, two in UTF-16, and one in UTF-32 assert("𐐷".byUTF!char().equal([0xF0, 0x90, 0x90, 0xB7])); assert("𐐷".byUTF!wchar().equal([0xD801, 0xDC37])); assert("𐐷".byUTF!dchar().equal([0x00010437])); ``` Examples: ``` import std.algorithm.comparison : equal; import std.exception : assertThrown; assert("hello\xF0betty".byChar.byUTF!(dchar, UseReplacementDchar.yes).equal("hello\uFFFDetty")); assertThrown!UTFException("hello\xF0betty".byChar.byUTF!(dchar, UseReplacementDchar.no).equal("hello betty")); ```
programming_docs
d std.experimental.logger.core std.experimental.logger.core ============================ Source [std/experimental/logger/core.d](https://github.com/dlang/phobos/blob/master/std/experimental/logger/core.d) template **isLoggingActiveAt**(LogLevel ll) This template evaluates if the passed `LogLevel` is active. The previously described version statements are used to decide if the `LogLevel` is active. The version statements only influence the compile unit they are used with, therefore this function can only disable logging this specific compile unit. enum bool **isLoggingActive**; This compile-time flag is `true` if logging is not statically disabled. @safe bool **isLoggingEnabled**()(LogLevel ll, LogLevel loggerLL, LogLevel globalLL, lazy bool condition = true); This functions is used at runtime to determine if a `LogLevel` is active. The same previously defined version statements are used to disable certain levels. Again the version statements are associated with a compile unit and can therefore not disable logging in other compile units. pure bool isLoggingEnabled()(LogLevel ll) @safe nothrow @nogc template **moduleLogLevel**(string moduleName) if (!moduleName.length) template **moduleLogLevel**(string moduleName) if (moduleName.length) This template returns the `LogLevel` named "logLevel" of type `LogLevel` defined in a user defined module where the filename has the suffix "loggerconfig.d". This `LogLevel` sets the minimal `LogLevel` of the module. A minimal `LogLevel` can be defined on a per module basis. In order to define a module `LogLevel` a file with a modulename "MODULENAME\_loggerconfig" must be found. If no such module exists and the module is a nested module, it is checked if there exists a "PARENT\_MODULE\_loggerconfig" module with such a symbol. If this module exists and it contains a `LogLevel` called logLevel this `LogLevel` will be used. This parent lookup is continued until there is no parent module. Then the moduleLogLevel is `LogLevel.all`. Examples: ``` static assert(moduleLogLevel!"" == LogLevel.all); ``` Examples: ``` static assert(moduleLogLevel!"not.amodule.path" == LogLevel.all); ``` void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy bool condition, lazy A args) Constraints: if (args.length != 1); void **log**(T, string moduleName = \_\_MODULE\_\_)(const LogLevel ll, lazy bool condition, lazy T arg, int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_); This function logs data. In order for the data to be processed, the `LogLevel` of the log call must be greater or equal to the `LogLevel` of the `sharedLog` and the `defaultLogLevel`; additionally the condition passed must be `true`. Parameters: | | | | --- | --- | | LogLevel `ll` | The `LogLevel` used by this log call. | | bool `condition` | The condition must be `true` for the data to be logged. | | A `args` | The data that should be logged. | Example ``` log(LogLevel.warning, true, "Hello World", 3.1415); ``` void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy A args) Constraints: if (args.length > 1 && !is(Unqual!(A[0]) : bool)); void **log**(T, string moduleName = \_\_MODULE\_\_)(const LogLevel ll, lazy T arg, int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_); This function logs data. In order for the data to be processed the `LogLevel` of the log call must be greater or equal to the `LogLevel` of the `sharedLog`. Parameters: | | | | --- | --- | | LogLevel `ll` | The `LogLevel` used by this log call. | | A `args` | The data that should be logged. | Example ``` log(LogLevel.warning, "Hello World", 3.1415); ``` void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy A args) Constraints: if (args.length != 1); void **log**(T, string moduleName = \_\_MODULE\_\_)(lazy bool condition, lazy T arg, int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_); This function logs data. In order for the data to be processed the `LogLevel` of the `sharedLog` must be greater or equal to the `defaultLogLevel` add the condition passed must be `true`. Parameters: | | | | --- | --- | | bool `condition` | The condition must be `true` for the data to be logged. | | A `args` | The data that should be logged. | Example ``` log(true, "Hello World", 3.1415); ``` void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) Constraints: if (args.length > 1 && !is(Unqual!(A[0]) : bool) && !is(Unqual!(A[0]) == LogLevel) || args.length == 0); This function logs data. In order for the data to be processed the `LogLevel` of the `sharedLog` must be greater or equal to the `defaultLogLevel`. Parameters: | | | | --- | --- | | A `args` | The data that should be logged. | Example ``` log("Hello World", 3.1415); ``` void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy bool condition, lazy string msg, lazy A args); This function logs data in a `printf`-style manner. In order for the data to be processed the `LogLevel` of the log call must be greater or equal to the `LogLevel` of the `sharedLog` and the `defaultLogLevel` additionally the condition passed must be `true`. Parameters: | | | | --- | --- | | LogLevel `ll` | The `LogLevel` used by this log call. | | bool `condition` | The condition must be `true` for the data to be logged. | | string `msg` | The `printf`-style string. | | A `args` | The data that should be logged. | Example ``` logf(LogLevel.warning, true, "Hello World %f", 3.1415); ``` void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy string msg, lazy A args); This function logs data in a `printf`-style manner. In order for the data to be processed the `LogLevel` of the log call must be greater or equal to the `LogLevel` of the `sharedLog` and the `defaultLogLevel`. Parameters: | | | | --- | --- | | LogLevel `ll` | The `LogLevel` used by this log call. | | string `msg` | The `printf`-style string. | | A `args` | The data that should be logged. | Example ``` logf(LogLevel.warning, "Hello World %f", 3.1415); ``` void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args); This function logs data in a `printf`-style manner. In order for the data to be processed the `LogLevel` of the log call must be greater or equal to the `defaultLogLevel` additionally the condition passed must be `true`. Parameters: | | | | --- | --- | | bool `condition` | The condition must be `true` for the data to be logged. | | string `msg` | The `printf`-style string. | | A `args` | The data that should be logged. | Example ``` logf(true, "Hello World %f", 3.1415); ``` void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args); This function logs data in a `printf`-style manner. In order for the data to be processed the `LogLevel` of the log call must be greater or equal to the `defaultLogLevel`. Parameters: | | | | --- | --- | | string `msg` | The `printf`-style string. | | A `args` | The data that should be logged. | Example ``` logf("Hello World %f", 3.1415); ``` template **defaultLogFunction**(LogLevel ll) This template provides the global log functions with the `LogLevel` is encoded in the function name. The aliases following this template create the public names of these log functions. alias **trace** = defaultLogFunction!LogLevel.**trace**.defaultLogFunction(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length > 0 && !is(Unqual!(A[0]) : bool) || args.length == 0); alias **info** = defaultLogFunction!LogLevel.**info**.defaultLogFunction(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length > 0 && !is(Unqual!(A[0]) : bool) || args.length == 0); alias **warning** = defaultLogFunction!LogLevel.**warning**.defaultLogFunction(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length > 0 && !is(Unqual!(A[0]) : bool) || args.length == 0); alias **error** = defaultLogFunction!LogLevel.**error**.defaultLogFunction(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length > 0 && !is(Unqual!(A[0]) : bool) || args.length == 0); alias **critical** = defaultLogFunction!LogLevel.**critical**.defaultLogFunction(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length > 0 && !is(Unqual!(A[0]) : bool) || args.length == 0); alias **fatal** = defaultLogFunction!LogLevel.**fatal**.defaultLogFunction(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length > 0 && !is(Unqual!(A[0]) : bool) || args.length == 0); This function logs data to the `stdThreadLocalLog`, optionally depending on a condition. In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the `stdThreadLocalLog` and must be greater or equal than the global `LogLevel`. Additionally the `LogLevel` must be greater or equal than the `LogLevel` of the `stdSharedLogger`. If a condition is given, it must evaluate to `true`. Parameters: | | | | --- | --- | | bool condition | The condition must be `true` for the data to be logged. | | A args | The data that should be logged. | Example ``` trace(1337, "is number"); info(1337, "is number"); error(1337, "is number"); critical(1337, "is number"); fatal(1337, "is number"); trace(true, 1337, "is number"); info(false, 1337, "is number"); error(true, 1337, "is number"); critical(false, 1337, "is number"); fatal(true, 1337, "is number"); ``` template **defaultLogFunctionf**(LogLevel ll) This template provides the global `printf`-style log functions with the `LogLevel` is encoded in the function name. The aliases following this template create the public names of the log functions. alias **tracef** = defaultLogFunctionf!LogLevel.trace.defaultLogFunctionf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args); alias **infof** = defaultLogFunctionf!LogLevel.info.defaultLogFunctionf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args); alias **warningf** = defaultLogFunctionf!LogLevel.warning.defaultLogFunctionf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args); alias **errorf** = defaultLogFunctionf!LogLevel.error.defaultLogFunctionf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args); alias **criticalf** = defaultLogFunctionf!LogLevel.critical.defaultLogFunctionf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args); alias **fatalf** = defaultLogFunctionf!LogLevel.fatal.defaultLogFunctionf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args); This function logs data to the `sharedLog` in a `printf`-style manner. In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the `sharedLog` and must be greater or equal than the global `LogLevel`. Additionally the `LogLevel` must be greater or equal than the `LogLevel` of the `stdSharedLogger`. Parameters: | | | | --- | --- | | string msg | The `printf`-style string. | | A args | The data that should be logged. | Example ``` tracef("is number %d", 1); infof("is number %d", 2); errorf("is number %d", 3); criticalf("is number %d", 4); fatalf("is number %d", 5); ``` The second version of the function logs data to the `sharedLog` in a `printf`-style manner. In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the `sharedLog` and must be greater or equal than the global `LogLevel`. Additionally the `LogLevel` must be greater or equal than the `LogLevel` of the `stdSharedLogger`. Parameters: | | | | --- | --- | | bool condition | The condition must be `true` for the data to be logged. | | string msg | The `printf`-style string. | | A args | The data that should be logged. | Example ``` tracef(false, "is number %d", 1); infof(false, "is number %d", 2); errorf(true, "is number %d", 3); criticalf(true, "is number %d", 4); fatalf(someFunct(), "is number %d", 5); ``` enum **LogLevel**: ubyte; There are eight usable logging level. These level are *all*, *trace*, *info*, *warning*, *error*, *critical*, *fatal*, and *off*. If a log function with `LogLevel.fatal` is called the shutdown handler of that logger is called. **all** Lowest possible assignable `LogLevel`. **trace** `LogLevel` for tracing the execution of the program. **info** This level is used to display information about the program. **warning** warnings about the program should be displayed with this level. **error** Information about errors should be logged with this level. **critical** Messages that inform about critical errors should be logged with this level. **fatal** Log messages that describe fatal errors should use this level. **off** Highest possible `LogLevel`. abstract class **Logger**; This class is the base of every logger. In order to create a new kind of logger a deriving class needs to implement the `writeLogMsg` method. By default this is not thread-safe. It is also possible to `override` the three methods `beginLogMsg`, `logMsgPart` and `finishLogMsg` together, this option gives more flexibility. struct **LogEntry**; LogEntry is a aggregation combining all information associated with a log message. This aggregation will be passed to the method writeLogMsg. string **file**; the filename the log function was called from int **line**; the line number the log function was called from string **funcName**; the name of the function the log function was called from string **prettyFuncName**; the pretty formatted name of the function the log function was called from string **moduleName**; the name of the module the log message is coming from LogLevel **logLevel**; the `LogLevel` associated with the log message Tid **threadId**; thread id of the log message SysTime **timestamp**; the time the message was logged string **msg**; the message of the log message Logger **logger**; A refernce to the `Logger` used to create this `LogEntry` @safe this(LogLevel lv); Every subclass of `Logger` has to call this constructor from their constructor. It sets the `LogLevel`, and creates a fatal handler. The fatal handler will throw an `Error` if a log call is made with level `LogLevel.fatal`. Parameters: | | | | --- | --- | | LogLevel `lv` | `LogLevel` to use for this `Logger` instance. | protected abstract @safe void **writeLogMsg**(ref LogEntry payload); A custom logger must implement this method in order to work in a `MultiLogger` and `ArrayLogger`. Parameters: | | | | --- | --- | | LogEntry `payload` | All information associated with call to log function. | See Also: beginLogMsg, logMsgPart, finishLogMsg protected @safe void **logMsgPart**(scope const(char)[] msg); Logs a part of the log message. protected @safe void **finishLogMsg**(); Signals that the message has been written and no more calls to `logMsgPart` follow. final const pure @nogc @property @safe LogLevel **logLevel**(); final @nogc @property @safe void **logLevel**(const LogLevel lv); The `LogLevel` determines if the log call are processed or dropped by the `Logger`. In order for the log call to be processed the `LogLevel` of the log call must be greater or equal to the `LogLevel` of the `logger`. These two methods set and get the `LogLevel` of the used `Logger`. Example ``` auto f = new FileLogger(stdout); f.logLevel = LogLevel.info; assert(f.logLevel == LogLevel.info); ``` final @nogc @property @safe void delegate() **fatalHandler**(); final @nogc @property @safe void **fatalHandler**(void delegate() @safe fh); This `delegate` is called in case a log message with `LogLevel.fatal` gets logged. By default an `Error` will be thrown. @trusted void **forwardMsg**(ref LogEntry payload); This method allows forwarding log entries from one logger to another. `forwardMsg` will ensure proper synchronization and then call `writeLogMsg`. This is an API for implementing your own loggers and should not be called by normal user code. A notable difference from other logging functions is that the `globalLogLevel` wont be evaluated again since it is assumed that the caller already checked that. template **memLogFunctions**(LogLevel ll) alias **trace** = .Logger.memLogFunctions!LogLevel.**trace**.logImpl(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length == 0 || args.length > 0 && !is(A[0] : bool)); alias **tracef** = .Logger.memLogFunctions!LogLevel.trace.logImplf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args); alias **info** = .Logger.memLogFunctions!LogLevel.**info**.logImpl(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length == 0 || args.length > 0 && !is(A[0] : bool)); alias **infof** = .Logger.memLogFunctions!LogLevel.info.logImplf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args); alias **warning** = .Logger.memLogFunctions!LogLevel.**warning**.logImpl(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length == 0 || args.length > 0 && !is(A[0] : bool)); alias **warningf** = .Logger.memLogFunctions!LogLevel.warning.logImplf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args); alias **error** = .Logger.memLogFunctions!LogLevel.**error**.logImpl(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length == 0 || args.length > 0 && !is(A[0] : bool)); alias **errorf** = .Logger.memLogFunctions!LogLevel.error.logImplf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args); alias **critical** = .Logger.memLogFunctions!LogLevel.**critical**.logImpl(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length == 0 || args.length > 0 && !is(A[0] : bool)); alias **criticalf** = .Logger.memLogFunctions!LogLevel.critical.logImplf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args); alias **fatal** = .Logger.memLogFunctions!LogLevel.**fatal**.logImpl(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length == 0 || args.length > 0 && !is(A[0] : bool)); alias **fatalf** = .Logger.memLogFunctions!LogLevel.fatal.logImplf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args); This template provides the log functions for the `Logger` `class` with the `LogLevel` encoded in the function name. For further information see the the two functions defined inside of this template. The aliases following this template create the public names of these log functions. void **logImpl**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) Constraints: if (args.length == 0 || args.length > 0 && !is(A[0] : bool)); This function logs data to the used `Logger`. In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the used `Logger` and must be greater or equal than the global `LogLevel`. Parameters: | | | | --- | --- | | A `args` | The data that should be logged. | Example ``` auto s = new FileLogger(stdout); s.trace(1337, "is number"); s.info(1337, "is number"); s.error(1337, "is number"); s.critical(1337, "is number"); s.fatal(1337, "is number"); ``` void **logImpl**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy A args); This function logs data to the used `Logger` depending on a condition. In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the used `Logger` and must be greater or equal than the global `LogLevel` additionally the condition passed must be `true`. Parameters: | | | | --- | --- | | bool `condition` | The condition must be `true` for the data to be logged. | | A `args` | The data that should be logged. | Example ``` auto s = new FileLogger(stdout); s.trace(true, 1337, "is number"); s.info(false, 1337, "is number"); s.error(true, 1337, "is number"); s.critical(false, 1337, "is number"); s.fatal(true, 1337, "is number"); ``` void **logImplf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args); This function logs data to the used `Logger` in a `printf`-style manner. In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the used `Logger` and must be greater or equal than the global `LogLevel` additionally the passed condition must be `true`. Parameters: | | | | --- | --- | | bool `condition` | The condition must be `true` for the data to be logged. | | string `msg` | The `printf`-style string. | | A `args` | The data that should be logged. | Example ``` auto s = new FileLogger(stderr); s.tracef(true, "is number %d", 1); s.infof(true, "is number %d", 2); s.errorf(false, "is number %d", 3); s.criticalf(someFunc(), "is number %d", 4); s.fatalf(true, "is number %d", 5); ``` void **logImplf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args); This function logs data to the used `Logger` in a `printf`-style manner. In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the used `Logger` and must be greater or equal than the global `LogLevel`. Parameters: | | | | --- | --- | | string `msg` | The `printf`-style string. | | A `args` | The data that should be logged. | Example ``` auto s = new FileLogger(stderr); s.tracef("is number %d", 1); s.infof("is number %d", 2); s.errorf("is number %d", 3); s.criticalf("is number %d", 4); s.fatalf("is number %d", 5); ``` void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy bool condition, lazy A args) Constraints: if (args.length != 1); void **log**(T, string moduleName = \_\_MODULE\_\_)(const LogLevel ll, lazy bool condition, lazy T args, int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_); This method logs data with the `LogLevel` of the used `Logger`. This method takes a `bool` as first argument. In order for the data to be processed the `bool` must be `true` and the `LogLevel` of the Logger must be greater or equal to the global `LogLevel`. Parameters: | | | | --- | --- | | A `args` | The data that should be logged. | | bool `condition` | The condition must be `true` for the data to be logged. | | A `args` | The data that is to be logged. | Returns: The logger used by the logging function as reference. Example ``` auto l = new StdioLogger(); l.log(1337); ``` void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy A args) Constraints: if (args.length > 1 && !is(Unqual!(A[0]) : bool) || args.length == 0); void **log**(T)(const LogLevel ll, lazy T args, int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_); This function logs data to the used `Logger` with a specific `LogLevel`. In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the used `Logger` and must be greater or equal than the global `LogLevel`. Parameters: | | | | --- | --- | | LogLevel `ll` | The specific `LogLevel` used for logging the log message. | | A `args` | The data that should be logged. | Example ``` auto s = new FileLogger(stdout); s.log(LogLevel.trace, 1337, "is number"); s.log(LogLevel.info, 1337, "is number"); s.log(LogLevel.warning, 1337, "is number"); s.log(LogLevel.error, 1337, "is number"); s.log(LogLevel.fatal, 1337, "is number"); ``` void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy A args) Constraints: if (args.length != 1); void **log**(T)(lazy bool condition, lazy T args, int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_); This function logs data to the used `Logger` depending on a explicitly passed condition with the `LogLevel` of the used `Logger`. In order for the resulting log message to be logged the `LogLevel` of the used `Logger` must be greater or equal than the global `LogLevel` and the condition must be `true`. Parameters: | | | | --- | --- | | bool `condition` | The condition must be `true` for the data to be logged. | | A `args` | The data that should be logged. | Example ``` auto s = new FileLogger(stdout); s.log(true, 1337, "is number"); s.log(true, 1337, "is number"); s.log(true, 1337, "is number"); s.log(false, 1337, "is number"); s.log(false, 1337, "is number"); ``` void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) Constraints: if (args.length > 1 && !is(Unqual!(A[0]) : bool) && !is(immutable(A[0]) == immutable(LogLevel)) || args.length == 0); void **log**(T)(lazy T arg, int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_); This function logs data to the used `Logger` with the `LogLevel` of the used `Logger`. In order for the resulting log message to be logged the `LogLevel` of the used `Logger` must be greater or equal than the global `LogLevel`. Parameters: | | | | --- | --- | | A `args` | The data that should be logged. | Example ``` auto s = new FileLogger(stdout); s.log(1337, "is number"); s.log(info, 1337, "is number"); s.log(1337, "is number"); s.log(1337, "is number"); s.log(1337, "is number"); ``` void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy bool condition, lazy string msg, lazy A args); This function logs data to the used `Logger` with a specific `LogLevel` and depending on a condition in a `printf`-style manner. In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the used `Logger` and must be greater or equal than the global `LogLevel` and the condition must be `true`. Parameters: | | | | --- | --- | | LogLevel `ll` | The specific `LogLevel` used for logging the log message. | | bool `condition` | The condition must be `true` for the data to be logged. | | string `msg` | The format string used for this log call. | | A `args` | The data that should be logged. | Example ``` auto s = new FileLogger(stdout); s.logf(LogLevel.trace, true ,"%d %s", 1337, "is number"); s.logf(LogLevel.info, true ,"%d %s", 1337, "is number"); s.logf(LogLevel.warning, true ,"%d %s", 1337, "is number"); s.logf(LogLevel.error, false ,"%d %s", 1337, "is number"); s.logf(LogLevel.fatal, true ,"%d %s", 1337, "is number"); ``` void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy string msg, lazy A args); This function logs data to the used `Logger` with a specific `LogLevel` in a `printf`-style manner. In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the used `Logger` and must be greater or equal than the global `LogLevel`. Parameters: | | | | --- | --- | | LogLevel `ll` | The specific `LogLevel` used for logging the log message. | | string `msg` | The format string used for this log call. | | A `args` | The data that should be logged. | Example ``` auto s = new FileLogger(stdout); s.logf(LogLevel.trace, "%d %s", 1337, "is number"); s.logf(LogLevel.info, "%d %s", 1337, "is number"); s.logf(LogLevel.warning, "%d %s", 1337, "is number"); s.logf(LogLevel.error, "%d %s", 1337, "is number"); s.logf(LogLevel.fatal, "%d %s", 1337, "is number"); ``` void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args); This function logs data to the used `Logger` depending on a condition with the `LogLevel` of the used `Logger` in a `printf`-style manner. In order for the resulting log message to be logged the `LogLevel` of the used `Logger` must be greater or equal than the global `LogLevel` and the condition must be `true`. Parameters: | | | | --- | --- | | bool `condition` | The condition must be `true` for the data to be logged. | | string `msg` | The format string used for this log call. | | A `args` | The data that should be logged. | Example ``` auto s = new FileLogger(stdout); s.logf(true ,"%d %s", 1337, "is number"); s.logf(true ,"%d %s", 1337, "is number"); s.logf(true ,"%d %s", 1337, "is number"); s.logf(false ,"%d %s", 1337, "is number"); s.logf(true ,"%d %s", 1337, "is number"); ``` void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args); This method logs data to the used `Logger` with the `LogLevel` of the this `Logger` in a `printf`-style manner. In order for the data to be processed the `LogLevel` of the `Logger` must be greater or equal to the global `LogLevel`. Parameters: | | | | --- | --- | | string `msg` | The format string used for this log call. | | A `args` | The data that should be logged. | Example ``` auto s = new FileLogger(stdout); s.logf("%d %s", 1337, "is number"); s.logf("%d %s", 1337, "is number"); s.logf("%d %s", 1337, "is number"); s.logf("%d %s", 1337, "is number"); s.logf("%d %s", 1337, "is number"); ``` @property @safe Logger **sharedLog**(); @property @trusted void **sharedLog**(Logger logger); This property sets and gets the default `Logger`. Example ``` sharedLog = new FileLogger(yourFile); ``` The example sets a new `FileLogger` as new `sharedLog`. If at some point you want to use the original default logger again, you can use `sharedLog = null;`. This will put back the original. Note While getting and setting `sharedLog` is thread-safe, it has to be considered that the returned reference is only a current snapshot and in the following code, you must make sure no other thread reassigns to it between reading and writing `sharedLog`. `sharedLog` is only thread-safe if the the used `Logger` is thread-safe. The default `Logger` is thread-safe. ``` if (sharedLog !is myLogger) sharedLog = new myLogger; ``` @nogc @property @safe LogLevel **globalLogLevel**(); @property @safe void **globalLogLevel**(LogLevel ll); This methods get and set the global `LogLevel`. Every log message with a `LogLevel` lower as the global `LogLevel` will be discarded before it reaches `writeLogMessage` method of any `Logger`. class **StdForwardLogger**: std.experimental.logger.core.Logger; The `StdForwardLogger` will always forward anything to the sharedLog. The `StdForwardLogger` will not throw if data is logged with `LogLevel.fatal`. Examples: ``` auto nl1 = new StdForwardLogger(LogLevel.all); ``` @safe this(const LogLevel lv = LogLevel.all); The default constructor for the `StdForwardLogger`. Parameters: | | | | --- | --- | | LogLevel `lv` | The `LogLevel` for the `MultiLogger`. By default the `LogLevel` is `all`. | @property @safe Logger **stdThreadLocalLog**(); @property @safe void **stdThreadLocalLog**(Logger logger); This function returns a thread unique `Logger`, that by default propergates all data logged to it to the `sharedLog`. These properties can be used to set and get this `Logger`. Every modification to this `Logger` will only be visible in the thread the modification has been done from. This `Logger` is called by the free standing log functions. This allows to create thread local redirections and still use the free standing log functions. Examples: Ditto ``` import std.experimental.logger.filelogger : FileLogger; import std.file : deleteme, remove; Logger l = stdThreadLocalLog; stdThreadLocalLog = new FileLogger(deleteme ~ "-someFile.log"); scope(exit) remove(deleteme ~ "-someFile.log"); auto tempLog = stdThreadLocalLog; stdThreadLocalLog = l; destroy(tempLog); ```
programming_docs
d rt.tracegc rt.tracegc ========== Contains implementations of functions called when the -profile=gc switch is thrown. Tests for this functionality can be found in test/profile/src/profilegc.d License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright Source [src/rt/tracegc.d](https://github.com/dlang/druntime/blob/master/src/src/rt/tracegc.d) d rt.unwind rt.unwind ========= Written in the D programming language. Equivalent to unwind.h See Also: Itanium C++ ABI: Exception Handling ($Revision: 1.22 $) Source [rt/unwind.d](https://github.com/dlang/druntime/blob/master/src/rt/unwind.d) d rt.deh_win32 rt.deh\_win32 ============= Implementation of exception handling support routines for Win32. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright Source [rt/deh\_win32.d](https://github.com/dlang/druntime/blob/master/src/rt/deh_win32.d) d Portability Portability =========== **Contents** 1. [32 to 64 Bit Portability](#32_to_64bit) 2. [Endianness](#endianness) 3. [OS Specific Code](#os_specific_code) It's good software engineering practice to minimize gratuitous portability problems in the code. Techniques to minimize potential portability problems are: * The integral and floating type sizes should be considered as minimums. Algorithms should be designed to continue to work properly if the type size increases. * Floating point computations can be carried out at a higher precision than the size of the floating point variable can hold. Floating point algorithms should continue to work properly if precision is arbitrarily increased. * Avoid depending on the order of side effects in a computation that may get reordered by the compiler. For example: ``` a + b + c ``` can be evaluated as (a + b) + c, a + (b + c), (a + c) + b, (c + b) + a, etc. Parentheses control operator precedence, parentheses do not control order of evaluation. If the operands of an associative operator + or \* are floating point values, the expression is not reordered. * Avoid dependence on byte order; i.e. whether the CPU is big-endian or little-endian. * Avoid dependence on the size of a pointer or reference being the same size as a particular integral type. * If size dependencies are inevitable, put a `static assert` in the code to verify it: ``` static assert(int.sizeof == (int*).sizeof); ``` 32 to 64 Bit Portability ------------------------ 64 bit processors and operating systems are here. With that in mind: * Integral types will remain the same sizes between 32 and 64 bit code. * Pointers and object references will increase in size from 4 bytes to 8 bytes going from 32 to 64 bit code. * Use `size_t` as an alias for an unsigned integral type that can span the address space. Array indices should be of type `size_t`. * Use `ptrdiff_t` as an alias for a signed integral type that can span the address space. A type representing the difference between two pointers should be of type `ptrdiff_t`. * The `.length`, `.size`, `.sizeof`, `.offsetof` and `.alignof` properties will be of type `size_t`. Endianness ---------- Endianness refers to the order in which multibyte types are stored. The two main orders are *big endian* and *little endian*. The compiler predefines the version identifier `BigEndian` or `LittleEndian` depending on the order of the target system. The x86 systems are all little endian. The times when endianness matters are: * When reading data from an external source (like a file) written in a different endian format. * When reading or writing individual bytes of a multibyte type like `long`s or `double`s. OS Specific Code ---------------- System specific code is handled by isolating the differences into separate modules. At compile time, the correct system specific module is imported. Minor differences can be handled by constant defined in a system specific import, and then using that constant in an *IfStatement* or *StaticIfStatement*. d core.stdc.ctype core.stdc.ctype =============== D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<ctype.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/ctype.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly Source [core/stdc/ctype.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/ctype.d) Standards: ISO/IEC 9899:1999 (E) pure nothrow @nogc @trusted int **isalnum**(int c); pure nothrow @nogc @trusted int **isalpha**(int c); pure nothrow @nogc @trusted int **isblank**(int c); pure nothrow @nogc @trusted int **iscntrl**(int c); pure nothrow @nogc @trusted int **isdigit**(int c); pure nothrow @nogc @trusted int **isgraph**(int c); pure nothrow @nogc @trusted int **islower**(int c); pure nothrow @nogc @trusted int **isprint**(int c); pure nothrow @nogc @trusted int **ispunct**(int c); pure nothrow @nogc @trusted int **isspace**(int c); pure nothrow @nogc @trusted int **isupper**(int c); pure nothrow @nogc @trusted int **isxdigit**(int c); pure nothrow @nogc @trusted int **tolower**(int c); pure nothrow @nogc @trusted int **toupper**(int c); d core.stdc.time core.stdc.time ============== D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<time.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/time.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly, Alex Rønne Petersen Source [core/stdc/time.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/time.d) Standards: ISO/IEC 9899:1999 (E) pure nothrow @nogc @trusted double **difftime**(time\_t time1, time\_t time0); nothrow @nogc @system time\_t **mktime**(scope tm\* timeptr); nothrow @nogc @trusted time\_t **time**(scope time\_t\* timer); nothrow @nogc @system char\* **asctime**(scope const tm\* timeptr); nothrow @nogc @system char\* **ctime**(scope const time\_t\* timer); nothrow @nogc @system tm\* **gmtime**(scope const time\_t\* timer); nothrow @nogc @system tm\* **localtime**(scope const time\_t\* timer); nothrow @nogc @system size\_t **strftime**(scope char\* s, size\_t maxsize, scope const char\* format, scope const tm\* timeptr); d std.datetime.stopwatch std.datetime.stopwatch ====================== Module containing some basic benchmarking and timing functionality. For convenience, this module publicly imports [`core.time`](core_time). | Category | Functions | | --- | --- | | Main functionality | [`StopWatch`](#StopWatch) [`benchmark`](#benchmark) | | Flags | [`AutoStart`](#AutoStart) | Unlike the other modules in std.datetime, this module is not currently publicly imported in std.datetime.package, because the old versions of this functionality which use [`core.time.TickDuration`](core_time#TickDuration) are in std.datetime.package and would conflict with the symbols in this module. After the old symbols have gone through the deprecation cycle and have been fully removed, then this module will be publicly imported in std.datetime.package. The old, deprecated symbols has been removed from the documentation in December 2019 and currently scheduled to be fully removed from Phobos after 2.094. So, for now, when using std.datetime.stopwatch, if other modules from std.datetime are needed, then either import them individually rather than importing std.datetime, or use selective or static imports to import std.datetime.stopwatch. e.g. ``` import std.datetime; import std.datetime.stopwatch : benchmark, StopWatch; ``` The compiler will then know to use the symbols from std.datetime.stopwatch rather than the deprecated ones from std.datetime.package. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Jonathan M Davis](http://jmdavisprog.com) and Kato Shoichi Source [std/datetime/stopwatch.d](https://github.com/dlang/phobos/blob/master/std/datetime/stopwatch.d) alias **AutoStart** = std.typecons.Flag!"autoStart".Flag; Used by StopWatch to indicate whether it should start immediately upon construction. If set to `AutoStart.no`, then the StopWatch is not started when it is constructed. Otherwise, if set to `AutoStart.yes`, then the StopWatch is started when it is constructed. struct **StopWatch**; StopWatch is used to measure time just like one would do with a physical stopwatch, including stopping, restarting, and/or resetting it. [`core.time.MonoTime`](core_time#MonoTime) is used to hold the time, and it uses the system's monotonic clock, which is high precision and never counts backwards (unlike the wall clock time, which *can* count backwards, which is why [`std.datetime.systime.SysTime`](std_datetime_systime#SysTime) should not be used for timing). Note that the precision of StopWatch differs from system to system. It is impossible for it to be the same for all systems, since the precision of the system clock and other system-dependent and situation-dependent factors (such as the overhead of a context switch between threads) varies from system to system and can affect StopWatch's accuracy. Examples: Measure a time in milliseconds, microseconds, or nanoseconds ``` auto sw = StopWatch(AutoStart.no); sw.start(); // ... Insert operations to be timed here ... sw.stop(); long msecs = sw.peek.total!"msecs"; long usecs = sw.peek.total!"usecs"; long nsecs = sw.peek.total!"nsecs"; assert(usecs >= msecs * 1000); assert(nsecs >= usecs * 1000); ``` Examples: ``` import core.thread : Thread; auto sw = StopWatch(AutoStart.yes); Duration t1 = sw.peek(); Thread.sleep(usecs(1)); Duration t2 = sw.peek(); assert(t2 > t1); Thread.sleep(usecs(1)); sw.stop(); Duration t3 = sw.peek(); assert(t3 > t2); Duration t4 = sw.peek(); writeln(t3); // t4 sw.start(); Thread.sleep(usecs(1)); Duration t5 = sw.peek(); assert(t5 > t4); // If stopping or resetting the StopWatch is not required, then // MonoTime can easily be used by itself without StopWatch. auto before = MonoTime.currTime; // do stuff... auto timeElapsed = MonoTime.currTime - before; ``` nothrow @nogc @safe this(AutoStart autostart); Constructs a StopWatch. Whether it starts immediately depends on the [`AutoStart`](#AutoStart) argument. If `StopWatch.init` is used, then the constructed StopWatch isn't running (and can't be, since no constructor ran). Examples: ``` import core.thread : Thread; { auto sw = StopWatch(AutoStart.yes); assert(sw.running); Thread.sleep(usecs(1)); assert(sw.peek() > Duration.zero); } { auto sw = StopWatch(AutoStart.no); assert(!sw.running); Thread.sleep(usecs(1)); writeln(sw.peek()); // Duration.zero } { StopWatch sw; assert(!sw.running); Thread.sleep(usecs(1)); writeln(sw.peek()); // Duration.zero } writeln(StopWatch.init); // StopWatch(AutoStart.no) assert(StopWatch.init != StopWatch(AutoStart.yes)); ``` nothrow @nogc @safe void **reset**(); Resets the StopWatch. The StopWatch can be reset while it's running, and resetting it while it's running will not cause it to stop. Examples: ``` import core.thread : Thread; auto sw = StopWatch(AutoStart.yes); Thread.sleep(usecs(1)); sw.stop(); assert(sw.peek() > Duration.zero); sw.reset(); writeln(sw.peek()); // Duration.zero ``` nothrow @nogc @safe void **start**(); Starts the StopWatch. start should not be called if the StopWatch is already running. Examples: ``` import core.thread : Thread; StopWatch sw; assert(!sw.running); writeln(sw.peek()); // Duration.zero sw.start(); assert(sw.running); Thread.sleep(usecs(1)); assert(sw.peek() > Duration.zero); ``` nothrow @nogc @safe void **stop**(); Stops the StopWatch. stop should not be called if the StopWatch is not running. Examples: ``` import core.thread : Thread; auto sw = StopWatch(AutoStart.yes); assert(sw.running); Thread.sleep(usecs(1)); immutable t1 = sw.peek(); assert(t1 > Duration.zero); sw.stop(); assert(!sw.running); immutable t2 = sw.peek(); assert(t2 >= t1); immutable t3 = sw.peek(); writeln(t2); // t3 ``` const nothrow @nogc @safe Duration **peek**(); Peek at the amount of time that the the StopWatch has been running. This does not include any time during which the StopWatch was stopped but does include *all* of the time that it was running and not just the time since it was started last. Calling [`reset`](#reset) will reset this to `Duration.zero`. Examples: ``` import core.thread : Thread; auto sw = StopWatch(AutoStart.no); writeln(sw.peek()); // Duration.zero sw.start(); Thread.sleep(usecs(1)); assert(sw.peek() >= usecs(1)); Thread.sleep(usecs(1)); assert(sw.peek() >= usecs(2)); sw.stop(); immutable stopped = sw.peek(); Thread.sleep(usecs(1)); writeln(sw.peek()); // stopped sw.start(); Thread.sleep(usecs(1)); assert(sw.peek() > stopped); ``` nothrow @nogc @safe void **setTimeElapsed**(Duration timeElapsed); Sets the total time which the StopWatch has been running (i.e. what peek returns). The StopWatch does not have to be stopped for setTimeElapsed to be called, nor will calling it cause the StopWatch to stop. Examples: ``` import core.thread : Thread; StopWatch sw; sw.setTimeElapsed(hours(1)); // As discussed in MonoTime's documentation, converting between // Duration and ticks is not exact, though it will be close. // How exact it is depends on the frequency/resolution of the // system's monotonic clock. assert(abs(sw.peek() - hours(1)) < usecs(1)); sw.start(); Thread.sleep(usecs(1)); assert(sw.peek() > hours(1) + usecs(1)); ``` const pure nothrow @nogc @property @safe bool **running**(); Returns whether this StopWatch is currently running. Examples: ``` StopWatch sw; assert(!sw.running); sw.start(); assert(sw.running); sw.stop(); assert(!sw.running); ``` Duration[fun.length] **benchmark**(fun...)(uint n); Benchmarks code for speed assessment and comparison. Parameters: | | | | --- | --- | | fun | aliases of callable objects (e.g. function names). Each callable object should take no arguments. | | uint `n` | The number of times each function is to be executed. | Returns: The amount of time (as a [`core.time.Duration`](core_time#Duration)) that it took to call each function `n` times. The first value is the length of time that it took to call `fun[0]` `n` times. The second value is the length of time it took to call `fun[1]` `n` times. Etc. Examples: ``` import std.conv : to; int a; void f0() {} void f1() { auto b = a; } void f2() { auto b = to!string(a); } auto r = benchmark!(f0, f1, f2)(10_000); Duration f0Result = r[0]; // time f0 took to run 10,000 times Duration f1Result = r[1]; // time f1 took to run 10,000 times Duration f2Result = r[2]; // time f2 took to run 10,000 times ``` d core.exception core.exception ============== The exception module defines all system-level exceptions and provides a mechanism to alter system-level error handling. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Sean Kelly and [Jonathan M Davis](http://jmdavisprog.com) Source [core/exception.d](https://github.com/dlang/druntime/blob/master/src/core/exception.d) class **RangeError**: object.Error; Thrown on a range error. class **AssertError**: object.Error; Thrown on an assert error. class **FinalizeError**: object.Error; Thrown on finalize error. class **OutOfMemoryError**: object.Error; Thrown on an out of memory error. class **InvalidMemoryOperationError**: object.Error; Thrown on an invalid memory operation. An invalid memory operation error occurs in circumstances when the garbage collector has detected an operation it cannot reliably handle. The default D GC is not re-entrant, so this can happen due to allocations done from within finalizers called during a garbage collection cycle. class **SwitchError**: object.Error; Thrown on a switch error. class **UnicodeException**: object.Exception; Thrown on a unicode conversion error. alias **AssertHandler** = void function(string file, ulong line, string msg) nothrow; nothrow @nogc @property @trusted AssertHandler **assertHandler**(); nothrow @nogc @property @trusted void **assertHandler**(AssertHandler handler); Gets/sets assert hander. null means the default handler is used. nothrow void **onAssertError**(string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_); A callback for assert errors in D. The user-supplied assert handler will be called if one has been supplied, otherwise an [`AssertError`](#AssertError) will be thrown. Parameters: | | | | --- | --- | | string `file` | The name of the file that signaled this error. | | size\_t `line` | The line number on which this error occurred. | nothrow void **onAssertErrorMsg**(string file, size\_t line, string msg); A callback for assert errors in D. The user-supplied assert handler will be called if one has been supplied, otherwise an [`AssertError`](#AssertError) will be thrown. Parameters: | | | | --- | --- | | string `file` | The name of the file that signaled this error. | | size\_t `line` | The line number on which this error occurred. | | string `msg` | An error message supplied by the user. | nothrow void **onUnittestErrorMsg**(string file, size\_t line, string msg); A callback for unittest errors in D. The user-supplied unittest handler will be called if one has been supplied, otherwise the error will be written to stderr. Parameters: | | | | --- | --- | | string `file` | The name of the file that signaled this error. | | size\_t `line` | The line number on which this error occurred. | | string `msg` | An error message supplied by the user. | pure nothrow @nogc @trusted void **onRangeError**(string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_); A callback for array bounds errors in D. A [`RangeError`](#RangeError) will be thrown. Parameters: | | | | --- | --- | | string `file` | The name of the file that signaled this error. | | size\_t `line` | The line number on which this error occurred. | Throws: [`RangeError`](#RangeError). nothrow @trusted void **onFinalizeError**(TypeInfo info, Throwable e, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_); A callback for finalize errors in D. A [`FinalizeError`](#FinalizeError) will be thrown. Parameters: | | | | --- | --- | | TypeInfo `info` | The TypeInfo instance for the object that failed finalization. | | Throwable `e` | The exception thrown during finalization. | | string `file` | The name of the file that signaled this error. | | size\_t `line` | The line number on which this error occurred. | Throws: [`FinalizeError`](#FinalizeError). pure nothrow @nogc @trusted void **onOutOfMemoryError**(void\* pretend\_sideffect = null); A callback for out of memory errors in D. An [`OutOfMemoryError`](#OutOfMemoryError) will be thrown. Throws: [`OutOfMemoryError`](#OutOfMemoryError). pure nothrow @nogc @trusted void **onInvalidMemoryOperationError**(void\* pretend\_sideffect = null); A callback for invalid memory operations in D. An [`InvalidMemoryOperationError`](#InvalidMemoryOperationError) will be thrown. Throws: [`InvalidMemoryOperationError`](#InvalidMemoryOperationError). pure @safe void **onUnicodeError**(string msg, size\_t idx, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_); A callback for unicode errors in D. A [`UnicodeException`](#UnicodeException) will be thrown. Parameters: | | | | --- | --- | | string `msg` | Information about the error. | | size\_t `idx` | String index where this error was detected. | | string `file` | The name of the file that signaled this error. | | size\_t `line` | The line number on which this error occurred. | Throws: [`UnicodeException`](#UnicodeException). void **\_d\_assertp**(immutable(char)\* file, uint line); These functions must be defined for any D program linked against this library. Function calls to these are generated by the compiler and inserted into the object code. void **\_d\_assert\_msg**(string msg, string file, uint line); These functions must be defined for any D program linked against this library. Function calls to these are generated by the compiler and inserted into the object code. void **\_d\_assert**(string file, uint line); These functions must be defined for any D program linked against this library. Function calls to these are generated by the compiler and inserted into the object code. void **\_d\_unittestp**(immutable(char)\* file, uint line); These functions must be defined for any D program linked against this library. Function calls to these are generated by the compiler and inserted into the object code. void **\_d\_unittest\_msg**(string msg, string file, uint line); These functions must be defined for any D program linked against this library. Function calls to these are generated by the compiler and inserted into the object code. void **\_d\_unittest**(string file, uint line); These functions must be defined for any D program linked against this library. Function calls to these are generated by the compiler and inserted into the object code. void **\_d\_arrayboundsp**(immutable(char\*) file, uint line); These functions must be defined for any D program linked against this library. Function calls to these are generated by the compiler and inserted into the object code. void **\_d\_arraybounds**(string file, uint line); These functions must be defined for any D program linked against this library. Function calls to these are generated by the compiler and inserted into the object code.
programming_docs
d std.traits std.traits ========== Templates which extract information about types and symbols at compile time. | Category | Templates | | --- | --- | | Symbol Name traits | [`fullyQualifiedName`](#fullyQualifiedName) [`moduleName`](#moduleName) [`packageName`](#packageName) | | Function traits | [`isFunction`](#isFunction) [`arity`](#arity) [`functionAttributes`](#functionAttributes) [`hasFunctionAttributes`](#hasFunctionAttributes) [`functionLinkage`](#functionLinkage) [`FunctionTypeOf`](#FunctionTypeOf) [`isSafe`](#isSafe) [`isUnsafe`](#isUnsafe) [`isFinal`](#isFinal) [`ParameterDefaults`](#ParameterDefaults) [`ParameterIdentifierTuple`](#ParameterIdentifierTuple) [`ParameterStorageClassTuple`](#ParameterStorageClassTuple) [`Parameters`](#Parameters) [`ReturnType`](#ReturnType) [`SetFunctionAttributes`](#SetFunctionAttributes) [`variadicFunctionStyle`](#variadicFunctionStyle) | | Aggregate Type traits | [`BaseClassesTuple`](#BaseClassesTuple) [`BaseTypeTuple`](#BaseTypeTuple) [`classInstanceAlignment`](#classInstanceAlignment) [`EnumMembers`](#EnumMembers) [`FieldNameTuple`](#FieldNameTuple) [`Fields`](#Fields) [`hasAliasing`](#hasAliasing) [`hasElaborateAssign`](#hasElaborateAssign) [`hasElaborateCopyConstructor`](#hasElaborateCopyConstructor) [`hasElaborateDestructor`](#hasElaborateDestructor) [`hasElaborateMove`](#hasElaborateMove) [`hasIndirections`](#hasIndirections) [`hasMember`](#hasMember) [`hasStaticMember`](#hasStaticMember) [`hasNested`](#hasNested) [`hasUnsharedAliasing`](#hasUnsharedAliasing) [`InterfacesTuple`](#InterfacesTuple) [`isInnerClass`](#isInnerClass) [`isNested`](#isNested) [`MemberFunctionsTuple`](#MemberFunctionsTuple) [`RepresentationTypeTuple`](#RepresentationTypeTuple) [`TemplateArgsOf`](#TemplateArgsOf) [`TemplateOf`](#TemplateOf) [`TransitiveBaseTypeTuple`](#TransitiveBaseTypeTuple) | | Type Conversion | [`CommonType`](#CommonType) [`ImplicitConversionTargets`](#ImplicitConversionTargets) [`CopyTypeQualifiers`](#CopyTypeQualifiers) [`CopyConstness`](#CopyConstness) [`isAssignable`](#isAssignable) [`isCovariantWith`](#isCovariantWith) [`isImplicitlyConvertible`](#isImplicitlyConvertible) | | SomethingTypeOf | [`rvalueOf`](#rvalueOf) [`lvalueOf`](#lvalueOf) [`InoutOf`](#InoutOf) [`ConstOf`](#ConstOf) [`SharedOf`](#SharedOf) [`SharedInoutOf`](#SharedInoutOf) [`SharedConstOf`](#SharedConstOf) [`ImmutableOf`](#ImmutableOf) [`QualifierOf`](#QualifierOf) | | Categories of types | [`allSameType`](#allSameType) [`ifTestable`](#ifTestable) [`isType`](#isType) [`isAggregateType`](#isAggregateType) [`isArray`](#isArray) [`isAssociativeArray`](#isAssociativeArray) [`isAutodecodableString`](#isAutodecodableString) [`isBasicType`](#isBasicType) [`isBoolean`](#isBoolean) [`isBuiltinType`](#isBuiltinType) [`isCopyable`](#isCopyable) [`isDynamicArray`](#isDynamicArray) [`isEqualityComparable`](#isEqualityComparable) [`isFloatingPoint`](#isFloatingPoint) [`isIntegral`](#isIntegral) [`isNarrowString`](#isNarrowString) [`isConvertibleToString`](#isConvertibleToString) [`isNumeric`](#isNumeric) [`isOrderingComparable`](#isOrderingComparable) [`isPointer`](#isPointer) [`isScalarType`](#isScalarType) [`isSigned`](#isSigned) [`isSIMDVector`](#isSIMDVector) [`isSomeChar`](#isSomeChar) [`isSomeString`](#isSomeString) [`isStaticArray`](#isStaticArray) [`isUnsigned`](#isUnsigned) | | Type behaviours | [`isAbstractClass`](#isAbstractClass) [`isAbstractFunction`](#isAbstractFunction) [`isCallable`](#isCallable) [`isDelegate`](#isDelegate) [`isExpressions`](#isExpressions) [`isFinalClass`](#isFinalClass) [`isFinalFunction`](#isFinalFunction) [`isFunctionPointer`](#isFunctionPointer) [`isInstanceOf`](#isInstanceOf) [`isIterable`](#isIterable) [`isMutable`](#isMutable) [`isSomeFunction`](#isSomeFunction) [`isTypeTuple`](#isTypeTuple) | | General Types | [`ForeachType`](#ForeachType) [`KeyType`](#KeyType) [`Largest`](#Largest) [`mostNegative`](#mostNegative) [`OriginalType`](#OriginalType) [`PointerTarget`](#PointerTarget) [`Signed`](#Signed) [`Unconst`](#Unconst) [`Unqual`](#Unqual) [`Unsigned`](#Unsigned) [`ValueType`](#ValueType) [`Promoted`](#Promoted) | | Misc | [`mangledName`](#mangledName) [`Select`](#Select) [`select`](#select) | | User-Defined Attributes | [`hasUDA`](#hasUDA) [`getUDAs`](#getUDAs) [`getSymbolsByUDA`](#getSymbolsByUDA) | License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com), Tomasz Stachowiak (`isExpressions`), [Andrei Alexandrescu](http://erdani.org), Shin Fujishiro, [Robert Clipsham](http://octarineparrot.com), [David Nadlinger](http://klickverbot.at), Kenji Hara, Shoichi Kato Source [std/traits.d](https://github.com/dlang/phobos/blob/master/std/traits.d) template **InoutOf**(T) Parameters: | | | | --- | --- | | T | The type to qualify | Returns: `T` with the `inout` qualifier added. Examples: ``` static assert(is(InoutOf!(int) == inout int)); static assert(is(InoutOf!(inout int) == inout int)); static assert(is(InoutOf!(const int) == inout const int)); static assert(is(InoutOf!(shared int) == inout shared int)); ``` template **ConstOf**(T) Parameters: | | | | --- | --- | | T | The type to qualify | Returns: `T` with the `const` qualifier added. Examples: ``` static assert(is(ConstOf!(int) == const int)); static assert(is(ConstOf!(const int) == const int)); static assert(is(ConstOf!(inout int) == const inout int)); static assert(is(ConstOf!(shared int) == const shared int)); ``` template **SharedOf**(T) Parameters: | | | | --- | --- | | T | The type to qualify | Returns: `T` with the `shared` qualifier added. Examples: ``` static assert(is(SharedOf!(int) == shared int)); static assert(is(SharedOf!(shared int) == shared int)); static assert(is(SharedOf!(inout int) == shared inout int)); static assert(is(SharedOf!(immutable int) == shared immutable int)); ``` template **SharedInoutOf**(T) Parameters: | | | | --- | --- | | T | The type to qualify | Returns: `T` with the `inout` and `shared` qualifiers added. Examples: ``` static assert(is(SharedInoutOf!(int) == shared inout int)); static assert(is(SharedInoutOf!(int) == inout shared int)); static assert(is(SharedInoutOf!(const int) == shared inout const int)); static assert(is(SharedInoutOf!(immutable int) == shared inout immutable int)); ``` template **SharedConstOf**(T) Parameters: | | | | --- | --- | | T | The type to qualify | Returns: `T` with the `const` and `shared` qualifiers added. Examples: ``` static assert(is(SharedConstOf!(int) == shared const int)); static assert(is(SharedConstOf!(int) == const shared int)); static assert(is(SharedConstOf!(inout int) == shared inout const int)); // immutable variables are implicitly shared and const static assert(is(SharedConstOf!(immutable int) == immutable int)); ``` template **ImmutableOf**(T) Parameters: | | | | --- | --- | | T | The type to qualify | Returns: `T` with the `immutable` qualifier added. Examples: ``` static assert(is(ImmutableOf!(int) == immutable int)); static assert(is(ImmutableOf!(const int) == immutable int)); static assert(is(ImmutableOf!(inout int) == immutable int)); static assert(is(ImmutableOf!(shared int) == immutable int)); ``` template **QualifierOf**(T) Gives a template that can be used to apply the same attributes that are on the given type `T`. E.g. passing `inout shared int` will return `SharedInoutOf`. Parameters: | | | | --- | --- | | T | the type to check qualifiers from | Returns: The qualifier template from the given type `T` Examples: ``` static assert(__traits(isSame, QualifierOf!(immutable int), ImmutableOf)); static assert(__traits(isSame, QualifierOf!(shared int), SharedOf)); static assert(__traits(isSame, QualifierOf!(shared inout int), SharedInoutOf)); ``` template **packageName**(alias T) Get the full package name for the given symbol. Examples: ``` static assert(packageName!packageName == "std"); ``` Examples: ``` static assert(packageName!moduleName == "std"); ``` template **moduleName**(alias T) Get the module name (including package) for the given symbol. Examples: ``` static assert(moduleName!moduleName == "std.traits"); ``` template **fullyQualifiedName**(T...) if (T.length == 1) Get the fully qualified name of a type or a symbol. Can act as an intelligent type/symbol to string converter. Example ``` module myModule; struct MyStruct {} static assert(fullyQualifiedName!(const MyStruct[]) == "const(myModule.MyStruct[])"); ``` Examples: ``` static assert(fullyQualifiedName!fullyQualifiedName == "std.traits.fullyQualifiedName"); ``` template **ReturnType**(func...) if (func.length == 1 && isCallable!func) Get the type of the return value from a function, a pointer to function, a delegate, a struct with an opCall, a pointer to a struct with an opCall, or a class with an `opCall`. Please note that ref is not part of a type, but the attribute of the function (see template [`functionAttributes`](#functionAttributes)). Examples: ``` int foo(); ReturnType!foo x; // x is declared as int ``` template **Parameters**(func...) if (func.length == 1 && isCallable!func) Get, as a tuple, the types of the parameters to a function, a pointer to function, a delegate, a struct with an `opCall`, a pointer to a struct with an `opCall`, or a class with an `opCall`. Examples: ``` int foo(int, long); void bar(Parameters!foo); // declares void bar(int, long); void abc(Parameters!foo[1]); // declares void abc(long); ``` alias **ParameterTypeTuple** = Parameters(func...) if (func.length == 1 && isCallable!func); Alternate name for [`Parameters`](#Parameters), kept for legacy compatibility. template **arity**(func...) if (func.length == 1 && isCallable!func && (variadicFunctionStyle!func == Variadic.no)) Returns the number of arguments of function `func`. arity is undefined for variadic functions. Examples: ``` void foo(){} static assert(arity!foo == 0); void bar(uint){} static assert(arity!bar == 1); void variadicFoo(uint...){} static assert(!__traits(compiles, arity!variadicFoo)); ``` enum **ParameterStorageClass**: uint; template **ParameterStorageClassTuple**(func...) if (func.length == 1 && isCallable!func) Get tuple, one per function parameter, of the storage classes of the parameters. Parameters: | | | | --- | --- | | func | function symbol or type of function, delegate, or pointer to function | Returns: A tuple of ParameterStorageClass bits Examples: ``` alias STC = ParameterStorageClass; // shorten the enum name void func(ref int ctx, out real result, in real param, void* ptr) { } alias pstc = ParameterStorageClassTuple!func; static assert(pstc.length == 4); // number of parameters static assert(pstc[0] == STC.ref_); static assert(pstc[1] == STC.out_); version (none) { // TODO: When the DMD PR (dlang/dmd#11474) gets merged, // remove the versioning and the second test static assert(pstc[2] == STC.in_); // This is the current behavior, before `in` is fixed to not be an alias static assert(pstc[2] == STC.scope_); } static assert(pstc[3] == STC.none); ``` **none** **in\_** **ref\_** **out\_** **lazy\_** **scope\_** **return\_** These flags can be bitwise OR-ed together to represent complex storage class. enum ParameterStorageClass **extractParameterStorageClassFlags**(Attribs...); Convert the result of `__traits(getParameterStorageClasses)` to [`ParameterStorageClass`](#ParameterStorageClass) `enum`s. Parameters: | | | | --- | --- | | Attribs | The return value of `__traits(getParameterStorageClasses)` | Returns: The bitwise OR of the equivalent [`ParameterStorageClass`](#ParameterStorageClass) `enum`s. Examples: ``` static void func(ref int ctx, out real result); enum param1 = extractParameterStorageClassFlags!( __traits(getParameterStorageClasses, func, 0) ); static assert(param1 == ParameterStorageClass.ref_); enum param2 = extractParameterStorageClassFlags!( __traits(getParameterStorageClasses, func, 1) ); static assert(param2 == ParameterStorageClass.out_); enum param3 = extractParameterStorageClassFlags!( __traits(getParameterStorageClasses, func, 0), __traits(getParameterStorageClasses, func, 1) ); static assert(param3 == (ParameterStorageClass.ref_ | ParameterStorageClass.out_)); ``` template **ParameterIdentifierTuple**(func...) if (func.length == 1 && isCallable!func) Get, as a tuple, the identifiers of the parameters to a function symbol. Examples: ``` int foo(int num, string name, int); static assert([ParameterIdentifierTuple!foo] == ["num", "name", ""]); ``` template **ParameterDefaults**(func...) if (func.length == 1 && isCallable!func) Get, as a tuple, the default value of the parameters to a function symbol. If a parameter doesn't have the default value, `void` is returned instead. Examples: ``` int foo(int num, string name = "hello", int[] = [1,2,3], lazy int x = 0); static assert(is(ParameterDefaults!foo[0] == void)); static assert( ParameterDefaults!foo[1] == "hello"); static assert( ParameterDefaults!foo[2] == [1,2,3]); static assert( ParameterDefaults!foo[3] == 0); ``` alias **ParameterDefaultValueTuple** = ParameterDefaults(func...) if (func.length == 1 && isCallable!func); Alternate name for [`ParameterDefaults`](#ParameterDefaults), kept for legacy compatibility. enum **FunctionAttribute**: uint; template **functionAttributes**(func...) if (func.length == 1 && isCallable!func) Returns the FunctionAttribute mask for function `func`. See Also: [`hasFunctionAttributes`](#hasFunctionAttributes) Examples: ``` alias FA = FunctionAttribute; // shorten the enum name real func(real x) pure nothrow @safe { return x; } static assert(functionAttributes!func & FA.pure_); static assert(functionAttributes!func & FA.safe); static assert(!(functionAttributes!func & FA.trusted)); // not @trusted ``` **none** **pure\_** **nothrow\_** **ref\_** **property** **trusted** **safe** **nogc** **system** **const\_** **immutable\_** **inout\_** **shared\_** **return\_** **scope\_** **live** These flags can be bitwise OR-ed together to represent a complex attribute. template **hasFunctionAttributes**(args...) if (args.length > 0 && isCallable!(args[0]) && allSatisfy!(isSomeString, typeof(args[1..$]))) Checks whether a function has the given attributes attached. Parameters: | | | | --- | --- | | args | Function to check, followed by a variadic number of function attributes as strings | Returns: `true`, if the function has the list of attributes attached and `false` otherwise. See Also: [`functionAttributes`](#functionAttributes) Examples: ``` real func(real x) pure nothrow @safe; static assert(hasFunctionAttributes!(func, "@safe", "pure")); static assert(!hasFunctionAttributes!(func, "@trusted")); // for templates attributes are automatically inferred bool myFunc(T)(T b) { return !b; } static assert(hasFunctionAttributes!(myFunc!bool, "@safe", "pure", "@nogc", "nothrow")); static assert(!hasFunctionAttributes!(myFunc!bool, "shared")); ``` template **isSafe**(alias func) if (isCallable!func) `true` if `func` is `@safe` or `@trusted`. Examples: ``` @safe int add(int a, int b) {return a+b;} @trusted int sub(int a, int b) {return a-b;} @system int mul(int a, int b) {return a*b;} static assert( isSafe!add); static assert( isSafe!sub); static assert(!isSafe!mul); ``` enum auto **isUnsafe**(alias func); `true` if `func` is `@system`. Examples: ``` @safe int add(int a, int b) {return a+b;} @trusted int sub(int a, int b) {return a-b;} @system int mul(int a, int b) {return a*b;} static assert(!isUnsafe!add); static assert(!isUnsafe!sub); static assert( isUnsafe!mul); ``` template **functionLinkage**(func...) if (func.length == 1 && isCallable!func) Determine the linkage attribute of the function. Parameters: | | | | --- | --- | | func | the function symbol, or the type of a function, delegate, or pointer to function | Returns: one of the strings "D", "C", "C++", "Windows", "Objective-C", or "System". Examples: ``` extern(D) void Dfunc() {} extern(C) void Cfunc() {} static assert(functionLinkage!Dfunc == "D"); static assert(functionLinkage!Cfunc == "C"); string a = functionLinkage!Dfunc; writeln(a); // "D" auto fp = &Cfunc; string b = functionLinkage!fp; writeln(b); // "C" ``` enum **Variadic**: int; template **variadicFunctionStyle**(func...) if (func.length == 1 && isCallable!func) Determines what kind of variadic parameters function has. Parameters: | | | | --- | --- | | func | function symbol or type of function, delegate, or pointer to function | Returns: enum Variadic Examples: ``` void func() {} static assert(variadicFunctionStyle!func == Variadic.no); extern(C) int printf(in char*, ...); static assert(variadicFunctionStyle!printf == Variadic.c); ``` **no** Function is not variadic. **c** Function is a C-style variadic function, which uses `core.stdc.stdarg` **d** Function is a D-style variadic function, which uses `__argptr` and `__arguments`. **typesafe** Function is a typesafe variadic function. template **FunctionTypeOf**(func...) if (func.length == 1 && isCallable!func) Get the function type from a callable object `func`. Using builtin `typeof` on a property function yields the types of the property value, not of the property function itself. Still, `FunctionTypeOf` is able to obtain function types of properties. Note Do not confuse function types with function pointer types; function types are usually used for compile-time reflection purposes. Examples: ``` class C { int value() @property { return 0; } } static assert(is( typeof(C.value) == int )); static assert(is( FunctionTypeOf!(C.value) == function )); ``` template **SetFunctionAttributes**(T, string linkage, uint attrs) if (isFunctionPointer!T || isDelegate!T) template **SetFunctionAttributes**(T, string linkage, uint attrs) if (is(T == function)) Constructs a new function or delegate type with the same basic signature as the given one, but different attributes (including linkage). This is especially useful for adding/removing attributes to/from types in generic code, where the actual type name cannot be spelt out. Parameters: | | | | --- | --- | | T | The base type. | | linkage | The desired linkage of the result type. | | attrs | The desired [`FunctionAttribute`](#FunctionAttribute)s of the result type. | Examples: ``` alias ExternC(T) = SetFunctionAttributes!(T, "C", functionAttributes!T); auto assumePure(T)(T t) if (isFunctionPointer!T || isDelegate!T) { enum attrs = functionAttributes!T | FunctionAttribute.pure_; return cast(SetFunctionAttributes!(T, functionLinkage!T, attrs)) t; } int f() { import core.thread : getpid; return getpid(); } int g() pure @trusted { auto pureF = assumePure(&f); return pureF(); } assert(g() > 0); ``` template **isInnerClass**(T) if (is(T == class)) Determines whether `T` is a class nested inside another class and that `T.outer` is the implicit reference to the outer class (i.e. `outer` has not been used as a field or method name) Parameters: | | | | --- | --- | | T | type to test | Returns: `true` if `T` is a class nested inside another, with the conditions described above; `false` otherwise Examples: ``` class C { int outer; } static assert(!isInnerClass!C); class Outer1 { class Inner1 { } class Inner2 { int outer; } } static assert(isInnerClass!(Outer1.Inner1)); static assert(!isInnerClass!(Outer1.Inner2)); static class Outer2 { static class Inner { int outer; } } static assert(!isInnerClass!(Outer2.Inner)); ``` template **isNested**(T) if (is(T == class) || is(T == struct) || is(T == union)) Determines whether `T` has its own context pointer. `T` must be either `class`, `struct`, or `union`. Examples: ``` static struct S { } static assert(!isNested!S); int i; struct NestedStruct { void f() { ++i; } } static assert(isNested!NestedStruct); ``` template **hasNested**(T) Determines whether `T` or any of its representation types have a context pointer. Examples: ``` static struct S { } int i; struct NS { void f() { ++i; } } static assert(!hasNested!(S[2])); static assert(hasNested!(NS[2])); ``` template **Fields**(T) Get as a tuple the types of the fields of a struct, class, or union. This consists of the fields that take up memory space, excluding the hidden fields like the virtual function table pointer or a context pointer for nested types. If `T` isn't a struct, class, or union returns a tuple with one element `T`. Examples: ``` import std.meta : AliasSeq; struct S { int x; float y; } static assert(is(Fields!S == AliasSeq!(int, float))); ``` alias **FieldTypeTuple** = Fields(T); Alternate name for [`Fields`](#Fields), kept for legacy compatibility. template **FieldNameTuple**(T) Get as an expression tuple the names of the fields of a struct, class, or union. This consists of the fields that take up memory space, excluding the hidden fields like the virtual function table pointer or a context pointer for nested types. Inherited fields (for classes) are not included. If `T` isn't a struct, class, or union, an expression tuple with an empty string is returned. Examples: ``` import std.meta : AliasSeq; struct S { int x; float y; } static assert(FieldNameTuple!S == AliasSeq!("x", "y")); static assert(FieldNameTuple!int == AliasSeq!""); ``` template **RepresentationTypeTuple**(T) Get the primitive types of the fields of a struct or class, in topological order. Examples: ``` struct S1 { int a; float b; } struct S2 { char[] a; union { S1 b; S1 * c; } } alias R = RepresentationTypeTuple!S2; assert(R.length == 4 && is(R[0] == char[]) && is(R[1] == int) && is(R[2] == float) && is(R[3] == S1*)); ``` enum auto **hasAliasing**(T...); Returns `true` if and only if `T`'s representation includes at least one of the following: 1. a raw pointer `U*` and `U` is not immutable; 2. an array `U[]` and `U` is not immutable; 3. a reference to a class or interface type `C` and `C` is not immutable. 4. an associative array that is not immutable. 5. a delegate. Examples: ``` struct S1 { int a; Object b; } struct S2 { string a; } struct S3 { int a; immutable Object b; } struct S4 { float[3] vals; } static assert( hasAliasing!S1); static assert(!hasAliasing!S2); static assert(!hasAliasing!S3); static assert(!hasAliasing!S4); ``` template **hasIndirections**(T) Returns `true` if and only if `T`'s representation includes at least one of the following: 1. a raw pointer `U*`; 2. an array `U[]`; 3. a reference to a class type `C`; 4. an associative array; 5. a delegate; 6. a [`context pointer`](#isNested). Examples: ``` static assert( hasIndirections!(int[string])); static assert( hasIndirections!(void delegate())); static assert( hasIndirections!(void delegate() immutable)); static assert( hasIndirections!(immutable(void delegate()))); static assert( hasIndirections!(immutable(void delegate() immutable))); static assert(!hasIndirections!(void function())); static assert( hasIndirections!(void*[1])); static assert(!hasIndirections!(byte[1])); ``` enum auto **hasUnsharedAliasing**(T...); Returns `true` if and only if `T`'s representation includes at least one of the following: 1. a raw pointer `U*` and `U` is not immutable or shared; 2. an array `U[]` and `U` is not immutable or shared; 3. a reference to a class type `C` and `C` is not immutable or shared. 4. an associative array that is not immutable or shared. 5. a delegate that is not shared. Examples: ``` struct S1 { int a; Object b; } struct S2 { string a; } struct S3 { int a; immutable Object b; } static assert( hasUnsharedAliasing!S1); static assert(!hasUnsharedAliasing!S2); static assert(!hasUnsharedAliasing!S3); struct S4 { int a; shared Object b; } struct S5 { char[] a; } struct S6 { shared char[] b; } struct S7 { float[3] vals; } static assert(!hasUnsharedAliasing!S4); static assert( hasUnsharedAliasing!S5); static assert(!hasUnsharedAliasing!S6); static assert(!hasUnsharedAliasing!S7); ``` template **hasElaborateCopyConstructor**(S) True if `S` or any type embedded directly in the representation of `S` defines an elaborate copy constructor. Elaborate copy constructors are introduced by defining `this(this)` for a `struct`. Classes and unions never have elaborate copy constructors. Examples: ``` static assert(!hasElaborateCopyConstructor!int); static struct S1 { } static struct S2 { this(this) {} } static struct S3 { S2 field; } static struct S4 { S3[1] field; } static struct S5 { S3[] field; } static struct S6 { S3[0] field; } static struct S7 { @disable this(); S3 field; } static assert(!hasElaborateCopyConstructor!S1); static assert( hasElaborateCopyConstructor!S2); static assert( hasElaborateCopyConstructor!(immutable S2)); static assert( hasElaborateCopyConstructor!S3); static assert( hasElaborateCopyConstructor!(S3[1])); static assert(!hasElaborateCopyConstructor!(S3[0])); static assert( hasElaborateCopyConstructor!S4); static assert(!hasElaborateCopyConstructor!S5); static assert(!hasElaborateCopyConstructor!S6); static assert( hasElaborateCopyConstructor!S7); ``` template **hasElaborateAssign**(S) True if `S` or any type directly embedded in the representation of `S` defines an elaborate assignment. Elaborate assignments are introduced by defining `opAssign(typeof(this))` or `opAssign(ref typeof(this))` for a `struct` or when there is a compiler-generated `opAssign`. A type `S` gets compiler-generated `opAssign` if it has an elaborate destructor. Classes and unions never have elaborate assignments. Note Structs with (possibly nested) postblit operator(s) will have a hidden yet elaborate compiler generated assignment operator (unless explicitly disabled). Examples: ``` static assert(!hasElaborateAssign!int); static struct S { void opAssign(S) {} } static assert( hasElaborateAssign!S); static assert(!hasElaborateAssign!(const(S))); static struct S1 { void opAssign(ref S1) {} } static struct S2 { void opAssign(int) {} } static struct S3 { S s; } static assert( hasElaborateAssign!S1); static assert(!hasElaborateAssign!S2); static assert( hasElaborateAssign!S3); static assert( hasElaborateAssign!(S3[1])); static assert(!hasElaborateAssign!(S3[0])); ``` template **hasElaborateDestructor**(S) True if `S` or any type directly embedded in the representation of `S` defines an elaborate destructor. Elaborate destructors are introduced by defining `~this()` for a `struct`. Classes and unions never have elaborate destructors, even though classes may define `~this()`. Examples: ``` static assert(!hasElaborateDestructor!int); static struct S1 { } static struct S2 { ~this() {} } static struct S3 { S2 field; } static struct S4 { S3[1] field; } static struct S5 { S3[] field; } static struct S6 { S3[0] field; } static struct S7 { @disable this(); S3 field; } static assert(!hasElaborateDestructor!S1); static assert( hasElaborateDestructor!S2); static assert( hasElaborateDestructor!(immutable S2)); static assert( hasElaborateDestructor!S3); static assert( hasElaborateDestructor!(S3[1])); static assert(!hasElaborateDestructor!(S3[0])); static assert( hasElaborateDestructor!S4); static assert(!hasElaborateDestructor!S5); static assert(!hasElaborateDestructor!S6); static assert( hasElaborateDestructor!S7); ``` template **hasElaborateMove**(S) True if `S` or any type embedded directly in the representation of `S` defines elaborate move semantics. Elaborate move semantics are introduced by defining `opPostMove(ref typeof(this))` for a `struct`. Classes and unions never have elaborate move semantics. Examples: ``` static assert(!hasElaborateMove!int); static struct S1 { } static struct S2 { void opPostMove(ref S2) {} } static struct S3 { void opPostMove(inout ref S3) inout {} } static struct S4 { void opPostMove(const ref S4) {} } static struct S5 { void opPostMove(S5) {} } static struct S6 { void opPostMove(int) {} } static struct S7 { S3[1] field; } static struct S8 { S3[] field; } static struct S9 { S3[0] field; } static struct S10 { @disable this(); S3 field; } static assert(!hasElaborateMove!S1); static assert( hasElaborateMove!S2); static assert( hasElaborateMove!S3); static assert( hasElaborateMove!(immutable S3)); static assert( hasElaborateMove!S4); static assert(!hasElaborateMove!S5); static assert(!hasElaborateMove!S6); static assert( hasElaborateMove!S7); static assert(!hasElaborateMove!S8); static assert(!hasElaborateMove!S9); static assert( hasElaborateMove!S10); ``` enum auto **hasMember**(T, string name); Yields `true` if and only if `T` is an aggregate that defines a symbol called `name`. Examples: ``` static assert(!hasMember!(int, "blah")); struct S1 { int blah; } struct S2 { int blah(){ return 0; } } class C1 { int blah; } class C2 { int blah(){ return 0; } } static assert(hasMember!(S1, "blah")); static assert(hasMember!(S2, "blah")); static assert(hasMember!(C1, "blah")); static assert(hasMember!(C2, "blah")); ``` template **hasStaticMember**(T, string member) Whether the symbol represented by the string, member, exists and is a static member of T. Parameters: | | | | --- | --- | | T | Type containing symbol `member`. | | member | Name of symbol to test that resides in `T`. | Returns: `true` iff `member` exists and is static. Examples: ``` static struct S { static void sf() {} void f() {} static int si; int i; } static assert( hasStaticMember!(S, "sf")); static assert(!hasStaticMember!(S, "f")); static assert( hasStaticMember!(S, "si")); static assert(!hasStaticMember!(S, "i")); static assert(!hasStaticMember!(S, "hello")); ``` template **EnumMembers**(E) if (is(E == enum)) Retrieves the members of an enumerated type `enum E`. Parameters: | | | | --- | --- | | E | An enumerated type. `E` may have duplicated values. | Returns: Static tuple composed of the members of the enumerated type `E`. The members are arranged in the same order as declared in `E`. The name of the enum can be found by querying the compiler for the name of the identifier, i.e. `__traits(identifier, EnumMembers!MyEnum[i])`. For enumerations with unique values, [`std.conv.to`](std_conv#to) can also be used. Note An enum can have multiple members which have the same value. If you want to use EnumMembers to e.g. generate switch cases at compile-time, you should use the [`std.meta.NoDuplicates`](std_meta#NoDuplicates) template to avoid generating duplicate switch cases. Note Returned values are strictly typed with `E`. Thus, the following code does not work without the explicit cast: ``` enum E : int { a, b, c } int[] abc = cast(int[]) [ EnumMembers!E ]; ``` Cast is not necessary if the type of the variable is inferred. See the example below. Examples: Create an array of enumerated values ``` enum Sqrts : real { one = 1, two = 1.41421, three = 1.73205 } auto sqrts = [EnumMembers!Sqrts]; writeln(sqrts); // [Sqrts.one, Sqrts.two, Sqrts.three] ``` Examples: A generic function `rank(v)` in the following example uses this template for finding a member `e` in an enumerated type `E`. ``` // Returns i if e is the i-th enumerator of E. static size_t rank(E)(E e) if (is(E == enum)) { static foreach (i, member; EnumMembers!E) { if (e == member) return i; } assert(0, "Not an enum member"); } enum Mode { read = 1, write = 2, map = 4 } writeln(rank(Mode.read)); // 0 writeln(rank(Mode.write)); // 1 writeln(rank(Mode.map)); // 2 ``` Examples: Use EnumMembers to generate a switch statement using static foreach. ``` import std.conv : to; class FooClass { string calledMethod; void foo() @safe { calledMethod = "foo"; } void bar() @safe { calledMethod = "bar"; } void baz() @safe { calledMethod = "baz"; } } enum FooEnum { foo, bar, baz } auto var = FooEnum.bar; auto fooObj = new FooClass(); s: final switch (var) { static foreach (member; EnumMembers!FooEnum) { case member: // Generate a case for each enum value. // Call fooObj.{name of enum value}(). __traits(getMember, fooObj, to!string(member))(); break s; } } // As we pass in FooEnum.bar, the bar() method gets called. writeln(fooObj.calledMethod); // "bar" ``` template **BaseTypeTuple**(A) Get a AliasSeq of the base class and base interfaces of this class or interface. BaseTypeTuple!Object returns the empty type tuple. Examples: ``` import std.meta : AliasSeq; interface I1 { } interface I2 { } interface I12 : I1, I2 { } static assert(is(BaseTypeTuple!I12 == AliasSeq!(I1, I2))); interface I3 : I1 { } interface I123 : I1, I2, I3 { } static assert(is(BaseTypeTuple!I123 == AliasSeq!(I1, I2, I3))); ``` template **BaseClassesTuple**(T) if (is(T == class)) Get a AliasSeq of *all* base classes of this class, in decreasing order. Interfaces are not included. BaseClassesTuple!Object yields the empty type tuple. Examples: ``` import std.meta : AliasSeq; class C1 { } class C2 : C1 { } class C3 : C2 { } static assert(!BaseClassesTuple!Object.length); static assert(is(BaseClassesTuple!C1 == AliasSeq!(Object))); static assert(is(BaseClassesTuple!C2 == AliasSeq!(C1, Object))); static assert(is(BaseClassesTuple!C3 == AliasSeq!(C2, C1, Object))); ``` template **InterfacesTuple**(T) Parameters: | | | | --- | --- | | T | The `class` or `interface` to search. | Returns: [`std.meta.AliasSeq`](std_meta#AliasSeq) of all interfaces directly or indirectly inherited by this class or interface. Interfaces do not repeat if multiply implemented. `InterfacesTuple!Object` yields an empty `AliasSeq`. Examples: ``` interface I1 {} interface I2 {} class A : I1, I2 {} class B : A, I1 {} class C : B {} alias TL = InterfacesTuple!C; static assert(is(TL[0] == I1) && is(TL[1] == I2)); ``` template **TransitiveBaseTypeTuple**(T) Get a AliasSeq of *all* base classes of T, in decreasing order, followed by T's interfaces. TransitiveBaseTypeTuple!Object yields the empty type tuple. Examples: ``` interface J1 {} interface J2 {} class B1 {} class B2 : B1, J1, J2 {} class B3 : B2, J1 {} alias TL = TransitiveBaseTypeTuple!B3; writeln(TL.length); // 5 assert(is (TL[0] == B2)); assert(is (TL[1] == B1)); assert(is (TL[2] == Object)); assert(is (TL[3] == J1)); assert(is (TL[4] == J2)); writeln(TransitiveBaseTypeTuple!Object.length); // 0 ``` template **MemberFunctionsTuple**(C, string name) if (is(C == class) || is(C == interface)) Returns a tuple of non-static functions with the name `name` declared in the class or interface `C`. Covariant duplicates are shrunk into the most derived one. Examples: ``` interface I { I foo(); } class B { real foo(real v) { return v; } } class C : B, I { override C foo() { return this; } // covariant overriding of I.foo() } alias foos = MemberFunctionsTuple!(C, "foo"); static assert(foos.length == 2); static assert(__traits(isSame, foos[0], C.foo)); static assert(__traits(isSame, foos[1], B.foo)); ``` template **TemplateOf**(alias T : Base!Args, alias Base, Args...) template **TemplateOf**(T : Base!Args, alias Base, Args...) template **TemplateOf**(T) Returns an alias to the template that `T` is an instance of. It will return `void` if a symbol without a template is given. Examples: ``` struct Foo(T, U) {} static assert(__traits(isSame, TemplateOf!(Foo!(int, real)), Foo)); ``` template **TemplateArgsOf**(alias T : Base!Args, alias Base, Args...) template **TemplateArgsOf**(T : Base!Args, alias Base, Args...) Returns a `AliasSeq` of the template arguments used to instantiate `T`. Examples: ``` import std.meta : AliasSeq; struct Foo(T, U) {} static assert(is(TemplateArgsOf!(Foo!(int, real)) == AliasSeq!(int, real))); ``` template **classInstanceAlignment**(T) if (is(T == class)) Returns class instance alignment. Examples: ``` class A { byte b; } class B { long l; } // As class instance always has a hidden pointer static assert(classInstanceAlignment!A == (void*).alignof); static assert(classInstanceAlignment!B == long.alignof); ``` template **CommonType**(T...) Get the type that all types can be implicitly converted to. Useful e.g. in figuring out an array type from a bunch of initializing values. Returns void if passed an empty list, or if the types have no common type. Examples: ``` alias X = CommonType!(int, long, short); assert(is(X == long)); alias Y = CommonType!(int, char[], short); assert(is(Y == void)); ``` Examples: ``` static assert(is(CommonType!(3) == int)); static assert(is(CommonType!(double, 4, float) == double)); static assert(is(CommonType!(string, char[]) == const(char)[])); static assert(is(CommonType!(3, 3U) == uint)); static assert(is(CommonType!(double, int) == double)); ``` template **ImplicitConversionTargets**(T) Parameters: | | | | --- | --- | | T | The type to check | Returns: An [`std.meta.AliasSeq`](std_meta#AliasSeq) with all possible target types of an implicit conversion `T`. If `T` is a class derived from `Object`, the the result of [`TransitiveBaseTypeTuple`](#TransitiveBaseTypeTuple) is returned. If the type is not a built-in value type or a class derived from `Object`, the an empty [`std.meta.AliasSeq`](std_meta#AliasSeq) is returned. Note The possible targets are computed more conservatively than the language allows, eliminating all dangerous conversions. For example, `ImplicitConversionTargets!double` does not include `float`. See Also: [`isImplicitlyConvertible`](#isImplicitlyConvertible) Examples: ``` import std.meta : AliasSeq; static assert(is(ImplicitConversionTargets!(ulong) == AliasSeq!(float, double, real))); static assert(is(ImplicitConversionTargets!(int) == AliasSeq!(long, ulong, float, double, real))); static assert(is(ImplicitConversionTargets!(float) == AliasSeq!(double, real))); static assert(is(ImplicitConversionTargets!(double) == AliasSeq!(real))); static assert(is(ImplicitConversionTargets!(char) == AliasSeq!( wchar, dchar, byte, ubyte, short, ushort, int, uint, long, ulong, float, double, real ))); static assert(is(ImplicitConversionTargets!(wchar) == AliasSeq!( dchar, short, ushort, int, uint, long, ulong, float, double, real ))); static assert(is(ImplicitConversionTargets!(dchar) == AliasSeq!( int, uint, long, ulong, float, double, real ))); static assert(is(ImplicitConversionTargets!(string) == AliasSeq!(const(char)[]))); static assert(is(ImplicitConversionTargets!(void*) == AliasSeq!(void*))); interface A {} interface B {} class C : A, B {} static assert(is(ImplicitConversionTargets!(C) == AliasSeq!(Object, A, B))); static assert(is(ImplicitConversionTargets!(const C) == AliasSeq!(const Object, const A, const B))); static assert(is(ImplicitConversionTargets!(immutable C) == AliasSeq!( immutable Object, immutable A, immutable B ))); ``` enum bool **isImplicitlyConvertible**(From, To); Is `From` implicitly convertible to `To`? Examples: ``` static assert( isImplicitlyConvertible!(immutable(char), char)); static assert( isImplicitlyConvertible!(const(char), char)); static assert( isImplicitlyConvertible!(char, wchar)); static assert(!isImplicitlyConvertible!(wchar, char)); static assert(!isImplicitlyConvertible!(const(ushort), ubyte)); static assert(!isImplicitlyConvertible!(const(uint), ubyte)); static assert(!isImplicitlyConvertible!(const(ulong), ubyte)); static assert(!isImplicitlyConvertible!(const(char)[], string)); static assert( isImplicitlyConvertible!(string, const(char)[])); ``` enum auto **isAssignable**(Lhs, Rhs = Lhs); Returns `true` iff a value of type `Rhs` can be assigned to a variable of type `Lhs`. `isAssignable` returns whether both an lvalue and rvalue can be assigned. If you omit `Rhs`, `isAssignable` will check identity assignable of `Lhs`. Examples: ``` static assert( isAssignable!(long, int)); static assert(!isAssignable!(int, long)); static assert( isAssignable!(const(char)[], string)); static assert(!isAssignable!(string, char[])); // int is assignable to int static assert( isAssignable!int); // immutable int is not assignable to immutable int static assert(!isAssignable!(immutable int)); ``` enum auto **isRvalueAssignable**(Lhs, Rhs = Lhs); Returns `true` iff an rvalue of type `Rhs` can be assigned to a variable of type `Lhs` enum auto **isLvalueAssignable**(Lhs, Rhs = Lhs); Returns `true` iff an lvalue of type `Rhs` can be assigned to a variable of type `Lhs` template **isCovariantWith**(F, G) if (is(F == function) && is(G == function) || is(F == delegate) && is(G == delegate) || isFunctionPointer!F && isFunctionPointer!G) Determines whether the function type `F` is covariant with `G`, i.e., functions of the type `F` can override ones of the type `G`. Examples: ``` interface I { I clone(); } interface J { J clone(); } class C : I { override C clone() // covariant overriding of I.clone() { return new C; } } // C.clone() can override I.clone(), indeed. static assert(isCovariantWith!(typeof(C.clone), typeof(I.clone))); // C.clone() can't override J.clone(); the return type C is not implicitly // convertible to J. static assert(!isCovariantWith!(typeof(C.clone), typeof(J.clone))); ``` @property T **rvalueOf**(T)(inout \_\_InoutWorkaroundStruct = \_\_InoutWorkaroundStruct.init); @property ref T **lvalueOf**(T)(inout \_\_InoutWorkaroundStruct = \_\_InoutWorkaroundStruct.init); Creates an lvalue or rvalue of type `T` for `typeof(...)` and `__traits(compiles, ...)` purposes. No actual value is returned. Parameters: | | | | --- | --- | | T | The type to transform | Note Trying to use returned value will result in a "Symbol Undefined" error at link time. Examples: ``` static int f(int); static assert(is(typeof(f(rvalueOf!int)) == int)); ``` Examples: ``` static bool f(ref int); static assert(is(typeof(f(lvalueOf!int)) == bool)); ``` enum bool **isBoolean**(T); Detect whether `T` is a built-in boolean type. Examples: ``` static assert( isBoolean!bool); enum EB : bool { a = true } static assert( isBoolean!EB); static assert(!isBoolean!(SubTypeOf!bool)); ``` enum bool **isIntegral**(T); Detect whether `T` is a built-in integral type. Types `bool`, `char`, `wchar`, and `dchar` are not considered integral. Examples: ``` static assert( isIntegral!byte && isIntegral!short && isIntegral!int && isIntegral!long && isIntegral!(const(long)) && isIntegral!(immutable(long)) ); static assert( !isIntegral!bool && !isIntegral!char && !isIntegral!double ); // types which act as integral values do not pass struct S { int val; alias val this; } static assert(!isIntegral!S); ``` enum bool **isFloatingPoint**(T); Detect whether `T` is a built-in floating point type. Examples: ``` static assert( isFloatingPoint!float && isFloatingPoint!double && isFloatingPoint!real && isFloatingPoint!(const(real)) && isFloatingPoint!(immutable(real)) ); static assert(!isFloatingPoint!int); // complex and imaginary numbers do not pass static assert( !isFloatingPoint!cfloat && !isFloatingPoint!ifloat ); // types which act as floating point values do not pass struct S { float val; alias val this; } static assert(!isFloatingPoint!S); ``` enum bool **isNumeric**(T); Detect whether `T` is a built-in numeric type (integral or floating point). Examples: ``` static assert( isNumeric!byte && isNumeric!short && isNumeric!int && isNumeric!long && isNumeric!float && isNumeric!double && isNumeric!real && isNumeric!(const(real)) && isNumeric!(immutable(real)) ); static assert( !isNumeric!void && !isNumeric!bool && !isNumeric!char && !isNumeric!wchar && !isNumeric!dchar ); // types which act as numeric values do not pass struct S { int val; alias val this; } static assert(!isIntegral!S); ``` enum bool **isScalarType**(T); Detect whether `T` is a scalar type (a built-in numeric, character or boolean type). Examples: ``` static assert(!isScalarType!void); static assert( isScalarType!(immutable(byte))); static assert( isScalarType!(immutable(ushort))); static assert( isScalarType!(immutable(int))); static assert( isScalarType!(ulong)); static assert( isScalarType!(shared(float))); static assert( isScalarType!(shared(const bool))); static assert( isScalarType!(const(char))); static assert( isScalarType!(wchar)); static assert( isScalarType!(const(dchar))); static assert( isScalarType!(const(double))); static assert( isScalarType!(const(real))); ``` enum bool **isBasicType**(T); Detect whether `T` is a basic type (scalar type or void). Examples: ``` static assert(isBasicType!void); static assert(isBasicType!(const(void))); static assert(isBasicType!(shared(void))); static assert(isBasicType!(immutable(void))); static assert(isBasicType!(shared const(void))); static assert(isBasicType!(shared inout(void))); static assert(isBasicType!(shared inout const(void))); static assert(isBasicType!(inout(void))); static assert(isBasicType!(inout const(void))); static assert(isBasicType!(immutable(int))); static assert(isBasicType!(shared(float))); static assert(isBasicType!(shared(const bool))); static assert(isBasicType!(const(dchar))); ``` enum bool **isUnsigned**(T); Detect whether `T` is a built-in unsigned numeric type. Examples: ``` static assert( isUnsigned!uint && isUnsigned!ulong ); static assert( !isUnsigned!char && !isUnsigned!int && !isUnsigned!long && !isUnsigned!char && !isUnsigned!wchar && !isUnsigned!dchar ); ``` enum bool **isSigned**(T); Detect whether `T` is a built-in signed numeric type. Examples: ``` static assert( isSigned!int && isSigned!long ); static assert( !isSigned!uint && !isSigned!ulong ); ``` enum bool **isSomeChar**(T); Detect whether `T` is one of the built-in character types. The built-in char types are any of `char`, `wchar` or `dchar`, with or without qualifiers. Examples: ``` //Char types static assert( isSomeChar!char); static assert( isSomeChar!wchar); static assert( isSomeChar!dchar); static assert( isSomeChar!(typeof('c'))); static assert( isSomeChar!(immutable char)); static assert( isSomeChar!(const dchar)); //Non char types static assert(!isSomeChar!int); static assert(!isSomeChar!byte); static assert(!isSomeChar!string); static assert(!isSomeChar!wstring); static assert(!isSomeChar!dstring); static assert(!isSomeChar!(char[4])); ``` enum bool **isSomeString**(T); Detect whether `T` is one of the built-in string types. The built-in string types are `Char[]`, where `Char` is any of `char`, `wchar` or `dchar`, with or without qualifiers. Static arrays of characters (like `char[80]`) are not considered built-in string types. Examples: ``` //String types static assert( isSomeString!string); static assert( isSomeString!(wchar[])); static assert( isSomeString!(dchar[])); static assert( isSomeString!(typeof("aaa"))); static assert( isSomeString!(const(char)[])); //Non string types static assert(!isSomeString!int); static assert(!isSomeString!(int[])); static assert(!isSomeString!(byte[])); static assert(!isSomeString!(typeof(null))); static assert(!isSomeString!(char[4])); enum ES : string { a = "aaa", b = "bbb" } static assert(!isSomeString!ES); static struct Stringish { string str; alias str this; } static assert(!isSomeString!Stringish); ``` enum bool **isNarrowString**(T); Detect whether type `T` is a narrow string. All arrays that use char, wchar, and their qualified versions are narrow strings. (Those include string and wstring). Examples: ``` static assert(isNarrowString!string); static assert(isNarrowString!wstring); static assert(isNarrowString!(char[])); static assert(isNarrowString!(wchar[])); static assert(!isNarrowString!dstring); static assert(!isNarrowString!(dchar[])); static assert(!isNarrowString!(typeof(null))); static assert(!isNarrowString!(char[4])); enum ES : string { a = "aaa", b = "bbb" } static assert(!isNarrowString!ES); static struct Stringish { string str; alias str this; } static assert(!isNarrowString!Stringish); ``` enum bool **isOrderingComparable**(T); enum bool **isEqualityComparable**(T); Detects whether `T` is a comparable type. Basic types and structs and classes that implement opCmp are ordering comparable. Examples: ``` static assert(isOrderingComparable!int); static assert(isOrderingComparable!string); static assert(!isOrderingComparable!creal); static struct Foo {} static assert(!isOrderingComparable!Foo); static struct Bar { int a; auto opCmp(Bar b1) const { return a - b1.a; } } Bar b1 = Bar(5); Bar b2 = Bar(7); assert(isOrderingComparable!Bar && b2 > b1); ``` enum auto **isConvertibleToString**(T); Warning: This trait will be deprecated as soon as it is no longer used in Phobos. For a function parameter to safely accept a type that implicitly converts to string as a string, the conversion needs to happen at the callsite; otherwise, the conversion is done inside the function, and in many cases, that means that local memory is sliced (e.g. if a static array is passed to the function, then it's copied, and the resulting dynamic array will be a slice of a local variable). So, if the resulting string escapes the function, the string refers to invalid memory, and accessing it would mean accessing invalid memory. As such, the only safe way for a function to accept types that implicitly convert to string is for the implicit conversion to be done at the callsite, and that can only occur if the parameter is explicitly typed as an array, whereas using isConvertibleToString in a template constraint would result in the conversion being done inside the function. As such, isConvertibleToString is inherently unsafe and is going to be deprecated. Detect whether `T` is a struct, static array, or enum that is implicitly convertible to a string. Examples: ``` static struct AliasedString { string s; alias s this; } enum StringEnum { a = "foo" } assert(!isConvertibleToString!string); assert(isConvertibleToString!AliasedString); assert(isConvertibleToString!StringEnum); assert(isConvertibleToString!(char[25])); assert(!isConvertibleToString!(char[])); ``` enum auto **isAutodecodableString**(T); Detect whether type `T` is a string that will be autodecoded. Given a type `S` that is one of: 1. `const(char)[]` 2. `const(wchar)[]` Type `T` can be one of: 1. `S` 2. implicitly convertible to `T` 3. an enum with a base type `T` 4. an aggregate with a base type `T` with the proviso that `T` cannot be a static array. Parameters: | | | | --- | --- | | T | type to be tested | Returns: true if T represents a string that is subject to autodecoding See Also: [`isNarrowString`](#isNarrowString) Examples: ``` static struct Stringish { string s; alias s this; } static assert(isAutodecodableString!wstring); static assert(isAutodecodableString!Stringish); static assert(!isAutodecodableString!dstring); enum E : const(char)[3] { X = "abc" } enum F : const(char)[] { X = "abc" } enum G : F { X = F.init } static assert(isAutodecodableString!(char[])); static assert(!isAutodecodableString!(E)); static assert(isAutodecodableString!(F)); static assert(isAutodecodableString!(G)); struct Stringish2 { Stringish s; alias s this; } enum H : Stringish { X = Stringish() } enum I : Stringish2 { X = Stringish2() } static assert(isAutodecodableString!(H)); static assert(isAutodecodableString!(I)); ``` enum bool **isStaticArray**(T); Detect whether type `T` is a static array. Examples: ``` static assert( isStaticArray!(int[3])); static assert( isStaticArray!(const(int)[5])); static assert( isStaticArray!(const(int)[][5])); static assert(!isStaticArray!(const(int)[])); static assert(!isStaticArray!(immutable(int)[])); static assert(!isStaticArray!(const(int)[4][])); static assert(!isStaticArray!(int[])); static assert(!isStaticArray!(int[char])); static assert(!isStaticArray!(int[1][])); static assert(!isStaticArray!(int[int])); static assert(!isStaticArray!int); ``` enum bool **isDynamicArray**(T); Detect whether type `T` is a dynamic array. Examples: ``` static assert( isDynamicArray!(int[])); static assert( isDynamicArray!(string)); static assert( isDynamicArray!(long[3][])); static assert(!isDynamicArray!(int[5])); static assert(!isDynamicArray!(typeof(null))); ``` enum bool **isArray**(T); Detect whether type `T` is an array (static or dynamic; for associative arrays see [`isAssociativeArray`](#isAssociativeArray)). Examples: ``` static assert( isArray!(int[])); static assert( isArray!(int[5])); static assert( isArray!(string)); static assert(!isArray!uint); static assert(!isArray!(uint[uint])); static assert(!isArray!(typeof(null))); ``` enum bool **isAssociativeArray**(T); Detect whether `T` is an associative array type enum bool **isBuiltinType**(T); Detect whether type `T` is a builtin type. Examples: ``` class C; union U; struct S; interface I; static assert( isBuiltinType!void); static assert( isBuiltinType!string); static assert( isBuiltinType!(int[])); static assert( isBuiltinType!(C[string])); static assert(!isBuiltinType!C); static assert(!isBuiltinType!U); static assert(!isBuiltinType!S); static assert(!isBuiltinType!I); static assert(!isBuiltinType!(void delegate(int))); ``` enum bool **isSIMDVector**(T); Detect whether type `T` is a SIMD vector type. enum bool **isPointer**(T); Detect whether type `T` is a pointer. template **PointerTarget**(T : T\*) Returns the target type of a pointer. Examples: ``` static assert(is(PointerTarget!(int*) == int)); static assert(is(PointerTarget!(void*) == void)); ``` enum bool **isAggregateType**(T); Detect whether type `T` is an aggregate type. Examples: ``` class C; union U; struct S; interface I; static assert( isAggregateType!C); static assert( isAggregateType!U); static assert( isAggregateType!S); static assert( isAggregateType!I); static assert(!isAggregateType!void); static assert(!isAggregateType!string); static assert(!isAggregateType!(int[])); static assert(!isAggregateType!(C[string])); static assert(!isAggregateType!(void delegate(int))); ``` enum bool **isIterable**(T); Returns `true` if T can be iterated over using a `foreach` loop with a single loop variable of automatically inferred type, regardless of how the `foreach` loop is implemented. This includes ranges, structs/classes that define `opApply` with a single loop variable, and builtin dynamic, static and associative arrays. Examples: ``` struct OpApply { int opApply(scope int delegate(ref uint) dg) { assert(0); } } struct Range { @property uint front() { assert(0); } void popFront() { assert(0); } enum bool empty = false; } static assert( isIterable!(uint[])); static assert( isIterable!OpApply); static assert( isIterable!(uint[string])); static assert( isIterable!Range); static assert(!isIterable!uint); ``` enum bool **isMutable**(T); Returns true if T is not const or immutable. Note that isMutable is true for string, or immutable(char)[], because the 'head' is mutable. Examples: ``` static assert( isMutable!int); static assert( isMutable!string); static assert( isMutable!(shared int)); static assert( isMutable!(shared const(int)[])); static assert(!isMutable!(const int)); static assert(!isMutable!(inout int)); static assert(!isMutable!(shared(const int))); static assert(!isMutable!(shared(inout int))); static assert(!isMutable!(immutable string)); ``` enum bool **isInstanceOf**(alias S, T); enum auto **isInstanceOf**(alias S, alias T); Returns true if T is an instance of the template S. Examples: ``` static struct Foo(T...) { } static struct Bar(T...) { } static struct Doo(T) { } static struct ABC(int x) { } static void fun(T)() { } template templ(T) { } static assert(isInstanceOf!(Foo, Foo!int)); static assert(!isInstanceOf!(Foo, Bar!int)); static assert(!isInstanceOf!(Foo, int)); static assert(isInstanceOf!(Doo, Doo!int)); static assert(isInstanceOf!(ABC, ABC!1)); static assert(!isInstanceOf!(Foo, Foo)); static assert(isInstanceOf!(fun, fun!int)); static assert(isInstanceOf!(templ, templ!int)); ``` Examples: To use `isInstanceOf` to check the identity of a template while inside of said template, use [`TemplateOf`](#TemplateOf). ``` static struct A(T = void) { // doesn't work as expected, only accepts A when T = void void func(B)(B b) if (isInstanceOf!(A, B)) {} // correct behavior void method(B)(B b) if (isInstanceOf!(TemplateOf!(A), B)) {} } A!(void) a1; A!(void) a2; A!(int) a3; static assert(!__traits(compiles, a1.func(a3))); static assert( __traits(compiles, a1.method(a2))); static assert( __traits(compiles, a1.method(a3))); ``` template **isExpressions**(T...) Check whether the tuple T is an expression tuple. An expression tuple only contains expressions. See Also: [`isTypeTuple`](#isTypeTuple). Examples: ``` static assert(isExpressions!(1, 2.0, "a")); static assert(!isExpressions!(int, double, string)); static assert(!isExpressions!(int, 2.0, "a")); ``` alias **isExpressionTuple** = isExpressions(T...); Alternate name for [`isExpressions`](#isExpressions), kept for legacy compatibility. template **isTypeTuple**(T...) Check whether the tuple `T` is a type tuple. A type tuple only contains types. See Also: [`isExpressions`](#isExpressions). Examples: ``` static assert(isTypeTuple!(int, float, string)); static assert(!isTypeTuple!(1, 2.0, "a")); static assert(!isTypeTuple!(1, double, string)); ``` template **isFunctionPointer**(T...) if (T.length == 1) Detect whether symbol or type `T` is a function pointer. Examples: ``` static void foo() {} void bar() {} auto fpfoo = &foo; static assert( isFunctionPointer!fpfoo); static assert( isFunctionPointer!(void function())); auto dgbar = &bar; static assert(!isFunctionPointer!dgbar); static assert(!isFunctionPointer!(void delegate())); static assert(!isFunctionPointer!foo); static assert(!isFunctionPointer!bar); static assert( isFunctionPointer!((int a) {})); ``` template **isDelegate**(T...) if (T.length == 1) Detect whether symbol or type `T` is a delegate. Examples: ``` static void sfunc() { } int x; void func() { x++; } int delegate() dg; assert(isDelegate!dg); assert(isDelegate!(int delegate())); assert(isDelegate!(typeof(&func))); int function() fp; assert(!isDelegate!fp); assert(!isDelegate!(int function())); assert(!isDelegate!(typeof(&sfunc))); ``` template **isSomeFunction**(T...) if (T.length == 1) Detect whether symbol or type `T` is a function, a function pointer or a delegate. Parameters: | | | | --- | --- | | T | The type to check | Returns: A `bool` Examples: ``` static real func(ref int) { return 0; } static void prop() @property { } class C { real method(ref int) { return 0; } real prop() @property { return 0; } } auto c = new C; auto fp = &func; auto dg = &c.method; real val; static assert( isSomeFunction!func); static assert( isSomeFunction!prop); static assert( isSomeFunction!(C.method)); static assert( isSomeFunction!(C.prop)); static assert( isSomeFunction!(c.prop)); static assert( isSomeFunction!(c.prop)); static assert( isSomeFunction!fp); static assert( isSomeFunction!dg); static assert(!isSomeFunction!int); static assert(!isSomeFunction!val); ``` template **isCallable**(alias callable) Detect whether `T` is a callable object, which can be called with the function call operator `(...)`. Examples: Functions, lambdas, and aggregate types with (static) opCall. ``` void f() { } int g(int x) { return x; } static assert( isCallable!f); static assert( isCallable!g); class C { int opCall(int) { return 0; } } auto c = new C; struct S { static int opCall(int) { return 0; } } interface I { real value() @property; } static assert( isCallable!c); static assert( isCallable!(c.opCall)); static assert( isCallable!S); static assert( isCallable!(I.value)); static assert( isCallable!((int a) { return a; })); static assert(!isCallable!I); ``` Examples: Templates ``` void f()() { } T g(T = int)(T x) { return x; } static assert( isCallable!f); static assert( isCallable!g); ``` Examples: Overloaded functions and function templates. ``` static struct Wrapper { void f() { } int f(int x) { return x; } void g()() { } T g(T = int)(T x) { return x; } } static assert(isCallable!(Wrapper.f)); static assert(isCallable!(Wrapper.g)); ``` template **isAbstractFunction**(T...) if (T.length == 1) Detect whether `T` is an abstract function. Parameters: | | | | --- | --- | | T | The type to check | Returns: A `bool` Examples: ``` struct S { void foo() { } } class C { void foo() { } } class AC { abstract void foo(); } static assert(!isAbstractFunction!(int)); static assert(!isAbstractFunction!(S.foo)); static assert(!isAbstractFunction!(C.foo)); static assert( isAbstractFunction!(AC.foo)); ``` template **isFinalFunction**(T...) if (T.length == 1) Detect whether `T` is a final function. Examples: ``` struct S { void bar() { } } final class FC { void foo(); } class C { void bar() { } final void foo(); } static assert(!isFinalFunction!(int)); static assert(!isFinalFunction!(S.bar)); static assert( isFinalFunction!(FC.foo)); static assert(!isFinalFunction!(C.bar)); static assert( isFinalFunction!(C.foo)); ``` enum auto **isNestedFunction**(alias f); Determines if `f` is a function that requires a context pointer. Parameters: | | | | --- | --- | | f | The type to check Returns A `bool` | Examples: ``` static void f() {} static void fun() { int i; int f() { return i; } static assert(isNestedFunction!(f)); } static assert(!isNestedFunction!f); ``` template **isAbstractClass**(T...) if (T.length == 1) Detect whether `T` is an abstract class. Examples: ``` struct S { } class C { } abstract class AC { } static assert(!isAbstractClass!S); static assert(!isAbstractClass!C); static assert( isAbstractClass!AC); C c; static assert(!isAbstractClass!c); AC ac; static assert( isAbstractClass!ac); ``` template **isFinalClass**(T...) if (T.length == 1) Detect whether `T` is a final class. Examples: ``` class C { } abstract class AC { } final class FC1 : C { } final class FC2 { } static assert(!isFinalClass!C); static assert(!isFinalClass!AC); static assert( isFinalClass!FC1); static assert( isFinalClass!FC2); C c; static assert(!isFinalClass!c); FC1 fc1; static assert( isFinalClass!fc1); ``` template **Unconst**(T) Removes `const`, `inout` and `immutable` qualifiers, if any, from type `T`. Examples: ``` static assert(is(Unconst!int == int)); static assert(is(Unconst!(const int) == int)); static assert(is(Unconst!(immutable int) == int)); static assert(is(Unconst!(shared int) == shared int)); static assert(is(Unconst!(shared(const int)) == shared int)); ``` template **Unqual**(T) Removes all qualifiers, if any, from type `T`. Examples: ``` static assert(is(Unqual!int == int)); static assert(is(Unqual!(const int) == int)); static assert(is(Unqual!(immutable int) == int)); static assert(is(Unqual!(shared int) == int)); static assert(is(Unqual!(shared(const int)) == int)); ``` template **CopyTypeQualifiers**(FromType, ToType) Copies type qualifiers from `FromType` to `ToType`. Supported type qualifiers: * `const` * `inout` * `immutable` * `shared` Examples: ``` static assert(is(CopyTypeQualifiers!(inout const real, int) == inout const int)); ``` template **CopyConstness**(FromType, ToType) Returns the type of `ToType` with the "constness" of `FromType`. A type's **constness** refers to whether it is `const`, `immutable`, or `inout`. If `FromType` has no constness, the returned type will be the same as `ToType`. Examples: ``` const(int) i; CopyConstness!(typeof(i), float) f; assert( is(typeof(f) == const float)); CopyConstness!(char, uint) u; assert( is(typeof(u) == uint)); //The 'shared' qualifier will not be copied assert(!is(CopyConstness!(shared bool, int) == shared int)); //But the constness will be assert( is(CopyConstness!(shared const real, double) == const double)); //Careful, const(int)[] is a mutable array of const(int) alias MutT = CopyConstness!(const(int)[], int); assert(!is(MutT == const(int))); //Okay, const(int[]) applies to array and contained ints alias CstT = CopyConstness!(const(int[]), int); assert( is(CstT == const(int))); ``` template **ForeachType**(T) Returns the inferred type of the loop variable when a variable of type T is iterated over using a `foreach` loop with a single loop variable and automatically inferred return type. Note that this may not be the same as `std.range.ElementType!Range` in the case of narrow strings, or if T has both opApply and a range interface. Examples: ``` static assert(is(ForeachType!(uint[]) == uint)); static assert(is(ForeachType!string == immutable(char))); static assert(is(ForeachType!(string[string]) == string)); static assert(is(ForeachType!(inout(int)[]) == inout(int))); ``` template **OriginalType**(T) Strips off all `enum`s from type `T`. Examples: ``` enum E : real { a = 0 } // NOTE: explicit initialization to 0 required during Enum init deprecation cycle enum F : E { a = E.a } alias G = const(F); static assert(is(OriginalType!E == real)); static assert(is(OriginalType!F == real)); static assert(is(OriginalType!G == const real)); ``` template **KeyType**(V : V[K], K) Get the Key type of an Associative Array. Examples: ``` alias Hash = int[string]; static assert(is(KeyType!Hash == string)); static assert(is(ValueType!Hash == int)); KeyType!Hash str = "a"; // str is declared as string ValueType!Hash num = 1; // num is declared as int ``` template **ValueType**(V : V[K], K) Get the Value type of an Associative Array. Examples: ``` alias Hash = int[string]; static assert(is(KeyType!Hash == string)); static assert(is(ValueType!Hash == int)); KeyType!Hash str = "a"; // str is declared as string ValueType!Hash num = 1; // num is declared as int ``` template **Unsigned**(T) Parameters: | | | | --- | --- | | T | A built in integral or vector type. | Returns: The corresponding unsigned numeric type for `T` with the same type qualifiers. If `T` is not a integral or vector, a compile-time error is given. Examples: ``` static assert(is(Unsigned!(int) == uint)); static assert(is(Unsigned!(long) == ulong)); static assert(is(Unsigned!(const short) == const ushort)); static assert(is(Unsigned!(immutable byte) == immutable ubyte)); static assert(is(Unsigned!(inout int) == inout uint)); ``` Examples: Unsigned types are forwarded ``` static assert(is(Unsigned!(uint) == uint)); static assert(is(Unsigned!(const uint) == const uint)); static assert(is(Unsigned!(ubyte) == ubyte)); static assert(is(Unsigned!(immutable uint) == immutable uint)); ``` template **Largest**(T...) if (T.length >= 1) Returns the largest type, i.e. T such that T.sizeof is the largest. If more than one type is of the same size, the leftmost argument of these in will be returned. Examples: ``` static assert(is(Largest!(uint, ubyte, ushort, real) == real)); static assert(is(Largest!(ulong, double) == ulong)); static assert(is(Largest!(double, ulong) == double)); static assert(is(Largest!(uint, byte, double, short) == double)); static if (is(ucent)) static assert(is(Largest!(uint, ubyte, ucent, ushort) == ucent)); ``` template **Signed**(T) Returns the corresponding signed type for T. T must be a numeric integral type, otherwise a compile-time error occurs. Examples: ``` alias S1 = Signed!uint; static assert(is(S1 == int)); alias S2 = Signed!(const(uint)); static assert(is(S2 == const(int))); alias S3 = Signed!(immutable(uint)); static assert(is(S3 == immutable(int))); static if (is(ucent)) { alias S4 = Signed!ucent; static assert(is(S4 == cent)); } ``` template **mostNegative**(T) if (isNumeric!T || isSomeChar!T || isBoolean!T) Returns the most negative value of the numeric type T. Examples: ``` static assert(mostNegative!float == -float.max); static assert(mostNegative!double == -double.max); static assert(mostNegative!real == -real.max); static assert(mostNegative!bool == false); ``` Examples: ``` import std.meta : AliasSeq; static foreach (T; AliasSeq!(bool, byte, short, int, long)) static assert(mostNegative!T == T.min); static foreach (T; AliasSeq!(ubyte, ushort, uint, ulong, char, wchar, dchar)) static assert(mostNegative!T == 0); ``` template **Promoted**(T) if (isScalarType!T) Get the type that a scalar type `T` will [promote](https://dlang.org/spec/type.html#integer-promotions) to in multi-term arithmetic expressions. Examples: ``` ubyte a = 3, b = 5; static assert(is(typeof(a * b) == Promoted!ubyte)); static assert(is(Promoted!ubyte == int)); static assert(is(Promoted!(shared(bool)) == shared(int))); static assert(is(Promoted!(const(int)) == const(int))); static assert(is(Promoted!double == double)); ``` template **mangledName**(sth...) if (sth.length == 1) Returns the mangled name of symbol or type `sth`. `mangledName` is the same as builtin `.mangleof` property, but might be more convenient in generic code, e.g. as a template argument when invoking staticMap. Examples: ``` import std.meta : AliasSeq; alias TL = staticMap!(mangledName, int, const int, immutable int); static assert(TL == AliasSeq!("i", "xi", "yi")); ``` template **Select**(bool condition, T...) if (T.length == 2) Aliases itself to `T[0]` if the boolean `condition` is `true` and to `T[1]` otherwise. Examples: ``` // can select types static assert(is(Select!(true, int, long) == int)); static assert(is(Select!(false, int, long) == long)); static struct Foo {} static assert(is(Select!(false, const(int), const(Foo)) == const(Foo))); // can select symbols int a = 1; int b = 2; alias selA = Select!(true, a, b); alias selB = Select!(false, a, b); writeln(selA); // 1 writeln(selB); // 2 // can select (compile-time) expressions enum val = Select!(false, -4, 9 - 6); static assert(val == 3); ``` A **select**(bool cond : true, A, B)(A a, lazy B b); B **select**(bool cond : false, A, B)(lazy A a, B b); Select one of two functions to run via template parameter. Parameters: | | | | --- | --- | | cond | A `bool` which determines which function is run | | A `a` | The first function | | B `b` | The second function | Returns: `a` without evaluating `b` if `cond` is `true`. Otherwise, returns `b` without evaluating `a`. Examples: ``` real run() { return 0; } int fail() { assert(0); } auto a = select!true(run(), fail()); auto b = select!false(fail(), run()); static assert(is(typeof(a) == real)); static assert(is(typeof(b) == real)); ``` enum auto **hasUDA**(alias symbol, alias attribute); Determine if a symbol has a given [user-defined attribute](https://dlang.org/spec/attribute.html#uda). See Also: [`getUDAs`](#getUDAs) Examples: ``` enum E; struct S {} @("alpha") int a; static assert(hasUDA!(a, "alpha")); static assert(!hasUDA!(a, S)); static assert(!hasUDA!(a, E)); @(E) int b; static assert(!hasUDA!(b, "alpha")); static assert(!hasUDA!(b, S)); static assert(hasUDA!(b, E)); @E int c; static assert(!hasUDA!(c, "alpha")); static assert(!hasUDA!(c, S)); static assert(hasUDA!(c, E)); @(S, E) int d; static assert(!hasUDA!(d, "alpha")); static assert(hasUDA!(d, S)); static assert(hasUDA!(d, E)); @S int e; static assert(!hasUDA!(e, "alpha")); static assert(hasUDA!(e, S)); static assert(!hasUDA!(e, S())); static assert(!hasUDA!(e, E)); @S() int f; static assert(!hasUDA!(f, "alpha")); static assert(hasUDA!(f, S)); static assert(hasUDA!(f, S())); static assert(!hasUDA!(f, E)); @(S, E, "alpha") int g; static assert(hasUDA!(g, "alpha")); static assert(hasUDA!(g, S)); static assert(hasUDA!(g, E)); @(100) int h; static assert(hasUDA!(h, 100)); struct Named { string name; } @Named("abc") int i; static assert(hasUDA!(i, Named)); static assert(hasUDA!(i, Named("abc"))); static assert(!hasUDA!(i, Named("def"))); struct AttrT(T) { string name; T value; } @AttrT!int("answer", 42) int j; static assert(hasUDA!(j, AttrT)); static assert(hasUDA!(j, AttrT!int)); static assert(!hasUDA!(j, AttrT!string)); @AttrT!string("hello", "world") int k; static assert(hasUDA!(k, AttrT)); static assert(!hasUDA!(k, AttrT!int)); static assert(hasUDA!(k, AttrT!string)); struct FuncAttr(alias f) { alias func = f; } static int fourtyTwo() { return 42; } static size_t getLen(string s) { return s.length; } @FuncAttr!getLen int l; static assert(hasUDA!(l, FuncAttr)); static assert(!hasUDA!(l, FuncAttr!fourtyTwo)); static assert(hasUDA!(l, FuncAttr!getLen)); static assert(!hasUDA!(l, FuncAttr!fourtyTwo())); static assert(!hasUDA!(l, FuncAttr!getLen())); @FuncAttr!getLen() int m; static assert(hasUDA!(m, FuncAttr)); static assert(!hasUDA!(m, FuncAttr!fourtyTwo)); static assert(hasUDA!(m, FuncAttr!getLen)); static assert(!hasUDA!(m, FuncAttr!fourtyTwo())); static assert(hasUDA!(m, FuncAttr!getLen())); ``` template **getUDAs**(alias symbol, alias attribute) Gets the matching [user-defined attributes](https://dlang.org/spec/attribute.html#uda) from the given symbol. If the UDA is a type, then any UDAs of the same type on the symbol will match. If the UDA is a template for a type, then any UDA which is an instantiation of that template will match. And if the UDA is a value, then any UDAs on the symbol which are equal to that value will match. See Also: [`hasUDA`](#hasUDA) Examples: ``` struct Attr { string name; int value; } @Attr("Answer", 42) int a; static assert(getUDAs!(a, Attr).length == 1); static assert(getUDAs!(a, Attr)[0].name == "Answer"); static assert(getUDAs!(a, Attr)[0].value == 42); @(Attr("Answer", 42), "string", 9999) int b; static assert(getUDAs!(b, Attr).length == 1); static assert(getUDAs!(b, Attr)[0].name == "Answer"); static assert(getUDAs!(b, Attr)[0].value == 42); @Attr("Answer", 42) @Attr("Pi", 3) int c; static assert(getUDAs!(c, Attr).length == 2); static assert(getUDAs!(c, Attr)[0].name == "Answer"); static assert(getUDAs!(c, Attr)[0].value == 42); static assert(getUDAs!(c, Attr)[1].name == "Pi"); static assert(getUDAs!(c, Attr)[1].value == 3); static assert(getUDAs!(c, Attr("Answer", 42)).length == 1); static assert(getUDAs!(c, Attr("Answer", 42))[0].name == "Answer"); static assert(getUDAs!(c, Attr("Answer", 42))[0].value == 42); static assert(getUDAs!(c, Attr("Answer", 99)).length == 0); struct AttrT(T) { string name; T value; } @AttrT!uint("Answer", 42) @AttrT!int("Pi", 3) @AttrT int d; static assert(getUDAs!(d, AttrT).length == 2); static assert(getUDAs!(d, AttrT)[0].name == "Answer"); static assert(getUDAs!(d, AttrT)[0].value == 42); static assert(getUDAs!(d, AttrT)[1].name == "Pi"); static assert(getUDAs!(d, AttrT)[1].value == 3); static assert(getUDAs!(d, AttrT!uint).length == 1); static assert(getUDAs!(d, AttrT!uint)[0].name == "Answer"); static assert(getUDAs!(d, AttrT!uint)[0].value == 42); static assert(getUDAs!(d, AttrT!int).length == 1); static assert(getUDAs!(d, AttrT!int)[0].name == "Pi"); static assert(getUDAs!(d, AttrT!int)[0].value == 3); struct SimpleAttr {} @SimpleAttr int e; static assert(getUDAs!(e, SimpleAttr).length == 1); static assert(is(getUDAs!(e, SimpleAttr)[0] == SimpleAttr)); @SimpleAttr() int f; static assert(getUDAs!(f, SimpleAttr).length == 1); static assert(is(typeof(getUDAs!(f, SimpleAttr)[0]) == SimpleAttr)); struct FuncAttr(alias f) { alias func = f; } static int add42(int v) { return v + 42; } static string concat(string l, string r) { return l ~ r; } @FuncAttr!add42 int g; static assert(getUDAs!(g, FuncAttr).length == 1); static assert(getUDAs!(g, FuncAttr)[0].func(5) == 47); static assert(getUDAs!(g, FuncAttr!add42).length == 1); static assert(getUDAs!(g, FuncAttr!add42)[0].func(5) == 47); static assert(getUDAs!(g, FuncAttr!add42()).length == 0); static assert(getUDAs!(g, FuncAttr!concat).length == 0); static assert(getUDAs!(g, FuncAttr!concat()).length == 0); @FuncAttr!add42() int h; static assert(getUDAs!(h, FuncAttr).length == 1); static assert(getUDAs!(h, FuncAttr)[0].func(5) == 47); static assert(getUDAs!(h, FuncAttr!add42).length == 1); static assert(getUDAs!(h, FuncAttr!add42)[0].func(5) == 47); static assert(getUDAs!(h, FuncAttr!add42()).length == 1); static assert(getUDAs!(h, FuncAttr!add42())[0].func(5) == 47); static assert(getUDAs!(h, FuncAttr!concat).length == 0); static assert(getUDAs!(h, FuncAttr!concat()).length == 0); @("alpha") @(42) int i; static assert(getUDAs!(i, "alpha").length == 1); static assert(getUDAs!(i, "alpha")[0] == "alpha"); static assert(getUDAs!(i, 42).length == 1); static assert(getUDAs!(i, 42)[0] == 42); static assert(getUDAs!(i, 'c').length == 0); ``` template **getSymbolsByUDA**(alias symbol, alias attribute) Parameters: | | | | --- | --- | | symbol | The aggregate type or module to search | | attribute | The user-defined attribute to search for | Returns: All symbols within `symbol` that have the given UDA `attribute`. Note This is not recursive; it will not search for symbols within symbols such as nested structs or unions. Examples: ``` enum Attr; struct A { @Attr int a; int b; } static assert(getSymbolsByUDA!(A, Attr).length == 1); static assert(hasUDA!(getSymbolsByUDA!(A, Attr)[0], Attr)); ``` Examples: ``` enum Attr; static struct A { @Attr int a; int b; @Attr void doStuff() {} void doOtherStuff() {} static struct Inner { // Not found by getSymbolsByUDA @Attr int c; } } // Finds both variables and functions with the attribute, but // doesn't include the variables and functions without it. static assert(getSymbolsByUDA!(A, Attr).length == 2); // Can access attributes on the symbols returned by getSymbolsByUDA. static assert(hasUDA!(getSymbolsByUDA!(A, Attr)[0], Attr)); static assert(hasUDA!(getSymbolsByUDA!(A, Attr)[1], Attr)); ``` Examples: Finds multiple attributes ``` static struct UDA { string name; } static struct B { @UDA("X") int x; @UDA("Y") int y; @(100) int z; } // Finds both UDA attributes. static assert(getSymbolsByUDA!(B, UDA).length == 2); // Finds one `100` attribute. static assert(getSymbolsByUDA!(B, 100).length == 1); // Can get the value of the UDA from the return value static assert(getUDAs!(getSymbolsByUDA!(B, UDA)[0], UDA)[0].name == "X"); ``` Examples: Checks for UDAs on the aggregate symbol itself ``` static struct UDA { string name; } @UDA("A") static struct C { @UDA("B") int d; } static assert(getSymbolsByUDA!(C, UDA).length == 2); static assert(getSymbolsByUDA!(C, UDA)[0].stringof == "C"); static assert(getSymbolsByUDA!(C, UDA)[1].stringof == "d"); ``` Examples: Finds nothing if there is no member with specific UDA ``` static struct UDA { string name; } static struct D { int x; } static assert(getSymbolsByUDA!(D, UDA).length == 0); ``` template **allSameType**(T...) Returns: `true` iff all types `T` are the same. Examples: ``` static assert(allSameType!(int, int)); static assert(allSameType!(int, int, int)); static assert(allSameType!(float, float, float)); static assert(!allSameType!(int, double)); static assert(!allSameType!(int, float, double)); static assert(!allSameType!(int, float, double, real)); static assert(!allSameType!(short, int, float, double, real)); ``` enum auto **ifTestable**(T, alias pred = (a) => a); Returns: `true` iff the type `T` can be tested in an `if`-expression, that is if `if (pred(T.init)) {}` is compilable. template **isType**(X...) if (X.length == 1) Detect whether `X` is a type. Analogous to `is(X)`. This is useful when used in conjunction with other templates, e.g. `allSatisfy!(isType, X)`. Returns: `true` if `X` is a type, `false` otherwise Examples: ``` struct S { template Test() {} } class C {} interface I {} union U {} static assert(isType!int); static assert(isType!string); static assert(isType!(int[int])); static assert(isType!S); static assert(isType!C); static assert(isType!I); static assert(isType!U); int n; void func(){} static assert(!isType!n); static assert(!isType!func); static assert(!isType!(S.Test)); static assert(!isType!(S.Test!())); ``` template **isFunction**(X...) if (X.length == 1) Detect whether symbol or type `X` is a function. This is different that finding if a symbol is callable or satisfying `is(X == function)`, it finds specifically if the symbol represents a normal function declaration, i.e. not a delegate or a function pointer. Returns: `true` if `X` is a function, `false` otherwise See Also: Use [`isFunctionPointer`](#isFunctionPointer) or [`isDelegate`](#isDelegate) for detecting those types respectively. Examples: ``` static void func(){} static assert(isFunction!func); struct S { void func(){} } static assert(isFunction!(S.func)); ``` template **isFinal**(X...) if (X.length == 1) Detect whether `X` is a final method or class. Returns: `true` if `X` is final, `false` otherwise Examples: ``` class C { void nf() {} static void sf() {} final void ff() {} } final class FC { } static assert(!isFinal!(C)); static assert( isFinal!(FC)); static assert(!isFinal!(C.nf)); static assert(!isFinal!(C.sf)); static assert( isFinal!(C.ff)); ``` enum auto **isCopyable**(S); Determines whether the type `S` can be copied. If a type cannot be copied, then code such as `MyStruct x; auto y = x;` will fail to compile. Copying for structs can be disabled by using `@disable this(this)`. Parameters: | | | | --- | --- | | S | The type to check. | Returns: `true` if `S` can be copied. `false` otherwise. Examples: ``` struct S1 {} // Fine. Can be copied struct S2 { this(this) {}} // Fine. Can be copied struct S3 {@disable this(this); } // Not fine. Copying is disabled. struct S4 {S3 s;} // Not fine. A field has copying disabled. class C1 {} static assert( isCopyable!S1); static assert( isCopyable!S2); static assert(!isCopyable!S3); static assert(!isCopyable!S4); static assert(isCopyable!C1); static assert(isCopyable!int); static assert(isCopyable!(int[])); ```
programming_docs
d core.stdcpp.type_traits core.stdcpp.type\_traits ======================== D header file for interaction with C++ std::type\_traits. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Manu Evans Source [core/stdcpp/type\_traits.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/type_traits.d) struct **integral\_constant**(T, T Val); enum T **value**; alias **value\_type** = T; alias **type** = typeof(this); template **bool\_constant**(bool b) alias **true\_type** = integral\_constant!(bool, true).integral\_constant; alias **false\_type** = integral\_constant!(bool, false).integral\_constant; struct **is\_empty**(T); enum bool **value**; alias **value\_type** = bool; alias **type** = integral\_constant!(bool, value); d std.socket std.socket ========== Socket primitives. Example See [/dmd/samples/d/listener.d](https://github.com/dlang/dmd/blob/master/samples/listener.d) and [/dmd/samples/d/htmlget.d](https://github.com/dlang/dmd/blob/master/samples/htmlget.d) License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Christopher E. Miller, [David Nadlinger](http://klickverbot.at), [Vladimir Panteleev](http://thecybershadow.net) Source [std/socket.d](https://github.com/dlang/phobos/blob/master/std/socket.d) class **SocketException**: object.Exception; Base exception thrown by `std.socket`. @property @safe string **lastSocketError**(); Retrieve the error message for the most recently encountered network error. class **SocketOSException**: std.socket.SocketException; Socket exceptions representing network errors reported by the operating system. int **errorCode**; Platform-specific error code. @safe this(string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null, int err = \_lasterr(), string function(int) @trusted errorFormatter = &formatSocketError); @safe this(string msg, Throwable next, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, int err = \_lasterr(), string function(int) @trusted errorFormatter = &formatSocketError); @safe this(string msg, int err, string function(int) @trusted errorFormatter = &formatSocketError, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null); class **SocketParameterException**: std.socket.SocketException; Socket exceptions representing invalid parameters specified by user code. class **SocketFeatureException**: std.socket.SocketException; Socket exceptions representing attempts to use network capabilities not available on the current system. nothrow @nogc @safe bool **wouldHaveBlocked**(); Returns: `true` if the last socket operation failed because the socket was in non-blocking mode and the operation would have blocked, or if the socket is in blocking mode and set a SNDTIMEO or RCVTIMEO, and the operation timed out. enum **AddressFamily**: ushort; The communication domain used to resolve an address. **UNSPEC** Unspecified address family **UNIX** Local communication **INET** Internet Protocol version 4 **IPX** Novell IPX **APPLETALK** AppleTalk **INET6** Internet Protocol version 6 enum **SocketType**: int; Communication semantics **STREAM** Sequenced, reliable, two-way communication-based byte streams **DGRAM** Connectionless, unreliable datagrams with a fixed maximum length; data may be lost or arrive out of order **RAW** Raw protocol access **RDM** Reliably-delivered message datagrams **SEQPACKET** Sequenced, reliable, two-way connection-based datagrams with a fixed maximum length enum **ProtocolType**: int; Protocol **IP** Internet Protocol version 4 **ICMP** Internet Control Message Protocol **IGMP** Internet Group Management Protocol **GGP** Gateway to Gateway Protocol **TCP** Transmission Control Protocol **PUP** PARC Universal Packet Protocol **UDP** User Datagram Protocol **IDP** Xerox NS protocol **RAW** Raw IP packets **IPV6** Internet Protocol version 6 class **Protocol**; `Protocol` is a class for retrieving protocol information. Example ``` auto proto = new Protocol; writeln("About protocol TCP:"); if (proto.getProtocolByType(ProtocolType.TCP)) { writefln(" Name: %s", proto.name); foreach (string s; proto.aliases) writefln(" Alias: %s", s); } else writeln(" No information found"); ``` ProtocolType **type**; string **name**; string[] **aliases**; These members are populated when one of the following functions are called successfully: nothrow @trusted bool **getProtocolByName**(scope const(char)[] name); Returns: false on failure nothrow @trusted bool **getProtocolByType**(ProtocolType type); Returns: false on failure class **Service**; `Service` is a class for retrieving service information. Example ``` auto serv = new Service; writeln("About service epmap:"); if (serv.getServiceByName("epmap", "tcp")) { writefln(" Service: %s", serv.name); writefln(" Port: %d", serv.port); writefln(" Protocol: %s", serv.protocolName); foreach (string s; serv.aliases) writefln(" Alias: %s", s); } else writefln(" No service for epmap."); ``` string **name**; string[] **aliases**; ushort **port**; string **protocolName**; These members are populated when one of the following functions are called successfully: nothrow @trusted bool **getServiceByName**(scope const(char)[] name, scope const(char)[] protocolName = null); nothrow @trusted bool **getServiceByPort**(ushort port, scope const(char)[] protocolName = null); If a protocol name is omitted, any protocol will be matched. Returns: false on failure. class **HostException**: std.socket.SocketOSException; Class for exceptions thrown from an `InternetHost`. class **InternetHost**; `InternetHost` is a class for resolving IPv4 addresses. Consider using `getAddress`, `parseAddress` and `Address` methods instead of using this class directly. Examples: ``` InternetHost ih = new InternetHost; ih.getHostByAddr(0x7F_00_00_01); writeln(ih.addrList[0]); // 0x7F_00_00_01 ih.getHostByAddr("127.0.0.1"); writeln(ih.addrList[0]); // 0x7F_00_00_01 if (!ih.getHostByName("www.digitalmars.com")) return; // don't fail if not connected to internet assert(ih.addrList.length); InternetAddress ia = new InternetAddress(ih.addrList[0], InternetAddress.PORT_ANY); assert(ih.name == "www.digitalmars.com" || ih.name == "digitalmars.com", ih.name); assert(ih.getHostByAddr(ih.addrList[0])); string getHostNameFromInt = ih.name.dup; assert(ih.getHostByAddr(ia.toAddrString())); string getHostNameFromStr = ih.name.dup; writeln(getHostNameFromInt); // getHostNameFromStr ``` string **name**; string[] **aliases**; uint[] **addrList**; These members are populated when one of the following functions are called successfully: @trusted bool **getHostByName**(scope const(char)[] name); Resolve host name. Returns: false if unable to resolve. @trusted bool **getHostByAddr**(uint addr); Resolve IPv4 address number. Parameters: | | | | --- | --- | | uint `addr` | The IPv4 address to resolve, in host byte order. | Returns: false if unable to resolve. @trusted bool **getHostByAddr**(scope const(char)[] addr); Same as previous, but addr is an IPv4 address string in the dotted-decimal form *a.b.c.d*. Returns: false if unable to resolve. struct **AddressInfo**; Holds information about a socket address retrieved by `getAddressInfo`. AddressFamily **family**; Address family SocketType **type**; Socket type ProtocolType **protocol**; Protocol Address **address**; Socket address string **canonicalName**; Canonical name, when `AddressInfoFlags.CANONNAME` is used. enum **AddressInfoFlags**: int; A subset of flags supported on all platforms with getaddrinfo. Specifies option flags for `getAddressInfo`. **PASSIVE** The resulting addresses will be used in a call to `Socket.bind`. **CANONNAME** The canonical name is returned in `canonicalName` member in the first `AddressInfo`. **NUMERICHOST** The `node` parameter passed to `getAddressInfo` must be a numeric string. This will suppress any potentially lengthy network host address lookups. AddressInfo[] **getAddressInfo**(T...)(scope const(char)[] node, scope T options); Provides protocol-independent translation from host names to socket addresses. If advanced functionality is not required, consider using `getAddress` for compatibility with older systems. Returns: Array with one `AddressInfo` per socket address. Throws: `SocketOSException` on failure, or `SocketFeatureException` if this functionality is not available on the current system. Parameters: | | | | --- | --- | | const(char)[] `node` | string containing host name or numeric address | | T `options` | optional additional parameters, identified by type: * `string` - service name or port number * `AddressInfoFlags` - option flags * `AddressFamily` - address family to filter by * `SocketType` - socket type to filter by * `ProtocolType` - protocol to filter by | Example ``` // Roundtrip DNS resolution auto results = getAddressInfo("www.digitalmars.com"); assert(results[0].address.toHostNameString() == "digitalmars.com"); // Canonical name results = getAddressInfo("www.digitalmars.com", AddressInfoFlags.CANONNAME); assert(results[0].canonicalName == "digitalmars.com"); // IPv6 resolution results = getAddressInfo("ipv6.google.com"); assert(results[0].family == AddressFamily.INET6); // Multihomed resolution results = getAddressInfo("google.com"); assert(results.length > 1); // Parsing IPv4 results = getAddressInfo("127.0.0.1", AddressInfoFlags.NUMERICHOST); assert(results.length && results[0].family == AddressFamily.INET); // Parsing IPv6 results = getAddressInfo("::1", AddressInfoFlags.NUMERICHOST); assert(results.length && results[0].family == AddressFamily.INET6); ``` @safe Address[] **getAddress**(scope const(char)[] hostname, scope const(char)[] service = null); @safe Address[] **getAddress**(scope const(char)[] hostname, ushort port); Provides protocol-independent translation from host names to socket addresses. Uses `getAddressInfo` if the current system supports it, and `InternetHost` otherwise. Returns: Array with one `Address` instance per socket address. Throws: `SocketOSException` on failure. Example ``` writeln("Resolving www.digitalmars.com:"); try { auto addresses = getAddress("www.digitalmars.com"); foreach (address; addresses) writefln(" IP: %s", address.toAddrString()); } catch (SocketException e) writefln(" Lookup failed: %s", e.msg); ``` @safe Address **parseAddress**(scope const(char)[] hostaddr, scope const(char)[] service = null); @safe Address **parseAddress**(scope const(char)[] hostaddr, ushort port); Provides protocol-independent parsing of network addresses. Does not attempt name resolution. Uses `getAddressInfo` with `AddressInfoFlags.NUMERICHOST` if the current system supports it, and `InternetAddress` otherwise. Returns: An `Address` instance representing specified address. Throws: `SocketException` on failure. Example ``` writeln("Enter IP address:"); string ip = readln().chomp(); try { Address address = parseAddress(ip); writefln("Looking up reverse of %s:", address.toAddrString()); try { string reverse = address.toHostNameString(); if (reverse) writefln(" Reverse name: %s", reverse); else writeln(" Reverse hostname not found."); } catch (SocketException e) writefln(" Lookup error: %s", e.msg); } catch (SocketException e) { writefln(" %s is not a valid IP address: %s", ip, e.msg); } ``` class **AddressException**: std.socket.SocketOSException; Class for exceptions thrown from an `Address`. abstract class **Address**; `Address` is an abstract class for representing a socket addresses. Example ``` writeln("About www.google.com port 80:"); try { Address[] addresses = getAddress("www.google.com", 80); writefln(" %d addresses found.", addresses.length); foreach (int i, Address a; addresses) { writefln(" Address %d:", i+1); writefln(" IP address: %s", a.toAddrString()); writefln(" Hostname: %s", a.toHostNameString()); writefln(" Port: %s", a.toPortString()); writefln(" Service name: %s", a.toServiceNameString()); } } catch (SocketException e) writefln(" Lookup error: %s", e.msg); ``` abstract pure nothrow @nogc @property @safe sockaddr\* **name**(); abstract const pure nothrow @nogc @property @safe const(sockaddr)\* **name**(); Returns pointer to underlying `sockaddr` structure. abstract const pure nothrow @nogc @property @safe socklen\_t **nameLen**(); Returns actual size of underlying `sockaddr` structure. const pure nothrow @nogc @property @safe AddressFamily **addressFamily**(); Family of this address. const @safe string **toAddrString**(); Attempts to retrieve the host address as a human-readable string. Throws: `AddressException` on failure, or `SocketFeatureException` if address retrieval for this address family is not available on the current system. const @safe string **toHostNameString**(); Attempts to retrieve the host name as a fully qualified domain name. Returns: The FQDN corresponding to this `Address`, or `null` if the host name did not resolve. Throws: `AddressException` on error, or `SocketFeatureException` if host name lookup for this address family is not available on the current system. const @safe string **toPortString**(); Attempts to retrieve the numeric port number as a string. Throws: `AddressException` on failure, or `SocketFeatureException` if port number retrieval for this address family is not available on the current system. const @safe string **toServiceNameString**(); Attempts to retrieve the service name as a string. Throws: `AddressException` on failure, or `SocketFeatureException` if service name lookup for this address family is not available on the current system. const @safe string **toString**(); Human readable string representing this address. class **UnknownAddress**: std.socket.Address; `UnknownAddress` encapsulates an unknown socket address. class **UnknownAddressReference**: std.socket.Address; `UnknownAddressReference` encapsulates a reference to an arbitrary socket address. pure nothrow @nogc @safe this(sockaddr\* sa, socklen\_t len); Constructs an `Address` with a reference to the specified `sockaddr`. pure nothrow @system this(const(sockaddr)\* sa, socklen\_t len); Constructs an `Address` with a copy of the specified `sockaddr`. class **InternetAddress**: std.socket.Address; `InternetAddress` encapsulates an IPv4 (Internet Protocol version 4) socket address. Consider using `getAddress`, `parseAddress` and `Address` methods instead of using this class directly. enum uint **ADDR\_ANY**; Any IPv4 host address. enum uint **ADDR\_NONE**; An invalid IPv4 host address. enum ushort **PORT\_ANY**; Any IPv4 port number. const pure nothrow @nogc @property @safe ushort **port**(); Returns the IPv4 port number (in host byte order). const pure nothrow @nogc @property @safe uint **addr**(); Returns the IPv4 address number (in host byte order). @safe this(scope const(char)[] addr, ushort port); Construct a new `InternetAddress`. Parameters: | | | | --- | --- | | const(char)[] `addr` | an IPv4 address string in the dotted-decimal form a.b.c.d, or a host name which will be resolved using an `InternetHost` object. | | ushort `port` | port number, may be `PORT_ANY`. | pure nothrow @nogc @safe this(uint addr, ushort port); pure nothrow @nogc @safe this(ushort port); Construct a new `InternetAddress`. Parameters: | | | | --- | --- | | uint `addr` | (optional) an IPv4 address in host byte order, may be `ADDR_ANY`. | | ushort `port` | port number, may be `PORT_ANY`. | pure nothrow @nogc @safe this(sockaddr\_in addr); Construct a new `InternetAddress`. Parameters: | | | | --- | --- | | sockaddr\_in `addr` | A sockaddr\_in as obtained from lower-level API calls such as getifaddrs. | const @trusted string **toAddrString**(); Human readable string representing the IPv4 address in dotted-decimal form. const @safe string **toPortString**(); Human readable string representing the IPv4 port. const @safe string **toHostNameString**(); Attempts to retrieve the host name as a fully qualified domain name. Returns: The FQDN corresponding to this `InternetAddress`, or `null` if the host name did not resolve. Throws: `AddressException` on error. const @safe bool **opEquals**(Object o); Compares with another InternetAddress of same type for equality Returns: true if the InternetAddresses share the same address and port number. Examples: ``` auto addr1 = new InternetAddress("127.0.0.1", 80); auto addr2 = new InternetAddress("127.0.0.2", 80); writeln(addr1); // addr1 assert(addr1 != addr2); ``` static nothrow @trusted uint **parse**(scope const(char)[] addr); Parse an IPv4 address string in the dotted-decimal form *a.b.c.d* and return the number. Returns: If the string is not a legitimate IPv4 address, `ADDR_NONE` is returned. static nothrow @trusted string **addrToString**(uint addr); Convert an IPv4 address number in host byte order to a human readable string representing the IPv4 address in dotted-decimal form. class **Internet6Address**: std.socket.Address; `Internet6Address` encapsulates an IPv6 (Internet Protocol version 6) socket address. Consider using `getAddress`, `parseAddress` and `Address` methods instead of using this class directly. static pure nothrow @nogc @property ref @safe const(ubyte)[16] **ADDR\_ANY**(); Any IPv6 host address. enum ushort **PORT\_ANY**; Any IPv6 port number. const pure nothrow @nogc @property @safe ushort **port**(); Returns the IPv6 port number. const pure nothrow @nogc @property @safe ubyte[16] **addr**(); Returns the IPv6 address. @trusted this(scope const(char)[] addr, scope const(char)[] service = null); Construct a new `Internet6Address`. Parameters: | | | | --- | --- | | const(char)[] `addr` | an IPv6 host address string in the form described in RFC 2373, or a host name which will be resolved using `getAddressInfo`. | | const(char)[] `service` | (optional) service name. | @safe this(scope const(char)[] addr, ushort port); Construct a new `Internet6Address`. Parameters: | | | | --- | --- | | const(char)[] `addr` | an IPv6 host address string in the form described in RFC 2373, or a host name which will be resolved using `getAddressInfo`. | | ushort `port` | port number, may be `PORT_ANY`. | pure nothrow @nogc @safe this(ubyte[16] addr, ushort port); pure nothrow @nogc @safe this(ushort port); Construct a new `Internet6Address`. Parameters: | | | | --- | --- | | ubyte[16] `addr` | (optional) an IPv6 host address in host byte order, or `ADDR_ANY`. | | ushort `port` | port number, may be `PORT_ANY`. | pure nothrow @nogc @safe this(sockaddr\_in6 addr); Construct a new `Internet6Address`. Parameters: | | | | --- | --- | | sockaddr\_in6 `addr` | A sockaddr\_in6 as obtained from lower-level API calls such as getifaddrs. | static @trusted ubyte[16] **parse**(scope const(char)[] addr); Parse an IPv6 host address string as described in RFC 2373, and return the address. Throws: `SocketException` on error. class **UnixAddress**: std.socket.Address; `UnixAddress` encapsulates an address for a Unix domain socket (`AF_UNIX`), i.e. a socket bound to a path name in the file system. Available only on supported systems. Linux also supports an abstract address namespace, in which addresses are independent of the file system. A socket address is abstract iff `path` starts with a null byte (`'\0'`). Null bytes in other positions of an abstract address are allowed and have no special meaning. Example ``` auto addr = new UnixAddress("/var/run/dbus/system_bus_socket"); auto abstractAddr = new UnixAddress("\0/tmp/dbus-OtHLWmCLPR"); ``` See Also: [UNIX(7)](http://http//man7.org/linux/man-pages/man7/unix.7.html) @safe this(scope const(char)[] path); Construct a new `UnixAddress` from the specified path. pure nothrow @nogc @safe this(sockaddr\_un addr); Construct a new `UnixAddress`. Parameters: | | | | --- | --- | | sockaddr\_un `addr` | A sockaddr\_un as obtained from lower-level API calls. | const @property @safe string **path**(); const @safe string **toString**(); Get the underlying path. class **SocketAcceptException**: std.socket.SocketOSException; Class for exceptions thrown by `Socket.accept`. enum **SocketShutdown**: int; How a socket is shutdown: **RECEIVE** socket receives are disallowed **SEND** socket sends are disallowed **BOTH** both RECEIVE and SEND enum **SocketFlags**: int; Flags may be OR'ed together: **NONE** no flags specified **OOB** out-of-band stream data **PEEK** peek at incoming data without removing it from the queue, only for receiving **DONTROUTE** data should not be subject to routing; this flag may be ignored. Only for sending struct **TimeVal**; Duration timeout value. tv\_sec\_t **seconds**; Number of seconds. tv\_usec\_t **microseconds**; Number of additional microseconds. class **SocketSet**; A collection of sockets for use with `Socket.select`. `SocketSet` wraps the platform `fd_set` type. However, unlike `fd_set`, `SocketSet` is not statically limited to `FD_SETSIZE` or any other limit, and grows as needed. pure nothrow @safe this(size\_t size = FD\_SETSIZE); Create a SocketSet with a specific initial capacity (defaults to `FD_SETSIZE`, the system's default capacity). pure nothrow @nogc @safe void **reset**(); Reset the `SocketSet` so that there are 0 `Socket`s in the collection. pure nothrow @safe void **add**(Socket s); Add a `Socket` to the collection. The socket must not already be in the collection. pure nothrow @safe void **remove**(Socket s); Remove this `Socket` from the collection. Does nothing if the socket is not in the collection already. const pure nothrow @nogc @safe int **isSet**(Socket s); Return nonzero if this `Socket` is in the collection. const pure nothrow @nogc @property @safe uint **max**(); Returns: The current capacity of this `SocketSet`. The exact meaning of the return value varies from platform to platform. Note Since D 2.065, this value does not indicate a restriction, and `SocketSet` will grow its capacity as needed automatically. enum **SocketOptionLevel**: int; The level at which a socket option is defined: **SOCKET** Socket level **IP** Internet Protocol version 4 level **ICMP** Internet Control Message Protocol level **IGMP** Internet Group Management Protocol level **GGP** Gateway to Gateway Protocol level **TCP** Transmission Control Protocol level **PUP** PARC Universal Packet Protocol level **UDP** User Datagram Protocol level **IDP** Xerox NS protocol level **RAW** Raw IP packet level **IPV6** Internet Protocol version 6 level struct **Linger**; Linger information for use with SocketOption.LINGER. l\_onoff\_t **on**; Nonzero for on. l\_linger\_t **time**; Linger time. enum **SocketOption**: int; Specifies a socket option: **DEBUG** Record debugging information **BROADCAST** Allow transmission of broadcast messages **REUSEADDR** Allow local reuse of address **LINGER** Linger on close if unsent data is present **OOBINLINE** Receive out-of-band data in band **SNDBUF** Send buffer size **RCVBUF** Receive buffer size **DONTROUTE** Do not route **SNDTIMEO** Send timeout **RCVTIMEO** Receive timeout **ERROR** Retrieve and clear error status **KEEPALIVE** Enable keep-alive packets **ACCEPTCONN** Listen **RCVLOWAT** Minimum number of input bytes to process **SNDLOWAT** Minimum number of output bytes to process **TYPE** Socket type **TCP\_NODELAY** Disable the Nagle algorithm for send coalescing **IPV6\_UNICAST\_HOPS** IP unicast hop limit **IPV6\_MULTICAST\_IF** IP multicast interface **IPV6\_MULTICAST\_LOOP** IP multicast loopback **IPV6\_MULTICAST\_HOPS** IP multicast hops **IPV6\_JOIN\_GROUP** Add an IP group membership **IPV6\_LEAVE\_GROUP** Drop an IP group membership **IPV6\_V6ONLY** Treat wildcard bind as AF\_INET6-only class **Socket**; `Socket` is a class that creates a network communication endpoint using the Berkeley sockets interface. @trusted this(AddressFamily af, SocketType type, ProtocolType protocol); @safe this(AddressFamily af, SocketType type); @trusted this(AddressFamily af, SocketType type, scope const(char)[] protocolName); Create a blocking socket. If a single protocol type exists to support this socket type within the address family, the `ProtocolType` may be omitted. @safe this(scope const AddressInfo info); Create a blocking socket using the parameters from the specified `AddressInfo` structure. pure nothrow @nogc @safe this(socket\_t sock, AddressFamily af); Use an existing socket handle. const pure nothrow @nogc @property @safe socket\_t **handle**(); Get underlying socket handle. const nothrow @nogc @property @trusted bool **blocking**(); @property @trusted void **blocking**(bool byes); Get/set socket's blocking flag. When a socket is blocking, calls to receive(), accept(), and send() will block and wait for data/action. A non-blocking socket will immediately return instead of blocking. @property @safe AddressFamily **addressFamily**(); Get the socket's address family. const @property @trusted bool **isAlive**(); Property that indicates if this is a valid, alive socket. @trusted void **bind**(Address addr); Associate a local address with this socket. Parameters: | | | | --- | --- | | Address `addr` | The [`Address`](#Address) to associate this socket with. | Throws: [`SocketOSException`](#SocketOSException) when unable to bind the socket. @trusted void **connect**(Address to); Establish a connection. If the socket is blocking, connect waits for the connection to be made. If the socket is nonblocking, connect returns immediately and the connection attempt is still in progress. @trusted void **listen**(int backlog); Listen for an incoming connection. `bind` must be called before you can `listen`. The `backlog` is a request of how many pending incoming connections are queued until `accept`ed. protected pure nothrow @safe Socket **accepting**(); Called by `accept` when a new `Socket` must be created for a new connection. To use a derived class, override this method and return an instance of your class. The returned `Socket`'s handle must not be set; `Socket` has a protected constructor `this()` to use in this situation. Override to use a derived class. The returned socket's handle must not be set. @trusted Socket **accept**(); Accept an incoming connection. If the socket is blocking, `accept` waits for a connection request. Throws `SocketAcceptException` if unable to accept. See `accepting` for use with derived classes. nothrow @nogc @trusted void **shutdown**(SocketShutdown how); Disables sends and/or receives. nothrow @nogc @trusted void **close**(); Immediately drop any connections and release socket resources. The `Socket` object is no longer usable after `close`. Calling `shutdown` before `close` is recommended for connection-oriented sockets. static @property @trusted string **hostName**(); Returns: the local machine's host name @property @trusted Address **remoteAddress**(); Remote endpoint `Address`. @property @trusted Address **localAddress**(); Local endpoint `Address`. enum int **ERROR**; Send or receive error code. See `wouldHaveBlocked`, `lastSocketError` and `Socket.getErrorText` for obtaining more information about the error. @trusted ptrdiff\_t **send**(const(void)[] buf, SocketFlags flags); @safe ptrdiff\_t **send**(const(void)[] buf); Send data on the connection. If the socket is blocking and there is no buffer space left, `send` waits. Returns: The number of bytes actually sent, or `Socket.ERROR` on failure. @trusted ptrdiff\_t **sendTo**(const(void)[] buf, SocketFlags flags, Address to); @safe ptrdiff\_t **sendTo**(const(void)[] buf, Address to); @trusted ptrdiff\_t **sendTo**(const(void)[] buf, SocketFlags flags); @safe ptrdiff\_t **sendTo**(const(void)[] buf); Send data to a specific destination Address. If the destination address is not specified, a connection must have been made and that address is used. If the socket is blocking and there is no buffer space left, `sendTo` waits. Returns: The number of bytes actually sent, or `Socket.ERROR` on failure. @trusted ptrdiff\_t **receive**(void[] buf, SocketFlags flags); @safe ptrdiff\_t **receive**(void[] buf); Receive data on the connection. If the socket is blocking, `receive` waits until there is data to be received. Returns: The number of bytes actually received, `0` if the remote side has closed the connection, or `Socket.ERROR` on failure. @trusted ptrdiff\_t **receiveFrom**(void[] buf, SocketFlags flags, ref Address from); @safe ptrdiff\_t **receiveFrom**(void[] buf, ref Address from); @trusted ptrdiff\_t **receiveFrom**(void[] buf, SocketFlags flags); @safe ptrdiff\_t **receiveFrom**(void[] buf); Receive data and get the remote endpoint `Address`. If the socket is blocking, `receiveFrom` waits until there is data to be received. Returns: The number of bytes actually received, `0` if the remote side has closed the connection, or `Socket.ERROR` on failure. @trusted int **getOption**(SocketOptionLevel level, SocketOption option, void[] result); Get a socket option. Returns: The number of bytes written to `result`. The length, in bytes, of the actual result - very different from getsockopt() @trusted int **getOption**(SocketOptionLevel level, SocketOption option, out int32\_t result); Common case of getting integer and boolean options. @trusted int **getOption**(SocketOptionLevel level, SocketOption option, out Linger result); Get the linger option. @trusted void **getOption**(SocketOptionLevel level, SocketOption option, out Duration result); Get a timeout (duration) option. @trusted void **setOption**(SocketOptionLevel level, SocketOption option, void[] value); Set a socket option. @trusted void **setOption**(SocketOptionLevel level, SocketOption option, int32\_t value); Common case for setting integer and boolean options. @trusted void **setOption**(SocketOptionLevel level, SocketOption option, Linger value); Set the linger option. @trusted void **setOption**(SocketOptionLevel level, SocketOption option, Duration value); Sets a timeout (duration) option, i.e. `SocketOption.SNDTIMEO` or `RCVTIMEO`. Zero indicates no timeout. In a typical application, you might also want to consider using a non-blocking socket instead of setting a timeout on a blocking one. Note While the receive timeout setting is generally quite accurate on \*nix systems even for smaller durations, there are two issues to be aware of on Windows: First, although undocumented, the effective timeout duration seems to be the one set on the socket plus half a second. `setOption()` tries to compensate for that, but still, timeouts under 500ms are not possible on Windows. Second, be aware that the actual amount of time spent until a blocking call returns randomly varies on the order of 10ms. Parameters: | | | | --- | --- | | SocketOptionLevel `level` | The level at which a socket option is defined. | | SocketOption `option` | Either `SocketOption.SNDTIMEO` or `SocketOption.RCVTIMEO`. | | Duration `value` | The timeout duration to set. Must not be negative. | Throws: `SocketException` if setting the options fails. Example ``` import std.datetime; import std.typecons; auto pair = socketPair(); scope(exit) foreach (s; pair) s.close(); // Set a receive timeout, and then wait at one end of // the socket pair, knowing that no data will arrive. pair[0].setOption(SocketOptionLevel.SOCKET, SocketOption.RCVTIMEO, dur!"seconds"(1)); auto sw = StopWatch(Yes.autoStart); ubyte[1] buffer; pair[0].receive(buffer); writefln("Waited %s ms until the socket timed out.", sw.peek.msecs); ``` @safe string **getErrorText**(); Get a text description of this socket's error status, and clear the socket's error status. @trusted void **setKeepAlive**(int time, int interval); Enables TCP keep-alive with the specified parameters. Parameters: | | | | --- | --- | | int `time` | Number of seconds with no activity until the first keep-alive packet is sent. | | int `interval` | Number of seconds between when successive keep-alive packets are sent if no acknowledgement is received. | Throws: `SocketOSException` if setting the options fails, or `SocketFeatureException` if setting keep-alive parameters is unsupported on the current platform. static @trusted int **select**(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, Duration timeout); static @safe int **select**(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError); static @trusted int **select**(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, TimeVal\* timeout); Wait for a socket to change status. A wait timeout of [`core.time.Duration`](core_time#Duration) or `TimeVal`, may be specified; if a timeout is not specified or the `TimeVal` is `null`, the maximum timeout is used. The `TimeVal` timeout has an unspecified value when `select` returns. Returns: The number of sockets with status changes, `0` on timeout, or `-1` on interruption. If the return value is greater than `0`, the `SocketSets` are updated to only contain the sockets having status changes. For a connecting socket, a write status change means the connection is established and it's able to send. For a listening socket, a read status change means there is an incoming connection request and it's able to accept. `SocketSet`'s updated to include only those sockets which an event occured. For a `connect()`ing socket, writeability means connected. For a `listen()`ing socket, readability means listening `Winsock`; possibly internally limited to 64 sockets per set. Returns: the number of events, 0 on timeout, or -1 on interruption protected pure nothrow @safe Address **createAddress**(); Can be overridden to support other addresses. Returns: a new `Address` object for the current address family. class **TcpSocket**: std.socket.Socket; `TcpSocket` is a shortcut class for a TCP Socket. @safe this(AddressFamily family); Constructs a blocking TCP Socket. @safe this(); Constructs a blocking IPv4 TCP Socket. @safe this(Address connectTo); Constructs a blocking TCP Socket and connects to an `Address`. class **UdpSocket**: std.socket.Socket; `UdpSocket` is a shortcut class for a UDP Socket. @safe this(AddressFamily family); Constructs a blocking UDP Socket. @safe this(); Constructs a blocking IPv4 UDP Socket. @trusted Socket[2] **socketPair**(); Creates a pair of connected sockets. The two sockets are indistinguishable. Throws: `SocketException` if creation of the sockets fails. Examples: ``` immutable ubyte[] data = [1, 2, 3, 4]; auto pair = socketPair(); scope(exit) foreach (s; pair) s.close(); pair[0].send(data); auto buf = new ubyte[data.length]; pair[1].receive(buf); writeln(buf); // data ```
programming_docs
d Phobos Runtime Library Phobos Runtime Library ====================== Phobos is the standard runtime library that comes with the D language compiler. Generally, the `std` namespace is used for the main modules in the Phobos standard library. The `etc` namespace is used for external C/C++ library bindings. The `core` namespace is used for low-level D runtime functions. The following table is a quick reference guide for which Phobos modules to use for a given category of functionality. Note that some modules may appear in more than one category, as some Phobos modules are quite generic and can be applied in a variety of situations. | Modules | Description | | --- | --- | | *Algorithms & ranges* | | [`std.algorithm`](std_algorithm) [`std.range`](std_range) [`std.range.primitives`](std_range_primitives) [`std.range.interfaces`](std_range_interfaces) | Generic algorithms that work with [ranges](std_range) of any type, including strings, arrays, and other kinds of sequentially-accessed data. Algorithms include searching, comparison, iteration, sorting, set operations, and mutation. | | *Array manipulation* | | [`std.array`](std_array) [`std.algorithm`](std_algorithm) | Convenient operations commonly used with built-in arrays. Note that many common array operations are subsets of more generic algorithms that work with arbitrary ranges, so they are found in `std.algorithm`. | | *Containers* | | [`std.container.array`](std_container_array) [`std.container.binaryheap`](std_container_binaryheap) [`std.container.dlist`](std_container_dlist) [`std.container.rbtree`](std_container_rbtree) [`std.container.slist`](std_container_slist) | See [std.container.\*](std_container) for an overview. | | *Data formats* | | [`std.base64`](std_base64) | Encoding / decoding Base64 format. | | [`std.csv`](std_csv) | Read Comma Separated Values and its variants from an input range of `dchar`. | | [`std.json`](std_json) | Read/write data in JSON format. | | [`std.xml`](std_xml) | Read/write data in XML format. | | [`std.zip`](std_zip) | Read/write data in the ZIP archive format. | | [`std.zlib`](std_zlib) | Compress/decompress data using the zlib library. | | *Data integrity* | | [`std.experimental.checkedint`](std_experimental_checkedint) | Checked integral types. | | [`std.digest`](std_digest) | Compute digests such as md5, sha1 and crc32. | | [`std.digest.crc`](std_digest_crc) | Cyclic Redundancy Check (32-bit) implementation. | | [`std.digest.hmac`](std_digest_hmac) | Compute HMAC digests of arbitrary data. | | [`std.digest.md`](std_digest_md) | Compute MD5 hash of arbitrary data. | | [`std.digest.murmurhash`](std_digest_murmurhash) | Compute MurmurHash of arbitrary data. | | [`std.digest.ripemd`](std_digest_ripemd) | Compute RIPEMD-160 hash of arbitrary data. | | [`std.digest.sha`](std_digest_sha) | Compute SHA1 and SHA2 hashes of arbitrary data. | | *Date & time* | | [`std.datetime`](std_datetime) | Provides convenient access to date and time representations. | | [`core.time`](core_time) | Implements low-level time primitives. | | *Exception handling* | | [`std.exception`](std_exception) | Implements routines related to exceptions. | | [`core.exception`](core_exception) | Defines built-in exception types and low-level language hooks required by the compiler. | | *External library bindings* | | [`etc.c.curl`](etc_c_curl) | Interface to libcurl C library. | | [`etc.c.odbc.sql`](etc_c_odbc_sql) | Interface to ODBC C library. | | [`etc.c.odbc.sqlext`](etc_c_odbc_sqlext) | | [`etc.c.odbc.sqltypes`](etc_c_odbc_sqltypes) | | [`etc.c.odbc.sqlucode`](etc_c_odbc_sqlucode) | | [`etc.c.sqlite3`](etc_c_sqlite3) | Interface to SQLite C library. | | [`etc.c.zlib`](etc_c_zlib) | Interface to zlib C library. | | *I/O & File system* | | [`std.file`](std_file) | Manipulate files and directories. | | [`std.path`](std_path) | Manipulate strings that represent filesystem paths. | | [`std.stdio`](std_stdio) | Perform buffered I/O. | | *Interoperability* | | [`core.stdc.complex`](core_stdc_complex) [`core.stdc.ctype`](core_stdc_ctype) [`core.stdc.errno`](core_stdc_errno) [`core.stdc.fenv`](core_stdc_fenv) [`core.stdc.float_`](core_stdc_float_) [`core.stdc.inttypes`](core_stdc_inttypes) [`core.stdc.limits`](core_stdc_limits) [`core.stdc.locale`](core_stdc_locale) [`core.stdc.math`](core_stdc_math) [`core.stdc.signal`](core_stdc_signal) [`core.stdc.stdarg`](core_stdc_stdarg) [`core.stdc.stddef`](core_stdc_stddef) [`core.stdc.stdint`](core_stdc_stdint) [`core.stdc.stdio`](core_stdc_stdio) [`core.stdc.stdlib`](core_stdc_stdlib) [`core.stdc.string`](core_stdc_string) [`core.stdc.tgmath`](core_stdc_tgmath) [`core.stdc.time`](core_stdc_time) [`core.stdc.wchar_`](core_stdc_wchar_) [`core.stdc.wctype`](core_stdc_wctype) | D bindings for standard C headers. These are mostly undocumented, as documentation for the functions these declarations provide bindings to can be found on external resources. | | *Memory management* | | [`core.memory`](core_memory) | Control the built-in garbage collector. | | [`std.typecons`](std_typecons) | Build scoped variables and reference-counted types. | | *Metaprogramming* | | [`core.attribute`](core_attribute) | Definitions of special attributes recognized by the compiler. | | [`core.demangle`](core_demangle) | Convert *mangled* D symbol identifiers to source representation. | | [`std.demangle`](std_demangle) | A simple wrapper around core.demangle. | | [`std.meta`](std_meta) | Construct and manipulate template argument lists (aka type lists). | | [`std.traits`](std_traits) | Extract information about types and symbols at compile time. | | [`std.typecons`](std_typecons) | Construct new, useful general purpose types. | | *Multitasking* | | [`std.concurrency`](std_concurrency) | Low level messaging API for threads. | | [`std.parallelism`](std_parallelism) | High level primitives for SMP parallelism. | | [`std.process`](std_process) | Starting and manipulating processes. | | [`core.atomic`](core_atomic) | Basic support for lock-free concurrent programming. | | [`core.sync.barrier`](core_sync_barrier) | Synchronize the progress of a group of threads. | | [`core.sync.condition`](core_sync_condition) | Synchronized condition checking. | | [`core.sync.exception`](core_sync_exception) | Base class for synchronization exceptions. | | [`core.sync.mutex`](core_sync_mutex) | Mutex for mutually exclusive access. | | [`core.sync.rwmutex`](core_sync_rwmutex) | Shared read access and mutually exclusive write access. | | [`core.sync.semaphore`](core_sync_semaphore) | General use synchronization semaphore. | | [`core.thread`](core_thread) | Thread creation and management. | | *Networking* | | [`std.socket`](std_socket) | Socket primitives. | | [`std.net.curl`](std_net_curl) | Networking client functionality as provided by libcurl. | | [`std.net.isemail`](std_net_isemail) | Validates an email address according to RFCs 5321, 5322 and others. | | [`std.uri`](std_uri) | Encode and decode Uniform Resource Identifiers (URIs). | | [`std.uuid`](std_uuid) | Universally-unique identifiers for resources in distributed systems. | | *Numeric* | | [`std.bigint`](std_bigint) | An arbitrary-precision integer type. | | [`std.complex`](std_complex) | A complex number type. | | [`std.math`](std_math) | Elementary mathematical functions (powers, roots, trigonometry). | | [`std.mathspecial`](std_mathspecial) | Families of transcendental functions. | | [`std.numeric`](std_numeric) | Floating point numerics functions. | | [`std.random`](std_random) | Pseudo-random number generators. | | [`core.checkedint`](core_checkedint) | Range-checking integral arithmetic primitives. | | [`core.math`](core_math) | Built-in mathematical intrinsics. | | *Paradigms* | | [`std.functional`](std_functional) | Functions that manipulate other functions. | | [`std.algorithm`](std_algorithm) | Generic algorithms for processing sequences. | | [`std.signals`](std_signals) | Signal-and-slots framework for event-driven programming. | | *Runtime utilities* | | [`object`](object) | Core language definitions. Automatically imported. | | [`std.getopt`](std_getopt) | Parsing of command-line arguments. | | [`std.compiler`](std_compiler) | Host compiler vendor string and language version. | | [`std.system`](std_system) | Runtime environment, such as OS type and endianness. | | [`core.cpuid`](core_cpuid) | Capabilities of the CPU the program is running on. | | [`core.memory`](core_memory) | Control the built-in garbage collector. | | [`core.runtime`](core_runtime) | Control and configure the D runtime. | | *String manipulation* | | [`std.string`](std_string) | Algorithms that work specifically with strings. | | [`std.array`](std_array) | Manipulate builtin arrays. | | [`std.algorithm`](std_algorithm) | Generic algorithms for processing sequences. | | [`std.uni`](std_uni) | Fundamental Unicode algorithms and data structures. | | [`std.utf`](std_utf) | Encode and decode UTF-8, UTF-16 and UTF-32 strings. | | [`std.format`](std_format) | Format data into strings. | | [`std.path`](std_path) | Manipulate strings that represent filesystem paths. | | [`std.regex`](std_regex) | Regular expressions. | | [`std.ascii`](std_ascii) | Routines specific to the ASCII subset of Unicode. | | [`std.encoding`](std_encoding) | Handle and transcode between various text encodings. | | [`std.windows.charset`](std_windows_charset) | Windows specific character set support. | | [`std.outbuffer`](std_outbuffer) | Serialize data to `ubyte` arrays. | | *Type manipulations* | | [`std.conv`](std_conv) | Convert types from one type to another. | | [`std.typecons`](std_typecons) | Type constructors for scoped variables, ref counted types, etc. | | [`std.bitmanip`](std_bitmanip) | High level bit level manipulation, bit arrays, bit fields. | | [`std.variant`](std_variant) | Discriminated unions and algebraic types. | | [`core.bitop`](core_bitop) | Low level bit manipulation. | | *Vector programming* | | [`core.simd`](core_simd) | SIMD intrinsics | d core.sync.config core.sync.config ================ The config module contains utility routines and configuration information specific to this package. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Sean Kelly Source [core/sync/config.d](https://github.com/dlang/druntime/blob/master/src/core/sync/config.d) d std.container.slist std.container.slist =================== This module implements a singly-linked list container. It can be used as a stack. This module is a submodule of [`std.container`](std_container). Source [std/container/slist.d](https://github.com/dlang/phobos/blob/master/std/container/slist.d) License: Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE\_1\_0.txt or copy at [boost.org/LICENSE\_1\_0.txt](http://boost.org/LICENSE_1_0.txt)). Authors: [Andrei Alexandrescu](http://erdani.com) Examples: ``` import std.algorithm.comparison : equal; import std.container : SList; auto s = SList!int(1, 2, 3); assert(equal(s[], [1, 2, 3])); s.removeFront(); assert(equal(s[], [2, 3])); s.insertFront([5, 6]); assert(equal(s[], [5, 6, 2, 3])); // If you want to apply range operations, simply slice it. import std.algorithm.searching : countUntil; import std.range : popFrontN, walkLength; auto sl = SList!int(1, 2, 3, 4, 5); writeln(countUntil(sl[], 2)); // 1 auto r = sl[]; popFrontN(r, 2); writeln(walkLength(r)); // 3 ``` struct **SList**(T) if (!is(T == shared)); Implements a simple and fast singly-linked list. It can be used as a stack. `SList` uses reference semantics. this(U)(U[] values...) Constraints: if (isImplicitlyConvertible!(U, T)); Constructor taking a number of nodes this(Stuff)(Stuff stuff) Constraints: if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T) && !is(Stuff == T[])); Constructor taking an [input range](std_range_primitives#isInputRange) const bool **opEquals**(const SList rhs); const bool **opEquals**(ref const SList rhs); Comparison for equality. Complexity Ο(`min(n, n1)`) where `n1` is the number of elements in `rhs`. struct **Range**; Defines the container's primary range, which embodies a forward range. const @property bool **empty**(); @property ref T **front**(); void **popFront**(); Input range primitives. @property Range **save**(); Forward range primitive. const @property bool **empty**(); Property returning `true` if and only if the container has no elements. Complexity Ο(`1`) @property SList **dup**(); Duplicates the container. The elements themselves are not transitively duplicated. Complexity Ο(`n`). Range **opSlice**(); Returns a range that iterates over all elements of the container, in forward order. Complexity Ο(`1`) @property ref T **front**(); Forward to `opSlice().front`. Complexity Ο(`1`) SList **opBinary**(string op, Stuff)(Stuff rhs) Constraints: if (op == "~" && is(typeof(SList(rhs)))); SList **opBinaryRight**(string op, Stuff)(Stuff lhs) Constraints: if (op == "~" && !is(typeof(lhs.opBinary!"~"(this))) && is(typeof(SList(lhs)))); Returns a new `SList` that's the concatenation of `this` and its argument. `opBinaryRight` is only defined if `Stuff` does not define `opBinary`. void **clear**(); Removes all contents from the `SList`. Postcondition `empty` Complexity Ο(`1`) void **reverse**(); Reverses SList in-place. Performs no memory allocation. Complexity Ο(`n`) size\_t **insertFront**(Stuff)(Stuff stuff) Constraints: if (isInputRange!Stuff || isImplicitlyConvertible!(Stuff, T)); alias **insert** = insertFront; alias **stableInsert** = insert; alias **stableInsertFront** = insertFront; Inserts `stuff` to the front of the container. `stuff` can be a value convertible to `T` or a range of objects convertible to `T`. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. Returns: The number of elements inserted Complexity Ο(`m`), where `m` is the length of `stuff` T **removeAny**(); alias **stableRemoveAny** = removeAny; Picks one value in an unspecified position in the container, removes it from the container, and returns it. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. Precondition `!empty` Returns: The element removed. Complexity Ο(`1`). void **removeFront**(); alias **stableRemoveFront** = removeFront; Removes the value at the front of the container. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. Precondition `!empty` Complexity Ο(`1`). size\_t **removeFront**(size\_t howMany); alias **stableRemoveFront** = removeFront; Removes `howMany` values at the front or back of the container. Unlike the unparameterized versions above, these functions do not throw if they could not remove `howMany` elements. Instead, if `howMany > n`, all elements are removed. The returned value is the effective number of elements removed. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. Returns: The number of elements removed Complexity Ο(`howMany * log(n)`). size\_t **insertAfter**(Stuff)(Range r, Stuff stuff) Constraints: if (isInputRange!Stuff || isImplicitlyConvertible!(Stuff, T)); Inserts `stuff` after range `r`, which must be a range previously extracted from this container. Given that all ranges for a list end at the end of the list, this function essentially appends to the list and uses `r` as a potentially fast way to reach the last node in the list. Ideally `r` is positioned near or at the last element of the list. `stuff` can be a value convertible to `T` or a range of objects convertible to `T`. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. Returns: The number of values inserted. Complexity Ο(`k + m`), where `k` is the number of elements in `r` and `m` is the length of `stuff`. Example ``` auto sl = SList!string(["a", "b", "d"]); sl.insertAfter(sl[], "e"); // insert at the end (slowest) assert(std.algorithm.equal(sl[], ["a", "b", "d", "e"])); sl.insertAfter(std.range.take(sl[], 2), "c"); // insert after "b" assert(std.algorithm.equal(sl[], ["a", "b", "c", "d", "e"])); ``` size\_t **insertAfter**(Stuff)(Take!Range r, Stuff stuff) Constraints: if (isInputRange!Stuff || isImplicitlyConvertible!(Stuff, T)); alias **stableInsertAfter** = insertAfter; Similar to `insertAfter` above, but accepts a range bounded in count. This is important for ensuring fast insertions in the middle of the list. For fast insertions after a specified position `r`, use `insertAfter(take(r, 1), stuff)`. The complexity of that operation only depends on the number of elements in `stuff`. Precondition `r.original.empty || r.maxLength > 0` Returns: The number of values inserted. Complexity Ο(`k + m`), where `k` is the number of elements in `r` and `m` is the length of `stuff`. Range **linearRemove**(Range r); Removes a range from the list in linear time. Returns: An empty range. Complexity Ο(`n`) Range **linearRemove**(Take!Range r); alias **stableLinearRemove** = linearRemove; Removes a `Take!Range` from the list in linear time. Returns: A range comprehending the elements after the removed range. Complexity Ο(`n`) bool **linearRemoveElement**(T value); Removes the first occurence of an element from the list in linear time. Returns: True if the element existed and was successfully removed, false otherwise. Parameters: | | | | --- | --- | | T `value` | value of the node to be removed | Complexity Ο(`n`) d rt.monitor_ rt.monitor\_ ============ Contains the implementation for object monitors. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Walter Bright, Sean Kelly, Martin Nowak d std.exception std.exception ============= This module defines functions related to exceptions and general error handling. It also defines functions intended to aid in unit testing. | Category | Functions | | --- | --- | | Assumptions | [`assertNotThrown`](#assertNotThrown) [`assertThrown`](#assertThrown) [`assumeUnique`](#assumeUnique) [`assumeWontThrow`](#assumeWontThrow) [`mayPointTo`](#mayPointTo) | | Enforce | [`doesPointTo`](#doesPointTo) [`enforce`](#enforce) [`errnoEnforce`](#errnoEnforce) | | Handlers | [`collectException`](#collectException) [`collectExceptionMsg`](#collectExceptionMsg) [`ifThrown`](#ifThrown) [`handle`](#handle) | | Other | [`basicExceptionCtors`](#basicExceptionCtors) [`emptyExceptionMsg`](#emptyExceptionMsg) [`ErrnoException`](#ErrnoException) [`RangePrimitive`](#RangePrimitive) | License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt) Authors: [Andrei Alexandrescu](http://erdani.org) and [Jonathan M Davis](http://jmdavisprog.com) Source [std/exception.d](https://github.com/dlang/phobos/blob/master/std/exception.d) Examples: Synopis ``` import core.stdc.stdlib : malloc, free; import std.algorithm.comparison : equal; import std.algorithm.iteration : map, splitter; import std.algorithm.searching : endsWith; import std.conv : ConvException, to; import std.range : front, retro; // use enforce like assert int a = 3; enforce(a > 2, "a needs to be higher than 2."); // enforce can throw a custom exception enforce!ConvException(a > 2, "a needs to be higher than 2."); // enforce will return it's input enum size = 42; auto memory = enforce(malloc(size), "malloc failed")[0 .. size]; scope(exit) free(memory.ptr); // collectException can be used to test for exceptions Exception e = collectException("abc".to!int); assert(e.file.endsWith("conv.d")); // and just for the exception message string msg = collectExceptionMsg("abc".to!int); writeln(msg); // "Unexpected 'a' when converting from type string to type int" // assertThrown can be used to assert that an exception is thrown assertThrown!ConvException("abc".to!int); // ifThrown can be used to provide a default value if an exception is thrown writeln("x".to!int().ifThrown(0)); // 0 // handle is a more advanced version of ifThrown for ranges auto r = "12,1337z32,54".splitter(',').map!(a => to!int(a)); auto h = r.handle!(ConvException, RangePrimitive.front, (e, r) => 0); assert(h.equal([12, 0, 54])); assertThrown!ConvException(h.retro.equal([54, 0, 12])); // basicExceptionCtors avoids the boilerplate when creating custom exceptions static class MeaCulpa : Exception { mixin basicExceptionCtors; } e = collectException((){throw new MeaCulpa("diagnostic message");}()); writeln(e.msg); // "diagnostic message" writeln(e.file); // __FILE__ writeln(e.line); // __LINE__ - 3 // assumeWontThrow can be used to cast throwing code into `nothrow` void exceptionFreeCode() nothrow { // auto-decoding only throws if an invalid UTF char is given assumeWontThrow("abc".front); } // assumeUnique can be used to cast mutable instance to an `immutable` one // use with care char[] str = " mutable".dup; str[0 .. 2] = "im"; immutable res = assumeUnique(str); writeln(res); // "immutable" ``` auto **assertNotThrown**(T : Throwable = Exception, E)(lazy E expression, string msg = null, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_); Asserts that the given expression does *not* throw the given type of `Throwable`. If a `Throwable` of the given type is thrown, it is caught and does not escape assertNotThrown. Rather, an `AssertError` is thrown. However, any other `Throwable`s will escape. Parameters: | | | | --- | --- | | T | The `Throwable` to test for. | | E `expression` | The expression to test. | | string `msg` | Optional message to output on test failure. If msg is empty, and the thrown exception has a non-empty msg field, the exception's msg field will be output on test failure. | | string `file` | The file where the error occurred. Defaults to `__FILE__`. | | size\_t `line` | The line where the error occurred. Defaults to `__LINE__`. | Throws: `AssertError` if the given `Throwable` is thrown. Returns: the result of `expression`. Examples: ``` import core.exception : AssertError; import std.string; assertNotThrown!StringException(enforce!StringException(true, "Error!")); //Exception is the default. assertNotThrown(enforce!StringException(true, "Error!")); assert(collectExceptionMsg!AssertError(assertNotThrown!StringException( enforce!StringException(false, "Error!"))) == `assertNotThrown failed: StringException was thrown: Error!`); ``` void **assertThrown**(T : Throwable = Exception, E)(lazy E expression, string msg = null, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_); Asserts that the given expression throws the given type of `Throwable`. The `Throwable` is caught and does not escape assertThrown. However, any other `Throwable`s *will* escape, and if no `Throwable` of the given type is thrown, then an `AssertError` is thrown. Parameters: | | | | --- | --- | | T | The `Throwable` to test for. | | E `expression` | The expression to test. | | string `msg` | Optional message to output on test failure. | | string `file` | The file where the error occurred. Defaults to `__FILE__`. | | size\_t `line` | The line where the error occurred. Defaults to `__LINE__`. | Throws: `AssertError` if the given `Throwable` is not thrown. Examples: ``` import core.exception : AssertError; import std.string; assertThrown!StringException(enforce!StringException(false, "Error!")); //Exception is the default. assertThrown(enforce!StringException(false, "Error!")); assert(collectExceptionMsg!AssertError(assertThrown!StringException( enforce!StringException(true, "Error!"))) == `assertThrown failed: No StringException was thrown.`); ``` template **enforce**(E : Throwable = Exception) if (is(typeof(new E("", string.init, size\_t.init)) : Throwable) || is(typeof(new E(string.init, size\_t.init)) : Throwable)) T **enforce**(T, Dg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_)(T value, scope Dg dg) Constraints: if (isSomeFunction!Dg && is(typeof(dg())) && is(typeof(() { if (!value) { } } ))); T **enforce**(T)(T value, lazy Throwable ex); Enforces that the given value is true. If the given value is false, an exception is thrown. The * `msg` - error message as a `string` * `dg` - custom delegate that return a string and is only called if an exception occurred * `ex` - custom exception to be thrown. It is `lazy` and is only created if an exception occurred Parameters: | | | | --- | --- | | T `value` | The value to test. | | E | Exception type to throw if the value evaluates to false. | | const(char)[] msg | The error message to put in the exception if it is thrown. | | Dg `dg` | The delegate to be called if the value evaluates to false. | | Throwable `ex` | The exception to throw if the value evaluates to false. | | string file | The source file of the caller. | | size\_t line | The line number of the caller. | Returns: `value`, if `cast(bool) value` is true. Otherwise, depending on the chosen overload, `new Exception(msg)`, `dg()` or `ex` is thrown. Note `enforce` is used to throw exceptions and is therefore intended to aid in error handling. It is *not* intended for verifying the logic of your program. That is what `assert` is for. Also, do not use `enforce` inside of contracts (i.e. inside of `in` and `out` blocks and `invariant`s), because contracts are compiled out when compiling with *-release*. If a delegate is passed, the safety and purity of this function are inferred from `Dg`'s safety and purity. Examples: ``` import core.stdc.stdlib : malloc, free; import std.conv : ConvException, to; // use enforce like assert int a = 3; enforce(a > 2, "a needs to be higher than 2."); // enforce can throw a custom exception enforce!ConvException(a > 2, "a needs to be higher than 2."); // enforce will return it's input enum size = 42; auto memory = enforce(malloc(size), "malloc failed")[0 .. size]; scope(exit) free(memory.ptr); ``` Examples: ``` assertNotThrown(enforce(true, new Exception("this should not be thrown"))); assertThrown(enforce(false, new Exception("this should be thrown"))); ``` Examples: ``` writeln(enforce(123)); // 123 try { enforce(false, "error"); assert(false); } catch (Exception e) { writeln(e.msg); // "error" writeln(e.file); // __FILE__ writeln(e.line); // __LINE__ - 7 } ``` Examples: Alias your own enforce function ``` import std.conv : ConvException; alias convEnforce = enforce!ConvException; assertNotThrown(convEnforce(true)); assertThrown!ConvException(convEnforce(false, "blah")); ``` T **enforce**(T)(T value, lazy const(char)[] msg = null, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_) Constraints: if (is(typeof(() { if (!value) { } } ))); alias **errnoEnforce** = enforce!(ErrnoException).enforce(T)(T value, lazy const(char)[] msg = null, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_) if (is(typeof(() { if (!value) { } } ))); Enforces that the given value is true, throwing an `ErrnoException` if it is not. Parameters: | | | | --- | --- | | T value | The value to test. | | const(char)[] msg | The message to include in the `ErrnoException` if it is thrown. | Returns: `value`, if `cast(bool) value` is true. Otherwise, `new ErrnoException(msg)` is thrown. It is assumed that the last operation set `errno` to an error code corresponding with the failed condition. Examples: ``` import core.stdc.stdio : fclose, fgets, fopen; import std.file : thisExePath; import std.string : toStringz; auto f = fopen(thisExePath.toStringz, "r").errnoEnforce; scope(exit) fclose(f); char[100] buf; auto line = fgets(buf.ptr, buf.length, f); enforce(line !is null); // expect a non-empty line ``` template **enforceEx**(E : Throwable) if (is(typeof(new E("", string.init, size\_t.init)))) Deprecated. Please use [`enforce`](#enforce) instead. This function will be removed 2.089. If `!value` is `false`, `value` is returned. Otherwise, `new E(msg, file, line)` is thrown. Or if `E` doesn't take a message and can be constructed with `new E(file, line)`, then `new E(file, line)` will be thrown. Example ``` auto f = enforceEx!FileMissingException(fopen("data.txt")); auto line = readln(f); enforceEx!DataCorruptionException(line.length); ``` T **enforceEx**(T)(T value, lazy string msg = "", string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_); Ditto T **collectException**(T = Exception, E)(lazy E expression, ref E result); Catches and returns the exception thrown from the given expression. If no exception is thrown, then null is returned and `result` is set to the result of the expression. Note that while `collectException` *can* be used to collect any `Throwable` and not just `Exception`s, it is generally ill-advised to catch anything that is neither an `Exception` nor a type derived from `Exception`. So, do not use `collectException` to collect non-`Exception`s unless you're sure that that's what you really want to do. Parameters: | | | | --- | --- | | T | The type of exception to catch. | | E `expression` | The expression which may throw an exception. | | E `result` | The result of the expression if no exception is thrown. | Examples: ``` int b; int foo() { throw new Exception("blah"); } assert(collectException(foo(), b)); int[] a = new int[3]; import core.exception : RangeError; assert(collectException!RangeError(a[4], b)); ``` T **collectException**(T : Throwable = Exception, E)(lazy E expression); Catches and returns the exception thrown from the given expression. If no exception is thrown, then null is returned. `E` can be `void`. Note that while `collectException` *can* be used to collect any `Throwable` and not just `Exception`s, it is generally ill-advised to catch anything that is neither an `Exception` nor a type derived from `Exception`. So, do not use `collectException` to collect non-`Exception`s unless you're sure that that's what you really want to do. Parameters: | | | | --- | --- | | T | The type of exception to catch. | | E `expression` | The expression which may throw an exception. | Examples: ``` int foo() { throw new Exception("blah"); } writeln(collectException(foo()).msg); // "blah" ``` string **collectExceptionMsg**(T = Exception, E)(lazy E expression); Catches the exception thrown from the given expression and returns the msg property of that exception. If no exception is thrown, then null is returned. `E` can be `void`. If an exception is thrown but it has an empty message, then `emptyExceptionMsg` is returned. Note that while `collectExceptionMsg` *can* be used to collect any `Throwable` and not just `Exception`s, it is generally ill-advised to catch anything that is neither an `Exception` nor a type derived from `Exception`. So, do not use `collectExceptionMsg` to collect non-`Exception`s unless you're sure that that's what you really want to do. Parameters: | | | | --- | --- | | T | The type of exception to catch. | | E `expression` | The expression which may throw an exception. | Examples: ``` void throwFunc() { throw new Exception("My Message."); } writeln(collectExceptionMsg(throwFunc())); // "My Message." void nothrowFunc() {} assert(collectExceptionMsg(nothrowFunc()) is null); void throwEmptyFunc() { throw new Exception(""); } writeln(collectExceptionMsg(throwEmptyFunc())); // emptyExceptionMsg ``` enum string **emptyExceptionMsg**; Value that collectExceptionMsg returns when it catches an exception with an empty exception message. pure nothrow immutable(T)[] **assumeUnique**(T)(T[] array); pure nothrow immutable(T)[] **assumeUnique**(T)(ref T[] array); pure nothrow immutable(T[U]) **assumeUnique**(T, U)(ref T[U] array); Casts a mutable array to an immutable array in an idiomatic manner. Technically, `assumeUnique` just inserts a cast, but its name documents assumptions on the part of the caller. `assumeUnique(arr)` should only be called when there are no more active mutable aliases to elements of `arr`. To strengthen this assumption, `assumeUnique(arr)` also clears `arr` before returning. Essentially `assumeUnique(arr)` indicates commitment from the caller that there is no more mutable access to any of `arr`'s elements (transitively), and that all future accesses will be done through the immutable array returned by `assumeUnique`. Typically, `assumeUnique` is used to return arrays from functions that have allocated and built them. Parameters: | | | | --- | --- | | T[] `array` | The array to cast to immutable. | Returns: The immutable array. Example ``` string letters() { char[] result = new char['z' - 'a' + 1]; foreach (i, ref e; result) { e = cast(char)('a' + i); } return assumeUnique(result); } ``` The use in the example above is correct because `result` was private to `letters` and is inaccessible in writing after the function returns. The following example shows an incorrect use of `assumeUnique`. Bad ``` private char[] buffer; string letters(char first, char last) { if (first >= last) return null; // fine auto sneaky = buffer; sneaky.length = last - first + 1; foreach (i, ref e; sneaky) { e = cast(char)('a' + i); } return assumeUnique(sneaky); // BAD } ``` The example above wreaks havoc on client code because it is modifying arrays that callers considered immutable. To obtain an immutable array from the writable array `buffer`, replace the last line with: ``` return to!(string)(sneaky); // not that sneaky anymore ``` The call will duplicate the array appropriately. Note that checking for uniqueness during compilation is possible in certain cases, especially when a function is marked as a pure function. The following example does not need to call assumeUnique because the compiler can infer the uniqueness of the array in the pure function: ``` string letters() pure { char[] result = new char['z' - 'a' + 1]; foreach (i, ref e; result) { e = cast(char)('a' + i); } return result; } ``` For more on infering uniqueness see the **unique** and **lent** keywords in the [ArchJava](http://www.cs.cmu.edu/~aldrich/papers/aldrich-dissertation.pdf) language. The downside of using `assumeUnique`'s convention-based usage is that at this time there is no formal checking of the correctness of the assumption; on the upside, the idiomatic use of `assumeUnique` is simple and rare enough to be tolerable. Examples: ``` int[] arr = new int[1]; auto arr1 = arr.assumeUnique; static assert(is(typeof(arr1) == immutable(int)[])); writeln(arr); // null writeln(arr1); // [0] ``` Examples: ``` int[string] arr = ["a":1]; auto arr1 = arr.assumeUnique; static assert(is(typeof(arr1) == immutable(int[string]))); writeln(arr); // null writeln(arr1.keys); // ["a"] ``` nothrow T **assumeWontThrow**(T)(lazy T expr, string msg = null, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_); Wraps a possibly-throwing expression in a `nothrow` wrapper so that it can be called by a `nothrow` function. This wrapper function documents commitment on the part of the caller that the appropriate steps have been taken to avoid whatever conditions may trigger an exception during the evaluation of `expr`. If it turns out that the expression *does* throw at runtime, the wrapper will throw an `AssertError`. (Note that `Throwable` objects such as `AssertError` that do not subclass `Exception` may be thrown even from `nothrow` functions, since they are considered to be serious runtime problems that cannot be recovered from.) Parameters: | | | | --- | --- | | T `expr` | The expression asserted not to throw. | | string `msg` | The message to include in the `AssertError` if the assumption turns out to be false. | | string `file` | The source file name of the caller. | | size\_t `line` | The line number of the caller. | Returns: The value of `expr`, if any. Examples: ``` import std.math : sqrt; // This function may throw. int squareRoot(int x) { if (x < 0) throw new Exception("Tried to take root of negative number"); return cast(int) sqrt(cast(double) x); } // This function never throws. int computeLength(int x, int y) nothrow { // Since x*x + y*y is always positive, we can safely assume squareRoot // won't throw, and use it to implement this nothrow function. If it // does throw (e.g., if x*x + y*y overflows a 32-bit value), then the // program will terminate. return assumeWontThrow(squareRoot(x*x + y*y)); } writeln(computeLength(3, 4)); // 5 ``` pure nothrow @nogc @trusted bool **doesPointTo**(S, T, Tdummy = void)(auto ref const S source, ref const T target) Constraints: if (\_\_traits(isRef, source) || isDynamicArray!S || isPointer!S || is(S == class)); pure nothrow @trusted bool **doesPointTo**(S, T)(auto ref const shared S source, ref const shared T target); pure nothrow @trusted bool **mayPointTo**(S, T, Tdummy = void)(auto ref const S source, ref const T target) Constraints: if (\_\_traits(isRef, source) || isDynamicArray!S || isPointer!S || is(S == class)); pure nothrow @trusted bool **mayPointTo**(S, T)(auto ref const shared S source, ref const shared T target); Checks whether a given source object contains pointers or references to a given target object. Parameters: | | | | --- | --- | | S `source` | The source object | | T `target` | The target object | Bugs: The function is explicitly annotated `@nogc` because inference could fail, see [issue 17084](https://issues.dlang.org/show_bug.cgi?id=17084). Returns: `true` if `source`'s representation embeds a pointer that points to `target`'s representation or somewhere inside it. If `source` is or contains a dynamic array, then, then these functions will check if there is overlap between the dynamic array and `target`'s representation. If `source` is a class, then it will be handled as a pointer. If `target` is a pointer, a dynamic array or a class, then these functions will only check if `source` points to `target`, *not* what `target` references. If `source` is or contains a union or `void[n]`, then there may be either false positives or false negatives: `doesPointTo` will return `true` if it is absolutely certain `source` points to `target`. It may produce false negatives, but never false positives. This function should be prefered when trying to validate input data. `mayPointTo` will return `false` if it is absolutely certain `source` does not point to `target`. It may produce false positives, but never false negatives. This function should be prefered for defensively choosing a code path. Note Evaluating `doesPointTo(x, x)` checks whether `x` has internal pointers. This should only be done as an assertive test, as the language is free to assume objects don't have internal pointers (TDPL 7.1.3.5). Examples: Pointers ``` int i = 0; int* p = null; assert(!p.doesPointTo(i)); p = &i; assert( p.doesPointTo(i)); ``` Examples: Structs and Unions ``` struct S { int v; int* p; } int i; auto s = S(0, &i); // structs and unions "own" their members // pointsTo will answer true if one of the members pointsTo. assert(!s.doesPointTo(s.v)); //s.v is just v member of s, so not pointed. assert( s.p.doesPointTo(i)); //i is pointed by s.p. assert( s .doesPointTo(i)); //which means i is pointed by s itself. // Unions will behave exactly the same. Points to will check each "member" // individually, even if they share the same memory ``` Examples: Arrays (dynamic and static) ``` int i; // trick the compiler when initializing slice // https://issues.dlang.org/show_bug.cgi?id=18637 int* p = &i; int[] slice = [0, 1, 2, 3, 4]; int[5] arr = [0, 1, 2, 3, 4]; int*[] slicep = [p]; int*[1] arrp = [&i]; // A slice points to all of its members: assert( slice.doesPointTo(slice[3])); assert(!slice[0 .. 2].doesPointTo(slice[3])); // Object 3 is outside of the // slice [0 .. 2] // Note that a slice will not take into account what its members point to. assert( slicep[0].doesPointTo(i)); assert(!slicep .doesPointTo(i)); // static arrays are objects that own their members, just like structs: assert(!arr.doesPointTo(arr[0])); // arr[0] is just a member of arr, so not // pointed. assert( arrp[0].doesPointTo(i)); // i is pointed by arrp[0]. assert( arrp .doesPointTo(i)); // which means i is pointed by arrp // itself. // Notice the difference between static and dynamic arrays: assert(!arr .doesPointTo(arr[0])); assert( arr[].doesPointTo(arr[0])); assert( arrp .doesPointTo(i)); assert(!arrp[].doesPointTo(i)); ``` Examples: Classes ``` class C { this(int* p){this.p = p;} int* p; } int i; C a = new C(&i); C b = a; // Classes are a bit particular, as they are treated like simple pointers // to a class payload. assert( a.p.doesPointTo(i)); // a.p points to i. assert(!a .doesPointTo(i)); // Yet a itself does not point i. //To check the class payload itself, iterate on its members: () { import std.traits : Fields; foreach (index, _; Fields!C) if (doesPointTo(a.tupleof[index], i)) return; assert(0); }(); // To check if a class points a specific payload, a direct memmory check // can be done: auto aLoc = cast(ubyte[__traits(classInstanceSize, C)]*) a; assert(b.doesPointTo(*aLoc)); // b points to where a is pointing ``` class **ErrnoException**: object.Exception; Thrown if errors that set `errno` occur. Examples: ``` import core.stdc.errno : EAGAIN; auto ex = new ErrnoException("oh no", EAGAIN); writeln(ex.errno); // EAGAIN ``` Examples: errno is used by default if no explicit error code is provided ``` import core.stdc.errno : errno, EAGAIN; auto old = errno; scope(exit) errno = old; // fake that errno got set by the callee errno = EAGAIN; auto ex = new ErrnoException("oh no"); writeln(ex.errno); // EAGAIN ``` final pure nothrow @nogc @property @safe uint **errno**(); Operating system error code. @safe this(string msg, string file = null, size\_t line = 0); Constructor which takes an error message. The current global [`core.stdc.errno.errno`](core_stdc_errno#errno) value is used as error code. @safe this(string msg, int errno, string file = null, size\_t line = 0); Constructor which takes an error message and error code. CommonType!(T1, T2) **ifThrown**(E : Throwable = Exception, T1, T2)(lazy scope T1 expression, lazy scope T2 errorHandler); CommonType!(T1, T2) **ifThrown**(E : Throwable, T1, T2)(lazy scope T1 expression, scope T2 delegate(E) errorHandler); CommonType!(T1, T2) **ifThrown**(T1, T2)(lazy scope T1 expression, scope T2 delegate(Exception) errorHandler); ML-style functional exception handling. Runs the supplied expression and returns its result. If the expression throws a `Throwable`, runs the supplied error handler instead and return its result. The error handler's type must be the same as the expression's type. Parameters: | | | | --- | --- | | E | The type of `Throwable`s to catch. Defaults to `Exception` | | T1 | The type of the expression. | | T2 | The return type of the error handler. | | T1 `expression` | The expression to run and return its result. | | T2 `errorHandler` | The handler to run if the expression throwed. | Returns: expression, if it does not throw. Otherwise, returns the result of errorHandler. Examples: Revert to a default value upon an error: ``` import std.conv : to; writeln("x".to!int.ifThrown(0)); // 0 ``` Examples: Chain multiple calls to ifThrown, each capturing errors from the entire preceding expression. ``` import std.conv : ConvException, to; string s = "true"; assert(s.to!int.ifThrown(cast(int) s.to!double) .ifThrown(cast(int) s.to!bool) == 1); s = "2.0"; assert(s.to!int.ifThrown(cast(int) s.to!double) .ifThrown(cast(int) s.to!bool) == 2); // Respond differently to different types of errors alias orFallback = (lazy a) => a.ifThrown!ConvException("not a number") .ifThrown!Exception("number too small"); writeln(orFallback(enforce("x".to!int < 1).to!string)); // "not a number" writeln(orFallback(enforce("2".to!int < 1).to!string)); // "number too small" ``` Examples: The expression and the errorHandler must have a common type they can both be implicitly casted to, and that type will be the type of the compound expression. ``` // null and new Object have a common type(Object). static assert(is(typeof(null.ifThrown(new Object())) == Object)); static assert(is(typeof((new Object()).ifThrown(null)) == Object)); // 1 and new Object do not have a common type. static assert(!__traits(compiles, 1.ifThrown(new Object()))); static assert(!__traits(compiles, (new Object()).ifThrown(1))); ``` Examples: Use a lambda to get the thrown object. ``` import std.format : format; // "std.format.FormatException" writeln("%s".format.ifThrown!Exception(e => e.classinfo.name)); ``` enum **RangePrimitive**: int; This `enum` is used to select the primitives of the range to handle by the [`handle`](#handle) range wrapper. The values of the `enum` can be `OR`'d to select multiple primitives to be handled. `RangePrimitive.access` is a shortcut for the access primitives; `front`, `back` and `opIndex`. `RangePrimitive.pop` is a shortcut for the mutating primitives; `popFront` and `popBack`. Examples: ``` import std.algorithm.comparison : equal; import std.algorithm.iteration : map, splitter; import std.conv : to, ConvException; auto s = "12,1337z32,54,2,7,9,1z,6,8"; // The next line composition will throw when iterated // as some elements of the input do not convert to integer auto r = s.splitter(',').map!(a => to!int(a)); // Substitute 0 for cases of ConvException auto h = r.handle!(ConvException, RangePrimitive.front, (e, r) => 0); assert(h.equal([12, 0, 54, 2, 7, 9, 0, 6, 8])); ``` Examples: ``` import std.algorithm.comparison : equal; import std.range : retro; import std.utf : UTFException; auto str = "hello\xFFworld"; // 0xFF is an invalid UTF-8 code unit auto handled = str.handle!(UTFException, RangePrimitive.access, (e, r) => ' '); // Replace invalid code points with spaces assert(handled.equal("hello world")); // `front` is handled, assert(handled.retro.equal("dlrow olleh")); // as well as `back` ``` **front** **back** **popFront** **popBack** **empty** **save** **length** **opDollar** **opIndex** **opSlice** **access** **pop** auto **handle**(E : Throwable, RangePrimitive primitivesToHandle, alias handler, Range)(Range input) Constraints: if (isInputRange!Range); Handle exceptions thrown from range primitives. Use the [`RangePrimitive`](#RangePrimitive) enum to specify which primitives to handle. Multiple range primitives can be handled at once by using the `OR` operator or the pseudo-primitives `RangePrimitive.access` and `RangePrimitive.pop`. All handled primitives must have return types or values compatible with the user-supplied handler. Parameters: | | | | --- | --- | | E | The type of `Throwable` to handle. | | primitivesToHandle | Set of range primitives to handle. | | handler | The callable that is called when a handled primitive throws a `Throwable` of type `E`. The handler must accept arguments of the form `E, ref IRange` and its return value is used as the primitive's return value whenever `E` is thrown. For `opIndex`, the handler can optionally recieve a third argument; the index that caused the exception. | | Range `input` | The range to handle. | Returns: A wrapper `struct` that preserves the range interface of `input`. Note Infinite ranges with slicing support must return an instance of [`std.range.Take`](std_range#Take) when sliced with a specific lower and upper bound (see [`std.range.primitives.hasSlicing`](std_range_primitives#hasSlicing)); `handle` deals with this by `take`ing 0 from the return value of the handler function and returning that when an exception is caught. Examples: ``` import std.algorithm.comparison : equal; import std.algorithm.iteration : map, splitter; import std.conv : to, ConvException; auto s = "12,1337z32,54,2,7,9,1z,6,8"; // The next line composition will throw when iterated // as some elements of the input do not convert to integer auto r = s.splitter(',').map!(a => to!int(a)); // Substitute 0 for cases of ConvException auto h = r.handle!(ConvException, RangePrimitive.front, (e, r) => 0); assert(h.equal([12, 0, 54, 2, 7, 9, 0, 6, 8])); ``` Examples: ``` import std.algorithm.comparison : equal; import std.range : retro; import std.utf : UTFException; auto str = "hello\xFFworld"; // 0xFF is an invalid UTF-8 code unit auto handled = str.handle!(UTFException, RangePrimitive.access, (e, r) => ' '); // Replace invalid code points with spaces assert(handled.equal("hello world")); // `front` is handled, assert(handled.retro.equal("dlrow olleh")); // as well as `back` ``` template **basicExceptionCtors**() Convenience mixin for trivially sub-classing exceptions Even trivially sub-classing an exception involves writing boilerplate code for the constructor to: 1) correctly pass in the source file and line number the exception was thrown from; 2) be usable with [`enforce`](#enforce) which expects exception constructors to take arguments in a fixed order. This mixin provides that boilerplate code. Note however that you need to mark the **mixin** line with at least a minimal (i.e. just **///**) DDoc comment if you want the mixed-in constructors to be documented in the newly created Exception subclass. Current limitation: Due to [bug #11500](https://issues.dlang.org/show_bug.cgi?id=11500), currently the constructors specified in this mixin cannot be overloaded with any other custom constructors. Thus this mixin can currently only be used when no such custom constructors need to be explicitly specified. Examples: ``` class MeaCulpa: Exception { /// mixin basicExceptionCtors; } try throw new MeaCulpa("test"); catch (MeaCulpa e) { writeln(e.msg); // "test" writeln(e.file); // __FILE__ writeln(e.line); // __LINE__ - 5 } ``` pure nothrow @nogc @safe this(string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null); Parameters: | | | | --- | --- | | string `msg` | The message for the exception. | | string `file` | The file where the exception occurred. | | size\_t `line` | The line number where the exception occurred. | | Throwable `next` | The previous exception in the chain of exceptions, if any. | pure nothrow @nogc @safe this(string msg, Throwable next, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_); Parameters: | | | | --- | --- | | string `msg` | The message for the exception. | | Throwable `next` | The previous exception in the chain of exceptions. | | string `file` | The file where the exception occurred. | | size\_t `line` | The line number where the exception occurred. |
programming_docs
d Statements Statements ========== **Contents** 1. [Scope Statements](#scope-statement) 2. [Scope Block Statements](#scope-block-statement) 3. [Labeled Statements](#labeled-statement) 4. [Block Statement](#block-statement) 5. [Expression Statement](#expression-statement) 6. [Declaration Statement](#declaration-statement) 7. [If Statement](#if-statement) 8. [While Statement](#while-statement) 9. [Do Statement](#do-statement) 10. [For Statement](#for-statement) 11. [Foreach Statement](#foreach-statement) 1. [Foreach over Arrays](#foreach_over_arrays) 2. [Foreach over Arrays of Characters](#foreach_over_arrays_of_characters) 3. [Foreach over Associative Arrays](#foreach_over_associative_arrays) 4. [Foreach over Structs and Classes with opApply](#foreach_over_struct_and_classes) 5. [Foreach over Structs and Classes with Ranges](#foreach-with-ranges) 6. [Foreach over Delegates](#foreach_over_delegates) 7. [Foreach over Sequences](#foreach_over_tuples) 8. [Foreach Ref Parameters](#foreach_ref_parameters) 9. [Foreach Restrictions](#foreach_restrictions) 12. [Foreach Range Statement](#foreach-range-statement) 1. [Break and Continue out of Foreach](#break_and_continue_out_of_foreach) 13. [Switch Statement](#switch-statement) 14. [Final Switch Statement](#final-switch-statement) 15. [Continue Statement](#continue-statement) 16. [Break Statement](#break-statement) 17. [Return Statement](#return-statement) 18. [Goto Statement](#goto-statement) 19. [With Statement](#with-statement) 20. [Synchronized Statement](#synchronized-statement) 21. [Try Statement](#try-statement) 22. [Throw Statement](#throw-statement) 23. [Scope Guard Statement](#scope-guard-statement) 1. [Catching C++ Class Objects](#catching_cpp_class_objects) 24. [Asm Statement](#asm) 25. [Pragma Statement](#pragma-statement) 26. [Mixin Statement](#mixin-statement) The order of execution within a function is controlled by [*Statement*](#Statement)s. A function's body consists of a sequence of zero or more *Statement*s. Execution occurs in lexical order, though certain statements may have deferred effects. A *Statement* has no value; it is executed for its effects. ``` Statement: ; NonEmptyStatement ScopeBlockStatement NoScopeNonEmptyStatement: NonEmptyStatement BlockStatement NoScopeStatement: ; NonEmptyStatement BlockStatement NonEmptyOrScopeBlockStatement: NonEmptyStatement ScopeBlockStatement NonEmptyStatement: NonEmptyStatementNoCaseNoDefault CaseStatement CaseRangeStatement DefaultStatement NonEmptyStatementNoCaseNoDefault: LabeledStatement ExpressionStatement DeclarationStatement IfStatement WhileStatement DoStatement ForStatement ForeachStatement SwitchStatement FinalSwitchStatement ContinueStatement BreakStatement ReturnStatement GotoStatement WithStatement SynchronizedStatement TryStatement ScopeGuardStatement ThrowStatement AsmStatement MixinStatement ForeachRangeStatement PragmaStatement ConditionalStatement StaticForeachStatement StaticAssert TemplateMixin ImportDeclaration ``` Any ambiguities in the grammar between *Statement*s and [*Declaration*](declaration#Declaration)s are resolved by the declarations taking precedence. Wrapping such a statement in parentheses will disambiguate it in favor of being a *Statement*. Scope Statements ---------------- ``` ScopeStatement: NonEmptyStatement BlockStatement ``` A new scope for local symbols is introduced for the *NonEmptyStatement* or [*BlockStatement*](#BlockStatement). Even though a new scope is introduced, local symbol declarations cannot shadow (hide) other local symbol declarations in the same function. ``` void func1(int x) { int x; // illegal, x shadows parameter x int y; { int y; } // illegal, y shadows enclosing scope's y void delegate() dg; dg = { int y; }; // ok, this y is not in the same function struct S { int y; // ok, this y is a member, not a local } { int z; } { int z; } // ok, this z is not shadowing the other z { int t; } { t++; } // illegal, t is undefined } ``` **Best Practices:** Local declarations within a function should all have unique names, even if they are in non-overlapping scopes. Scope Block Statements ---------------------- ``` ScopeBlockStatement: BlockStatement ``` A scope block statement introduces a new scope for the [*BlockStatement*](#BlockStatement). Labeled Statements ------------------ Statements can be labeled. A label is an identifier that precedes a statement. ``` LabeledStatement: Identifier : Identifier : NoScopeStatement Identifier : Statement ``` Any statement can be labeled, including empty statements, and so can serve as the target of a goto statement. Labeled statements can also serve as the target of a break or continue statement. A label can appear without a following statement at the end of a block. Labels are in a name space independent of declarations, variables, types, etc. Even so, labels cannot have the same name as local declarations. The label name space is the body of the function they appear in. Label name spaces do not nest, i.e. a label inside a block statement is accessible from outside that block. Labels in one function cannot be referenced from another function. Block Statement --------------- ``` BlockStatement: { } { StatementList } StatementList: Statement Statement StatementList ``` A block statement is a sequence of statements enclosed by `{ }`. The statements are executed in lexical order, until the end of the block is reached or a statement transfers control elsewhere. Expression Statement -------------------- ``` ExpressionStatement: Expression ; ``` The expression is evaluated. Expressions that have no effect, like `(x + x)`, are illegal as expression statements unless they are cast to void. ``` int x; x++; // ok x; // illegal 1+1; // illegal cast(void)(x + x); // ok ``` Declaration Statement --------------------- Declaration statements define variables, and declare types, templates, functions, imports, conditionals, static foreaches, and static asserts. ``` DeclarationStatement: StorageClassesopt Declaration ``` Some declaration statements: ``` int a; // declare a as type int and initialize it to 0 struct S { } // declare struct s alias myint = int; ``` If Statement ------------ If statements provide simple conditional execution of statements. ``` IfStatement: if ( IfCondition ) ThenStatement if ( IfCondition ) ThenStatement else ElseStatement IfCondition: Expression auto Identifier = Expression TypeCtors Identifier = Expression TypeCtorsopt BasicType Declarator = Expression ThenStatement: ScopeStatement ElseStatement: ScopeStatement ``` [*Expression*](expression#Expression) is evaluated and must have a type that can be converted to a boolean. If it's true the *ThenStatement* is transferred to, else the *ElseStatement* is transferred to. The *ElseStatement*is associated with the innermost if statement which does not already have an associated *ElseStatement*. If an `auto` *Identifier* is provided, it is declared and initialized to the value and type of the [*Expression*](expression#Expression). Its scope extends from when it is initialized to the end of the *ThenStatement*. If a *TypeCtors* *Identifier* is provided, it is declared to be of the type specified by *TypeCtors* and is initialized with the value of the [*Expression*](expression#Expression). Its scope extends from when it is initialized to the end of the *ThenStatement*. If a *Declarator* is provided, it is declared and initialized to the value of the [*Expression*](expression#Expression). Its scope extends from when it is initialized to the end of the *ThenStatement*. ``` import std.regex; ... if (auto m = std.regex.matchFirst("abcdef", "b(c)d")) { writefln("[%s]", m.pre); // prints [a] writefln("[%s]", m.post); // prints [ef] writefln("[%s]", m[0]); // prints [bcd] writefln("[%s]", m[1]); // prints [c] } else { writeln(m.post); // Error: undefined identifier 'm' } writeln(m.pre); // Error: undefined identifier 'm' ``` While Statement --------------- ``` WhileStatement: while ( IfCondition ) ScopeStatement ``` A *While Statement* implements a simple loop. If the [*IfCondition*](#IfCondition) is an [*Expression*](expression#Expression), it is evaluated and must have a type that can be converted to a boolean. If it's true the [*ScopeStatement*](#ScopeStatement) is executed. After the [*ScopeStatement*](#ScopeStatement) is executed, the [*Expression*](expression#Expression) is evaluated again, and if true the [*ScopeStatement*](#ScopeStatement) is executed again. This continues until the [*Expression*](expression#Expression) evaluates to false. ``` int i = 0; while (i < 10) { foo(i); ++i; } ``` If an `auto` *Identifier* is provided, it is declared and initialized to the value and type of the [*Expression*](expression#Expression). Its scope extends from when it is initialized to the end of the [*ScopeStatement*](#ScopeStatement). If a *TypeCtors* *Identifier* is provided, it is declared to be of the type specified by *TypeCtors* and is initialized with the value of the [*Expression*](expression#Expression). Its scope extends from when it is initialized to the end of the [*ScopeStatement*](#ScopeStatement). If a *Declarator* is provided, it is declared and initialized to the value of the [*Expression*](expression#Expression). Its scope extends from when it is initialized to the end of the [*ScopeStatement*](#ScopeStatement). A [*BreakStatement*](#BreakStatement) will exit the loop. A [*ContinueStatement*](#ContinueStatement) will transfer directly to evaluating [*IfCondition*](#IfCondition) again. Do Statement ------------ ``` DoStatement: do ScopeStatement while ( Expression ) ; ``` Do while statements implement simple loops. [*ScopeStatement*](#ScopeStatement) is executed. Then [*Expression*](expression#Expression) is evaluated and must have a type that can be converted to a boolean. If it's true the loop is iterated again. This continues until the [*Expression*](expression#Expression) evaluates to false. ``` int i = 0; do { foo(i); } while (++i < 10); ``` A [*BreakStatement*](#BreakStatement) will exit the loop. A [*ContinueStatement*](#ContinueStatement) will transfer directly to evaluating [*Expression*](expression#Expression) again. For Statement ------------- For statements implement loops with initialization, test, and increment clauses. ``` ForStatement: for ( Initialize Testopt ; Incrementopt ) ScopeStatement Initialize: ; NoScopeNonEmptyStatement Test: Expression Increment: Expression ``` *Initialize* is executed. *Test* is evaluated and must have a type that can be converted to a boolean. If it's true the statement is executed. After the statement is executed, the *Increment* is executed. Then *Test* is evaluated again, and if true the statement is executed again. This continues until the *Test* evaluates to false. A [*BreakStatement*](#BreakStatement) will exit the loop. A [*ContinueStatement*](#ContinueStatement) will transfer directly to the *Increment*. A *ForStatement* creates a new scope. If *Initialize* declares a variable, that variable's scope extends through the end of the for statement. For example: ``` for (int i = 0; i < 10; i++) foo(i); ``` is equivalent to: ``` { int i; for (i = 0; i < 10; i++) foo(i); } ``` Function bodies cannot be empty: ``` for (int i = 0; i < 10; i++) ; // illegal ``` Use instead: ``` for (int i = 0; i < 10; i++) { } ``` The *Initialize* may be omitted (although the trailing `;` is still required). *Test* may also be omitted, and if so, it is treated as if it evaluated to true. **Best Practices:** Consider replacing *ForStatements* with [Foreach Statements](statement#foreach-statement) or [Foreach Range Statements](statement#ForeachRangeStatement). Foreach loops are easier to understand, less prone to error, and easier to refactor. Foreach Statement ----------------- A `foreach` statement loops over the contents of an aggregate. ``` AggregateForeach: Foreach ( ForeachTypeList ; ForeachAggregate ) ForeachStatement: AggregateForeach NoScopeNonEmptyStatement Foreach: foreach foreach_reverse ForeachTypeList: ForeachType ForeachType , ForeachTypeList ForeachType: ForeachTypeAttributesopt BasicType Declarator ForeachTypeAttributesopt Identifier ForeachTypeAttributesopt alias Identifier ForeachTypeAttributes ForeachTypeAttribute ForeachTypeAttribute ForeachTypeAttributesopt ForeachTypeAttribute: ref TypeCtor enum ForeachAggregate: Expression ``` *ForeachAggregate* is evaluated. It must evaluate to an expression of type static array, dynamic array, associative array, struct, class, delegate, or sequence. The [*NoScopeNonEmptyStatement*](#NoScopeNonEmptyStatement) is executed, once for each element of the aggregate. At the start of each iteration, the variables declared by the *ForeachTypeList* are set to be a copy of the elements of the aggregate. If the variable is `ref`, it is a reference to the contents of that aggregate. The aggregate must be loop invariant, meaning that elements to the aggregate cannot be added or removed from it in the [*NoScopeNonEmptyStatement*](#NoScopeNonEmptyStatement). ### Foreach over Arrays If the aggregate is a static or dynamic array, there can be one or two variables declared. If one, then the variable is said to be the *value* set to the elements of the array, one by one. The type of the variable must match the type of the array contents, except for the special cases outlined below. If there are two variables declared, the first is said to be the *index* and the second is said to be the *value*. The *index* must be of type `size_t` for dynamic arrays. Static arrays may use any integral type that spans the length of the array. *index* cannot be `ref`. It is set to be the index of the array element. ``` char[] a; ... foreach (int i, char c; a) { writefln("a[%d] = '%c'", i, c); } ``` For `foreach`, the elements for the array are iterated over starting at index 0 and continuing to the maximum of the array. For `foreach_reverse`, the array elements are visited in the reverse order. **Note:** The *ForeachTypeAttribute* is implicit, and when a type is not specified, it is inferred. In that case, `auto` is implied, and it is not necessary (and actually forbidden) to use it. ``` int[] arr; ... foreach (n; arr) // ok, n is an int writeln(n); foreach (auto n; arr) // error, auto is redundant writeln(n); ``` ### Foreach over Arrays of Characters If the aggregate expression is a static or dynamic array of `char`s, `wchar`s, or `dchar`s, then the *Type* of the *value* can be any of `char`, `wchar`, or `dchar`. In this manner any UTF array can be decoded into any UTF type: ``` char[] a = "\xE2\x89\xA0".dup; // \u2260 encoded as 3 UTF-8 bytes foreach (dchar c; a) { writefln("a[] = %x", c); // prints 'a[] = 2260' } dchar[] b = "\u2260"d.dup; foreach (char c; b) { writef("%x, ", c); // prints 'e2, 89, a0, ' } ``` Aggregates can be string literals, which can be accessed as char, wchar, or dchar arrays: ``` void test() { foreach (char c; "ab") { writefln("'%s'", c); } foreach (wchar w; "xy") { writefln("'%s'", w); } } ``` which would print: ``` 'a' 'b' 'x' 'y' ``` ### Foreach over Associative Arrays If the aggregate expression is an associative array, there can be one or two variables declared. If one, then the variable is said to be the *value* set to the elements of the array, one by one. The type of the variable must match the type of the array contents. If there are two variables declared, the first is said to be the *index* and the second is said to be the *value*. The *index* must be of the same type as the indexing type of the associative array. It cannot be `ref`, and it is set to be the index of the array element. The order in which the elements of the array are iterated over is unspecified for `foreach`. `foreach_reverse` for associative arrays is illegal. ``` double[string] a; // index type is string, value type is double ... foreach (string s, double d; a) { writefln("a['%s'] = %g", s, d); } ``` ### Foreach over Structs and Classes with opApply If the aggregate expression is a struct or class object, the `foreach` is defined by the special `opApply` member function, and the `foreach_reverse` behavior is defined by the special `opApplyReverse` member function. These functions have the type: ``` int opApply(scope int delegate(ref Type [, ...]) dg); int opApplyReverse(scope int delegate(ref Type [, ...]) dg); ``` where *Type* matches the *Type* used in the *ForeachType* declaration of *Identifier*. Multiple *ForeachType*s correspond with multiple *Type*s in the delegate type passed to `opApply` or `opApplyReverse`. There can be multiple `opApply` and `opApplyReverse` functions, one is selected by matching the type of *dg* to the *ForeachType*s of the *ForeachStatement*. The body of the apply function iterates over the elements it aggregates, passing them each to the *dg* function. If the *dg* returns 0, then apply goes on to the next element. If the *dg* returns a nonzero value, apply must cease iterating and return that value. Otherwise, after done iterating across all the elements, apply will return 0. For example, consider a class that is a container for two elements: ``` class Foo { uint[2] array; int opApply(scope int delegate(ref uint) dg) { int result = 0; for (int i = 0; i < array.length; i++) { result = dg(array[i]); if (result) break; } return result; } } ``` An example using this might be: ``` void test() { Foo a = new Foo(); a.array[0] = 73; a.array[1] = 82; foreach (uint u; a) { writefln("%d", u); } } ``` which would print: ``` 73 82 ``` The `scope` storage class on the *dg* parameter means that the parameter's value does not escape the scope of the *opApply* function (an example would be assigning *dg* to a global). If it cannot be statically guaranteed that *dg* does not escape, a closure may be allocated for it on the heap instead of the stack. Best practice is to annotate delegate parameters with `scope` when possible. *opApply* can also be a templated function, which will infer the types of parameters based on the *ForeachStatement*. For example: ``` struct S { import std.traits : ParameterTypeTuple; // introspection template int opApply(Dg)(scope Dg dg) if (ParameterTypeTuple!Dg.length == 2) // foreach with 2 parameters { return 0; } int opApply(Dg)(scope Dg dg) if (ParameterTypeTuple!Dg.length == 3) // foreach with takes 3 parameters { return 0; } } void main() { foreach (int a, int b; S()) { } // calls first opApply function foreach (int a, int b, float c; S()) { } // calls second opApply function } ``` It is important to make sure that, if `opApply` catches any exceptions, that those exceptions did not originate from the delegate passed to *opApply*. The user would expect exceptions thrown from a `foreach` body to both terminate the loop, and propagate outside the `foreach` body. ### Foreach over Structs and Classes with Ranges If the aggregate expression is a struct or class object, but the `opApply` for `foreach`, or `opApplyReverse` `foreach_reverse` do not exist, then iteration over struct and class objects can be done with range primitives. For `foreach`, this means the following properties and methods must be defined: Foreach Range Properties| **Property** | **Purpose** | | `.empty` | returns true if no more elements | | `.front` | return the leftmost element of the range | Foreach Range Methods| **Method** | **Purpose** | | `.popFront()` | move the left edge of the range right by one | Meaning: ``` foreach (e; range) { ... } ``` translates to: ``` for (auto __r = range; !__r.empty; __r.popFront()) { auto e = __r.front; ... } ``` Similarly, for `foreach_reverse`, the following properties and methods must be defined: Foreach\_reverse Range Properties| **Property** | **Purpose** | | `.empty` | returns true if no more elements | | `.back` | return the rightmost element of the range | Foreach\_reverse Range Methods| **Method** | **Purpose** | | `.popBack()` | move the right edge of the range left by one | Meaning: ``` foreach_reverse (e; range) { ... } ``` translates to: ``` for (auto __r = range; !__r.empty; __r.popBack()) { auto e = __r.back; ... } ``` ### Foreach over Delegates If *ForeachAggregate* is a delegate, the type signature of the delegate is of the same as for `opApply`. This enables many different named looping strategies to coexist in the same class or struct. For example: ``` void main() { // Custom loop implementation, that iterates over powers of 2 with // alternating sign. The loop body is passed in dg. int myLoop(int delegate(ref int) dg) { for (int z = 1; z < 128; z *= -2) { auto ret = dg(z); // If the loop body contains a break, ret will be non-zero. if (ret != 0) return ret; } return 0; } // This example loop simply collects the loop index values into an array. int[] result; foreach (ref x; &myLoop) { result ~= x; } assert(result == [1, -2, 4, -8, 16, -32, 64, -128]); } ``` **Note:** When *ForeachAggregate* is a delegate, the compiler does not try to implement reverse traversal of the results returned by the delegate when `foreach_reverse` is used. This may result in code that is confusing to read. Therefore, using `foreach_reverse` with a delegate is now deprecated, and will be rejected in the future. ### Foreach over Sequences If the aggregate expression is a sequence, there can be one or two iteration symbols declared. If one, then the symbol is an *element alias* of each element in the sequence in turn. If the sequence is a *TypeSeq*, then the foreach statement is executed once for each type, and the element alias is set to each type. When the sequence is a *ValueSeq*, the element alias is a variable and is set to each value in the sequence. If the type of the variable is given, it must match the type of the sequence contents. If no type is given, the type of the variable is set to the type of the sequence element, which may change from iteration to iteration. If there are two symbols declared, the first is the *index variable* and the second is the *element alias*. The index must be of `int`, `uint`, `long` or `ulong` type, it cannot be `ref`, and it is set to the index of each sequence element. Example: ``` import std.meta : AliasSeq; void main() { alias Seq = AliasSeq!(int, "literal", main); foreach (sym; Seq) { pragma(msg, sym.stringof); } } ``` Output: ``` int "literal" main() ``` See also: [Static Foreach](version#staticforeach). ### Foreach Ref Parameters `ref` can be used to update the original elements: ``` void test() { static uint[2] a = [7, 8]; foreach (ref uint u; a) { u++; } foreach (uint u; a) { writefln("%d", u); } } ``` which would print: ``` 8 9 ``` `ref` can not be applied to the index values. If not specified, the *Type*s in the *ForeachType* can be inferred from the type of the *ForeachAggregate*. ### Foreach Restrictions The aggregate itself must not be resized, reallocated, free'd, reassigned or destructed while the foreach is iterating over the elements. ``` int[] a; int[] b; foreach (int i; a) { a = null; // error a.length += 10; // error a = b; // error } a = null; // ok ``` Foreach Range Statement ----------------------- A foreach range statement loops over the specified range. ``` RangeForeach: Foreach ( ForeachType ; LwrExpression .. UprExpression ) LwrExpression: Expression UprExpression: Expression ForeachRangeStatement: RangeForeach ScopeStatement ``` *ForeachType* declares a variable with either an explicit type, or a type inferred from *LwrExpression* and *UprExpression*. The *ScopeStatement* is then executed *n* times, where *n* is the result of *UprExpression* - *LwrExpression*. If *UprExpression* is less than or equal to *LwrExpression*, the *ScopeStatement* is executed zero times. If *Foreach* is `foreach`, then the variable is set to *LwrExpression*, then incremented at the end of each iteration. If *Foreach* is `foreach_reverse`, then the variable is set to *UprExpression*, then decremented before each iteration. *LwrExpression* and *UprExpression* are each evaluated exactly once, regardless of how many times the *ScopeStatement* is executed. ``` import std.stdio; int foo() { write("foo"); return 10; } void main() { foreach (i; 0 .. foo()) { write(i); } } ``` prints: ``` foo0123456789 ``` ### Break and Continue out of Foreach A [*BreakStatement*](#BreakStatement) in the body of the foreach will exit the foreach, a [*ContinueStatement*](#ContinueStatement) will immediately start the next iteration. Switch Statement ---------------- A switch statement goes to one of a collection of case statements depending on the value of the switch expression. ``` SwitchStatement: switch ( Expression ) ScopeStatement CaseStatement: case ArgumentList : ScopeStatementList CaseRangeStatement: case FirstExp : .. case LastExp : ScopeStatementList FirstExp: AssignExpression LastExp: AssignExpression DefaultStatement: default : ScopeStatementList ScopeStatementList: StatementListNoCaseNoDefault StatementListNoCaseNoDefault: StatementNoCaseNoDefault StatementNoCaseNoDefault StatementListNoCaseNoDefault StatementNoCaseNoDefault: ; NonEmptyStatementNoCaseNoDefault ScopeBlockStatement ``` [*Expression*](expression#Expression) is evaluated. The result type T must be of integral type or `char[]`, `wchar[]` or `dchar[]`. The result is compared against each of the case expressions. If there is a match, the corresponding case statement is transferred to. The case expressions, [*ArgumentList*](expression#ArgumentList), are a comma separated list of expressions. A *CaseRangeStatement* is a shorthand for listing a series of case statements from *FirstExp* to *LastExp*. If none of the case expressions match, and there is a default statement, the default statement is transferred to. A switch statement must have a default statement. The case expressions must all evaluate to a constant value or array, or a runtime initialized const or immutable variable of integral type. They must be implicitly convertible to the type of the switch [*Expression*](expression#Expression). Case expressions must all evaluate to distinct values. Const or immutable variables must all have different names. If they share a value, the first case statement with that value gets control. There must be exactly one default statement. The [*ScopeStatementList*](#ScopeStatementList) introduces a new scope. Case statements and default statements associated with the switch can be nested within block statements; they do not have to be in the outermost block. For example, this is allowed: ``` switch (i) { case 1: { case 2: } break; } ``` A [*ScopeStatementList*](#ScopeStatementList) must either be empty, or be ended with a [*ContinueStatement*](#ContinueStatement), [*BreakStatement*](#BreakStatement), [*ReturnStatement*](#ReturnStatement), [*GotoStatement*](#GotoStatement), [*ThrowStatement*](#ThrowStatement) or assert(0) expression unless this is the last case. This is to set apart with C's error-prone implicit fall-through behavior. `goto case;` could be used for explicit fall-through: ``` int number; string message; switch (number) { default: // valid: ends with 'throw' throw new Exception("unknown number"); case 3: // valid: ends with 'break' (break out of the 'switch' only) message ~= "three "; break; case 4: // valid: ends with 'continue' (continue the enclosing loop) message ~= "four "; continue; case 5: // valid: ends with 'goto' (explicit fall-through to next case.) message ~= "five "; goto case; case 6: // ERROR: implicit fall-through message ~= "six "; case 1: // valid: the body is empty case 2: // valid: this is the last case in the switch statement. message = "one or two"; } ``` A break statement will exit the switch *BlockStatement*. Strings can be used in switch expressions. For example: ``` string name; ... switch (name) { case "fred": case "sally": ... } ``` For applications like command line switch processing, this can lead to much more straightforward code, being clearer and less error prone. char, wchar and dchar strings are allowed. `Implementation Note:` The compiler's code generator may assume that the case statements are sorted by frequency of use, with the most frequent appearing first and the least frequent last. Although this is irrelevant as far as program correctness is concerned, it is of performance interest. Final Switch Statement ---------------------- ``` FinalSwitchStatement: final switch ( Expression ) ScopeStatement ``` A final switch statement is just like a switch statement, except that: * No [*DefaultStatement*](#DefaultStatement) is allowed. * No [*CaseRangeStatement*](#CaseRangeStatement)s are allowed. * If the switch [*Expression*](expression#Expression) is of enum type, all the enum members must appear in the [*CaseStatement*](#CaseStatement)s. * The case expressions cannot evaluate to a run time initialized value. **Implementation Defined:** If the [*Expression*](expression#Expression) value does not match any of the *CaseRangeStatements*, whether that is diagnosed at compile time or at runtime. Continue Statement ------------------ ``` ContinueStatement: continue Identifieropt ; ``` `continue` aborts the current iteration of its enclosing loop statement, and starts the next iteration. continue executes the next iteration of its innermost enclosing while, for, foreach, or do loop. The increment clause is executed. If continue is followed by *Identifier*, the *Identifier* must be the label of an enclosing while, for, or do loop, and the next iteration of that loop is executed. It is an error if there is no such statement. Any intervening finally clauses are executed, and any intervening synchronization objects are released. `Note:` If a finally clause executes a throw out of the finally clause, the continue target is never reached. ``` for (i = 0; i < 10; i++) { if (foo(i)) continue; bar(); } ``` Break Statement --------------- ``` BreakStatement: break Identifieropt ; ``` `break` exits the innermost enclosing while, for, foreach, do, or switch statement, resuming execution at the statement following it. If break is followed by *Identifier*, the *Identifier* must be the label of an enclosing while, for, do or switch statement, and that statement is exited. It is an error if there is no such statement. Any intervening finally clauses are executed, and any intervening synchronization objects are released. `Note:` If a finally clause executes a throw out of the finally clause, the break target is never reached. ``` for (i = 0; i < 10; i++) { if (foo(i)) break; } ``` Return Statement ---------------- ``` ReturnStatement: return Expressionopt ; ``` `return` exits the current function and supplies its return value. [*Expression*](expression#Expression) is required if the function specifies a return type that is not void. The [*Expression*](expression#Expression) is implicitly converted to the function return type. At least one return statement, throw statement, or assert(0) expression is required if the function specifies a return type that is not void, unless the function contains inline assembler code. Before the function actually returns, any objects with scope storage duration are destroyed, any enclosing finally clauses are executed, any scope(exit) statements are executed, any scope(success) statements are executed, and any enclosing synchronization objects are released. The function will not return if any enclosing finally clause does a return, goto or throw that exits the finally clause. If there is an out postcondition (see [Contract Programming](contracts)), that postcondition is executed after the [*Expression*](expression#Expression) is evaluated and before the function actually returns. ``` int foo(int x) { return x + 3; } ``` Goto Statement -------------- ``` GotoStatement: goto Identifier ; goto default ; goto case ; goto case Expression ; ``` `goto` transfers to the statement labeled with *Identifier*. ``` if (foo) goto L1; x = 3; L1: x++; ``` The second form, `goto default;`, transfers to the innermost [*DefaultStatement*](#DefaultStatement) of an enclosing [*SwitchStatement*](#SwitchStatement). The third form, `goto case;`, transfers to the next [*CaseStatement*](#CaseStatement) of the innermost enclosing [*SwitchStatement*](#SwitchStatement). The fourth form, `goto case` [*Expression*](expression#Expression)`;`, transfers to the [*CaseStatement*](#CaseStatement) of the innermost enclosing [*SwitchStatement*](#SwitchStatement) with a matching [*Expression*](expression#Expression). ``` switch (x) { case 3: goto case; case 4: goto default; case 5: goto case 4; default: x = 4; break; } ``` Any intervening finally clauses are executed, along with releasing any intervening synchronization mutexes. It is illegal for a *GotoStatement* to be used to skip initializations. With Statement -------------- The `with` statement is a way to simplify repeated references to the same object. ``` WithStatement: with ( Expression ) ScopeStatement with ( Symbol ) ScopeStatement with ( TemplateInstance ) ScopeStatement ``` where [*Expression*](expression#Expression) evaluates to a class reference or struct instance. Within the with body the referenced object is searched first for identifier symbols. The *WithStatement* ``` with (expression) { ... ident; } ``` is semantically equivalent to: ``` { Object tmp; tmp = expression; ... tmp.ident; } ``` Note that [*Expression*](expression#Expression) only gets evaluated once and is not copied. The with statement does not change what `this` or `super` refer to. For *Symbol* which is a scope or *TemplateInstance*, the corresponding scope is searched when looking up symbols. For example: ``` struct Foo { alias Y = int; } ... Y y; // error, Y undefined with (Foo) { Y y; // same as Foo.Y y; } ``` Use of with object symbols that shadow local symbols with the same identifier are not allowed. This is to reduce the risk of inadvertent breakage of with statements when new members are added to the object declaration. ``` struct S { float x; } void main() { int x; S s; with (s) { x++; // error, shadows the int x declaration } } ``` In nested *WithStatement*s, the inner-most scope takes precedence. If a symbol cannot be resolved at the inner-most scope, resolution is forwarded incrementally up the scope hierarchy. ``` import std.stdio; struct Foo { void f() { writeln("Foo.f"); } } struct Bar { void f() { writeln("Bar.f"); } } struct Baz { // f() is not implemented } void f() { writeln("f"); } void main() { Foo foo; Bar bar; Baz baz; f(); // prints "f" with(foo) { f(); // prints "Foo.f" with(bar) { f(); // prints "Bar.f" with(baz) { f(); // prints "Bar.f". `Baz` does not implement `f()` so // resolution is forwarded to `with(bar)`'s scope } } with(baz) { f(); // prints "Foo.f". `Baz` does not implement `f()` so // resolution is forwarded to `with(foo)`'s scope } } with(baz) { f(); // prints "f". `Baz` does not implement `f()` so // resolution is forwarded to `main`'s scope. `f()` is // not implemented in `main`'s scope, so resolution is // subsequently forward to module scope. } } ``` Synchronized Statement ---------------------- The synchronized statement wraps a statement with a mutex to synchronize access among multiple threads. ``` SynchronizedStatement: synchronized ScopeStatement synchronized ( Expression ) ScopeStatement ``` Synchronized allows only one thread at a time to execute *ScopeStatement* by using a mutex. What mutex is used is determined by the [*Expression*](expression#Expression). If there is no [*Expression*](expression#Expression), then a global mutex is created, one per such synchronized statement. Different synchronized statements will have different global mutexes. If there is an [*Expression*](expression#Expression), it must evaluate to either an Object or an instance of an *Interface*, in which case it is cast to the Object instance that implemented that *Interface*. The mutex used is specific to that Object instance, and is shared by all synchronized statements referring to that instance. The synchronization gets released even if *ScopeStatement* terminates with an exception, goto, or return. Example: ``` synchronized { ... } ``` This implements a standard critical section. Synchronized statements support recursive locking; that is, a function wrapped in synchronized is allowed to recursively call itself and the behavior will be as expected: The mutex will be locked and unlocked as many times as there is recursion. Try Statement ------------- Exception handling is done with the try-catch-finally statement. ``` TryStatement: try ScopeStatement Catches try ScopeStatement Catches FinallyStatement try ScopeStatement FinallyStatement Catches: Catch Catch Catches Catch: catch ( CatchParameter ) NoScopeNonEmptyStatement CatchParameter: BasicType Identifieropt FinallyStatement: finally NoScopeNonEmptyStatement ``` *CatchParameter* declares a variable v of type T, where T is Throwable or derived from Throwable. v is initialized by the throw expression if T is of the same type or a base class of the throw expression. The catch clause will be executed if the exception object is of type T or derived from T. If just type T is given and no variable v, then the catch clause is still executed. It is an error if any *CatchParameter* type T1 hides a subsequent *Catch* with type T2, i.e. it is an error if T1 is the same type as or a base class of T2. The *FinallyStatement* is always executed, whether the `try` *ScopeStatement* exits with a goto, break, continue, return, exception, or fall-through. If an exception is raised in the *FinallyStatement* and is not caught before the original exception is caught, it is chained to the previous exception via the *next* member of *Throwable*. Note that, in contrast to most other programming languages, the new exception does not replace the original exception. Instead, later exceptions are regarded as 'collateral damage' caused by the first exception. The original exception must be caught, and this results in the capture of the entire chain. Thrown objects derived from [`class $Error`](https://dlang.org/phobos/object.html#Error) are treated differently. They bypass the normal chaining mechanism, such that the chain can only be caught by catching the first `Error`. In addition to the list of subsequent exceptions, `Error` also contains a pointer that points to the original exception (the head of the chain) if a bypass occurred, so that the entire exception history is retained. ``` import std.stdio; int main() { try { try { throw new Exception("first"); } finally { writeln("finally"); throw new Exception("second"); } } catch (Exception e) { writeln("catch %s", e.msg); } writeln("done"); return 0; } ``` prints: ``` finally catch first done ``` A *FinallyStatement* may not exit with a goto, break, continue, or return; nor may it be entered with a goto. A *FinallyStatement* may not contain any *Catches*. This restriction may be relaxed in future versions. Throw Statement --------------- Throws an exception. ``` ThrowStatement: throw Expression ; ``` [*Expression*](expression#Expression) is evaluated and must be a `Throwable` reference. The `Throwable` reference is thrown as an exception. ``` throw new Exception("message"); ``` **Best Practices:** Use [Assert Expressions](expression#assert_expressions) rather than [Error](https://dlang.org/library/object#Error) to report program bugs and abort the program. Scope Guard Statement --------------------- ``` ScopeGuardStatement: scope(exit) NonEmptyOrScopeBlockStatement scope(success) NonEmptyOrScopeBlockStatement scope(failure) NonEmptyOrScopeBlockStatement ``` The *ScopeGuardStatement* executes [*NonEmptyOrScopeBlockStatement*](#NonEmptyOrScopeBlockStatement) at the close of the current scope, rather than at the point where the *ScopeGuardStatement* appears. `scope(exit)` executes [*NonEmptyOrScopeBlockStatement*](#NonEmptyOrScopeBlockStatement) when the scope exits normally or when it exits due to exception unwinding. `scope(failure)` executes [*NonEmptyOrScopeBlockStatement*](#NonEmptyOrScopeBlockStatement) when the scope exits due to exception unwinding. `scope(success)` executes [*NonEmptyOrScopeBlockStatement*](#NonEmptyOrScopeBlockStatement) when the scope exits normally. If there are multiple *ScopeGuardStatement*s in a scope, they will be executed in the reverse lexical order in which they appear. If any scope instances are to be destroyed upon the close of the scope, their destructions will be interleaved with the *ScopeGuardStatement*s in the reverse lexical order in which they appear. ``` write("1"); { write("2"); scope(exit) write("3"); scope(exit) write("4"); write("5"); } writeln(); ``` writes: ``` 12543 ``` ``` { scope(exit) write("1"); scope(success) write("2"); scope(exit) write("3"); scope(success) write("4"); } writeln(); ``` writes: ``` 4321 ``` ``` struct Foo { this(string s) { write(s); } ~this() { write("1"); } } try { scope(exit) write("2"); scope(success) write("3"); Foo f = Foo("0"); scope(failure) write("4"); throw new Exception("msg"); scope(exit) write("5"); scope(success) write("6"); scope(failure) write("7"); } catch (Exception e) { } writeln(); ``` writes: ``` 0412 ``` A `scope(exit)` or `scope(success)` statement may not exit with a throw, goto, break, continue, or return; nor may it be entered with a goto. ### Catching C++ Class Objects On many platforms, catching C++ class objects is supported. Catching C++ objects and D objects cannot both be done in the same *TryStatement*. Upon exit from the *Catch*, any destructors for the C++ object will be run and the storage used for it reclaimed. C++ objects cannot be caught in `@safe` code. Asm Statement ------------- Inline assembler is supported with the asm statement: ``` AsmStatement: asm FunctionAttributesopt { AsmInstructionListopt } AsmInstructionList: AsmInstruction ; AsmInstruction ; AsmInstructionList ``` An asm statement enables the direct use of assembly language instructions. This makes it easy to obtain direct access to special CPU features without resorting to an external assembler. The D compiler will take care of the function calling conventions, stack setup, etc. The format of the instructions is, of course, highly dependent on the native instruction set of the target CPU, and so is [implementation defined](iasm). But, the format will follow the following conventions: * It must use the same tokens as the D language uses. * The comment form must match the D language comments. * Asm instructions are terminated by a ;, not by an end of line. These rules exist to ensure that D source code can be tokenized independently of syntactic or semantic analysis. For example, for the Intel Pentium: ``` int x = 3; asm { mov EAX,x; // load x and put it in register EAX } ``` Inline assembler can be used to access hardware directly: ``` int gethardware() { asm { mov EAX, dword ptr 0x1234; } } ``` For some D implementations, such as a translator from D to C, an inline assembler makes no sense, and need not be implemented. The version statement can be used to account for this: ``` version (D_InlineAsm_X86) { asm { ... } } else { /* ... some workaround ... */ } ``` Semantically consecutive *AsmStatement*s shall not have any other instructions (such as register save or restores) inserted between them by the compiler. Pragma Statement ---------------- ``` PragmaStatement ``` Mixin Statement --------------- ``` MixinStatement: mixin ( ArgumentList ) ; ``` Each [*AssignExpression*](expression#AssignExpression) in the *ArgumentList* is evaluated at compile time, and the result must be representable as a string. The resulting strings are concatenated to form a string. The text contents of the string must be compilable as a valid [*StatementList*](#StatementList), and is compiled as such. ``` import std.stdio; void main() { int j; mixin(" int x = 3; for (int i = 0; i < 3; i++) writeln(x + i, ++j); "); // ok string s = "int y;"; mixin(s); // ok y = 4; // ok, mixin declared y string t = "y = 3;"; mixin(t); // error, t is not evaluatable at compile time mixin("y =") 4; // error, string must be complete statement mixin("y =" ~ "4;"); // ok mixin("y =", 2+2, ";"); // ok } ```
programming_docs
d std.digest.ripemd std.digest.ripemd ================= Computes RIPEMD-160 hashes of arbitrary data. RIPEMD-160 hashes are 20 byte quantities that are like a checksum or CRC, but are more robust. | Category | Functions | | --- | --- | | Template API | [*RIPEMD160*](#RIPEMD160) | | OOP API | [*RIPEMD160Digest*](#RIPEMD160Digest) | | Helpers | [*ripemd160Of*](#ripemd160Of) | This module conforms to the APIs defined in [`std.digest`](std_digest). To understand the differences between the template and the OOP API, see [`std.digest`](std_digest). This module publicly imports `std.digest` and can be used as a stand-alone module. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). CTFE Digests do not work in CTFE Authors: Kai Nacke The algorithm was designed by Hans Dobbertin, Antoon Bosselaers, and Bart Preneel. The D implementation is a direct translation of the ANSI C implementation by Antoon Bosselaers. References * [The hash function RIPEMD-160](http://homes.esat.kuleuven.be/~bosselae/ripemd160.html) * [Wikipedia on RIPEMD-160](http://en.wikipedia.org/wiki/RIPEMD-160) Source [std/digest/ripemd.d](https://github.com/dlang/phobos/blob/master/std/digest/ripemd.d) Examples: ``` //Template API import std.digest.md; ubyte[20] hash = ripemd160Of("abc"); writeln(toHexString(hash)); // "8EB208F7E05D987A9B044A8E98C6B087F15A0BFC" //Feeding data ubyte[1024] data; RIPEMD160 md; md.start(); md.put(data[]); md.start(); //Start again md.put(data[]); hash = md.finish(); ``` Examples: ``` //OOP API import std.digest.md; auto md = new RIPEMD160Digest(); ubyte[] hash = md.digest("abc"); writeln(toHexString(hash)); // "8EB208F7E05D987A9B044A8E98C6B087F15A0BFC" //Feeding data ubyte[1024] data; md.put(data[]); md.reset(); //Start again md.put(data[]); hash = md.finish(); ``` struct **RIPEMD160**; Template API RIPEMD160 implementation. See `std.digest` for differences between template and OOP API. Examples: ``` //Simple example, hashing a string using ripemd160Of helper function ubyte[20] hash = ripemd160Of("abc"); //Let's get a hash string writeln(toHexString(hash)); // "8EB208F7E05D987A9B044A8E98C6B087F15A0BFC" ``` Examples: ``` //Using the basic API RIPEMD160 hash; hash.start(); ubyte[1024] data; //Initialize data here... hash.put(data); ubyte[20] result = hash.finish(); ``` Examples: ``` //Let's use the template features: void doSomething(T)(ref T hash) if (isDigest!T) { hash.put(cast(ubyte) 0); } RIPEMD160 md; md.start(); doSomething(md); writeln(toHexString(md.finish())); // "C81B94933420221A7AC004A90242D8B1D3E5070D" ``` Examples: ``` //Simple example RIPEMD160 hash; hash.start(); hash.put(cast(ubyte) 0); ubyte[20] result = hash.finish(); writeln(toHexString(result)); // "C81B94933420221A7AC004A90242D8B1D3E5070D" ``` pure nothrow @nogc @trusted void **put**(scope const(ubyte)[] data...); Use this to feed the digest with data. Also implements the [`std.range.primitives.isOutputRange`](std_range_primitives#isOutputRange) interface for `ubyte` and `const(ubyte)[]`. Example ``` RIPEMD160 dig; dig.put(cast(ubyte) 0); //single ubyte dig.put(cast(ubyte) 0, cast(ubyte) 0); //variadic ubyte[10] buf; dig.put(buf); //buffer ``` pure nothrow @nogc @safe void **start**(); Used to (re)initialize the RIPEMD160 digest. Note For this RIPEMD160 Digest implementation calling start after default construction is not necessary. Calling start is only necessary to reset the Digest. Generic code which deals with different Digest types should always call start though. Example ``` RIPEMD160 digest; //digest.start(); //Not necessary digest.put(0); ``` pure nothrow @nogc @trusted ubyte[20] **finish**(); Returns the finished RIPEMD160 hash. This also calls [`start`](#start) to reset the internal state. Example ``` //Simple example RIPEMD160 hash; hash.start(); hash.put(cast(ubyte) 0); ubyte[20] result = hash.finish(); assert(toHexString(result) == "C81B94933420221A7AC004A90242D8B1D3E5070D"); ``` auto **ripemd160Of**(T...)(T data); This is a convenience alias for [`std.digest.digest`](std_digest#digest) using the RIPEMD160 implementation. Examples: ``` ubyte[20] hash = ripemd160Of("abc"); writeln(hash); // digest!RIPEMD160("abc") ``` alias **RIPEMD160Digest** = std.digest.WrapperDigest!(RIPEMD160).WrapperDigest; OOP API RIPEMD160 implementation. See `std.digest` for differences between template and OOP API. This is an alias for `[std.digest.WrapperDigest](std_digest#WrapperDigest)!RIPEMD160`, see there for more information. Examples: ``` //Simple example, hashing a string using Digest.digest helper function auto md = new RIPEMD160Digest(); ubyte[] hash = md.digest("abc"); //Let's get a hash string writeln(toHexString(hash)); // "8EB208F7E05D987A9B044A8E98C6B087F15A0BFC" ``` Examples: ``` //Let's use the OOP features: void test(Digest dig) { dig.put(cast(ubyte) 0); } auto md = new RIPEMD160Digest(); test(md); //Let's use a custom buffer: ubyte[20] buf; ubyte[] result = md.finish(buf[]); writeln(toHexString(result)); // "C81B94933420221A7AC004A90242D8B1D3E5070D" ``` d etc.c.curl etc.c.curl ========== This is an interface to the libcurl library. Converted to D from curl headers by [htod](http://www.digitalmars.com/d/2.0/htod.html) and cleaned up by Jonas Drewsen (jdrewsen) Windows x86 note: A DMD compatible libcurl static library can be downloaded from the dlang.org [download page](http://dlang.org/download.html). Copyright (C) 1998 - 2010, Daniel Stenberg, <[email protected]>, et al. This software is licensed as described in the file COPYING, which you should have received as part of this distribution. The terms are also available at <http://curl.haxx.se/docs/copyright.html>. You may opt to use, copy, modify, merge, publish, distribute and/or sell copies of the Software, and permit persons to whom the Software is furnished to do so, under the terms of the COPYING file. This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. enum string **LIBCURL\_COPYRIGHT**; This is the global package copyright enum string **LIBCURL\_VERSION**; This is the version number of the libcurl package from which this header file origins: enum int **LIBCURL\_VERSION\_MAJOR**; enum int **LIBCURL\_VERSION\_MINOR**; enum int **LIBCURL\_VERSION\_PATCH**; The numeric version number is also available "in parts" by using these constants enum int **LIBCURL\_VERSION\_NUM**; This is the numeric version of the libcurl version number, meant for easier parsing and comparions by programs. The LIBCURL\_VERSION\_NUM define will always follow this syntax: 0xXXYYZZ Where XX, YY and ZZ are the main version, release and patch numbers in hexadecimal (using 8 bits each). All three numbers are always represented using two digits. 1.2 would appear as "0x010200" while version 9.11.7 appears as "0x090b07". This 6-digit (24 bits) hexadecimal number does not show pre-release number, and it is always a greater number in a more recent release. It makes comparisons with greater than and less than work. enum string **LIBCURL\_TIMESTAMP**; This is the date and time when the full source package was created. The timestamp is not stored in git, as the timestamp is properly set in the tarballs by the maketgz script. The format of the date should follow this template: "Mon Feb 12 11:35:33 UTC 2007" alias **curl\_off\_t** = long; Data type definition of curl\_off\_t. jdrewsen - Always 64bit signed and that is what long is in D. Comment below is from curlbuild.h: NOTE 2: For any given platform/compiler curl\_off\_t must be typedef'ed to a 64-bit wide signed integral data type. The width of this data type must remain constant and independent of any possible large file support settings. As an exception to the above, curl\_off\_t shall be typedef'ed to a 32-bit wide signed integral data type if there is no 64-bit type. alias **CURL** = void; alias **curl\_socket\_t** = std.socket.socket\_t; jdrewsen - Get socket alias from std.socket struct **curl\_httppost**; curl\_httppost\* **next**; next entry in the list char\* **name**; pointer to allocated name c\_long **namelength**; length of name length char\* **contents**; pointer to allocated data contents c\_long **contentslength**; length of contents field char\* **buffer**; pointer to allocated buffer contents c\_long **bufferlength**; length of buffer field char\* **contenttype**; Content-Type curl\_slist\* **contentheader**; list of extra headers for this form curl\_httppost\* **more**; if one field name has more than one file, this link should link to following files c\_long **flags**; as defined below char\* **showfilename**; The file name to show. If not set, the actual file name will be used (if this is a file part) void\* **userp**; custom pointer used for HTTPPOST\_CALLBACK posts enum int **HTTPPOST\_FILENAME**; specified content is a file name enum int **HTTPPOST\_READFILE**; specified content is a file name enum int **HTTPPOST\_PTRNAME**; name is only stored pointer do not free in formfree enum int **HTTPPOST\_PTRCONTENTS**; contents is only stored pointer do not free in formfree enum int **HTTPPOST\_BUFFER**; upload file from buffer enum int **HTTPPOST\_PTRBUFFER**; upload file from pointer contents enum int **HTTPPOST\_CALLBACK**; upload file contents by using the regular read callback to get the data and pass the given pointer as custom pointer alias **curl\_progress\_callback** = int function(void\* clientp, double dltotal, double dlnow, double ultotal, double ulnow); enum int **CURL\_MAX\_WRITE\_SIZE**; Tests have proven that 20K is a very bad buffer size for uploads on Windows, while 16K for some odd reason performed a lot better. We do the ifndef check to allow this value to easier be changed at build time for those who feel adventurous. The practical minimum is about 400 bytes since libcurl uses a buffer of this size as a scratch area (unrelated to network send operations). enum int **CURL\_MAX\_HTTP\_HEADER**; The only reason to have a max limit for this is to avoid the risk of a bad server feeding libcurl with a never-ending header that will cause reallocs infinitely enum int **CURL\_WRITEFUNC\_PAUSE**; This is a magic return code for the write callback that, when returned, will signal libcurl to pause receiving on the current transfer. alias **curl\_write\_callback** = ulong function(char\* buffer, ulong size, ulong nitems, void\* outstream); enum **CurlFileType**: int; enumeration of file types **file** **directory** **symlink** **device\_block** **device\_char** **namedpipe** **socket** **door** **unknown** is possible only on Sun Solaris now alias **curlfiletype** = int; enum **CurlFInfoFlagKnown**: int; **filename** **filetype** **time** **perm** **uid** **gid** **size** **hlinkcount** struct **\_N2**; Content of this structure depends on information which is known and is achievable (e.g. by FTP LIST parsing). Please see the url\_easy\_setopt(3) man page for callbacks returning this structure -- some fields are mandatory, some others are optional. The FLAG field has special meaning. If some of these fields is not NULL, it is a pointer to b\_data. char\* **time**; char\* **perm**; char\* **user**; char\* **group**; char\* **target**; pointer to the target filename of a symlink struct **curl\_fileinfo**; Content of this structure depends on information which is known and is achievable (e.g. by FTP LIST parsing). Please see the url\_easy\_setopt(3) man page for callbacks returning this structure -- some fields are mandatory, some others are optional. The FLAG field has special meaning. char\* **filename**; curlfiletype **filetype**; time\_t **time**; uint **perm**; int **uid**; int **gid**; curl\_off\_t **size**; c\_long **hardlinks**; \_N2 **strings**; uint **flags**; char\* **b\_data**; size\_t **b\_size**; size\_t **b\_used**; enum **CurlChunkBgnFunc**: int; return codes for CURLOPT\_CHUNK\_BGN\_FUNCTION **ok** **fail** tell the lib to end the task **skip** skip this chunk over alias **curl\_chunk\_bgn\_callback** = long function(const(void)\* transfer\_info, void\* ptr, int remains); if splitting of data transfer is enabled, this callback is called before download of an individual chunk started. Note that parameter "remains" works only for FTP wildcard downloading (for now), otherwise is not used enum **CurlChunkEndFunc**: int; return codes for CURLOPT\_CHUNK\_END\_FUNCTION **ok** **fail** alias **curl\_chunk\_end\_callback** = long function(void\* ptr); If splitting of data transfer is enabled this callback is called after download of an individual chunk finished. Note! After this callback was set then it have to be called FOR ALL chunks. Even if downloading of this chunk was skipped in CHUNK\_BGN\_FUNC. This is the reason why we don't need "transfer\_info" parameter in this callback and we are not interested in "remains" parameter too. enum **CurlFnMAtchFunc**: int; return codes for FNMATCHFUNCTION **match** **nomatch** **fail** alias **curl\_fnmatch\_callback** = int function(void\* ptr, in char\* pattern, in char\* string); callback type for wildcard downloading pattern matching. If the string matches the pattern, return CURL\_FNMATCHFUNC\_MATCH value, etc. enum **CurlSeekPos**: int; seek whence... **set** **current** **end** enum **CurlSeek**: int; These are the return codes for the seek callbacks **ok** **fail** fail the entire transfer **cantseek** tell libcurl seeking can't be done, so libcurl might try other means instead alias **curl\_seek\_callback** = int function(void\* instream, long offset, int origin); enum **CurlReadFunc**: int; **abort** This is a return code for the read callback that, when returned, will signal libcurl to immediately abort the current transfer. **pause** This is a return code for the read callback that, when returned, will const signal libcurl to pause sending data on the current transfer. alias **curl\_read\_callback** = ulong function(char\* buffer, ulong size, ulong nitems, void\* instream); enum **CurlSockType**: int; **ipcxn** socket created for a specific IP connection **last** never use alias **curlsocktype** = int; alias **curl\_sockopt\_callback** = int function(void\* clientp, socket\_t curlfd, int purpose); struct **curl\_sockaddr**; addrlen was a socklen\_t type before 7.18.0 but it turned really ugly and painful on the systems that lack this type int **family**; int **socktype**; int **protocol**; uint **addrlen**; addrlen was a socklen\_t type before 7.18.0 but it turned really ugly and painful on the systems that lack this type sockaddr **addr**; alias **curl\_opensocket\_callback** = socket\_t function(void\* clientp, int purpose, curl\_sockaddr\* address); enum **CurlIoError**: int; **ok** I/O operation successful **unknowncmd** command was unknown to callback **failrestart** failed to restart the read **last** never use alias **curlioerr** = int; enum **CurlIoCmd**: int; **nop** command was unknown to callback **restartread** failed to restart the read **last** never use alias **curliocmd** = int; alias **curl\_ioctl\_callback** = int function(void\* handle, int cmd, void\* clientp); alias **curl\_malloc\_callback** = void\* function(ulong size); alias **curl\_free\_callback** = void function(void\* ptr); alias **curl\_realloc\_callback** = void\* function(void\* ptr, ulong size); alias **curl\_strdup\_callback** = char\* function(in char\* str); alias **curl\_calloc\_callback** = void\* function(ulong nmemb, ulong size); The following typedef's are signatures of malloc, free, realloc, strdup and calloc respectively. Function pointers of these types can be passed to the curl\_global\_init\_mem() function to set user defined memory management callback routines. enum **CurlCallbackInfo**: int; the kind of data that is passed to information\_callback **text** **header\_in** **header\_out** **data\_in** **data\_out** **ssl\_data\_in** **ssl\_data\_out** **end** alias **curl\_infotype** = int; alias **curl\_debug\_callback** = int function(void\* handle, int type, char\* data, ulong size, void\* userptr); enum **CurlError**: int; All possible error codes from all sorts of curl functions. Future versions may return other values, stay prepared. Always add new return codes last. Never *EVER* remove any. The return codes must remain the same! **ok** **unsupported\_protocol** 1 **failed\_init** 2 **url\_malformat** 3 **not\_built\_in** 4 - [was obsoleted in August 2007 for 7.17.0, reused in April 2011 for 7.21.5] **couldnt\_resolve\_proxy** 5 **couldnt\_resolve\_host** 6 **couldnt\_connect** 7 **ftp\_weird\_server\_reply** 8 **remote\_access\_denied** 9 a service was denied by the server due to lack of access - when login fails this is not returned. **obsolete10** 10 - NOT USED **ftp\_weird\_pass\_reply** 11 **obsolete12** 12 - NOT USED **ftp\_weird\_pasv\_reply** 13 **ftp\_weird\_227\_format** 14 **ftp\_cant\_get\_host** 15 **obsolete16** 16 - NOT USED **ftp\_couldnt\_set\_type** 17 **partial\_file** 18 **ftp\_couldnt\_retr\_file** 19 **obsolete20** 20 - NOT USED **quote\_error** 21 - quote command failure **http\_returned\_error** 22 **write\_error** 23 **obsolete24** 24 - NOT USED **upload\_failed** 25 - failed upload "command" **read\_error** 26 - couldn't open/read from file **out\_of\_memory** 27 **operation\_timedout** Note CURLE\_OUT\_OF\_MEMORY may sometimes indicate a conversion error instead of a memory allocation error if CURL\_DOES\_CONVERSIONS is defined 28 - the timeout time was reached **obsolete29** 29 - NOT USED **ftp\_port\_failed** 30 - FTP PORT operation failed **ftp\_couldnt\_use\_rest** 31 - the REST command failed **obsolete32** 32 - NOT USED **range\_error** 33 - RANGE "command" didn't work **http\_post\_error** 34 **ssl\_connect\_error** 35 - wrong when connecting with SSL **bad\_download\_resume** 36 - couldn't resume download **file\_couldnt\_read\_file** 37 **ldap\_cannot\_bind** 38 **ldap\_search\_failed** 39 **obsolete40** 40 - NOT USED **function\_not\_found** 41 **aborted\_by\_callback** 42 **bad\_function\_argument** 43 **obsolete44** 44 - NOT USED **interface\_failed** 45 - CURLOPT\_INTERFACE failed **obsolete46** 46 - NOT USED **too\_many\_redirects** 47 - catch endless re-direct loops **unknown\_option** 48 - User specified an unknown option **telnet\_option\_syntax** 49 - Malformed telnet option **obsolete50** 50 - NOT USED **peer\_failed\_verification** 51 - peer's certificate or fingerprint wasn't verified fine **got\_nothing** 52 - when this is a specific error **ssl\_engine\_notfound** 53 - SSL crypto engine not found **ssl\_engine\_setfailed** 54 - can not set SSL crypto engine as default **send\_error** 55 - failed sending network data **recv\_error** 56 - failure in receiving network data **obsolete57** 57 - NOT IN USE **ssl\_certproblem** 58 - problem with the local certificate **ssl\_cipher** 59 - couldn't use specified cipher **ssl\_cacert** 60 - problem with the CA cert (path?) **bad\_content\_encoding** 61 - Unrecognized transfer encoding **ldap\_invalid\_url** 62 - Invalid LDAP URL **filesize\_exceeded** 63 - Maximum file size exceeded **use\_ssl\_failed** 64 - Requested FTP SSL level failed **send\_fail\_rewind** 65 - Sending the data requires a rewind that failed **ssl\_engine\_initfailed** 66 - failed to initialise ENGINE **login\_denied** 67 - user, password or similar was not accepted and we failed to login **tftp\_notfound** 68 - file not found on server **tftp\_perm** 69 - permission problem on server **remote\_disk\_full** 70 - out of disk space on server **tftp\_illegal** 71 - Illegal TFTP operation **tftp\_unknownid** 72 - Unknown transfer ID **remote\_file\_exists** 73 - File already exists **tftp\_nosuchuser** 74 - No such user **conv\_failed** 75 - conversion failed **conv\_reqd** 76 - caller must register conversion callbacks using curl\_easy\_setopt options CURLOPT\_CONV\_FROM\_NETWORK\_FUNCTION, CURLOPT\_CONV\_TO\_NETWORK\_FUNCTION, and CURLOPT\_CONV\_FROM\_UTF8\_FUNCTION **ssl\_cacert\_badfile** 77 - could not load CACERT file, missing or wrong format **remote\_file\_not\_found** 78 - remote file not found **ssh** 79 - error from the SSH layer, somewhat generic so the error message will be of interest when this has happened **ssl\_shutdown\_failed** 80 - Failed to shut down the SSL connection **again** 81 - socket is not ready for send/recv, wait till it's ready and try again (Added in 7.18.2) **ssl\_crl\_badfile** 82 - could not load CRL file, missing or wrong format (Added in 7.19.0) **ssl\_issuer\_error** 83 - Issuer check failed. (Added in 7.19.0) **ftp\_pret\_failed** 84 - a PRET command failed **rtsp\_cseq\_error** 85 - mismatch of RTSP CSeq numbers **rtsp\_session\_error** 86 - mismatch of RTSP Session Identifiers **ftp\_bad\_file\_list** 87 - unable to parse FTP file list **chunk\_failed** 88 - chunk callback reported error **curl\_last** never use! alias **CURLcode** = int; alias **curl\_conv\_callback** = int function(char\* buffer, ulong length); This prototype applies to all conversion callbacks alias **curl\_ssl\_ctx\_callback** = int function(void\* curl, void\* ssl\_ctx, void\* userptr); actually an OpenSSL SSL\_CTX enum **CurlProxy**: int; **http** added in 7.10, new in 7.19.4 default is to use CONNECT HTTP/1.1 **http\_1\_0** added in 7.19.4, force to use CONNECT HTTP/1.0 **socks4** support added in 7.15.2, enum existed already in 7.10 **socks5** added in 7.10 **socks4a** added in 7.18.0 **socks5\_hostname** Use the SOCKS5 protocol but pass along the host name rather than the IP address. added in 7.18.0 alias **curl\_proxytype** = int; enum **CurlAuth**: long; **basic** Basic (default) **digest** Digest **gssnegotiate** GSS-Negotiate **ntlm** NTLM **digest\_ie** Digest with IE flavour **only** used together with a single other type to force no auth or just that single type **any** all fine types set **anysafe** enum **CurlSshAuth**: int; **any** all types supported by the server **none** none allowed, silly but complete **publickey** public/private key files **password** password **host** host key files **keyboard** keyboard interactive enum int **CURL\_ERROR\_SIZE**; enum **CurlKHType**: int; points to a zero-terminated string encoded with base64 if len is zero, otherwise to the "raw" data **unknown** **rsa1** **rsa** **dss** struct **curl\_khkey**; const(char)\* **key**; points to a zero-terminated string encoded with base64 if len is zero, otherwise to the "raw" data size\_t **len**; CurlKHType **keytype**; enum **CurlKHStat**: int; this is the set of return values expected from the curl\_sshkeycallback callback **fine\_add\_to\_file** **fine** **reject** reject the connection, return an error **defer** do not accept it, but we can't answer right now so this causes a CURLE\_DEFER error but otherwise the connection will be left intact etc **last** not for use, only a marker for last-in-list enum **CurlKHMatch**: int; this is the set of status codes pass in to the callback **ok** match **mismatch** host found, key mismatch! **missing** no matching host/key found **last** not for use, only a marker for last-in-list alias **curl\_sshkeycallback** = int function(void\* easy, const(curl\_khkey)\* knownkey, const(curl\_khkey)\* foundkey, CurlKHMatch m, void\* clientp); enum **CurlUseSSL**: int; parameter for the CURLOPT\_USE\_SSL option **none** do not attempt to use SSL **tryssl** try using SSL, proceed anyway otherwise **control** SSL for the control connection or fail **all** SSL for all communication or fail **last** not an option, never use alias **curl\_usessl** = int; enum **CurlFtpSSL**: int; parameter for the CURLOPT\_FTP\_SSL\_CCC option **ccc\_none** do not send CCC **ccc\_passive** Let the server initiate the shutdown **ccc\_active** Initiate the shutdown **ccc\_last** not an option, never use alias **curl\_ftpccc** = int; enum **CurlFtpAuth**: int; parameter for the CURLOPT\_FTPSSLAUTH option **defaultauth** let libcurl decide **ssl** use "AUTH SSL" **tls** use "AUTH TLS" **last** not an option, never use alias **curl\_ftpauth** = int; enum **CurlFtp**: int; parameter for the CURLOPT\_FTP\_CREATE\_MISSING\_DIRS option **create\_dir\_none** do NOT create missing dirs! **create\_dir** (FTP/SFTP) if CWD fails, try MKD and then CWD again if MKD succeeded, for SFTP this does similar magic **create\_dir\_retry** (FTP only) if CWD fails, try MKD and then CWD again even if MKD failed! **create\_dir\_last** not an option, never use alias **curl\_ftpcreatedir** = int; enum **CurlFtpMethod**: int; parameter for the CURLOPT\_FTP\_FILEMETHOD option **defaultmethod** let libcurl pick **multicwd** single CWD operation for each path part **nocwd** no CWD at all **singlecwd** one CWD to full dir, then work on file **last** not an option, never use alias **curl\_ftpmethod** = int; enum **CurlProto**: int; CURLPROTO\_ defines are for the CURLOPT\_\*PROTOCOLS options **http** **https** **ftp** **ftps** **scp** **sftp** **telnet** **ldap** **ldaps** **dict** **file** **tftp** **imap** **imaps** **pop3** **pop3s** **smtp** **smtps** **rtsp** **rtmp** **rtmpt** **rtmpe** **rtmpte** **rtmps** **rtmpts** **gopher** **all** enable everything enum int **CURLOPTTYPE\_LONG**; enum int **CURLOPTTYPE\_OBJECTPOINT**; enum int **CURLOPTTYPE\_FUNCTIONPOINT**; enum int **CURLOPTTYPE\_OFF\_T**; long may be 32 or 64 bits, but we should never depend on anything else but 32 alias **LONG** = CURLOPTTYPE\_LONG; alias **OBJECTPOINT** = CURLOPTTYPE\_OBJECTPOINT; alias **FUNCTIONPOINT** = CURLOPTTYPE\_FUNCTIONPOINT; alias **OFF\_T** = CURLOPTTYPE\_OFF\_T; name is uppercase CURLOPT\_<name>, type is one of the defined CURLOPTTYPE\_<type> number is unique identifier The macro "##" is ISO C, we assume pre-ISO C doesn't support it. enum **CurlOption**: int; **file** This is the FILE \* or void \* the regular output should be written to. **url** The full URL to get/put **port** Port number to connect to, if other than default. **proxy** Name of proxy to use. **userpwd** "name:password" to use when fetching. **proxyuserpwd** "name:password" to use with proxy. **range** Range to get, specified as an ASCII string. **infile** not used Specified file stream to upload from (use as input): **errorbuffer** Buffer to receive error messages in, must be at least CURL\_ERROR\_SIZE bytes big. If this is not used, error messages go to stderr instead: **writefunction** Function that will be called to store the output (instead of fwrite). The parameters will use fwrite() syntax, make sure to follow them. **readfunction** Function that will be called to read the input (instead of fread). The parameters will use fread() syntax, make sure to follow them. **timeout** Time-out the read operation after this amount of seconds **infilesize** If the CURLOPT\_INFILE is used, this can be used to inform libcurl about how large the file being sent really is. That allows better error checking and better verifies that the upload was successful. -1 means unknown size. For large file support, there is also a LARGE version of the key which takes an off\_t type, allowing platforms with larger off\_t sizes to handle larger files. See below for INFILESIZE\_LARGE. **postfields** POST static input fields. **referer** Set the referrer page (needed by some CGIs) **ftpport** Set the FTP PORT string (interface name, named or numerical IP address) Use i.e '-' to use default address. **useragent** Set the User-Agent string (examined by some CGIs) **low\_speed\_limit** If the download receives less than "low speed limit" bytes/second during "low speed time" seconds, the operations is aborted. You could i.e if you have a pretty high speed connection, abort if it is less than 2000 bytes/sec during 20 seconds. Set the "low speed limit" **low\_speed\_time** Set the "low speed time" **resume\_from** Set the continuation offset. Note there is also a LARGE version of this key which uses off\_t types, allowing for large file offsets on platforms which use larger-than-32-bit off\_t's. Look below for RESUME\_FROM\_LARGE. **cookie** Set cookie in request: **httpheader** This points to a linked list of headers, struct curl\_slist kind **httppost** This points to a linked list of post entries, struct curl\_httppost **sslcert** name of the file keeping your private SSL-certificate **keypasswd** password for the SSL or SSH private key **crlf** send TYPE parameter? **quote** send linked-list of QUOTE commands **writeheader** send FILE \* or void \* to store headers to, if you use a callback it is simply passed to the callback unmodified **cookiefile** point to a file to read the initial cookies from, also enables "cookie awareness" **sslversion** What version to specifically try to use. See CURL\_SSLVERSION defines below. **timecondition** What kind of HTTP time condition to use, see defines **timevalue** Time to use with the above condition. Specified in number of seconds since 1 Jan 1970 **customrequest** Custom request, for customizing the get command like HTTP DELETE, TRACE and others FTP to use a different list command **stderr** HTTP request, for odd commands like DELETE, TRACE and others **postquote** send linked-list of post-transfer QUOTE commands **writeinfo** Pass a pointer to string of the output using full variable-replacement as described elsewhere. **verbose** talk a lot **header** throw the header out too **noprogress** shut off the progress meter **nobody** use HEAD to get http document **failonerror** no output on http error codes >= 300 **upload** this is an upload **post** HTTP POST method **dirlistonly** return bare names when listing directories **append** Append instead of overwrite on upload! **netrc** Specify whether to read the user+password from the .netrc or the URL. This must be one of the CURL\_NETRC\_\* enums below. **followlocation** use Location: Luke! **transfertext** transfer data in text/ASCII format **put** HTTP PUT **progressfunction** Function that will be called instead of the internal progress display function. This function should be defined as the curl\_progress\_callback prototype defines. **progressdata** Data passed to the progress callback **autoreferer** We want the referrer field set automatically when following locations **proxyport** Port of the proxy, can be set in the proxy string as well with: `[host]:[port]` **postfieldsize** size of the POST input data, if strlen() is not good to use **httpproxytunnel** tunnel non-http operations through a HTTP proxy **intrface** Set the interface string to use as outgoing network interface **krblevel** Set the krb4/5 security level, this also enables krb4/5 awareness. This is a string, 'clear', 'safe', 'confidential' or 'private'. If the string is set but doesn't match one of these, 'private' will be used. **ssl\_verifypeer** Set if we should verify the peer in ssl handshake, set 1 to verify. **cainfo** The CApath or CAfile used to validate the peer certificate this option is used only if SSL\_VERIFYPEER is true **maxredirs** Maximum number of http redirects to follow **filetime** Pass a long set to 1 to get the date of the requested document (if possible)! Pass a zero to shut it off. **telnetoptions** This points to a linked list of telnet options **maxconnects** Max amount of cached alive connections **closepolicy** What policy to use when closing connections when the cache is filled up **fresh\_connect** Set to explicitly use a new connection for the upcoming transfer. Do not use this unless you're absolutely sure of this, as it makes the operation slower and is less friendly for the network. **forbid\_reuse** Set to explicitly forbid the upcoming transfer's connection to be re-used when done. Do not use this unless you're absolutely sure of this, as it makes the operation slower and is less friendly for the network. **random\_file** Set to a file name that contains random data for libcurl to use to seed the random engine when doing SSL connects. **egdsocket** Set to the Entropy Gathering Daemon socket pathname **connecttimeout** Time-out connect operations after this amount of seconds, if connects are OK within this time, then fine... This only aborts the connect phase. [Only works on unix-style/SIGALRM operating systems] **headerfunction** Function that will be called to store headers (instead of fwrite). The parameters will use fwrite() syntax, make sure to follow them. **httpget** Set this to force the HTTP request to get back to GET. Only really usable if POST, PUT or a custom request have been used first. **ssl\_verifyhost** Set if we should verify the Common name from the peer certificate in ssl handshake, set 1 to check existence, 2 to ensure that it matches the provided hostname. **cookiejar** Specify which file name to write all known cookies in after completed operation. Set file name to "-" (dash) to make it go to stdout. **ssl\_cipher\_list** Specify which SSL ciphers to use **http\_version** Specify which HTTP version to use! This must be set to one of the CURL\_HTTP\_VERSION\* enums set below. **ftp\_use\_epsv** Specifically switch on or off the FTP engine's use of the EPSV command. By default, that one will always be attempted before the more traditional PASV command. **sslcerttype** type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") **sslkey** name of the file keeping your private SSL-key **sslkeytype** type of the file keeping your private SSL-key ("DER", "PEM", "ENG") **sslengine** crypto engine for the SSL-sub system **sslengine\_default** set the crypto engine for the SSL-sub system as default the param has no meaning... **dns\_use\_global\_cache** Non-zero value means to use the global dns cache **dns\_cache\_timeout** DNS cache timeout **prequote** send linked-list of pre-transfer QUOTE commands **debugfunction** set the debug function **debugdata** set the data for the debug function **cookiesession** mark this as start of a cookie session **capath** The CApath directory used to validate the peer certificate this option is used only if SSL\_VERIFYPEER is true **buffersize** Instruct libcurl to use a smaller receive buffer **nosignal** Instruct libcurl to not use any signal/alarm handlers, even when using timeouts. This option is useful for multi-threaded applications. See libcurl-the-guide for more background information. **share** Provide a CURLShare for mutexing non-ts data **proxytype** indicates type of proxy. accepted values are CURLPROXY\_HTTP (default), CURLPROXY\_SOCKS4, CURLPROXY\_SOCKS4A and CURLPROXY\_SOCKS5. **encoding** Set the Accept-Encoding string. Use this to tell a server you would like the response to be compressed. **private\_opt** Set pointer to private data **http200aliases** Set aliases for HTTP 200 in the HTTP Response header **unrestricted\_auth** Continue to send authentication (user+password) when following locations, even when hostname changed. This can potentially send off the name and password to whatever host the server decides. **ftp\_use\_eprt** Specifically switch on or off the FTP engine's use of the EPRT command ( it also disables the LPRT attempt). By default, those ones will always be attempted before the good old traditional PORT command. **httpauth** Set this to a bitmask value to enable the particular authentications methods you like. Use this in combination with CURLOPT\_USERPWD. Note that setting multiple bits may cause extra network round-trips. **ssl\_ctx\_function** Set the ssl context callback function, currently only for OpenSSL ssl\_ctx in second argument. The function must be matching the curl\_ssl\_ctx\_callback proto. **ssl\_ctx\_data** Set the userdata for the ssl context callback function's third argument **ftp\_create\_missing\_dirs** FTP Option that causes missing dirs to be created on the remote server. In 7.19.4 we introduced the convenience enums for this option using the CURLFTP\_CREATE\_DIR prefix. **proxyauth** Set this to a bitmask value to enable the particular authentications methods you like. Use this in combination with CURLOPT\_PROXYUSERPWD. Note that setting multiple bits may cause extra network round-trips. **ftp\_response\_timeout** FTP option that changes the timeout, in seconds, associated with getting a response. This is different from transfer timeout time and essentially places a demand on the FTP server to acknowledge commands in a timely manner. **ipresolve** Set this option to one of the CURL\_IPRESOLVE\_\* defines (see below) to tell libcurl to resolve names to those IP versions only. This only has affect on systems with support for more than one, i.e IPv4 and\_ IPv6. **maxfilesize** Set this option to limit the size of a file that will be downloaded from an HTTP or FTP server. Note there is also LARGE version which adds large file support for platforms which have larger off\_t sizes. See MAXFILESIZE\_LARGE below. **infilesize\_large** See the comment for INFILESIZE above, but in short, specifies the size of the file being uploaded. -1 means unknown. **resume\_from\_large** Sets the continuation offset. There is also a LONG version of this; look above for RESUME\_FROM. **maxfilesize\_large** Sets the maximum size of data that will be downloaded from an HTTP or FTP server. See MAXFILESIZE above for the LONG version. **netrc\_file** Set this option to the file name of your .netrc file you want libcurl to parse (using the CURLOPT\_NETRC option). If not set, libcurl will do a poor attempt to find the user's home directory and check for a .netrc file in there. **use\_ssl** Enable SSL/TLS for FTP, pick one of: CURLFTPSSL\_TRY - try using SSL, proceed anyway otherwise CURLFTPSSL\_CONTROL - SSL for the control connection or fail CURLFTPSSL\_ALL - SSL for all communication or fail **postfieldsize\_large** The LARGE version of the standard POSTFIELDSIZE option **tcp\_nodelay** Enable/disable the TCP Nagle algorithm **ftpsslauth** When FTP over SSL/TLS is selected (with CURLOPT\_USE\_SSL), this option can be used to change libcurl's default action which is to first try "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK response has been received. Available parameters are: CURLFTPAUTH\_DEFAULT - let libcurl decide CURLFTPAUTH\_SSL - try "AUTH SSL" first, then TLS CURLFTPAUTH\_TLS - try "AUTH TLS" first, then SSL **ioctlfunction** **ioctldata** **ftp\_account** zero terminated string for pass on to the FTP server when asked for "account" info **cookielist** feed cookies into cookie engine **ignore\_content\_length** ignore Content-Length **ftp\_skip\_pasv\_ip** Set to non-zero to skip the IP address received in a 227 PASV FTP server response. Typically used for FTP-SSL purposes but is not restricted to that. libcurl will then instead use the same IP address it used for the control connection. **ftp\_filemethod** Select "file method" to use when doing FTP, see the curl\_ftpmethod above. **localport** Local port number to bind the socket to **localportrange** Number of ports to try, including the first one set with LOCALPORT. Thus, setting it to 1 will make no additional attempts but the first. **connect\_only** no transfer, set up connection and let application use the socket by extracting it with CURLINFO\_LASTSOCKET **conv\_from\_network\_function** Function that will be called to convert from the network encoding (instead of using the iconv calls in libcurl) **conv\_to\_network\_function** Function that will be called to convert to the network encoding (instead of using the iconv calls in libcurl) **conv\_from\_utf8\_function** Function that will be called to convert from UTF8 (instead of using the iconv calls in libcurl) Note that this is used only for SSL certificate processing **max\_send\_speed\_large** **max\_recv\_speed\_large** If the connection proceeds too quickly then need to slow it down limit-rate: maximum number of bytes per second to send or receive **ftp\_alternative\_to\_user** Pointer to command string to send if USER/PASS fails. **sockoptfunction** callback function for setting socket options **ssl\_sessionid\_cache** set to 0 to disable session ID re-use for this transfer, default is enabled (== 1) **ssh\_auth\_types** allowed SSH authentication methods **ssh\_public\_keyfile** Used by scp/sftp to do public/private key authentication **ftp\_ssl\_ccc** Send CCC (Clear Command Channel) after authentication **timeout\_ms** **connecttimeout\_ms** Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution **http\_transfer\_decoding** **http\_content\_decoding** set to zero to disable the libcurl's decoding and thus pass the raw body data to the application even when it is encoded/compressed **new\_file\_perms** **new\_directory\_perms** Permission used when creating new files and directories on the remote server for protocols that support it, SFTP/SCP/FILE **postredir** Set the behaviour of POST when redirecting. Values must be set to one of CURL\_REDIR\* defines below. This used to be called CURLOPT\_POST301 **ssh\_host\_public\_key\_md5** used by scp/sftp to verify the host's public key **opensocketfunction** **opensocketdata** Callback function for opening socket (instead of socket(2)). Optionally, callback is able change the address or refuse to connect returning CURL\_SOCKET\_BAD. The callback should have type curl\_opensocket\_callback **copypostfields** POST volatile input fields. **proxy\_transfer\_mode** set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy **seekfunction** **seekdata** Callback function for seeking in the input stream **crlfile** CRL file **issuercert** Issuer certificate **address\_scope** (IPv6) Address scope **certinfo** Collect certificate chain info and allow it to get retrievable with CURLINFO\_CERTINFO after the transfer is complete. (Unfortunately) only working with OpenSSL-powered builds. **username** **password** "name" and "pwd" to use when fetching. **proxyusername** **proxypassword** "name" and "pwd" to use with Proxy when fetching. **noproxy** Comma separated list of hostnames defining no-proxy zones. These should match both hostnames directly, and hostnames within a domain. For example, local.com will match local.com and www.local.com, but NOT notlocal.com or www.notlocal.com. For compatibility with other implementations of this, .local.com will be considered to be the same as local.com. A single \* is the only valid wildcard, and effectively disables the use of proxy. **tftp\_blksize** block size for TFTP transfers **socks5\_gssapi\_service** Socks Service **socks5\_gssapi\_nec** Socks Service **protocols** set the bitmask for the protocols that are allowed to be used for the transfer, which thus helps the app which takes URLs from users or other external inputs and want to restrict what protocol(s) to deal with. Defaults to CURLPROTO\_ALL. **redir\_protocols** set the bitmask for the protocols that libcurl is allowed to follow to, as a subset of the CURLOPT\_PROTOCOLS ones. That means the protocol needs to be set in both bitmasks to be allowed to get redirected to. Defaults to all protocols except FILE and SCP. **ssh\_knownhosts** set the SSH knownhost file name to use **ssh\_keyfunction** set the SSH host key callback, must point to a curl\_sshkeycallback function **ssh\_keydata** set the SSH host key callback custom pointer **mail\_from** set the SMTP mail originator **mail\_rcpt** set the SMTP mail receiver(s) **ftp\_use\_pret** FTP send PRET before PASV **rtsp\_request** RTSP request method (OPTIONS, SETUP, PLAY, etc...) **rtsp\_session\_id** The RTSP session identifier **rtsp\_stream\_uri** The RTSP stream URI **rtsp\_transport** The Transport: header to use in RTSP requests **rtsp\_client\_cseq** Manually initialize the client RTSP CSeq for this handle **rtsp\_server\_cseq** Manually initialize the server RTSP CSeq for this handle **interleavedata** The stream to pass to INTERLEAVEFUNCTION. **interleavefunction** Let the application define a custom write method for RTP data **wildcardmatch** Turn on wildcard matching **chunk\_bgn\_function** Directory matching callback called before downloading of an individual file (chunk) started **chunk\_end\_function** Directory matching callback called after the file (chunk) was downloaded, or skipped **fnmatch\_function** Change match (fnmatch-like) callback for wildcard matching **chunk\_data** Let the application define custom chunk data pointer **fnmatch\_data** FNMATCH\_FUNCTION user pointer **resolve** send linked-list of name:port:address sets **tlsauth\_username** Set a username for authenticated TLS **tlsauth\_password** Set a password for authenticated TLS **tlsauth\_type** Set authentication type for authenticated TLS **lastentry** the last unused **writedata** **readdata** **headerdata** **rtspheader** convenient alias alias **CURLoption** = int; enum CurlOption **CURLOPT\_SERVER\_RESPONSE\_TIMEOUT**; enum **CurlIpResolve**: int; Below here follows defines for the CURLOPT\_IPRESOLVE option. If a host name resolves addresses using more than one IP protocol version, this option might be handy to force libcurl to use a specific IP version. **whatever** default, resolves addresses to all IP versions that your system allows **v4** resolve to ipv4 addresses **v6** resolve to ipv6 addresses enum CurlOption **CURLOPT\_WRITEDATA**; enum CurlOption **CURLOPT\_READDATA**; enum CurlOption **CURLOPT\_HEADERDATA**; enum CurlOption **CURLOPT\_RTSPHEADER**; three convenient "aliases" that follow the name scheme better enum **CurlHttpVersion**: int; These enums are for use with the CURLOPT\_HTTP\_VERSION option. **none** setting this means we don't care, and that we'd like the library to choose the best possible for us! **v1\_0** please use HTTP 1.0 in the request **v1\_1** please use HTTP 1.1 in the request **last** *ILLEGAL* http version enum **CurlRtspReq**: int; Public API enums for RTSP requests **none** **options** **describe** **announce** **setup** **play** **pause** **teardown** **get\_parameter** **set\_parameter** **record** **receive** **last** enum **CurlNetRcOption**: int; These enums are for use with the CURLOPT\_NETRC option. **ignored** The .netrc will never be read. This is the default. **optional** A user:password in the URL will be preferred to one in the .netrc. **required** A user:password in the URL will be ignored. Unless one is set programmatically, the .netrc will be queried. **last** enum **CurlSslVersion**: int; **default\_version** **tlsv1** **sslv2** **sslv3** **last** never use enum **CurlTlsAuth**: int; **none** **srp** **last** never use enum **CurlRedir**: int; symbols to use with CURLOPT\_POSTREDIR. CURL\_REDIR\_POST\_301 and CURL\_REDIR\_POST\_302 can be bitwise ORed so that CURL\_REDIR\_POST\_301 | CURL\_REDIR\_POST\_302 == CURL\_REDIR\_POST\_ALL **get\_all** **post\_301** **post\_302** **post\_all** enum **CurlTimeCond**: int; **none** **ifmodsince** **ifunmodsince** **lastmod** **last** alias **curl\_TimeCond** = int; int **curl\_strequal**(in const(char)\* s1, in const(char)\* s2); curl\_strequal() and curl\_strnequal() are subject for removal in a future libcurl, see lib/README.curlx for details int **curl\_strnequal**(in const(char)\* s1, in const(char)\* s2, size\_t n); ditto curl\_strequal() and curl\_strnequal() are subject for removal in a future libcurl, see lib/README.curlx for details struct **curl\_forms**; structure to be used as parameter for CURLFORM\_ARRAY CURLformoption **option**; const(char)\* **value**; enum **CurlFormAdd**: int; Use this for multipart formpost building Returns code for curl\_formadd() Returns: * CURL\_FORMADD\_OK on success * CURL\_FORMADD\_MEMORY if the FormInfo allocation fails * CURL\_FORMADD\_OPTION\_TWICE if one option is given twice for one Form * CURL\_FORMADD\_NULL if a null pointer was given for a char * CURL\_FORMADD\_MEMORY if the allocation of a FormInfo struct failed * CURL\_FORMADD\_UNKNOWN\_OPTION if an unknown option was used * CURL\_FORMADD\_INCOMPLETE if the some FormInfo is not complete (or error) * CURL\_FORMADD\_MEMORY if a curl\_httppost struct cannot be allocated * CURL\_FORMADD\_MEMORY if some allocation for string copying failed. * CURL\_FORMADD\_ILLEGAL\_ARRAY if an illegal option is used in an array **ok** first, no error **memory** **option\_twice** **null\_ptr** **unknown\_option** **incomplete** **illegal\_array** **disabled** libcurl was built with this disabled **last** alias **CURLFORMcode** = int; CURLFORMcode **curl\_formadd**(curl\_httppost\*\* httppost, curl\_httppost\*\* last\_post, ...); Name curl\_formadd() Description Pretty advanced function for building multi-part formposts. Each invoke adds one part that together construct a full post. Then use CURLOPT\_HTTPPOST to send it off to libcurl. alias **curl\_formget\_callback** = extern (C) ulong function(void\* arg, in char\* buf, ulong len); callback function for curl\_formget() The void \*arg pointer will be the one passed as second argument to curl\_formget(). The character buffer passed to it must not be freed. Should return the buffer length passed to it as the argument "len" on success. int **curl\_formget**(curl\_httppost\* form, void\* arg, curl\_formget\_callback append); Name curl\_formget() Description Serialize a curl\_httppost struct built with curl\_formadd(). Accepts a void pointer as second argument which will be passed to the curl\_formget\_callback function. Returns 0 on success. void **curl\_formfree**(curl\_httppost\* form); Name curl\_formfree() Description Free a multipart formpost previously built with curl\_formadd(). char\* **curl\_getenv**(in const(char)\* variable); Name curl\_getenv() Description Returns a malloc()'ed string that MUST be curl\_free()ed after usage is complete. DEPRECATED - see lib/README.curlx char\* **curl\_version**(); Name curl\_version() Description Returns a static ascii string of the libcurl version. char\* **curl\_easy\_escape**(CURL\* handle, in const(char)\* string, int length); Name curl\_easy\_escape() Description Escapes URL strings (converts all letters consider illegal in URLs to their %XX versions). This function returns a new allocated string or NULL if an error occurred. char\* **curl\_escape**(in const(char)\* string, int length); the previous version: char\* **curl\_easy\_unescape**(CURL\* handle, in const(char)\* string, int length, int\* outlength); Name curl\_easy\_unescape() Description Unescapes URL encoding in strings (converts all %XX codes to their 8bit versions). This function returns a new allocated string or NULL if an error occurred. Conversion Note: On non-ASCII platforms the ASCII %XX codes are converted into the host encoding. char\* **curl\_unescape**(in const(char)\* string, int length); the previous version void **curl\_free**(void\* p); Name curl\_free() Description Provided for de-allocation in the same translation unit that did the allocation. Added in libcurl 7.10 CURLcode **curl\_global\_init**(c\_long flags); Name curl\_global\_init() Description curl\_global\_init() should be invoked exactly once for each application that uses libcurl and before any call of other libcurl functions. This function is not thread-safe! CURLcode **curl\_global\_init\_mem**(c\_long flags, curl\_malloc\_callback m, curl\_free\_callback f, curl\_realloc\_callback r, curl\_strdup\_callback s, curl\_calloc\_callback c); Name curl\_global\_init\_mem() Description curl\_global\_init() or curl\_global\_init\_mem() should be invoked exactly once for each application that uses libcurl. This function can be used to initialize libcurl and set user defined memory management callback functions. Users can implement memory management routines to check for memory leaks, check for mis-use of the curl library etc. User registered callback routines with be invoked by this library instead of the system memory management routines like malloc, free etc. void **curl\_global\_cleanup**(); Name curl\_global\_cleanup() Description curl\_global\_cleanup() should be invoked exactly once for each application that uses libcurl struct **curl\_slist**; linked-list structure for the CURLOPT\_QUOTE option (and other) curl\_slist\* **curl\_slist\_append**(curl\_slist\*, in const(char)\*); Name curl\_slist\_append() Description Appends a string to a linked list. If no list exists, it will be created first. Returns the new list, after appending. linked-list structure for the CURLOPT\_QUOTE option (and other) void **curl\_slist\_free\_all**(curl\_slist\*); Name curl\_slist\_free\_all() Description free a previously built curl\_slist. linked-list structure for the CURLOPT\_QUOTE option (and other) time\_t **curl\_getdate**(const(char)\* p, const(time\_t)\* unused); Name curl\_getdate() Description Returns the time, in seconds since 1 Jan 1970 of the time string given in the first argument. The time argument in the second parameter is unused and should be set to NULL. linked-list structure for the CURLOPT\_QUOTE option (and other) struct **curl\_certinfo**; info about the certificate chain, only for OpenSSL builds. Asked for with CURLOPT\_CERTINFO / CURLINFO\_CERTINFO linked-list structure for the CURLOPT\_QUOTE option (and other) int **num\_of\_certs**; number of certificates with information curl\_slist\*\* **certinfo**; for each index in this array, there's a linked list with textual information in the format "name: value" enum int **CURLINFO\_STRING**; enum int **CURLINFO\_LONG**; enum int **CURLINFO\_DOUBLE**; enum int **CURLINFO\_SLIST**; enum int **CURLINFO\_MASK**; enum int **CURLINFO\_TYPEMASK**; enum **CurlInfo**: int; **none** **effective\_url** **response\_code** **total\_time** **namelookup\_time** **connect\_time** **pretransfer\_time** **size\_upload** **size\_download** **speed\_download** **speed\_upload** **header\_size** **request\_size** **ssl\_verifyresult** **filetime** **content\_length\_download** **content\_length\_upload** **starttransfer\_time** **content\_type** **redirect\_time** **redirect\_count** **private\_info** **http\_connectcode** **httpauth\_avail** **proxyauth\_avail** **os\_errno** **num\_connects** **ssl\_engines** **cookielist** **lastsocket** **ftp\_entry\_path** **redirect\_url** **primary\_ip** **appconnect\_time** **certinfo** **condition\_unmet** **rtsp\_session\_id** **rtsp\_client\_cseq** **rtsp\_server\_cseq** **rtsp\_cseq\_recv** **primary\_port** **local\_ip** **local\_port** **lastone** Fill in new entries below here! alias **CURLINFO** = int; enum CurlInfo **CURLINFO\_HTTP\_CODE**; CURLINFO\_RESPONSE\_CODE is the new name for the option previously known as CURLINFO\_HTTP\_CODE enum **CurlClosePolicy**: int; **none** **oldest** **least\_recently\_used** **least\_traffic** **slowest** **callback** **last** alias **curl\_closepolicy** = int; enum **CurlGlobal**: int; **ssl** **win32** **all** **nothing** **default\_** all enum **CurlLockData**: int; Setup defines, protos etc for the sharing stuff. Different data locks for a single share **none** **share** CURL\_LOCK\_DATA\_SHARE is used internally to say that the locking is just made to change the internal state of the share itself. **cookie** **dns** **ssl\_session** **connect** **last** alias **curl\_lock\_data** = int; enum **CurlLockAccess**: int; Different lock access types **none** unspecified action **shared\_access** for read perhaps **single** for write perhaps **last** never use alias **curl\_lock\_access** = int; alias **curl\_lock\_function** = void function(void\* handle, int data, int locktype, void\* userptr); alias **curl\_unlock\_function** = void function(void\* handle, int data, void\* userptr); alias **CURLSH** = void; enum **CurlShError**: int; **ok** all is fine **bad\_option** 1 **in\_use** 2 **invalid** 3 **nomem** out of memory **last** never use alias **CURLSHcode** = int; enum **CurlShOption**: int; pass in a user data pointer used in the lock/unlock callback functions **none** don't use **share** specify a data type to share **unshare** specify which data type to stop sharing **lockfunc** pass in a 'curl\_lock\_function' pointer **unlockfunc** pass in a 'curl\_unlock\_function' pointer **userdata** pass in a user data pointer used in the lock/unlock callback functions **last** never use alias **CURLSHoption** = int; CURLSH\* **curl\_share\_init**(); CURLSHcode **curl\_share\_setopt**(CURLSH\*, CURLSHoption option, ...); CURLSHcode **curl\_share\_cleanup**(CURLSH\*); enum **CurlVer**: int; Structures for querying information about the curl library at runtime. **first** **second** **third** **fourth** **last** alias **CURLversion** = int; enum CurlVer **CURLVERSION\_NOW**; The 'CURLVERSION\_NOW' is the symbolic name meant to be used by basically all programs ever that want to get version information. It is meant to be a built-in version number for what kind of struct the caller expects. If the struct ever changes, we redefine the NOW to another enum from above. struct **\_N28**; CURLversion **age**; age of the returned struct const(char)\* **version\_**; LIBCURL\_VERSION uint **version\_num**; LIBCURL\_VERSION\_NUM const(char)\* **host**; OS/host/cpu/machine when configured int **features**; bitmask, see defines below const(char)\* **ssl\_version**; human readable string c\_long **ssl\_version\_num**; not used anymore, always 0 const(char)\* **libz\_version**; human readable string const(char)\*\* **protocols**; protocols is terminated by an entry with a NULL protoname const(char)\* **ares**; The fields below this were added in CURLVERSION\_SECOND const(char)\* **libidn**; This field was added in CURLVERSION\_THIRD int **iconv\_ver\_num**; These field were added in CURLVERSION\_FOURTH. Same as 'libiconv\_version' if built with HAVE\_ICONV const(char)\* **libssh\_version**; human readable string alias **curl\_version\_info\_data** = \_N28; enum **CurlVersion**: int; **ipv6** IPv6-enabled **kerberos4** kerberos auth is supported **ssl** SSL options are present **libz** libz features are present **ntlm** NTLM auth is supported **gssnegotiate** Negotiate auth support **dbg** built with debug capabilities **asynchdns** asynchronous dns resolves **spnego** SPNEGO auth **largefile** supports files bigger than 2GB **idn** International Domain Names support **sspi** SSPI is supported **conv** character conversions supported **curldebug** debug memory tracking supported **tlsauth\_srp** TLS-SRP auth is supported curl\_version\_info\_data\* **curl\_version\_info**(CURLversion); Name curl\_version\_info() Description This function returns a pointer to a static copy of the version info struct. See above. const(char)\* **curl\_easy\_strerror**(CURLcode); Name curl\_easy\_strerror() Description The curl\_easy\_strerror function may be used to turn a CURLcode value into the equivalent human readable error string. This is useful for printing meaningful error messages. const(char)\* **curl\_share\_strerror**(CURLSHcode); Name curl\_share\_strerror() Description The curl\_share\_strerror function may be used to turn a CURLSHcode value into the equivalent human readable error string. This is useful for printing meaningful error messages. CURLcode **curl\_easy\_pause**(CURL\* handle, int bitmask); Name curl\_easy\_pause() Description The curl\_easy\_pause function pauses or unpauses transfers. Select the new state by setting the bitmask, use the convenience defines below. enum **CurlPause**: int; **recv** **recv\_cont** **send** **send\_cont** **all** **cont** CURL\* **curl\_easy\_init**(); CURLcode **curl\_easy\_setopt**(CURL\* curl, CURLoption option, ...); CURLcode **curl\_easy\_perform**(CURL\* curl); void **curl\_easy\_cleanup**(CURL\* curl); CURLcode **curl\_easy\_getinfo**(CURL\* curl, CURLINFO info, ...); Name curl\_easy\_getinfo() Description Request internal information from the curl session with this function. The third argument MUST be a pointer to a long, a pointer to a char \* or a pointer to a double (as the documentation describes elsewhere). The data pointed to will be filled in accordingly and can be relied upon only if the function returns CURLE\_OK. This function is intended to get used *AFTER* a performed transfer, all results from this function are undefined until the transfer is completed. CURL\* **curl\_easy\_duphandle**(CURL\* curl); Name curl\_easy\_duphandle() Description Creates a new curl session handle with the same options set for the handle passed in. Duplicating a handle could only be a matter of cloning data and options, internal state info and things like persistant connections cannot be transfered. It is useful in multithreaded applications when you can run curl\_easy\_duphandle() for each new thread to avoid a series of identical curl\_easy\_setopt() invokes in every thread. void **curl\_easy\_reset**(CURL\* curl); Name curl\_easy\_reset() Description Re-initializes a CURL handle to the default values. This puts back the handle to the same state as it was in when it was just created. It does keep: live connections, the Session ID cache, the DNS cache and the cookies. CURLcode **curl\_easy\_recv**(CURL\* curl, void\* buffer, size\_t buflen, size\_t\* n); Name curl\_easy\_recv() Description Receives data from the connected socket. Use after successful curl\_easy\_perform() with CURLOPT\_CONNECT\_ONLY option. CURLcode **curl\_easy\_send**(CURL\* curl, void\* buffer, size\_t buflen, size\_t\* n); Name curl\_easy\_send() Description Sends data over the connected socket. Use after successful curl\_easy\_perform() with CURLOPT\_CONNECT\_ONLY option. alias **CURLM** = void; enum **CurlM**: int; **call\_multi\_perform** please call curl\_multi\_perform() or curl\_multi\_socket\*() soon **ok** **bad\_handle** the passed-in handle is not a valid CURLM handle **bad\_easy\_handle** an easy handle was not good/valid **out\_of\_memory** if you ever get this, you're in deep sh\*t **internal\_error** this is a libcurl bug **bad\_socket** the passed in socket argument did not match **unknown\_option** curl\_multi\_setopt() with unsupported option **last** alias **CURLMcode** = int; enum CurlM **CURLM\_CALL\_MULTI\_SOCKET**; just to make code nicer when using curl\_multi\_socket() you can now check for CURLM\_CALL\_MULTI\_SOCKET too in the same style it works for curl\_multi\_perform() and CURLM\_CALL\_MULTI\_PERFORM enum **CurlMsg**: int; **none** **done** This easy handle has completed. 'result' contains the CURLcode of the transfer **last** no used alias **CURLMSG** = int; union **\_N31**; void\* **whatever**; message-specific data CURLcode **result**; return code for transfer struct **CURLMsg**; CURLMSG **msg**; what this message means CURL\* **easy\_handle**; the handle it concerns \_N31 **data**; CURLM\* **curl\_multi\_init**(); Name curl\_multi\_init() Desc inititalize multi-style curl usage Returns: a new CURLM handle to use in all 'curl\_multi' functions. CURLMcode **curl\_multi\_add\_handle**(CURLM\* multi\_handle, CURL\* curl\_handle); Name curl\_multi\_add\_handle() Desc add a standard curl handle to the multi stack Returns: CURLMcode type, general multi error code. CURLMcode **curl\_multi\_remove\_handle**(CURLM\* multi\_handle, CURL\* curl\_handle); Name curl\_multi\_remove\_handle() Desc removes a curl handle from the multi stack again Returns: CURLMcode type, general multi error code. alias **fd\_set** = int; Name curl\_multi\_fdset() Desc Ask curl for its fd\_set sets. The app can use these to select() or poll() on. We want curl\_multi\_perform() called as soon as one of them are ready. Returns: CURLMcode type, general multi error code. tmp decl CURLMcode **curl\_multi\_fdset**(CURLM\* multi\_handle, fd\_set\* read\_fd\_set, fd\_set\* write\_fd\_set, fd\_set\* exc\_fd\_set, int\* max\_fd); CURLMcode **curl\_multi\_perform**(CURLM\* multi\_handle, int\* running\_handles); Name curl\_multi\_perform() Desc When the app thinks there's data available for curl it calls this function to read/write whatever there is right now. This returns as soon as the reads and writes are done. This function does not require that there actually is data available for reading or that data can be written, it can be called just in case. It returns the number of handles that still transfer data in the second argument's integer-pointer. Returns: CURLMcode type, general multi error code. *NOTE* that this only returns errors etc regarding the whole multi stack. There might still have occurred problems on invidual transfers even when this returns OK. CURLMcode **curl\_multi\_cleanup**(CURLM\* multi\_handle); Name curl\_multi\_cleanup() Desc Cleans up and removes a whole multi stack. It does not free or touch any individual easy handles in any way. We need to define in what state those handles will be if this function is called in the middle of a transfer. Returns: CURLMcode type, general multi error code. CURLMsg\* **curl\_multi\_info\_read**(CURLM\* multi\_handle, int\* msgs\_in\_queue); Name curl\_multi\_info\_read() Desc Ask the multi handle if there's any messages/informationals from the individual transfers. Messages include informationals such as error code from the transfer or just the fact that a transfer is completed. More details on these should be written down as well. Repeated calls to this function will return a new struct each time, until a special "end of msgs" struct is returned as a signal that there is no more to get at this point. The data the returned pointer points to will not survive calling curl\_multi\_cleanup(). The 'CURLMsg' struct is meant to be very simple and only contain very basic informations. If more involved information is wanted, we will provide the particular "transfer handle" in that struct and that should/could/would be used in subsequent curl\_easy\_getinfo() calls (or similar). The point being that we must never expose complex structs to applications, as then we'll undoubtably get backwards compatibility problems in the future. Returns: A pointer to a filled-in struct, or NULL if it failed or ran out of structs. It also writes the number of messages left in the queue (after this read) in the integer the second argument points to. const(char)\* **curl\_multi\_strerror**(CURLMcode); Name curl\_multi\_strerror() Desc The curl\_multi\_strerror function may be used to turn a CURLMcode value into the equivalent human readable error string. This is useful for printing meaningful error messages. Returns: A pointer to a zero-terminated error message. enum **CurlPoll**: int; Name curl\_multi\_socket() and curl\_multi\_socket\_all() Desc An alternative version of curl\_multi\_perform() that allows the application to pass in one of the file descriptors that have been detected to have "action" on them and let libcurl perform. See man page for details. **none\_** jdrewsen - underscored in order not to clash with reserved D symbols **in\_** **out\_** **inout\_** **remove\_** alias **CURL\_SOCKET\_TIMEOUT** = CURL\_SOCKET\_BAD; enum **CurlCSelect**: int; **in\_** jdrewsen - underscored in order not to clash with reserved D symbols **out\_** **err\_** alias **curl\_socket\_callback** = extern (C) int function(void\* easy, socket\_t s, int what, void\* userp, void\* socketp); private socket pointer alias **curl\_multi\_timer\_callback** = extern (C) int function(void\* multi, long timeout\_ms, void\* userp); private callback pointer Name curl\_multi\_timer\_callback Desc Called by libcurl whenever the library detects a change in the maximum number of milliseconds the app is allowed to wait before curl\_multi\_socket() or curl\_multi\_perform() must be called (to allow libcurl's timed events to take place). Returns: The callback should return zero. CURLMcode **curl\_multi\_socket**(CURLM\* multi\_handle, curl\_socket\_t s, int\* running\_handles); ditto Name curl\_multi\_timer\_callback Desc Called by libcurl whenever the library detects a change in the maximum number of milliseconds the app is allowed to wait before curl\_multi\_socket() or curl\_multi\_perform() must be called (to allow libcurl's timed events to take place). Returns: The callback should return zero. CURLMcode **curl\_multi\_socket\_action**(CURLM\* multi\_handle, curl\_socket\_t s, int ev\_bitmask, int\* running\_handles); ditto Name curl\_multi\_timer\_callback Desc Called by libcurl whenever the library detects a change in the maximum number of milliseconds the app is allowed to wait before curl\_multi\_socket() or curl\_multi\_perform() must be called (to allow libcurl's timed events to take place). Returns: The callback should return zero. CURLMcode **curl\_multi\_socket\_all**(CURLM\* multi\_handle, int\* running\_handles); ditto Name curl\_multi\_timer\_callback Desc Called by libcurl whenever the library detects a change in the maximum number of milliseconds the app is allowed to wait before curl\_multi\_socket() or curl\_multi\_perform() must be called (to allow libcurl's timed events to take place). Returns: The callback should return zero. CURLMcode **curl\_multi\_timeout**(CURLM\* multi\_handle, c\_long\* milliseconds); This macro below was added in 7.16.3 to push users who recompile to use the new curl\_multi\_socket\_action() instead of the old curl\_multi\_socket() Name curl\_multi\_timeout() Desc Returns the maximum number of milliseconds the app is allowed to wait before curl\_multi\_socket() or curl\_multi\_perform() must be called (to allow libcurl's timed events to take place). Returns: CURLM error code. enum **CurlMOption**: int; **socketfunction** This is the socket callback function pointer **socketdata** This is the argument passed to the socket callback **pipelining** set to 1 to enable pipelining for this multi handle **timerfunction** This is the timer callback function pointer **timerdata** This is the argument passed to the timer callback **maxconnects** maximum number of entries in the connection cache **lastentry** alias **CURLMoption** = int; CURLMcode **curl\_multi\_setopt**(CURLM\* multi\_handle, CURLMoption option, ...); Name curl\_multi\_setopt() Desc Sets options for the multi handle. Returns: CURLM error code. CURLMcode **curl\_multi\_assign**(CURLM\* multi\_handle, curl\_socket\_t sockfd, void\* sockp); Name curl\_multi\_assign() Desc This function sets an association in the multi handle between the given socket and a private pointer of the application. This is (only) useful for curl\_multi\_socket uses. Returns: CURLM error code.
programming_docs
d std.experimental.logger.multilogger std.experimental.logger.multilogger =================================== Source [std/experimental/logger/multilogger.d](https://github.com/dlang/phobos/blob/master/std/experimental/logger/multilogger.d) struct **MultiLoggerEntry**; This Element is stored inside the `MultiLogger` and associates a `Logger` to a `string`. string **name**; The name if the `Logger` Logger **logger**; The stored `Logger` class **MultiLogger**: std.experimental.logger.core.Logger; MultiLogger logs to multiple `Logger`. The `Logger`s are stored in an `Logger[]` in their order of insertion. Every data logged to this `MultiLogger` will be distributed to all the `Logger`s inserted into it. This `MultiLogger` implementation can hold multiple `Logger`s with the same name. If the method `removeLogger` is used to remove a `Logger` only the first occurrence with that name will be removed. @safe this(const LogLevel lv = LogLevel.all); A constructor for the `MultiLogger` Logger. Parameters: | | | | --- | --- | | LogLevel `lv` | The `LogLevel` for the `MultiLogger`. By default the `LogLevel` for `MultiLogger` is `LogLevel.all`. | Example ``` auto l1 = new MultiLogger(LogLevel.trace); ``` protected MultiLoggerEntry[] **logger**; This member holds all `Logger`s stored in the `MultiLogger`. When inheriting from `MultiLogger` this member can be used to gain access to the stored `Logger`. @safe void **insertLogger**(string name, Logger newLogger); This method inserts a new Logger into the `MultiLogger`. Parameters: | | | | --- | --- | | string `name` | The name of the `Logger` to insert. | | Logger `newLogger` | The `Logger` to insert. | @safe Logger **removeLogger**(in char[] toRemove); This method removes a Logger from the `MultiLogger`. Parameters: | | | | --- | --- | | char[] `toRemove` | The name of the `Logger` to remove. If the `Logger` is not found `null` will be returned. Only the first occurrence of a `Logger` with the given name will be removed. | Returns: The removed `Logger`. d Types Types ===== **Contents** 1. [Basic Data Types](#basic-data-types) 2. [Derived Data Types](#derived-data-types) 3. [User-Defined Types](#user-defined-types) 4. [Type Conversions](#type-conversions) 1. [Pointer Conversions](#pointer-conversions) 2. [Implicit Conversions](#implicit-conversions) 3. [Integer Promotions](#integer-promotions) 4. [Usual Arithmetic Conversions](#usual-arithmetic-conversions) 5. [`bool`](#bool) 6. [Delegates](#delegates) 7. [`typeof`](#typeof) 8. [Mixin Types](#mixin_types) 9. [Aliased Types](#aliased-types) 1. [`size_t`](#size_t) 2. [`ptrdiff_t`](#ptrdiff_t) 3. [`string`](#string) D is statically typed. Every expression has a type. Types constrain the values an expression can hold, and determine the semantics of operations on those values. ``` Type: TypeCtorsopt BasicType TypeSuffixesopt TypeCtors: TypeCtor TypeCtor TypeCtors TypeCtor: const immutable inout shared BasicType: FundamentalType . QualifiedIdentifier QualifiedIdentifier Typeof Typeof . QualifiedIdentifier TypeCtor ( Type ) Vector Traits MixinType Vector: __vector ( VectorBaseType ) VectorBaseType: Type FundamentalType: bool byte ubyte short ushort int uint long ulong cent ucent char wchar dchar float double real ifloat idouble ireal cfloat cdouble creal void TypeSuffixes: TypeSuffix TypeSuffixesopt TypeSuffix: * [ ] [ AssignExpression ] [ AssignExpression .. AssignExpression ] [ Type ] delegate Parameters MemberFunctionAttributesopt function Parameters FunctionAttributesopt QualifiedIdentifier: Identifier Identifier . QualifiedIdentifier TemplateInstance TemplateInstance . QualifiedIdentifier Identifier [ AssignExpression ] Identifier [ AssignExpression ]. QualifiedIdentifier ``` [Basic Data Types](#basic_data_types) are leaf types. [Derived Data Types](#derived-data_types) build on leaf types. [User-Defined Types](#user-defined-types) are aggregates of basic and derived types. Basic Data Types ---------------- Basic Data Types| **Keyword** | **Default Initializer (`.init`)** | **Description** | | `void` | no default initializer | `void` has no value | | [`bool`](#bool) | `false` | boolean value | | `byte` | `0` | signed 8 bits | | `ubyte` | `0u` | unsigned 8 bits | | `short` | `0` | signed 16 bits | | `ushort` | `0u` | unsigned 16 bits | | `int` | `0` | signed 32 bits | | `uint` | `0u` | unsigned 32 bits | | `long` | `0L` | signed 64 bits | | `ulong` | `0uL` | unsigned 64 bits | | `cent` | `0` | signed 128 bits (reserved for future use) | | `ucent` | `0u` | unsigned 128 bits (reserved for future use) | | `float` | `float.nan` | 32 bit floating point | | `double` | `double.nan` | 64 bit floating point | | `real` | `real.nan` | largest floating point size available | | `ifloat` | `float.nan*1.0i` | imaginary float | | `idouble` | `double.nan*1.0i` | imaginary double | | `ireal` | `real.nan*1.0i` | imaginary real | | `cfloat` | `float.nan+float.nan*1.0i` | a complex number of two float values | | `cdouble` | `double.nan+double.nan*1.0i` | complex double | | `creal` | `real.nan+real.nan*1.0i` | complex real | | `char` | `'xFF'` | unsigned 8 bit (UTF-8 code unit) | | `wchar` | `'uFFFF'` | unsigned 16 bit (UTF-16 code unit) | | `dchar` | `'U0000FFFF'` | unsigned 32 bit (UTF-32 code unit) | **Implementation Defined:** The real floating point type has at least the range and precision of the `double` type. On x86 CPUs it is often implemented as the 80 bit Extended Real type supported by the x86 FPU. Derived Data Types ------------------ * [Pointer](https://dlang.org/arrays.html#pointers) * [Static Array](https://dlang.org/arrays.html#static-arrays) * [Dynamic Array](https://dlang.org/arrays.html#dynamic-arrays) * [Associative Array](hash-map) * [Functions](function) * [Delegates](#delegates) User-Defined Types ------------------ * [Enums](enum) * [Structs and Unions](struct) * [Classes](class) * [Interfaces](interface) Type Conversions ---------------- See also: [*CastExpression*](expression#CastExpression). ### Pointer Conversions Casting pointers to non-pointers and vice versa is allowed. **Best Practices:** do not do this for any pointers that point to data allocated by the garbage collector. ### Implicit Conversions Implicit conversions are used to automatically convert types as required. An enum can be implicitly converted to its base type, but going the other way requires an explicit conversion. For example: ``` int i; enum Foo { E } Foo f; i = f; // OK f = i; // error f = cast(Foo)i; // OK f = 0; // error f = Foo.E; // OK ``` A derived class can be implicitly converted to its base class, but going the other way requires an explicit cast. For example: ``` class Base {} class Derived : Base {} Base bd = new Derived(); // implicit conversion Derived db = cast(Derived)new Base(); // explicit conversion ``` A dynamic array, say `x`, of a derived class can be implicitly converted to a dynamic array, say `y`, of a base class iff elements of `x` and `y` are qualified as being either both `const` or `both` `immutable`. ``` class Base {} class Derived : Base {} const(Base)[] ca = (const(Derived)[]).init; // `const` elements immutable(Base)[] ia = (immutable(Derived)[]).init; // `immutable` elements ``` A static array, say `x`, of a derived class can be implicitly converted to a static array, say `y`, of a base class iff elements of `x` and `y` are qualified as being either both `const` or `both` `immutable` or both mutable (neither `const` nor `immutable`). ``` class Base {} class Derived : Base {} Base[3] ma = (Derived[3]).init; // mutable elements const(Base)[3] ca = (const(Derived)[3]).init; // `const` elements immutable(Base)[3] ia = (immutable(Derived)[3]).init; // `immutable` elements ``` ### Integer Promotions Integer Promotions are conversions of the following types: Integer Promotions| **from** | **to** | | `bool` | `int` | | `byte` | `int` | | `ubyte` | `int` | | `short` | `int` | | `ushort` | `int` | | `char` | `int` | | `wchar` | `int` | | `dchar` | `uint` | If an enum has as a base type one of the types in the left column, it is converted to the type in the right column. ### Usual Arithmetic Conversions The usual arithmetic conversions convert operands of binary operators to a common type. The operands must already be of arithmetic types. The following rules are applied in order, looking at the base type: 1. If either operand is `real`, the other operand is converted to `real`. 2. Else if either operand is `double`, the other operand is converted to `double`. 3. Else if either operand is `float`, the other operand is converted to `float`. 4. Else the integer promotions are done on each operand, followed by: 1. If both are the same type, no more conversions are done. 2. If both are signed or both are unsigned, the smaller type is converted to the larger. 3. If the signed type is larger than the unsigned type, the unsigned type is converted to the signed type. 4. The signed type is converted to the unsigned type. If one or both of the operand types is an enum after undergoing the above conversions, the result type is: 1. If the operands are the same type, the result will be of that type. 2. If one operand is an enum and the other is the base type of that enum, the result is the base type. 3. If the two operands are different enums, the result is the closest base type common to both. A base type being closer means there is a shorter sequence of conversions to base type to get there from the original type. Integer values cannot be implicitly converted to another type that cannot represent the integer bit pattern after integral promotion. For example: ``` ubyte u1 = -1; // error, -1 cannot be represented in a ubyte ushort u2 = -1; // error, -1 cannot be represented in a ushort uint u3 = int(-1); // ok, -1 can be represented in a uint ulong u4 = long(-1); // ok, -1 can be represented in a ulong ``` Floating point types cannot be implicitly converted to integral types. Complex or imaginary floating point types cannot be implicitly converted to non-complex floating point types. Non-complex floating point types cannot be implicitly converted to imaginary floating point types. `bool` ------ The bool type is a byte-size type that can only hold the value `true` or `false`. The only operators that can accept operands of type bool are: `&` `|`, `^`, `&``=`, `|``=`, `^=`, !, `&``&`, `|``|`, and `?:`. A `bool` value can be implicitly converted to any integral type, with `false` becoming 0 and `true` becoming 1. The numeric literals `0` and `1` can be implicitly converted to the `bool` values `false` and `true`, respectively. Casting an expression to `bool` means testing for `0` or `!=0` for arithmetic types, and `null` or `!=null` for pointers or references. Delegates --------- Delegates are an aggregate of two pieces of data: an object reference and a pointer to a non-static member function, or a pointer to a closure and a pointer to a nested function. The object reference forms the `this` pointer when the function is called. Delegates are declared similarly to function pointers: ``` int function(int) fp; // fp is pointer to a function int delegate(int) dg; // dg is a delegate to a function ``` A delegate is initialized analogously to function pointers: ``` int func(int); fp = &func; // fp points to func class OB { int member(int); } OB o; dg = &o.member; // dg is a delegate to object o and // member function member ``` Delegates cannot be initialized with static member functions or non-member functions. Delegates are called analogously to function pointers: ``` fp(3); // call func(3) dg(3); // call o.member(3) ``` The equivalent of member function pointers can be constructed using [anonymous lambda functions](expression#function_literals): ``` class C { int a; int foo(int i) { return i + a; } } // mfp is the member function pointer auto mfp = function(C self, int i) { return self.foo(i); }; auto c = new C(); // create an instance of C mfp(c, 1); // and call c.foo(1) ``` The C style syntax for declaring pointers to functions is deprecated: ``` int (*fp)(int); // fp is pointer to a function ``` `typeof` -------- ``` Typeof: typeof ( Expression ) typeof ( return ) ``` `typeof` is a way to specify a type based on the type of an expression. For example: ``` void func(int i) { typeof(i) j; // j is of type int typeof(3 + 6.0) x; // x is of type double typeof(1)* p; // p is of type pointer to int int[typeof(p)] a; // a is of type int[int*] writeln(typeof('c').sizeof); // prints 1 double c = cast(typeof(1.0))j; // cast j to double } ``` *Expression* is not evaluated, it is used purely to generate the type: ``` void func() { int i = 1; typeof(++i) j; // j is declared to be an int, i is not incremented writeln(i); // prints 1 } ``` Special cases: 1. `typeof(this)` will generate the type of what `this` would be in a non-static member function, even if not in a member function. 2. Analogously, `typeof(super)` will generate the type of what `super` would be in a non-static member function. 3. `typeof(return)` will, when inside a function scope, give the return type of that function. ``` class A { } class B : A { typeof(this) x; // x is declared to be a B typeof(super) y; // y is declared to be an A } struct C { static typeof(this) z; // z is declared to be a C typeof(super) q; // error, no super struct for C } typeof(this) r; // error, no enclosing struct or class ``` If the expression is a [Property Function](function#property-functions), `typeof` gives its return type. ``` struct S { @property int foo() { return 1; } } typeof(S.foo) n; // n is declared to be an int ``` **Best Practices:** 1. *Typeof* is most useful in writing generic template code. Mixin Types ----------- ``` MixinType: mixin ( ArgumentList ) ``` Each [*AssignExpression*](expression#AssignExpression) in the *ArgumentList* is evaluated at compile time, and the result must be representable as a string. The resulting strings are concatenated to form a string. The text contents of the string must be compilable as a valid [*Type*](type#Type), and is compiled as such. ``` void test(mixin("int")* p) // int* p { mixin("int")[] a; // int[] a; mixin("int[]") b; // int[] b; } ``` Aliased Types ------------- ### `size_t` `size_t` is an alias to one of the unsigned integral basic types, and represents a type that is large enough to represent an offset into all addressable memory. ### `ptrdiff_t` `ptrdiff_t` is an alias to the signed integral basic type the same size as `size_t`. ### `string` A [*string* is a special case of an array.](arrays#strings) d Properties Properties ========== **Contents** 1. [.init Property](#init) 2. [.stringof Property](#stringof) 3. [.sizeof Property](#sizeof) 4. [.alignof Property](#alignof) 5. [.mangleof Property](#mangleof) 6. [.classinfo Property](#classinfo) 7. [User-Defined Properties](#classproperties) Every symbol, type, and expression has properties that can be queried: Property Examples| **Expression** | **Value** | | `int.sizeof` | yields 4 | | `float.nan` | yields the floating point nan (Not A Number) value | | `(float).nan` | yields the floating point nan value | | `(3).sizeof` | yields 4 (because 3 is an int) | | `int.init` | default initializer for ints | | `int.mangleof` | yields the string "i" | | `int.stringof` | yields the string "int" | | `(1+2).stringof` | yields the string "1 + 2" | Properties for All Types| **Property** | **Description** | | [`.init`](#init) | initializer | | [`.sizeof`](#sizeof) | size in bytes | | [`.alignof`](#alignof) | alignment size | | [`.mangleof`](#mangleof) | string representing the ‘mangled’ representation of the type | | [`.stringof`](#stringof) | string representing the source representation of the type | Properties for Integral Types| **Property** | **Description** | | `.init` | initializer | | `.max` | maximum value | | `.min` | minimum value | Properties for Floating Point Types| **Property** | **Description** | | `.init` | initializer (NaN) | | `.infinity` | infinity value | | `.nan` | NaN value | | `.dig` | number of decimal digits of precision | | `.epsilon` | smallest increment to the value 1 | | `.mant_dig` | number of bits in mantissa | | `.max_10_exp` | maximum int value such that 10`max_10_exp` is representable | | `.max_exp` | maximum int value such that 2`max_exp-1` is representable | | `.min_10_exp` | minimum int value such that 10`min_10_exp` is representable as a normalized value | | `.min_exp` | minimum int value such that 2`min_exp-1` is representable as a normalized value | | `.max` | largest representable value that's not infinity | | `.min_normal` | smallest representable normalized value that's not 0 | | `.re` | real part | | `.im` | imaginary part | Properties for Class Types| **Property** | **Description** | | [`.classinfo`](#classinfo) | Information about the dynamic type of the class | .init Property -------------- `.init` produces a constant expression that is the default initializer. If applied to a type, it is the default initializer for that type. If applied to a variable or field, it is the default initializer for that variable or field's type. ``` int a; int b = 1; int.init // is 0 a.init // is 0 b.init // is 0 struct Foo { int a; int b = 7; } Foo.init.a // is 0 Foo.init.b // is 7 ``` **Note:** `.init` produces a default initialized object, not default constructed. If there is a default constructor for an object, it may produce a different value. 1. If `T` is a nested struct, the context pointer in `T.init` is `null`. ``` void main() { int x; struct S { void foo() { x = 1; } // access x in enclosing scope via context pointer } S s1; // OK. S() correctly initialize its context pointer. S s2 = S(); // OK. same as s1 S s3 = S.init; // Bad. the context pointer in s3 is null s3.foo(); // Access violation } ``` 3. If `T` is a struct which has `@disable this();`, `T.init` might return a logically incorrect object. ``` struct S { int x; @disable this(); this(int n) { x = n; } invariant { assert(x > 0); } void check() {} } void main() { //S s1; // Error: variable s1 initializer required for type S //S s2 = S(); // Error: constructor S.this is not callable // because it is annotated with @disable S s3 = S.init; // Bad. s3.x == 0, and it violates the invariant of S s3.check(); // Assertion failure } ``` .stringof Property ------------------ `.stringof` produces a constant string that is the source representation of its prefix. If applied to a type, it is the string for that type. If applied to an expression, it is the source representation of that expression. The expression will not be evaluated. ``` module test; import std.stdio; struct Dog { } enum Color { Red } int i = 4; void main() { writeln((1+2).stringof); // "1 + 2" writeln(Dog.stringof); // "Dog" writeln(test.Dog.stringof); // "Dog" writeln(int.stringof); // "int" writeln((int*[5][]).stringof); // "int*[5][]" writeln(Color.Red.stringof); // "Red" writeln((5).stringof); // "5" writeln((++i).stringof); // "i += 1" writeln(i); // 4 } ``` **Implementation Defined:** The string representation for a type or expression can vary. **Best Practices:** Do not use `.stringof` for code generation. Instead use the [identifier](traits#identifier) trait, or one of the Phobos helper functions such as [`std.traits.fullyQualifiedName`](https://dlang.org/phobos/std_traits.html#fullyQualifiedName). .sizeof Property ---------------- `e.sizeof` gives the size in bytes of the expression `e`. When getting the size of a member, it is not necessary for there to be a *this* object: ``` struct S { int a; static int foo() { return a.sizeof; // returns 4 } } void test() { int x = S.a.sizeof; // sets x to 4 } ``` `.sizeof` applied to a class object returns the size of the class reference, not the class instantiation. .alignof Property ----------------- `.alignof` gives the aligned size of an expression or type. For example, an aligned size of 1 means that it is aligned on a byte boundary, 4 means it is aligned on a 32 bit boundary. **Implementation Defined:** the actual aligned size. **Best Practices:** Be particularly careful when laying out an object that must line up with an externally imposed layout. Data misalignment can result in particularly pernicious bugs. It's often worth putting in an `assert` to assure it is correct. .mangleof Property ------------------ Mangling refers to how a symbol is represented in text form in the generated object file. `.mangleof` returns a string literal of the representation of the type or symbol it is applied to. The mangling of types and symbols with D linkage is defined by [Name Mangling](abi#name_mangling). **Implementation Defined:** 1. whether a leading underscore is added to a symbol 2. the mangling of types and symbols with non-D linkage. For C and C++ linkage, this will typically match what the associated C or C++ compiler does. .classinfo Property ------------------- `.classinfo` provides information about the dynamic type of a class object. It returns a reference to type [`object.TypeInfo_Class`](https://dlang.org/phobos/object.html). `.classinfo` applied to an interface gives the information for the interface, not the class it might be an instance of. User-Defined Properties ----------------------- User-defined properties can be created using [Property Functions](function#property-functions).
programming_docs
d std.experimental.allocator.building_blocks.free_list std.experimental.allocator.building\_blocks.free\_list ====================================================== Source [std/experimental/allocator/building\_blocks/free\_list.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/free_list.d) struct **FreeList**(ParentAllocator, size\_t minSize, size\_t maxSize = minSize, Flag!"adaptive" adaptive = No.adaptive); [Free list allocator](http://en.wikipedia.org/wiki/Free_list), stackable on top of another allocator. Allocation requests between `min` and `max` bytes are rounded up to `max` and served from a singly-linked list of buffers deallocated in the past. All other allocations are directed to `ParentAllocator`. Due to the simplicity of free list management, allocations from the free list are fast. If `adaptive` is set to `Yes.adaptive`, the free list gradually reduces its size if allocations tend to use the parent allocator much more than the lists' available nodes. One instantiation is of particular interest: `FreeList!(0, unbounded)` puts every deallocation in the freelist, and subsequently serves any allocation from the freelist (if not empty). There is no checking of size matching, which would be incorrect for a freestanding allocator but is both correct and fast when an owning allocator on top of the free list allocator (such as `Segregator`) is already in charge of handling size checking. The following methods are defined if `ParentAllocator` defines them, and forward to it: `expand`, `owns`, `reallocate`. const @property size\_t **min**(); Returns the smallest allocation size eligible for allocation from the freelist. (If `minSize != chooseAtRuntime`, this is simply an alias for `minSize`.) @property void **min**(size\_t low); If `FreeList` has been instantiated with `minSize == chooseAtRuntime`, then the `min` property is writable. Setting it must precede any allocation. Parameters: | | | | --- | --- | | size\_t `low` | new value for `min` | Precondition `low <= max`, or `maxSize == chooseAtRuntime` and `max` has not yet been initialized. Also, no allocation has been yet done with this allocator. Postcondition `min == low` const @property size\_t **max**(); Returns the largest allocation size eligible for allocation from the freelist. (If `maxSize != chooseAtRuntime`, this is simply an alias for `maxSize`.) All allocation requests for sizes greater than or equal to `min` and less than or equal to `max` are rounded to `max` and forwarded to the parent allocator. When the block fitting the same constraint gets deallocated, it is put in the freelist with the allocated size assumed to be `max`. @property void **max**(size\_t high); If `FreeList` has been instantiated with `maxSize == chooseAtRuntime`, then the `max` property is writable. Setting it must precede any allocation. Parameters: | | | | --- | --- | | size\_t `high` | new value for `max` | Precondition `high >= min`, or `minSize == chooseAtRuntime` and `min` has not yet been initialized. Also `high >= (void*).sizeof`. Also, no allocation has been yet done with this allocator. Postcondition `max == high` ParentAllocator **parent**; The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`. alias **alignment** = ParentAllocator.**alignment**; Alignment offered. size\_t **goodAllocSize**(size\_t bytes); If `maxSize == unbounded`, returns `parent.goodAllocSize(bytes)`. Otherwise, returns `max` for sizes in the interval `[min, max]`, and `parent.goodAllocSize(bytes)` otherwise. Precondition If set at runtime, `min` and/or `max` must be initialized appropriately. Postcondition `result >= bytes` void[] **allocate**(size\_t n); Allocates memory either off of the free list or from the parent allocator. If `n` is within `[min, max]` or if the free list is unchecked (`minSize == 0 && maxSize == size_t.max`), then the free list is consulted first. If not empty (hit), the block at the front of the free list is removed from the list and returned. Otherwise (miss), a new block of `max` bytes is allocated, truncated to `n` bytes, and returned. Parameters: | | | | --- | --- | | size\_t `n` | number of bytes to allocate | Returns: The allocated block, or `null`. Precondition If set at runtime, `min` and/or `max` must be initialized appropriately. Postcondition `result.length == bytes || result is null` bool **deallocate**(void[] block); If `block.length` is within `[min, max]` or if the free list is unchecked (`minSize == 0 && maxSize == size_t.max`), then inserts the block at the front of the free list. For all others, forwards to `parent.deallocate` if `Parent.deallocate` is defined. Parameters: | | | | --- | --- | | void[] `block` | Block to deallocate. | Precondition If set at runtime, `min` and/or `max` must be initialized appropriately. The block must have been allocated with this freelist, and no dynamic changing of `min` or `max` is allowed to occur between allocation and deallocation. bool **deallocateAll**(); Defined only if `ParentAllocator` defines `deallocateAll`. If so, forwards to it and resets the freelist. void **minimize**(); Nonstandard function that minimizes the memory usage of the freelist by freeing each element in turn. Defined only if `ParentAllocator` defines `deallocate`. `FreeList!(0, unbounded)` does not have this function. struct **ContiguousFreeList**(ParentAllocator, size\_t minSize, size\_t maxSize = minSize); Free list built on top of exactly one contiguous block of memory. The block is assumed to have been allocated with `ParentAllocator`, and is released in `ContiguousFreeList`'s destructor (unless `ParentAllocator` is `NullAllocator`). `ContiguousFreeList` has most advantages of `FreeList` but fewer disadvantages. It has better cache locality because items are closer to one another. It imposes less fragmentation on its parent allocator. The disadvantages of `ContiguousFreeList` over `FreeList` are its pay upfront model (as opposed to `FreeList`'s pay-as-you-go approach), and a hard limit on the number of nodes in the list. Thus, a large number of long- lived objects may occupy the entire block, making it unavailable for serving allocations from the free list. However, an absolute cap on the free list size may be beneficial. The options `minSize == unbounded` and `maxSize == unbounded` are not available for `ContiguousFreeList`. Examples: ``` import std.experimental.allocator.building_blocks.allocator_list : AllocatorList; import std.experimental.allocator.gc_allocator : GCAllocator; import std.experimental.allocator.common : unbounded; alias ScalableFreeList = AllocatorList!((n) => ContiguousFreeList!(GCAllocator, 0, unbounded)(4096) ); ``` SParent **parent**; The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`. enum uint **alignment**; Alignment offered. this(ubyte[] buffer); this(ParentAllocator parent, ubyte[] buffer); this(size\_t bytes); this(ParentAllocator parent, size\_t bytes); this(size\_t bytes, size\_t max); this(ParentAllocator parent, size\_t bytes, size\_t max); this(size\_t bytes, size\_t min, size\_t max); this(ParentAllocator parent, size\_t bytes, size\_t min, size\_t max); Constructors setting up the memory structured as a free list. Parameters: | | | | --- | --- | | ubyte[] `buffer` | Buffer to structure as a free list. If `ParentAllocator` is not `NullAllocator`, the buffer is assumed to be allocated by `parent` and will be freed in the destructor. | | ParentAllocator `parent` | Parent allocator. For construction from stateless allocators, use their `instance` static member. | | size\_t `bytes` | Bytes (not items) to be allocated for the free list. Memory will be allocated during construction and deallocated in the destructor. | | size\_t `max` | Maximum size eligible for freelisting. Construction with this parameter is defined only if `maxSize == chooseAtRuntime` or `maxSize == unbounded`. | | size\_t `min` | Minimum size eligible for freelisting. Construction with this parameter is defined only if `minSize == chooseAtRuntime`. If this condition is met and no `min` parameter is present, `min` is initialized with `max`. | size\_t **goodAllocSize**(size\_t n); If `n` is eligible for freelisting, returns `max`. Otherwise, returns `parent.goodAllocSize(n)`. Precondition If set at runtime, `min` and/or `max` must be initialized appropriately. Postcondition `result >= bytes` void[] **allocate**(size\_t n); Allocate `n` bytes of memory. If `n` is eligible for freelist and the freelist is not empty, pops the memory off the free list. In all other cases, uses the parent allocator. Ternary **owns**(void[] b); Defined if `ParentAllocator` defines it. Checks whether the block belongs to this allocator. bool **deallocate**(void[] b); Deallocates `b`. If it's of eligible size, it's put on the free list. Otherwise, it's returned to `parent`. Precondition `b` has been allocated with this allocator, or is `null`. bool **deallocateAll**(); Deallocates everything from the parent. Ternary **empty**(); Returns `Ternary.yes` if no memory is currently allocated with this allocator, `Ternary.no` otherwise. This method never returns `Ternary.unknown`. struct **SharedFreeList**(ParentAllocator, size\_t minSize, size\_t maxSize = minSize, size\_t approxMaxNodes = unbounded); FreeList shared across threads. Allocation and deallocation are lock-free. The parameters have the same semantics as for `FreeList`. `expand` is defined to forward to `ParentAllocator.expand` (it must be also `shared`). Examples: ``` import std.experimental.allocator.common : chooseAtRuntime; import std.experimental.allocator.mallocator : Mallocator; shared SharedFreeList!(Mallocator, chooseAtRuntime, chooseAtRuntime) a; a.setBounds(64, 128); writeln(a.max); // 128 writeln(a.min); // 64 ``` Examples: ``` import std.experimental.allocator.common : chooseAtRuntime; import std.experimental.allocator.mallocator : Mallocator; shared SharedFreeList!(Mallocator, 50, 50, chooseAtRuntime) a; // Set the maxSize first so setting the minSize doesn't throw a.approxMaxLength = 128; writeln(a.approxMaxLength); // 128 a.approxMaxLength = 1024; writeln(a.approxMaxLength); // 1024 a.approxMaxLength = 1; writeln(a.approxMaxLength); // 1 ``` @property size\_t **min**(); @property void **min**(size\_t newMinSize); @property size\_t **max**(); @property void **max**(size\_t newMaxSize); void **setBounds**(size\_t newMin, size\_t newMax); Properties for getting (and possibly setting) the bounds. Setting bounds is allowed only once , and before any allocation takes place. Otherwise, the primitives have the same semantics as those of `FreeList`. shared const @property size\_t **approxMaxLength**(); shared @property void **approxMaxLength**(size\_t x); Properties for getting (and possibly setting) the approximate maximum length of a shared freelist. shared ParentAllocator **parent**; The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`. enum uint **alignment**; shared size\_t **goodAllocSize**(size\_t bytes); shared const Ternary **owns**(const void[] b); shared bool **reallocate**(ref void[] b, size\_t s); shared void[] **allocate**(size\_t bytes); shared bool **deallocate**(void[] b); shared bool **deallocateAll**(); Standard primitives. shared void **minimize**(); Nonstandard function that minimizes the memory usage of the freelist by freeing each element in turn. Defined only if `ParentAllocator` defines `deallocate`. d D Grammar D Grammar ========= **Contents** 1. [Modules](#modules) 2. [Declarations](#declarations) 3. [Types](#types) 4. [Attributes](#attributes) 5. [Pragmas](#pragmas) 6. [Expressions](#expressions) 7. [Statements](#statements) 8. [Structs and Unions](#structs%20and%20unions) 9. [Classes](#classes) 10. [Interfaces](#interfaces) 11. [Enums](#enums) 12. [Functions](#functions) 13. [Templates](#templates) 14. [Template Mixins](#template%20mixins) 15. [Conditional Compilation](#conditional%20compilation) 16. [Traits](#traits) 17. [Unit Tests](#unit%20tests) 18. [D x86 Inline Assembler](#d%20x86%20inline%20assembler) 19. [Named Character Entities](#named%20character%20entities) 20. [Application Binary Interface](#application%20binary%20interface) Lexical Syntax -------------- Refer to the page for [lexical syntax](lex). Modules ------- ``` Module: ModuleDeclaration DeclDefs DeclDefs DeclDefs: DeclDef DeclDef DeclDefs DeclDef: AttributeSpecifier Declaration Constructor Destructor Postblit Allocator Deallocator ClassInvariant StructInvariant UnitTest AliasThis StaticConstructor StaticDestructor SharedStaticConstructor SharedStaticDestructor ConditionalDeclaration DebugSpecification VersionSpecification StaticAssert TemplateDeclaration TemplateMixinDeclaration TemplateMixin MixinDeclaration ; ``` ``` ModuleDeclaration: ModuleAttributesopt module ModuleFullyQualifiedName ; ModuleAttributes: ModuleAttribute ModuleAttribute ModuleAttributes ModuleAttribute: DeprecatedAttribute UserDefinedAttribute ModuleFullyQualifiedName: ModuleName Packages . ModuleName ModuleName: Identifier Packages: PackageName Packages . PackageName PackageName: Identifier ``` ``` ImportDeclaration: import ImportList ; static import ImportList ; ImportList: Import ImportBindings Import , ImportList Import: ModuleFullyQualifiedName ModuleAliasIdentifier = ModuleFullyQualifiedName ImportBindings: Import : ImportBindList ImportBindList: ImportBind ImportBind , ImportBindList ImportBind: Identifier Identifier = Identifier ModuleAliasIdentifier: Identifier ``` ``` MixinDeclaration: mixin ( ArgumentList ) ; ``` Declarations ------------ ``` Declaration: FuncDeclaration VarDeclarations AliasDeclaration AggregateDeclaration EnumDeclaration ImportDeclaration ConditionalDeclaration StaticForeachDeclaration StaticAssert ``` ``` VarDeclarations: StorageClassesopt BasicType Declarators ; AutoDeclaration Declarators: DeclaratorInitializer DeclaratorInitializer , DeclaratorIdentifierList DeclaratorInitializer: VarDeclarator VarDeclarator TemplateParametersopt = Initializer AltDeclarator AltDeclarator = Initializer DeclaratorIdentifierList: DeclaratorIdentifier DeclaratorIdentifier , DeclaratorIdentifierList DeclaratorIdentifier: VarDeclaratorIdentifier AltDeclaratorIdentifier VarDeclaratorIdentifier: Identifier Identifier TemplateParametersopt = Initializer AltDeclaratorIdentifier: TypeSuffixes Identifier AltDeclaratorSuffixesopt TypeSuffixes Identifier AltDeclaratorSuffixesopt = Initializer TypeSuffixesopt Identifier AltDeclaratorSuffixes TypeSuffixesopt Identifier AltDeclaratorSuffixes = Initializer Declarator: VarDeclarator AltDeclarator VarDeclarator: TypeSuffixesopt Identifier AltDeclarator: TypeSuffixesopt Identifier AltDeclaratorSuffixes TypeSuffixesopt ( AltDeclaratorInner ) TypeSuffixesopt ( AltDeclaratorInner ) AltFuncDeclaratorSuffix TypeSuffixesopt ( AltDeclaratorInner ) AltDeclaratorSuffixes AltDeclaratorInner: TypeSuffixesopt Identifier TypeSuffixesopt Identifier AltFuncDeclaratorSuffix AltDeclarator AltDeclaratorSuffixes: AltDeclaratorSuffix AltDeclaratorSuffix AltDeclaratorSuffixes AltDeclaratorSuffix: [ ] [ AssignExpression ] [ Type ] AltFuncDeclaratorSuffix: Parameters MemberFunctionAttributesopt ``` ``` StorageClasses: StorageClass StorageClass StorageClasses StorageClass: LinkageAttribute AlignAttribute deprecated enum static extern abstract final override synchronized auto scope const immutable inout shared __gshared Property nothrow pure ref ``` ``` Initializer: VoidInitializer NonVoidInitializer NonVoidInitializer: ExpInitializer ArrayInitializer StructInitializer ExpInitializer: AssignExpression ArrayInitializer: [ ArrayMemberInitializationsopt ] ArrayMemberInitializations: ArrayMemberInitialization ArrayMemberInitialization , ArrayMemberInitialization , ArrayMemberInitializations ArrayMemberInitialization: NonVoidInitializer AssignExpression : NonVoidInitializer StructInitializer: { StructMemberInitializersopt } StructMemberInitializers: StructMemberInitializer StructMemberInitializer , StructMemberInitializer , StructMemberInitializers StructMemberInitializer: NonVoidInitializer Identifier : NonVoidInitializer ``` ``` AutoDeclaration: StorageClasses AutoAssignments ; AutoAssignments: AutoAssignment AutoAssignments , AutoAssignment AutoAssignment: Identifier TemplateParametersopt = Initializer ``` ``` AliasDeclaration: alias StorageClassesopt BasicType Declarators ; alias StorageClassesopt BasicType FuncDeclarator ; alias AliasAssignments ; AliasAssignments: AliasAssignment AliasAssignments , AliasAssignment AliasAssignment: Identifier TemplateParametersopt = StorageClassesopt Type Identifier TemplateParametersopt = FunctionLiteral Identifier TemplateParametersopt = StorageClassesopt BasicType Parameters MemberFunctionAttributesopt ``` ``` VoidInitializer: void ``` Types ----- ``` Type: TypeCtorsopt BasicType TypeSuffixesopt TypeCtors: TypeCtor TypeCtor TypeCtors TypeCtor: const immutable inout shared BasicType: FundamentalType . QualifiedIdentifier QualifiedIdentifier Typeof Typeof . QualifiedIdentifier TypeCtor ( Type ) Vector Traits MixinType Vector: __vector ( VectorBaseType ) VectorBaseType: Type FundamentalType: bool byte ubyte short ushort int uint long ulong cent ucent char wchar dchar float double real ifloat idouble ireal cfloat cdouble creal void TypeSuffixes: TypeSuffix TypeSuffixesopt TypeSuffix: * [ ] [ AssignExpression ] [ AssignExpression .. AssignExpression ] [ Type ] delegate Parameters MemberFunctionAttributesopt function Parameters FunctionAttributesopt QualifiedIdentifier: Identifier Identifier . QualifiedIdentifier TemplateInstance TemplateInstance . QualifiedIdentifier Identifier [ AssignExpression ] Identifier [ AssignExpression ]. QualifiedIdentifier ``` ``` Typeof: typeof ( Expression ) typeof ( return ) ``` ``` MixinType: mixin ( ArgumentList ) ``` Attributes ---------- ``` AttributeSpecifier: Attribute : Attribute DeclarationBlock Attribute: LinkageAttribute AlignAttribute DeprecatedAttribute VisibilityAttribute Pragma static extern abstract final override synchronized auto scope const immutable inout shared __gshared AtAttribute FunctionAttributeKwd ref return FunctionAttributeKwd: nothrow pure AtAttribute: @ disable @ nogc @ live Property @ safe @ system @ trusted UserDefinedAttribute Property: @ property DeclarationBlock: DeclDef { DeclDefsopt } ``` ``` LinkageAttribute: extern ( LinkageType ) extern ( C++, QualifiedIdentifier ) extern ( C++, NamespaceList ) LinkageType: C C++ D Windows System Objective-C NamespaceList: ConditionalExpression ConditionalExpression, ConditionalExpression, NamespaceList ``` ``` AlignAttribute: align align ( AssignExpression ) ``` ``` DeprecatedAttribute: deprecated deprecated ( AssignExpression ) ``` ``` VisibilityAttribute: private package package ( QualifiedIdentifier ) protected public export ``` ``` UserDefinedAttribute: @ ( ArgumentList ) @ Identifier @ Identifier ( ArgumentListopt ) @ TemplateInstance @ TemplateInstance ( ArgumentListopt ) ``` Pragmas ------- ``` PragmaDeclaration: Pragma; Pragma DeclarationBlock PragmaStatement: Pragma; Pragma NoScopeStatement Pragma: pragma ( Identifier ) pragma ( Identifier , ArgumentList ) ``` Expressions ----------- ``` Expression: CommaExpression CommaExpression: AssignExpression AssignExpression , CommaExpression ``` ``` AssignExpression: ConditionalExpression ConditionalExpression = AssignExpression ConditionalExpression += AssignExpression ConditionalExpression -= AssignExpression ConditionalExpression *= AssignExpression ConditionalExpression /= AssignExpression ConditionalExpression %= AssignExpression ConditionalExpression &= AssignExpression ConditionalExpression |= AssignExpression ConditionalExpression ^= AssignExpression ConditionalExpression ~= AssignExpression ConditionalExpression <<= AssignExpression ConditionalExpression >>= AssignExpression ConditionalExpression >>>= AssignExpression ConditionalExpression ^^= AssignExpression ``` ``` ConditionalExpression: OrOrExpression OrOrExpression ? Expression : ConditionalExpression ``` ``` OrOrExpression: AndAndExpression OrOrExpression || AndAndExpression ``` ``` AndAndExpression: OrExpression AndAndExpression && OrExpression ``` ``` OrExpression: XorExpression OrExpression | XorExpression ``` ``` XorExpression: AndExpression XorExpression ^ AndExpression ``` ``` AndExpression: CmpExpression AndExpression & CmpExpression ``` ``` CmpExpression: ShiftExpression EqualExpression IdentityExpression RelExpression InExpression ``` ``` EqualExpression: ShiftExpression == ShiftExpression ShiftExpression != ShiftExpression ``` ``` IdentityExpression: ShiftExpression is ShiftExpression ShiftExpression !is ShiftExpression ``` ``` RelExpression: ShiftExpression < ShiftExpression ShiftExpression <= ShiftExpression ShiftExpression > ShiftExpression ShiftExpression >= ShiftExpression ``` ``` InExpression: ShiftExpression in ShiftExpression ShiftExpression !in ShiftExpression ``` ``` ShiftExpression: AddExpression ShiftExpression << AddExpression ShiftExpression >> AddExpression ShiftExpression >>> AddExpression ``` ``` AddExpression: MulExpression AddExpression + MulExpression AddExpression - MulExpression CatExpression ``` ``` CatExpression: AddExpression ~ MulExpression ``` ``` MulExpression: UnaryExpression MulExpression * UnaryExpression MulExpression / UnaryExpression MulExpression % UnaryExpression ``` ``` UnaryExpression: & UnaryExpression ++ UnaryExpression -- UnaryExpression * UnaryExpression - UnaryExpression + UnaryExpression ! UnaryExpression ComplementExpression ( Type ) . Identifier ( Type ) . TemplateInstance DeleteExpression CastExpression PowExpression ``` ``` ComplementExpression: ~ UnaryExpression ``` ``` NewExpression: new AllocatorArgumentsopt Type NewExpressionWithArgs NewExpressionWithArgs: new AllocatorArgumentsopt Type [ AssignExpression ] new AllocatorArgumentsopt Type ( ArgumentListopt ) NewAnonClassExpression AllocatorArguments: ( ArgumentListopt ) ArgumentList: AssignExpression AssignExpression , AssignExpression , ArgumentList ``` ``` DeleteExpression: delete UnaryExpression ``` ``` CastExpression: cast ( Type ) UnaryExpression cast ( TypeCtorsopt ) UnaryExpression ``` ``` PowExpression: PostfixExpression PostfixExpression ^^ UnaryExpression ``` ``` PostfixExpression: PrimaryExpression PostfixExpression . Identifier PostfixExpression . TemplateInstance PostfixExpression . NewExpression PostfixExpression ++ PostfixExpression -- PostfixExpression ( ArgumentListopt ) TypeCtorsopt BasicType ( ArgumentListopt ) IndexExpression SliceExpression ``` ``` IndexExpression: PostfixExpression [ ArgumentList ] ``` ``` SliceExpression: PostfixExpression [ ] PostfixExpression [ Slice ,opt ] Slice: AssignExpression AssignExpression , Slice AssignExpression .. AssignExpression AssignExpression .. AssignExpression , Slice ``` ``` PrimaryExpression: Identifier . Identifier TemplateInstance . TemplateInstance this super null true false $ IntegerLiteral FloatLiteral CharacterLiteral StringLiterals ArrayLiteral AssocArrayLiteral FunctionLiteral AssertExpression MixinExpression ImportExpression NewExpressionWithArgs FundamentalType . Identifier FundamentalType ( ArgumentListopt ) TypeCtor ( Type ) . Identifier TypeCtor ( Type ) ( ArgumentListopt ) Typeof TypeidExpression IsExpression ( Expression ) SpecialKeyword TraitsExpression ``` ``` StringLiterals: StringLiteral StringLiterals StringLiteral ``` ``` ArrayLiteral: [ ArgumentListopt ] ``` ``` AssocArrayLiteral: [ KeyValuePairs ] KeyValuePairs: KeyValuePair KeyValuePair , KeyValuePairs KeyValuePair: KeyExpression : ValueExpression KeyExpression: AssignExpression ValueExpression: AssignExpression ``` ``` FunctionLiteral: function refopt Typeopt ParameterWithAttributes opt FunctionLiteralBody2 delegate refopt Typeopt ParameterWithMemberAttributes opt FunctionLiteralBody2 refopt ParameterWithMemberAttributes FunctionLiteralBody2 FunctionLiteralBody Identifier => AssignExpression ParameterWithAttributes: Parameters FunctionAttributesopt ParameterWithMemberAttributes: Parameters MemberFunctionAttributesopt FunctionLiteralBody2: => AssignExpression FunctionLiteralBody FunctionLiteralBody: BlockStatement FunctionContractsopt BodyStatement ``` ``` AssertExpression: assert ( AssertArguments ) AssertArguments: AssignExpression ,opt AssignExpression , AssignExpression ,opt ``` ``` MixinExpression: mixin ( ArgumentList ) ``` ``` ImportExpression: import ( AssignExpression ) ``` ``` TypeidExpression: typeid ( Type ) typeid ( Expression ) ``` ``` IsExpression: is ( Type ) is ( Type : TypeSpecialization ) is ( Type == TypeSpecialization ) is ( Type : TypeSpecialization , TemplateParameterList ) is ( Type == TypeSpecialization , TemplateParameterList ) is ( Type Identifier ) is ( Type Identifier : TypeSpecialization ) is ( Type Identifier == TypeSpecialization ) is ( Type Identifier : TypeSpecialization , TemplateParameterList ) is ( Type Identifier == TypeSpecialization , TemplateParameterList ) TypeSpecialization: Type struct union class interface enum __vector function delegate super const immutable inout shared return __parameters module package ``` ``` SpecialKeyword: __FILE__ __FILE_FULL_PATH__ __MODULE__ __LINE__ __FUNCTION__ __PRETTY_FUNCTION__ ``` Statements ---------- ``` Statement: ; NonEmptyStatement ScopeBlockStatement NoScopeNonEmptyStatement: NonEmptyStatement BlockStatement NoScopeStatement: ; NonEmptyStatement BlockStatement NonEmptyOrScopeBlockStatement: NonEmptyStatement ScopeBlockStatement NonEmptyStatement: NonEmptyStatementNoCaseNoDefault CaseStatement CaseRangeStatement DefaultStatement NonEmptyStatementNoCaseNoDefault: LabeledStatement ExpressionStatement DeclarationStatement IfStatement WhileStatement DoStatement ForStatement ForeachStatement SwitchStatement FinalSwitchStatement ContinueStatement BreakStatement ReturnStatement GotoStatement WithStatement SynchronizedStatement TryStatement ScopeGuardStatement ThrowStatement AsmStatement MixinStatement ForeachRangeStatement PragmaStatement ConditionalStatement StaticForeachStatement StaticAssert TemplateMixin ImportDeclaration ``` ``` ScopeStatement: NonEmptyStatement BlockStatement ``` ``` ScopeBlockStatement: BlockStatement ``` ``` LabeledStatement: Identifier : Identifier : NoScopeStatement Identifier : Statement ``` ``` BlockStatement: { } { StatementList } StatementList: Statement Statement StatementList ``` ``` ExpressionStatement: Expression ; ``` ``` DeclarationStatement: StorageClassesopt Declaration ``` ``` IfStatement: if ( IfCondition ) ThenStatement if ( IfCondition ) ThenStatement else ElseStatement IfCondition: Expression auto Identifier = Expression TypeCtors Identifier = Expression TypeCtorsopt BasicType Declarator = Expression ThenStatement: ScopeStatement ElseStatement: ScopeStatement ``` ``` WhileStatement: while ( IfCondition ) ScopeStatement ``` ``` DoStatement: do ScopeStatement while ( Expression ) ; ``` ``` ForStatement: for ( Initialize Testopt ; Incrementopt ) ScopeStatement Initialize: ; NoScopeNonEmptyStatement Test: Expression Increment: Expression ``` ``` AggregateForeach: Foreach ( ForeachTypeList ; ForeachAggregate ) ForeachStatement: AggregateForeach NoScopeNonEmptyStatement Foreach: foreach foreach_reverse ForeachTypeList: ForeachType ForeachType , ForeachTypeList ForeachType: ForeachTypeAttributesopt BasicType Declarator ForeachTypeAttributesopt Identifier ForeachTypeAttributesopt alias Identifier ForeachTypeAttributes ForeachTypeAttribute ForeachTypeAttribute ForeachTypeAttributesopt ForeachTypeAttribute: ref TypeCtor enum ForeachAggregate: Expression ``` ``` RangeForeach: Foreach ( ForeachType ; LwrExpression .. UprExpression ) LwrExpression: Expression UprExpression: Expression ForeachRangeStatement: RangeForeach ScopeStatement ``` ``` SwitchStatement: switch ( Expression ) ScopeStatement CaseStatement: case ArgumentList : ScopeStatementList CaseRangeStatement: case FirstExp : .. case LastExp : ScopeStatementList FirstExp: AssignExpression LastExp: AssignExpression DefaultStatement: default : ScopeStatementList ScopeStatementList: StatementListNoCaseNoDefault StatementListNoCaseNoDefault: StatementNoCaseNoDefault StatementNoCaseNoDefault StatementListNoCaseNoDefault StatementNoCaseNoDefault: ; NonEmptyStatementNoCaseNoDefault ScopeBlockStatement ``` ``` FinalSwitchStatement: final switch ( Expression ) ScopeStatement ``` ``` ContinueStatement: continue Identifieropt ; ``` ``` BreakStatement: break Identifieropt ; ``` ``` ReturnStatement: return Expressionopt ; ``` ``` GotoStatement: goto Identifier ; goto default ; goto case ; goto case Expression ; ``` ``` WithStatement: with ( Expression ) ScopeStatement with ( Symbol ) ScopeStatement with ( TemplateInstance ) ScopeStatement ``` ``` SynchronizedStatement: synchronized ScopeStatement synchronized ( Expression ) ScopeStatement ``` ``` TryStatement: try ScopeStatement Catches try ScopeStatement Catches FinallyStatement try ScopeStatement FinallyStatement Catches: Catch Catch Catches Catch: catch ( CatchParameter ) NoScopeNonEmptyStatement CatchParameter: BasicType Identifieropt FinallyStatement: finally NoScopeNonEmptyStatement ``` ``` ThrowStatement: throw Expression ; ``` ``` ScopeGuardStatement: scope(exit) NonEmptyOrScopeBlockStatement scope(success) NonEmptyOrScopeBlockStatement scope(failure) NonEmptyOrScopeBlockStatement ``` ``` AsmStatement: asm FunctionAttributesopt { AsmInstructionListopt } AsmInstructionList: AsmInstruction ; AsmInstruction ; AsmInstructionList ``` ``` PragmaStatement ``` ``` MixinStatement: mixin ( ArgumentList ) ; ``` Structs and Unions ------------------ ``` AggregateDeclaration: ClassDeclaration InterfaceDeclaration StructDeclaration UnionDeclaration StructDeclaration: struct Identifier ; struct Identifier AggregateBody StructTemplateDeclaration AnonStructDeclaration AnonStructDeclaration: struct AggregateBody UnionDeclaration: union Identifier ; union Identifier AggregateBody UnionTemplateDeclaration AnonUnionDeclaration AnonUnionDeclaration: union AggregateBody AggregateBody: { DeclDefsopt } ``` ``` Postblit: this ( this ) MemberFunctionAttributesopt ; this ( this ) MemberFunctionAttributesopt FunctionBody ``` ``` StructInvariant: invariant ( ) BlockStatement invariant BlockStatement invariant ( AssertArguments ) ; ``` Classes ------- ``` ClassDeclaration: class Identifier ; class Identifier BaseClassListopt AggregateBody ClassTemplateDeclaration BaseClassList: : SuperClass : SuperClass , Interfaces : Interfaces SuperClass: BasicType Interfaces: Interface Interface , Interfaces Interface: BasicType ``` ``` Constructor: this Parameters MemberFunctionAttributesopt ; this Parameters MemberFunctionAttributesopt FunctionBody ConstructorTemplate ``` ``` Destructor: ~ this ( ) MemberFunctionAttributesopt ; ~ this ( ) MemberFunctionAttributesopt FunctionBody ``` ``` StaticConstructor: static this ( ) MemberFunctionAttributesopt ; static this ( ) MemberFunctionAttributesopt FunctionBody ``` ``` StaticDestructor: static ~ this ( ) MemberFunctionAttributesopt ; static ~ this ( ) MemberFunctionAttributesopt FunctionBody ``` ``` SharedStaticConstructor: shared static this ( ) MemberFunctionAttributesopt ; shared static this ( ) MemberFunctionAttributesopt FunctionBody ``` ``` SharedStaticDestructor: shared static ~ this ( ) MemberFunctionAttributesopt ; shared static ~ this ( ) MemberFunctionAttributesopt FunctionBody ``` ``` ClassInvariant: invariant ( ) BlockStatement invariant BlockStatement invariant ( AssertArguments ) ; ``` ``` Allocator: new Parameters ; new Parameters FunctionBody ``` ``` Deallocator: delete Parameters ; delete Parameters FunctionBody ``` ``` AliasThis: alias Identifier this ; ``` ``` NewAnonClassExpression: new AllocatorArgumentsopt class ConstructorArgsopt SuperClassopt Interfacesopt AggregateBody ConstructorArgs: ( ArgumentListopt ) ``` ``` class Identifier : SuperClass Interfaces AggregateBody // ... new AllocatorArguments Identifier ConstructorArgs ``` Interfaces ---------- ``` InterfaceDeclaration: interface Identifier ; interface Identifier BaseInterfaceListopt AggregateBody InterfaceTemplateDeclaration BaseInterfaceList: : Interfaces ``` Enums ----- ``` EnumDeclaration: enum Identifier EnumBody enum Identifier : EnumBaseType EnumBody AnonymousEnumDeclaration EnumBaseType: Type EnumBody: { EnumMembers } ; EnumMembers: EnumMember EnumMember , EnumMember , EnumMembers EnumMemberAttributes: EnumMemberAttribute EnumMemberAttribute EnumMemberAttributes EnumMemberAttribute: DeprecatedAttribute UserDefinedAttribute @disable EnumMember: EnumMemberAttributesopt Identifier EnumMemberAttributesopt Identifier = AssignExpression AnonymousEnumDeclaration: enum : EnumBaseType { EnumMembers } enum { EnumMembers } enum { AnonymousEnumMembers } AnonymousEnumMembers: AnonymousEnumMember AnonymousEnumMember , AnonymousEnumMember , AnonymousEnumMembers AnonymousEnumMember: EnumMember Type Identifier = AssignExpression ``` Functions --------- ``` FuncDeclaration: StorageClassesopt BasicType FuncDeclarator FunctionBody AutoFuncDeclaration AutoFuncDeclaration: StorageClasses Identifier FuncDeclaratorSuffix FunctionBody FuncDeclarator: TypeSuffixesopt Identifier FuncDeclaratorSuffix FuncDeclaratorSuffix: Parameters MemberFunctionAttributesopt TemplateParameters Parameters MemberFunctionAttributesopt Constraintopt ``` ``` Parameters: ( ParameterListopt ) ParameterList: Parameter Parameter , ParameterList VariadicArgumentsAttributes ... Parameter: ParameterAttributesopt BasicType Declarator ParameterAttributesopt BasicType Declarator ... ParameterAttributesopt BasicType Declarator = AssignExpression ParameterAttributesopt Type ParameterAttributesopt Type ... ParameterAttributes: InOut UserDefinedAttribute ParameterAttributes InOut ParameterAttributes UserDefinedAttribute ParameterAttributes InOut: auto TypeCtor final in lazy out ref return ref scope VariadicArgumentsAttributes: VariadicArgumentsAttribute VariadicArgumentsAttribute VariadicArgumentsAttributes VariadicArgumentsAttribute: const immutable return scope shared ``` ``` FunctionAttributes: FunctionAttribute FunctionAttribute FunctionAttributes FunctionAttribute: FunctionAttributeKwd Property MemberFunctionAttributes: MemberFunctionAttribute MemberFunctionAttribute MemberFunctionAttributes MemberFunctionAttribute: const immutable inout return shared FunctionAttribute ``` ``` FunctionBody: SpecifiedFunctionBody MissingFunctionBody ShortenedFunctionBody FunctionLiteralBody: SpecifiedFunctionBody SpecifiedFunctionBody: doopt BlockStatement FunctionContractsopt InOutContractExpression doopt BlockStatement FunctionContractsopt InOutStatement do BlockStatement MissingFunctionBody: ; FunctionContractsopt InOutContractExpression ; FunctionContractsopt InOutStatement ShortenedFunctionBody: => AssignExpression ; ``` ``` FunctionContracts: FunctionContract FunctionContract FunctionContracts FunctionContract: InOutContractExpression InOutStatement InOutContractExpression: InContractExpression OutContractExpression InOutStatement: InStatement OutStatement InContractExpression: in ( AssertArguments ) OutContractExpression: out ( ; AssertArguments ) out ( Identifier ; AssertArguments ) InStatement: in BlockStatement OutStatement: out BlockStatement out ( Identifier ) BlockStatement ``` Templates --------- ``` TemplateDeclaration: template Identifier TemplateParameters Constraintopt { DeclDefsopt } TemplateParameters: ( TemplateParameterListopt ) TemplateParameterList: TemplateParameter TemplateParameter , TemplateParameter , TemplateParameterList TemplateParameter: TemplateTypeParameter TemplateValueParameter TemplateAliasParameter TemplateSequenceParameter TemplateThisParameter ``` ``` TemplateInstance: Identifier TemplateArguments TemplateArguments: ! ( TemplateArgumentListopt ) ! TemplateSingleArgument TemplateArgumentList: TemplateArgument TemplateArgument , TemplateArgument , TemplateArgumentList TemplateArgument: Type AssignExpression Symbol Symbol: SymbolTail . SymbolTail SymbolTail: Identifier Identifier . SymbolTail TemplateInstance TemplateInstance . SymbolTail TemplateSingleArgument: Identifier FundamentalType CharacterLiteral StringLiteral IntegerLiteral FloatLiteral true false null this SpecialKeyword ``` ``` TemplateTypeParameter: Identifier Identifier TemplateTypeParameterSpecialization Identifier TemplateTypeParameterDefault Identifier TemplateTypeParameterSpecialization TemplateTypeParameterDefault TemplateTypeParameterSpecialization: : Type TemplateTypeParameterDefault: = Type ``` ``` TemplateThisParameter: this TemplateTypeParameter ``` ``` TemplateValueParameter: BasicType Declarator BasicType Declarator TemplateValueParameterSpecialization BasicType Declarator TemplateValueParameterDefault BasicType Declarator TemplateValueParameterSpecialization TemplateValueParameterDefault TemplateValueParameterSpecialization: : ConditionalExpression TemplateValueParameterDefault: = AssignExpression = SpecialKeyword ``` ``` TemplateAliasParameter: alias Identifier TemplateAliasParameterSpecializationopt TemplateAliasParameterDefaultopt alias BasicType Declarator TemplateAliasParameterSpecializationopt TemplateAliasParameterDefaultopt TemplateAliasParameterSpecialization: : Type : ConditionalExpression TemplateAliasParameterDefault: = Type = ConditionalExpression ``` ``` TemplateSequenceParameter: Identifier ... ``` ``` ConstructorTemplate: this TemplateParameters Parameters MemberFunctionAttributesopt Constraintopt : this TemplateParameters Parameters MemberFunctionAttributesopt Constraintopt FunctionBody ``` ``` ClassTemplateDeclaration: class Identifier TemplateParameters ; class Identifier TemplateParameters Constraintopt BaseClassListopt AggregateBody class Identifier TemplateParameters BaseClassListopt Constraintopt AggregateBody InterfaceTemplateDeclaration: interface Identifier TemplateParameters ; interface Identifier TemplateParameters Constraintopt BaseInterfaceListopt AggregateBody interface Identifier TemplateParameters BaseInterfaceList Constraint AggregateBody StructTemplateDeclaration: struct Identifier TemplateParameters ; struct Identifier TemplateParameters Constraintopt AggregateBody UnionTemplateDeclaration: union Identifier TemplateParameters ; union Identifier TemplateParameters Constraintopt AggregateBody ``` ``` Constraint: if ( Expression ) ``` Template Mixins --------------- ``` TemplateMixinDeclaration: mixin template Identifier TemplateParameters Constraintopt { DeclDefsopt } TemplateMixin: mixin MixinTemplateName TemplateArgumentsopt Identifieropt ; MixinTemplateName: . MixinQualifiedIdentifier MixinQualifiedIdentifier Typeof . MixinQualifiedIdentifier MixinQualifiedIdentifier: Identifier Identifier . MixinQualifiedIdentifier TemplateInstance . MixinQualifiedIdentifier ``` Conditional Compilation ----------------------- ``` ConditionalDeclaration: Condition DeclarationBlock Condition DeclarationBlock else DeclarationBlock Condition : DeclDefsopt Condition DeclarationBlock else : DeclDefsopt ConditionalStatement: Condition NoScopeNonEmptyStatement Condition NoScopeNonEmptyStatement else NoScopeNonEmptyStatement ``` ``` Condition: VersionCondition DebugCondition StaticIfCondition ``` ``` VersionCondition: version ( IntegerLiteral ) version ( Identifier ) version ( unittest ) version ( assert ) ``` ``` VersionSpecification: version = Identifier ; version = IntegerLiteral ; ``` ``` DebugCondition: debug debug ( IntegerLiteral ) debug ( Identifier ) ``` ``` DebugSpecification: debug = Identifier ; debug = IntegerLiteral ; ``` ``` StaticIfCondition: static if ( AssignExpression ) ``` ``` StaticForeach: static AggregateForeach static RangeForeach StaticForeachDeclaration: StaticForeach DeclarationBlock StaticForeach : DeclDefsopt StaticForeachStatement: StaticForeach NoScopeNonEmptyStatement ``` ``` StaticAssert: static assert ( AssertArguments ); ``` Traits ------ ``` TraitsExpression: __traits ( TraitsKeyword , TraitsArguments ) TraitsKeyword: isAbstractClass isArithmetic isAssociativeArray isFinalClass isPOD isNested isFuture isDeprecated isFloating isIntegral isScalar isStaticArray isUnsigned isDisabled isVirtualFunction isVirtualMethod isAbstractFunction isFinalFunction isStaticFunction isOverrideFunction isTemplate isRef isOut isLazy isReturnOnStack isZeroInit isModule isPackage hasMember hasCopyConstructor hasPostblit identifier getAliasThis getAttributes getFunctionAttributes getFunctionVariadicStyle getLinkage getLocation getMember getOverloads getParameterStorageClasses getPointerBitmap getCppNamespaces getVisibility getProtection getTargetInfo getVirtualFunctions getVirtualMethods getUnitTests parent child classInstanceSize getVirtualIndex allMembers derivedMembers isSame compiles TraitsArguments: TraitsArgument TraitsArgument , TraitsArguments TraitsArgument: AssignExpression Type ``` Unit Tests ---------- ``` UnitTest: unittest BlockStatement ``` D x86 Inline Assembler ---------------------- ``` AsmStatement: asm FunctionAttributesopt { AsmInstructionListopt } AsmInstructionList: AsmInstruction ; AsmInstruction ; AsmInstructionList ``` ``` AsmInstruction: Identifier : AsmInstruction align IntegerExpression even naked db Operands ds Operands di Operands dl Operands df Operands dd Operands de Operands db StringLiteral ds StringLiteral di StringLiteral dl StringLiteral dw StringLiteral dq StringLiteral Opcode Opcode Operands Operands: Operand Operand , Operands ``` ``` IntegerExpression: IntegerLiteral Identifier ``` ``` Register: AL AH AX EAX BL BH BX EBX CL CH CX ECX DL DH DX EDX BP EBP SP ESP DI EDI SI ESI ES CS SS DS GS FS CR0 CR2 CR3 CR4 DR0 DR1 DR2 DR3 DR6 DR7 TR3 TR4 TR5 TR6 TR7 ST ST(0) ST(1) ST(2) ST(3) ST(4) ST(5) ST(6) ST(7) MM0 MM1 MM2 MM3 MM4 MM5 MM6 MM7 XMM0 XMM1 XMM2 XMM3 XMM4 XMM5 XMM6 XMM7 ``` ``` Register64: RAX RBX RCX RDX BPL RBP SPL RSP DIL RDI SIL RSI R8B R8W R8D R8 R9B R9W R9D R9 R10B R10W R10D R10 R11B R11W R11D R11 R12B R12W R12D R12 R13B R13W R13D R13 R14B R14W R14D R14 R15B R15W R15D R15 XMM8 XMM9 XMM10 XMM11 XMM12 XMM13 XMM14 XMM15 YMM0 YMM1 YMM2 YMM3 YMM4 YMM5 YMM6 YMM7 YMM8 YMM9 YMM10 YMM11 YMM12 YMM13 YMM14 YMM15 ``` ``` Operand: AsmExp AsmExp: AsmLogOrExp AsmLogOrExp ? AsmExp : AsmExp AsmLogOrExp: AsmLogAndExp AsmLogOrExp || AsmLogAndExp AsmLogAndExp: AsmOrExp AsmLogAndExp && AsmOrExp AsmOrExp: AsmXorExp AsmOrExp | AsmXorExp AsmXorExp: AsmAndExp AsmXorExp ^ AsmAndExp AsmAndExp: AsmEqualExp AsmAndExp & AsmEqualExp AsmEqualExp: AsmRelExp AsmEqualExp == AsmRelExp AsmEqualExp != AsmRelExp AsmRelExp: AsmShiftExp AsmRelExp < AsmShiftExp AsmRelExp <= AsmShiftExp AsmRelExp > AsmShiftExp AsmRelExp >= AsmShiftExp AsmShiftExp: AsmAddExp AsmShiftExp << AsmAddExp AsmShiftExp >> AsmAddExp AsmShiftExp >>> AsmAddExp AsmAddExp: AsmMulExp AsmAddExp + AsmMulExp AsmAddExp - AsmMulExp AsmMulExp: AsmBrExp AsmMulExp * AsmBrExp AsmMulExp / AsmBrExp AsmMulExp % AsmBrExp AsmBrExp: AsmUnaExp AsmBrExp [ AsmExp ] AsmUnaExp: AsmTypePrefix AsmExp offsetof AsmExp seg AsmExp + AsmUnaExp - AsmUnaExp ! AsmUnaExp ~ AsmUnaExp AsmPrimaryExp AsmPrimaryExp: IntegerLiteral FloatLiteral __LOCAL_SIZE $ Register Register : AsmExp Register64 Register64 : AsmExp DotIdentifier this DotIdentifier: Identifier Identifier . DotIdentifier FundamentalType . Identifier ``` ``` AsmTypePrefix: near ptr far ptr word ptr dword ptr qword ptr FundamentalType ptr ``` Named Character Entities ------------------------ ``` NamedCharacterEntity: & Identifier ; ``` Application Binary Interface ---------------------------- ``` MangledName: _D QualifiedName Type _D QualifiedName Z // Internal ``` ``` QualifiedName: SymbolFunctionName SymbolFunctionName QualifiedName SymbolFunctionName: SymbolName SymbolName TypeFunctionNoReturn SymbolName M TypeModifiersopt TypeFunctionNoReturn ``` ``` SymbolName: LName TemplateInstanceName IdentifierBackRef 0 // anonymous symbols ``` ``` TemplateInstanceName: TemplateID LName TemplateArgs Z TemplateID: __T __U // for symbols declared inside template constraint TemplateArgs: TemplateArg TemplateArg TemplateArgs TemplateArg: TemplateArgX H TemplateArgX ``` ``` TemplateArgX: T Type V Type Value S QualifiedName X Number ExternallyMangledName ``` ``` Value: n i Number N Number e HexFloat c HexFloat c HexFloat CharWidth Number _ HexDigits A Number Value... S Number Value... HexFloat: NAN INF NINF N HexDigits P Exponent HexDigits P Exponent Exponent: N Number Number HexDigits: HexDigit HexDigit HexDigits HexDigit: Digit A B C D E F CharWidth: a w d ``` ``` Name: Namestart Namestart Namechars Namestart: _ Alpha Namechar: Namestart Digit Namechars: Namechar Namechar Namechars ``` ``` LName: Number Name Number: Digit Digit Number Digit: 0 1 2 3 4 5 6 7 8 9 ``` ``` TypeBackRef: Q NumberBackRef IdentifierBackRef: Q NumberBackRef NumberBackRef: lower-case-letter upper-case-letter NumberBackRef ``` ``` Type: TypeModifiersopt TypeX TypeBackRef TypeX: TypeArray TypeStaticArray TypeAssocArray TypePointer TypeFunction TypeIdent TypeClass TypeStruct TypeEnum TypeTypedef TypeDelegate TypeVoid TypeByte TypeUbyte TypeShort TypeUshort TypeInt TypeUint TypeLong TypeUlong TypeCent TypeUcent TypeFloat TypeDouble TypeReal TypeIfloat TypeIdouble TypeIreal TypeCfloat TypeCdouble TypeCreal TypeBool TypeChar TypeWchar TypeDchar TypeNull TypeTuple TypeVector TypeModifiers: Const Wild Wild Const Shared Shared Const Shared Wild Shared Wild Const Immutable Shared: O Const: x Immutable: y Wild: Ng TypeArray: A Type TypeStaticArray: G Number Type TypeAssocArray: H Type Type TypePointer: P Type TypeVector: Nh Type TypeFunction: TypeFunctionNoReturn Type TypeFunctionNoReturn: CallConvention FuncAttrsopt Parametersopt ParamClose CallConvention: F // D U // C W // Windows R // C++ Y // Objective-C FuncAttrs: FuncAttr FuncAttr FuncAttrs FuncAttr: FuncAttrPure FuncAttrNothrow FuncAttrRef FuncAttrProperty FuncAttrNogc FuncAttrReturn FuncAttrScope FuncAttrTrusted FuncAttrSafe FuncAttrLive ``` ``` FuncAttrPure: Na FuncAttrNogc: Ni FuncAttrNothrow: Nb FuncAttrProperty: Nd FuncAttrRef: Nc FuncAttrReturn: Nj FuncAttrScope: Nl FuncAttrTrusted: Ne FuncAttrSafe: Nf FuncAttrLive: Nm Parameters: Parameter Parameter Parameters Parameter: Parameter2 M Parameter2 // scope Nk Parameter2 // return Parameter2: Type I Type // in J Type // out K Type // ref L Type // lazy ParamClose X // variadic T t...) style Y // variadic T t,...) style Z // not variadic TypeIdent: I QualifiedName TypeClass: C QualifiedName TypeStruct: S QualifiedName TypeEnum: E QualifiedName TypeTypedef: T QualifiedName TypeDelegate: D TypeModifiersopt TypeFunction TypeVoid: v TypeByte: g TypeUbyte: h TypeShort: s TypeUshort: t TypeInt: i TypeUint: k TypeLong: l TypeUlong: m TypeCent: zi TypeUcent: zk TypeFloat: f TypeDouble: d TypeReal: e TypeIfloat: o TypeIdouble: p TypeIreal: j TypeCfloat: q TypeCdouble: r TypeCreal: c TypeBool: b TypeChar: a TypeWchar: u TypeDchar: w TypeNull: n TypeTuple: B Parameters Z ```
programming_docs
d Interfaces Interfaces ========== **Contents** 1. [Interfaces with Contracts](#interface-contracts) 2. [Const and Immutable Interfaces](#const-interface) 3. [COM Interfaces](#com-interfaces) 4. [C++ Interfaces](#cpp-interfaces) An *Interface* describes a list of functions that a class which inherits from the interface must implement. ``` InterfaceDeclaration: interface Identifier ; interface Identifier BaseInterfaceListopt AggregateBody InterfaceTemplateDeclaration BaseInterfaceList: : Interfaces ``` **Implementation Defined:** Specialized interfaces may be supported: 1. [*COM Interfaces*](#com-interfaces) are binary compatible with COM/OLE/ActiveX objects for Windows. 2. [*C++ Interfaces*](#cpp-interfaces) are binary compatible with C++ abstract classes. 3. [Objective-C Interfaces](objc_interface#protocols) are binary compatible with Objective-C protocols. A class that implements an interface can be implicitly converted to a reference to that interface. Interfaces cannot derive from classes; only from other interfaces. Classes cannot derive from an interface multiple times. ``` interface D { void foo(); } class A : D, D // error, duplicate interface { } ``` An instance of an interface cannot be created. ``` interface D { void foo(); } ... D d = new D(); // error, cannot create instance of interface ``` Virtual interface member functions do not have implementations. Interfaces are expected to implement static or final functions. ``` interface D { void bar() { } // error, implementation not allowed static void foo() { } // ok final void abc() { } // ok } ``` Interfaces can have function templates in the members. All instantiated functions are implicitly `final`. ``` interface D { void foo(T)() { } // ok, it's implicitly final } ``` Classes that inherit from an interface may not override final or static interface member functions. ``` interface D { void bar(); static void foo() { } final void abc() { } } class C : D { void bar() { } // ok void foo() { } // error, cannot override static D.foo() void abc() { } // error, cannot override final D.abc() } ``` All interface functions must be defined in a class that inherits from that interface: ``` interface D { void foo(); } class A : D { void foo() { } // ok, provides implementation } class B : D { int foo() { } // error, no void foo() implementation } ``` Interfaces can be inherited and functions overridden: ``` interface D { int foo(); } class A : D { int foo() { return 1; } } class B : A { int foo() { return 2; } } ... B b = new B(); b.foo(); // returns 2 D d = cast(D) b; // ok since B inherits A's D implementation d.foo(); // returns 2; ``` Interfaces can be reimplemented in derived classes: ``` interface D { int foo(); } class A : D { int foo() { return 1; } } class B : A, D { int foo() { return 2; } } ... B b = new B(); b.foo(); // returns 2 D d = cast(D) b; d.foo(); // returns 2 A a = cast(A) b; D d2 = cast(D) a; d2.foo(); // returns 2, even though it is A's D, not B's D ``` A reimplemented interface must implement all the interface functions, it does not inherit them from a super class: ``` interface D { int foo(); } class A : D { int foo() { return 1; } } class B : A, D { } // error, no foo() for interface D ``` Interfaces with Contracts ------------------------- Interface member functions can have contracts even though there is no body for the function. The contracts are inherited by any class member function that implements that interface member function. ``` interface I { int foo(int i) in { assert(i > 7); } out (result) { assert(result & 1); } void bar(); } ``` Const and Immutable Interfaces ------------------------------ If an interface has `const` or `immutable` storage class, then all members of the interface are `const` or `immutable`. This storage class is not inherited. COM Interfaces -------------- A variant on interfaces is the COM interface. A COM interface is designed to map directly onto a Windows COM object. Any COM object can be represented by a COM interface, and any D object with a COM interface can be used by external COM clients. A COM interface is defined as one that derives from the interface `core.stdc.win`­`dows.com.IUnknown`. A COM interface differs from a regular D interface in that: * It derives from the interface `core.stdc.windows.com.IUnknown`. * It cannot be the argument to [`destroy`](https://dlang.org/phobos/object.html#destroy). * References cannot be upcast to the enclosing class object, nor can they be downcast to a derived interface. Implement `QueryInterface()` for that interface in standard COM fashion to convert to another COM interface. * Classes derived from COM interfaces are COM classes. * The default linkage for member functions of COM classes is `extern(System)`. **Note:** To implement or override any base-class methods of D interfaces or classes (ones which do not inherit from `IUnknown`), explicitly mark them as having the `extern(D)` linkage. ``` import core.sys.windows.windows; import core.stdc.windows.com; interface IText { void write(); } abstract class Printer : IText { void print() { } } class C : Printer, IUnknown { // Implements the IText `write` class method. extern(D) void write() { } // Overrides the Printer `print` class method. extern(D) override void print() { } // Overrides the Object base class `toString` method. extern(D) override string toString() { return "Class C"; } // Methods of class implementing the IUnknown interface have // the extern(System) calling convention by default. HRESULT QueryInterface(const(IID)*, void**); uint AddRef(); uint Release(); } ``` The same applies to other `Object` methods such as `opCmp`, `toHash`, etc. * The first member of the COM `vtbl[]` is not the pointer to the InterfaceInfo, but the first virtual function pointer. See also [Modern COM Programming in D](http://www.lunesu.com/uploads/ModernCOMProgramminginD.pdf) C++ Interfaces -------------- C++ interfaces are interfaces declared with C++ linkage: ``` extern (C++) interface Ifoo { void foo(); void bar(); } ``` which is meant to correspond with the following C++ declaration: ``` class Ifoo { virtual void foo(); virtual void bar(); }; ``` Any interface that derives from a C++ interface is also a C++ interface. A C++ interface differs from a D interface in that: * It cannot be the argument to [`destroy`](https://dlang.org/phobos/object.html#destroy). * References cannot be upcast to the enclosing class object, nor can they be downcast to a derived interface. * The C++ calling convention is the default convention for its member functions, rather than the D calling convention. * The first member of the `vtbl[]` is not the pointer to the `Interface`, but the first virtual function pointer. d rt.alloca rt.alloca ========= Implementation of alloca() standard C routine. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright Source [rt/alloca.d](https://github.com/dlang/druntime/blob/master/src/rt/alloca.d) void\* **\_\_alloca**(int nbytes); Allocate data from the caller's stack frame. This is a 'magic' function that needs help from the compiler to work right, do not change its name, do not call it from other compilers. Input nbytes number of bytes to allocate ECX address of variable with # of bytes in locals This is adjusted upon return to reflect the additional size of the stack frame. Returns: EAX allocated data, null if stack overflows d std.windows.syserror std.windows.syserror ==================== Convert Win32 error code to string. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com) Credits Based on code written by Regan Heath @trusted string **sysErrorString**(DWORD errCode, int langId = LANG\_NEUTRAL, int subLangId = SUBLANG\_DEFAULT); Query the text for a Windows error code, as returned by [`GetLastError`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms679360.aspx), as a D string. class **WindowsException**: object.Exception; Thrown if errors that set [`GetLastError`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms679360.aspx) occur. final @property DWORD **code**(); `GetLastError`'s return value. @safe T **wenforce**(T, S)(T value, lazy S msg = null, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_) Constraints: if (isSomeString!S); If `!!value` is true, `value` is returned. Otherwise, `new WindowsException(GetLastError(), msg)` is thrown. `WindowsException` assumes that the last operation set `GetLastError()` appropriately. Example ``` wenforce(DeleteFileA("junk.tmp"), "DeleteFile failed"); ``` d core.stdc.locale core.stdc.locale ================ D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<locale.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/locale.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly Source [core/stdc/locale.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/locale.d) Standards: ISO/IEC 9899:1999 (E) struct **lconv**; enum int **LC\_CTYPE**; enum int **LC\_NUMERIC**; enum int **LC\_TIME**; enum int **LC\_COLLATE**; enum int **LC\_MONETARY**; enum int **LC\_MESSAGES**; enum int **LC\_ALL**; enum int **LC\_PAPER**; enum int **LC\_NAME**; enum int **LC\_ADDRESS**; enum int **LC\_TELEPHONE**; enum int **LC\_MEASUREMENT**; enum int **LC\_IDENTIFICATION**; nothrow @nogc @system char\* **setlocale**(int category, scope const char\* locale); nothrow @nogc @trusted lconv\* **localeconv**(); d core.stdc.errno core.stdc.errno =============== D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<errno.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/errno.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly, Alex Rønne Petersen Source <https://github.com/dlang/druntime/blob/master/src/core/stdc/errno.d> Standards: ISO/IEC 9899:1999 (E) enum int **EPERM**; enum int **ENOENT**; enum int **ESRCH**; enum int **EINTR**; enum int **EIO**; enum int **ENXIO**; enum int **E2BIG**; enum int **ENOEXEC**; enum int **EBADF**; enum int **ECHILD**; enum int **EAGAIN**; enum int **ENOMEM**; enum int **EACCES**; enum int **EFAULT**; enum int **ENOTBLK**; enum int **EBUSY**; enum int **EEXIST**; enum int **EXDEV**; enum int **ENODEV**; enum int **ENOTDIR**; enum int **EISDIR**; enum int **EINVAL**; enum int **ENFILE**; enum int **EMFILE**; enum int **ENOTTY**; enum int **ETXTBSY**; enum int **EFBIG**; enum int **ENOSPC**; enum int **ESPIPE**; enum int **EROFS**; enum int **EMLINK**; enum int **EPIPE**; enum int **EDOM**; enum int **ERANGE**; enum int **EDEADLK**; enum int **ENAMETOOLONG**; enum int **ENOLCK**; enum int **ENOSYS**; enum int **ENOTEMPTY**; enum int **ELOOP**; enum int **EWOULDBLOCK**; enum int **ENOMSG**; enum int **EIDRM**; enum int **ECHRNG**; enum int **EL2NSYNC**; enum int **EL3HLT**; enum int **EL3RST**; enum int **ELNRNG**; enum int **EUNATCH**; enum int **ENOCSI**; enum int **EL2HLT**; enum int **EBADE**; enum int **EBADR**; enum int **EXFULL**; enum int **ENOANO**; enum int **EBADRQC**; enum int **EBADSLT**; enum int **EDEADLOCK**; enum int **EBFONT**; enum int **ENOSTR**; enum int **ENODATA**; enum int **ETIME**; enum int **ENOSR**; enum int **ENONET**; enum int **ENOPKG**; enum int **EREMOTE**; enum int **ENOLINK**; enum int **EADV**; enum int **ESRMNT**; enum int **ECOMM**; enum int **EPROTO**; enum int **EMULTIHOP**; enum int **EDOTDOT**; enum int **EBADMSG**; enum int **EOVERFLOW**; enum int **ENOTUNIQ**; enum int **EBADFD**; enum int **EREMCHG**; enum int **ELIBACC**; enum int **ELIBBAD**; enum int **ELIBSCN**; enum int **ELIBMAX**; enum int **ELIBEXEC**; enum int **EILSEQ**; enum int **ERESTART**; enum int **ESTRPIPE**; enum int **EUSERS**; enum int **ENOTSOCK**; enum int **EDESTADDRREQ**; enum int **EMSGSIZE**; enum int **EPROTOTYPE**; enum int **ENOPROTOOPT**; enum int **EPROTONOSUPPORT**; enum int **ESOCKTNOSUPPORT**; enum int **EOPNOTSUPP**; enum int **ENOTSUP**; enum int **EPFNOSUPPORT**; enum int **EAFNOSUPPORT**; enum int **EADDRINUSE**; enum int **EADDRNOTAVAIL**; enum int **ENETDOWN**; enum int **ENETUNREACH**; enum int **ENETRESET**; enum int **ECONNABORTED**; enum int **ECONNRESET**; enum int **ENOBUFS**; enum int **EISCONN**; enum int **ENOTCONN**; enum int **ESHUTDOWN**; enum int **ETOOMANYREFS**; enum int **ETIMEDOUT**; enum int **ECONNREFUSED**; enum int **EHOSTDOWN**; enum int **EHOSTUNREACH**; enum int **EALREADY**; enum int **EINPROGRESS**; enum int **ESTALE**; enum int **EUCLEAN**; enum int **ENOTNAM**; enum int **ENAVAIL**; enum int **EISNAM**; enum int **EREMOTEIO**; enum int **EDQUOT**; enum int **ENOMEDIUM**; enum int **EMEDIUMTYPE**; enum int **ECANCELED**; enum int **ENOKEY**; enum int **EKEYEXPIRED**; enum int **EKEYREVOKED**; enum int **EKEYREJECTED**; enum int **EOWNERDEAD**; enum int **ENOTRECOVERABLE**; enum int **ERFKILL**; enum int **EHWPOISON**; d Lexical Lexical ======= **Contents** 1. [Source Text](#source_text) 2. [Character Set](#character_set) 3. [End of File](#end_of_file) 4. [End of Line](#end_of_line) 5. [White Space](#white_space) 6. [Comments](#comment) 7. [Tokens](#tokens) 8. [Identifiers](#identifiers) 9. [String Literals](#string_literals) 1. [Wysiwyg Strings](#wysiwyg) 2. [Double Quoted Strings](#double_quoted_strings) 3. [Hex Strings](#hex_strings) 4. [Delimited Strings](#delimited_strings) 5. [Token Strings](#token_strings) 6. [String Postfix](#string_postfix) 10. [Escape Sequences](#escape_sequences) 11. [Character Literals](#characterliteral) 12. [Integer Literals](#integerliteral) 13. [Floating Point Literals](#floatliteral) 14. [Keywords](#keywords) 15. [Special Tokens](#specialtokens) 16. [Special Token Sequences](#special-token-sequence) The lexical analysis is independent of the syntax parsing and the semantic analysis. The lexical analyzer splits the source text up into tokens. The lexical grammar describes the syntax of these tokens. The grammar is designed to be suitable for high speed scanning and to make it easy to write a correct scanner. It has a minimum of special case rules and there is only one phase of translation. Source Text ----------- Source text can be in any one of the following encodings: * ASCII (strictly, 7-bit ASCII) * UTF-8 * UTF-16BE * UTF-16LE * UTF-32BE * UTF-32LE One of the following UTF BOMs (Byte Order Marks) can be present at the beginning of the source text: UTF Byte Order Marks| **Format** | **BOM** | | UTF-8 | EF BB BF | | UTF-16BE | FE FF | | UTF-16LE | FF FE | | UTF-32BE | 00 00 FE FF | | UTF-32LE | FF FE 00 00 | | ASCII | no BOM | If the source file does not start with a BOM, then the first character must be less than or equal to U+0000007F. The source text is decoded from its source representation into Unicode [*Character*](#Character)s. The [*Character*](#Character)s are further divided into: [*WhiteSpace*](#WhiteSpace), [*EndOfLine*](#EndOfLine), [*Comment*](#Comment)s, [*SpecialTokenSequence*](#SpecialTokenSequence)s, and [*Token*](#Token)s, with the source terminated by an [*EndOfFile*](#EndOfFile). The source text is split into tokens using the maximal munch algorithm, i.e., the lexical analyzer makes the longest possible token. For example `>>` is a right shift token, not two greater than tokens. There are two exceptions to this rule: * A `..` embedded inside what looks like two floating point literals, as in `1..2`, is interpreted as if the `..` was separated by a space from the first integer. * A `1.a` is interpreted as the three tokens `1`, `.`, and `a`, whereas `1. a` is interpreted as the two tokens `1.` and `a`. Character Set ------------- ``` Character: any Unicode character ``` End of File ----------- ``` EndOfFile: physical end of the file \u0000 \u001A ``` The source text is terminated by whichever comes first. End of Line ----------- ``` EndOfLine: \u000D \u000A \u000D \u000A \u2028 \u2029 EndOfFile ``` White Space ----------- ``` WhiteSpace: Space Space WhiteSpace Space: \u0020 \u0009 \u000B \u000C ``` Comments -------- ``` Comment: BlockComment LineComment NestingBlockComment BlockComment: /* Charactersopt */ LineComment: // Charactersopt EndOfLine NestingBlockComment: /+ NestingBlockCommentCharactersopt +/ NestingBlockCommentCharacters: NestingBlockCommentCharacter NestingBlockCommentCharacter NestingBlockCommentCharacters NestingBlockCommentCharacter: Character NestingBlockComment Characters: Character Character Characters ``` There are three kinds of comments: 1. Block comments can span multiple lines, but do not nest. 2. Line comments terminate at the end of the line. 3. Nesting block comments can span multiple lines and can nest. The contents of strings and comments are not tokenized. Consequently, comment openings occurring within a string do not begin a comment, and string delimiters within a comment do not affect the recognition of comment closings and nested `/+` comment openings. With the exception of `/+` occurring within a `/+` comment, comment openings within a comment are ignored. ``` a = /+ // +/ 1; // parses as if 'a = 1;' a = /+ "+/" +/ 1"; // parses as if 'a = " +/ 1";' a = /+ /* +/ */ 3; // parses as if 'a = */ 3;' ``` Comments cannot be used as token concatenators, for example, `abc/**/def` is two tokens, `abc` and `def`, not one `abcdef` token. Tokens ------ ``` Token: Identifier StringLiteral CharacterLiteral IntegerLiteral FloatLiteral Keyword / /= . .. ... & &= && | |= || - -= -- + += ++ < <= << <<= > >= >>= >>>= >> >>> ! != ( ) [ ] { } ? , ; : $ = == * *= % %= ^ ^= ^^ ^^= ~ ~= @ => # ``` Identifiers ----------- ``` Identifier: IdentifierStart IdentifierStart IdentifierChars IdentifierChars: IdentifierChar IdentifierChar IdentifierChars IdentifierStart: _ Letter UniversalAlpha IdentifierChar: IdentifierStart 0 NonZeroDigit ``` Identifiers start with a letter, `_`, or universal alpha, and are followed by any number of letters, `_`, digits, or universal alphas. Universal alphas are as defined in ISO/IEC 9899:1999(E) Appendix D of the C99 Standard. Identifiers can be arbitrarily long, and are case sensitive. **Implementation Defined:** Identifiers starting with `__` (two underscores) are reserved. String Literals --------------- ``` StringLiteral: WysiwygString AlternateWysiwygString DoubleQuotedString HexString DelimitedString TokenString WysiwygString: r" WysiwygCharactersopt " StringPostfixopt AlternateWysiwygString: ` WysiwygCharactersopt ` StringPostfixopt WysiwygCharacters: WysiwygCharacter WysiwygCharacter WysiwygCharacters WysiwygCharacter: Character EndOfLine DoubleQuotedString: " DoubleQuotedCharactersopt " StringPostfixopt DoubleQuotedCharacters: DoubleQuotedCharacter DoubleQuotedCharacter DoubleQuotedCharacters DoubleQuotedCharacter: Character EscapeSequence EndOfLine EscapeSequence: \' \" \? \\ \0 \a \b \f \n \r \t \v \x HexDigit HexDigit \ OctalDigit \ OctalDigit OctalDigit \ OctalDigit OctalDigit OctalDigit \u HexDigit HexDigit HexDigit HexDigit \U HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit \ NamedCharacterEntity HexString: x" HexStringCharsopt " StringPostfixopt HexStringChars: HexStringChar HexStringChar HexStringChars HexStringChar: HexDigit WhiteSpace EndOfLine StringPostfix: c w d DelimitedString: q" Delimiter WysiwygCharactersopt MatchingDelimiter " TokenString: q{ Tokensopt } ``` A string literal is either a double quoted string, a wysiwyg quoted string, a delimited string, a token string, or a hex string. In all string literal forms, an [*EndOfLine*](#EndOfLine) is regarded as a single `\n` character. String literals are read only. **Undefined Behavior:** Writes to string literals cannot always be detected, but cause undefined behavior. ### Wysiwyg Strings Wysiwyg ("what you see is what you get") quoted strings can be defined using either of two syntaxes. In the first form, they are enclosed between `r"` and `"`. All characters between the `r"` and `"` are part of the string. There are no escape sequences inside wysiwyg strings. ``` r"I am Oz" r"c:\games\Sudoku.exe" r"ab\n" // string is 4 characters, // 'a', 'b', '\', 'n' ``` Alternatively, wysiwyg strings can be enclosed by backquotes, using the ` character. ``` `the Great and Powerful.` `c:\games\Empire.exe` `The "lazy" dog` `a"b\n` // string is 5 characters, // 'a', '"', 'b', '\', 'n' ``` ### Double Quoted Strings Double quoted strings are enclosed by "". [*EscapeSequence*](#EscapeSequence)s can be embedded in them. ``` "Who are you?" "c:\\games\\Doom.exe" "ab\n" // string is 3 characters, // 'a', 'b', and a linefeed "ab " // string is 3 characters, // 'a', 'b', and a linefeed ``` ### Hex Strings Hex strings allow string literals to be created using hex data. The hex data need not form valid UTF characters. ``` x"0A" // same as "\x0A" x"00 FBCD 32FD 0A" // same as // "\x00\xFB\xCD\x32\xFD\x0A" ``` Whitespace and newlines are ignored, so the hex data can be easily formatted. The number of hex characters must be a multiple of 2. Note: Hex Strings are **deprecated**. Please use [`std.conv.hexString`](https://dlang.org/phobos/std_conv.html#hexString) instead. ### Delimited Strings Delimited strings use various forms of delimiters. The delimiter, whether a character or identifier, must immediately follow the " without any intervening whitespace. The terminating delimiter must immediately precede the closing " without any intervening whitespace. A *nesting delimiter* nests, and is one of the following characters: Nesting Delimiters| **Delimiter** | **Matching Delimiter** | | `[` | `]` | | ( | ) | | `<` | `>` | | `{` | `}` | ``` q"(foo(xxx))" // "foo(xxx)" q"[foo{]" // "foo{" ``` If the delimiter is an identifier, the identifier must be immediately followed by a newline, and the matching delimiter must be the same identifier starting at the beginning of the line: ``` writeln(q"EOS This is a multi-line heredoc string EOS" ); ``` The newline following the opening identifier is not part of the string, but the last newline before the closing identifier is part of the string. The closing identifier must be placed on its own line at the leftmost column. Otherwise, the matching delimiter is the same as the delimiter character: ``` q"/foo]/" // "foo]" // q"/abc/def/" // error ``` ### Token Strings Token strings open with the characters `q``{` and close with the token `}`. In between must be valid D tokens. The `{` and `}` tokens nest. The string is formed of all the characters between the opening and closing of the token string, including comments. ``` q{this is the voice of} // "this is the voice of" q{/*}*/ } // "/*}*/ " q{ world(q{control}); } // " world(q{control}); " q{ __TIME__ } // " __TIME__ " // i.e. it is not replaced with the time // q{ __EOF__ } // error // __EOF__ is not a token, it's end of file ``` ### String Postfix The optional *StringPostfix* character gives a specific type to the string, rather than it being inferred from the context. The types corresponding to the postfix characters are: String Literal Postfix Characters| **Postfix** | **Type** | **Alias** | | c | `immutable(char)[]` | `string` | | w | `immutable(wchar)[]` | `wstring` | | d | `immutable(dchar)[]` | `dstring` | ``` "hello"c // string "hello"w // wstring "hello"d // dstring ``` The string literals are assembled as UTF-8 char arrays, and the postfix is applied to convert to wchar or dchar as necessary as a final step. Escape Sequences ---------------- The escape sequences listed in [*EscapeSequence*](#EscapeSequence) are: Escape Sequences| **Sequence** | **Meaning** | | `'` | Literal single-quote: `'` | | `"` | Literal double-quote: `"` | | `?` | Literal question mark: `?` | | `\` | Literal backslash: | | `\0` | Binary zero (NUL, U+0000). | | `\a` | BEL (alarm) character (U+0007). | | `\b` | Backspace (U+0008). | | `\f` | Form feed (FF) (U+000C). | | `\n` | End-of-line (U+000A). | | `\r` | Carriage return (U+000D). | | `\t` | Horizontal tab (U+0009). | | `\v` | Vertical tab (U+000B). | | `\x`*nn* | Byte value in hexadecimal, where *nn* is specified as two hexadecimal digits.For example: `\xFF` represents the character with the value 255. | | *n**nn**nnn* | Byte value in octal.For example: `\101` represents the character with the value 65 (`'A'`). Analogous to hexadecimal characters, the largest byte value is `\377` (= `\xFF` in hexadecimal or `255` in decimal) | | `\u`*nnnn* | Unicode character U+*nnnn*, where *nnnn* are four hexadecimal digits.For example, `\u03B3` represents the Unicode character γ (U+03B3 - GREEK SMALL LETTER GAMMA). | | `\U`*nnnnnnnn* | Unicode character U+*nnnnnnnn*, where *nnnnnnnn* are 8 hexadecimal digits.For example, `\U0001F603` represents the Unicode character U+1F603 (SMILING FACE WITH OPEN MOUTH). | | *name* | Named character entity from the HTML5 specification. These names begin with `&` and end with `;` | e.g. | `&`$D(euro;). See [*NamedCharacterEntity*](entity#NamedCharacterEntity). | Character Literals ------------------ ``` CharacterLiteral: ' SingleQuotedCharacter ' SingleQuotedCharacter: Character EscapeSequence ``` Character literals are a single character or escape sequence enclosed by single quotes. ``` 'h' // the letter h '\n' // newline '\\' // the backslash character ``` Integer Literals ---------------- ``` IntegerLiteral: Integer Integer IntegerSuffix Integer: DecimalInteger BinaryInteger HexadecimalInteger IntegerSuffix: L u U Lu LU uL UL DecimalInteger: 0 NonZeroDigit NonZeroDigit DecimalDigitsUS BinaryInteger: BinPrefix BinaryDigitsNoSingleUS BinPrefix: 0b 0B HexadecimalInteger: HexPrefix HexDigitsNoSingleUS NonZeroDigit: 1 2 3 4 5 6 7 8 9 DecimalDigits: DecimalDigit DecimalDigit DecimalDigits DecimalDigitsUS: DecimalDigitUS DecimalDigitUS DecimalDigitsUS DecimalDigitsNoSingleUS: DecimalDigit DecimalDigit DecimalDigitsUS DecimalDigitsUS DecimalDigit DecimalDigitsNoStartingUS: DecimalDigit DecimalDigit DecimalDigitsUS DecimalDigit: 0 NonZeroDigit DecimalDigitUS: DecimalDigit _ BinaryDigitsNoSingleUS: BinaryDigit BinaryDigit BinaryDigitsUS BinaryDigitsUS BinaryDigit BinaryDigitsUS BinaryDigit BinaryDigitsUS BinaryDigitsUS: BinaryDigitUS BinaryDigitUS BinaryDigitsUS BinaryDigit: 0 1 BinaryDigitUS: BinaryDigit _ OctalDigit: 0 1 2 3 4 5 6 7 HexDigits: HexDigit HexDigit HexDigits HexDigitsUS: HexDigitUS HexDigitUS HexDigitsUS HexDigitsNoSingleUS: HexDigit HexDigit HexDigitsUS HexDigitsUS HexDigit HexDigitsNoStartingUS: HexDigit HexDigit HexDigitsUS HexDigit: DecimalDigit HexLetter HexDigitUS: HexDigit _ HexLetter: a b c d e f A B C D E F ``` Integers can be specified in decimal, binary, or hexadecimal. Decimal integers are a sequence of decimal digits. Binary integers are a sequence of binary digits preceded by a ‘0b’ or ‘0B’. C-style octal integer notation was deemed too easy to mix up with decimal notation; it is only fully supported in string literals. D still supports octal integer literals interpreted at compile time through the [`std.conv.octal`](https://dlang.org/phobos/std_conv.html#octal) template, as in `octal!167`. Hexadecimal integers are a sequence of hexadecimal digits preceded by a ‘0x’ or ‘0X’. Integers can have embedded ‘\_’ characters to improve readability, and which are ignored. ``` 20_000 // leagues under the sea 867_5309 // number on the wall 1_522_000 // thrust of F1 engine (lbf sea level) ``` Integers can be immediately followed by one ‘L’ or one of ‘u’ or ‘U’ or both. Note that there is no ‘l’ suffix. The type of the integer is resolved as follows: Decimal Literal Types| **Literal** | **Type** | *Usual decimal notation* || `0 .. 2_147_483_647` | `int` | | `2_147_483_648 .. 9_223_372_036_854_775_807` | `long` | | `9_223_372_036_854_775_808 .. 18_446_744_073_709_551_615` | `ulong` | *Explicit suffixes* || `0L .. 9_223_372_036_854_775_807L` | `long` | | `0U .. 4_294_967_295U` | `uint` | | `4_294_967_296U .. 18_446_744_073_709_551_615U` | `ulong` | | `0UL .. 18_446_744_073_709_551_615UL` | `ulong` | *Hexadecimal notation* || `0x0 .. 0x7FFF_FFFF` | `int` | | `0x8000_0000 .. 0xFFFF_FFFF` | `uint` | | `0x1_0000_0000 .. 0x7FFF_FFFF_FFFF_FFFF` | `long` | | `0x8000_0000_0000_0000 .. 0xFFFF_FFFF_FFFF_FFFF` | `ulong` | *Hexadecimal notation with explicit suffixes* || `0x0L .. 0x7FFF_FFFF_FFFF_FFFFL` | `long` | | `0x8000_0000_0000_0000L .. 0xFFFF_FFFF_FFFF_FFFFL` | `ulong` | | `0x0U .. 0xFFFF_FFFFU` | `uint` | | `0x1_0000_0000U .. 0xFFFF_FFFF_FFFF_FFFFU` | `ulong` | | `0x0UL .. 0xFFFF_FFFF_FFFF_FFFFUL` | `ulong` | An integer literal may not exceed these values. **Best Practices:** Octal integer notation is not supported for integer literals. However, octal integer literals can be interpreted at compile time through the [`std.conv.octal`](https://dlang.org/phobos/std_conv.html#octal) template, as in `octal!167`. Floating Point Literals ----------------------- ``` FloatLiteral: Float Float Suffix Integer FloatSuffix Integer ImaginarySuffix Integer FloatSuffix ImaginarySuffix Integer RealSuffix ImaginarySuffix Float: DecimalFloat HexFloat DecimalFloat: LeadingDecimal . LeadingDecimal . DecimalDigits DecimalDigits . DecimalDigitsNoStartingUS DecimalExponent . DecimalInteger . DecimalInteger DecimalExponent LeadingDecimal DecimalExponent DecimalExponent DecimalExponentStart DecimalDigitsNoSingleUS DecimalExponentStart e E e+ E+ e- E- HexFloat: HexPrefix HexDigitsNoSingleUS . HexDigitsNoStartingUS HexExponent HexPrefix . HexDigitsNoStartingUS HexExponent HexPrefix HexDigitsNoSingleUS HexExponent HexPrefix: 0x 0X HexExponent: HexExponentStart DecimalDigitsNoSingleUS HexExponentStart: p P p+ P+ p- P- Suffix: FloatSuffix RealSuffix ImaginarySuffix FloatSuffix ImaginarySuffix RealSuffix ImaginarySuffix FloatSuffix: f F RealSuffix: L ImaginarySuffix: i LeadingDecimal: DecimalInteger 0 DecimalDigitsNoSingleUS ``` Floats can be in decimal or hexadecimal format. Hexadecimal floats are preceded by a **0x** or **0X** and the exponent is a **p** or **P** followed by a decimal number serving as the exponent of 2. Floating literals can have embedded ‘\_’ characters to improve readability, and which are ignored. ``` 2.645_751 6.022140857E+23 6_022.140857E+20 6_022_.140_857E+20_ ``` Floating literals with no suffix are of type `double`. Floating literals followed by **f** or **F** are of type `float`, and those followed by **L** are of type `real`. If a floating literal is followed by **i**, then it is an *ireal* (imaginary) type. Examples: ``` 0x1.FFFFFFFFFFFFFp1023 // double.max 0x1p-52 // double.epsilon 1.175494351e-38F // float.min 6.3i // idouble 6.3 6.3fi // ifloat 6.3 6.3Li // ireal 6.3 ``` The literal may not exceed the range of the type. The literal is rounded to fit into the significant digits of the type. If a floating literal has a **.** and a type suffix, at least one digit must be in-between: ``` 1f; // OK, float 1.f; // error 1.; // OK, double ``` Keywords -------- Keywords are reserved identifiers. ``` Keyword: abstract alias align asm assert auto body bool break byte case cast catch cdouble cent cfloat char class const continue creal dchar debug default delegate delete (deprecated) deprecated do double else enum export extern false final finally float for foreach foreach_reverse function goto idouble if ifloat immutable import in inout int interface invariant ireal is lazy long macro (reserved) mixin module new nothrow null out override package pragma private protected public pure real ref return scope shared short static struct super switch synchronized template this throw true try typeid typeof ubyte ucent uint ulong union unittest ushort version void wchar while with __FILE__ __FILE_FULL_PATH__ __MODULE__ __LINE__ __FUNCTION__ __PRETTY_FUNCTION__ __gshared __traits __vector __parameters ``` Special Tokens -------------- These tokens are replaced with other tokens according to the following table: Special Tokens| **Special Token** | **Replaced with** | | `__DATE__` | string literal of the date of compilation "*mmm dd yyyy*" | | `__EOF__` | tells the scanner to ignore everything after this token | | `__TIME__` | string literal of the time of compilation "*hh:mm:ss*" | | `__TIMESTAMP__` | string literal of the date and time of compilation "*www mmm dd hh:mm:ss yyyy*" | | `__VENDOR__` | Compiler vendor string | | `__VERSION__` | Compiler version as an integer | **Implementation Defined:** The replacement string literal for `__VENDOR__` and the replacement integer value for `__VERSION__`. Special Token Sequences ----------------------- ``` SpecialTokenSequence: # line IntegerLiteral EndOfLine # line IntegerLiteral Filespec EndOfLine Filespec: " Charactersopt " ``` Special token sequences are processed by the lexical analyzer, may appear between any other tokens, and do not affect the syntax parsing. There is currently only one special token sequence, `#line`. This sets the current source line number to [*IntegerLiteral*](#IntegerLiteral), and optionally the current source file name to [*Filespec*](#Filespec), beginning with the next line of source text. The backslash character is not treated specially inside [*Filespec*](#Filespec) strings. For example: ``` int #line 6 "pkg/mod.d" x; // this is now line 6 of file pkg/mod.d ``` **Implementation Defined:** The source file and line number is typically used for printing error messages and for mapping generated code back to the source for the symbolic debugging output.
programming_docs
d rt.critical_ rt.critical\_ ============= Implementation of support routines for synchronized blocks. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Walter Bright, Sean Kelly d std.file std.file ======== Utilities for manipulating files and scanning directories. Functions in this module handle files as a unit, e.g., read or write one file at a time. For opening files and manipulating them via handles refer to module [`std.stdio`](std_stdio). | Category | Functions | | --- | --- | | General | [`exists`](#exists) [`isDir`](#isDir) [`isFile`](#isFile) [`isSymlink`](#isSymlink) [`rename`](#rename) [`thisExePath`](#thisExePath) | | Directories | [`chdir`](#chdir) [`dirEntries`](#dirEntries) [`getcwd`](#getcwd) [`mkdir`](#mkdir) [`mkdirRecurse`](#mkdirRecurse) [`rmdir`](#rmdir) [`rmdirRecurse`](#rmdirRecurse) [`tempDir`](#tempDir) | | Files | [`append`](#append) [`copy`](#copy) [`read`](#read) [`readText`](#readText) [`remove`](#remove) [`slurp`](#slurp) [`write`](#write) | | Symlinks | [`symlink`](#symlink) [`readLink`](#readLink) | | Attributes | [`attrIsDir`](#attrIsDir) [`attrIsFile`](#attrIsFile) [`attrIsSymlink`](#attrIsSymlink) [`getAttributes`](#getAttributes) [`getLinkAttributes`](#getLinkAttributes) [`getSize`](#getSize) [`setAttributes`](#setAttributes) | | Timestamp | [`getTimes`](#getTimes) [`getTimesWin`](#getTimesWin) [`setTimes`](#setTimes) [`timeLastModified`](#timeLastModified) [`timeLastAccessed`](#timeLastAccessed) [`timeStatusChanged`](#timeStatusChanged) | | Other | [`DirEntry`](#DirEntry) [`FileException`](#FileException) [`PreserveAttributes`](#PreserveAttributes) [`SpanMode`](#SpanMode) [`getAvailableDiskSpace`](#getAvailableDiskSpace) | See Also: The [official tutorial](http://ddili.org/ders/d.en/files.html) for an introduction to working with files in D, module [`std.stdio`](std_stdio) for opening files and manipulating them via handles, and module [`std.path`](std_path) for manipulating path strings. License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com), [Andrei Alexandrescu](http://erdani.org), [Jonathan M Davis](http://jmdavisprog.com) Source [std/file.d](https://github.com/dlang/phobos/blob/master/std/file.d) class **FileException**: object.Exception; Exception thrown for file I/O errors. Examples: ``` import std.exception : assertThrown; assertThrown!FileException("non.existing.file.".readText); ``` immutable uint **errno**; OS error code. pure @safe this(scope const(char)[] name, scope const(char)[] msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_); Constructor which takes an error message. Parameters: | | | | --- | --- | | const(char)[] `name` | Name of file for which the error occurred. | | const(char)[] `msg` | Message describing the error. | | string `file` | The file where the error occurred. | | size\_t `line` | The line where the error occurred. | @trusted this(scope const(char)[] name, uint errno = .errno, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_); Constructor which takes the error number ([GetLastError](https://google.com/search?btnI=I%27m+Feeling+Lucky&ie=UTF-8&oe=UTF-8&q=GetLastError) in Windows, errno in POSIX). Parameters: | | | | --- | --- | | const(char)[] `name` | Name of file for which the error occurred. | | uint `errno` | The error number. | | string `file` | The file where the error occurred. Defaults to `__FILE__`. | | size\_t `line` | The line where the error occurred. Defaults to `__LINE__`. | void[] **read**(R)(R name, size\_t upTo = size\_t.max) Constraints: if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isInfinite!R && !isConvertibleToString!R); void[] **read**(R)(auto ref R name, size\_t upTo = size\_t.max) Constraints: if (isConvertibleToString!R); Read entire contents of file `name` and returns it as an untyped array. If the file size is larger than `upTo`, only `upTo` bytes are read. Parameters: | | | | --- | --- | | R `name` | string or range of characters representing the file name | | size\_t `upTo` | if present, the maximum number of bytes to read | Returns: Untyped array of bytes read. Throws: [`FileException`](#FileException) on error. Examples: ``` import std.utf : byChar; scope(exit) { assert(exists(deleteme)); remove(deleteme); } std.file.write(deleteme, "1234"); // deleteme is the name of a temporary file writeln(read(deleteme, 2)); // "12" writeln(read(deleteme.byChar)); // "1234" writeln((cast(const(ubyte)[])read(deleteme)).length); // 4 ``` S **readText**(S = string, R)(auto ref R name) Constraints: if (isSomeString!S && (isInputRange!R && !isInfinite!R && isSomeChar!(ElementType!R) || is(StringTypeOf!R))); Reads and validates (using [`std.utf.validate`](std_utf#validate)) a text file. S can be an array of any character type. However, no width or endian conversions are performed. So, if the width or endianness of the characters in the given file differ from the width or endianness of the element type of S, then validation will fail. Parameters: | | | | --- | --- | | S | the string type of the file | | R `name` | string or range of characters representing the file name | Returns: Array of characters read. Throws: [`FileException`](#FileException) if there is an error reading the file, [`std.utf.UTFException`](std_utf#UTFException) on UTF decoding error. Examples: Read file with UTF-8 text. ``` write(deleteme, "abc"); // deleteme is the name of a temporary file scope(exit) remove(deleteme); string content = readText(deleteme); writeln(content); // "abc" ``` void **write**(R)(R name, const void[] buffer) Constraints: if ((isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || isSomeString!R) && !isConvertibleToString!R); void **write**(R)(auto ref R name, const void[] buffer) Constraints: if (isConvertibleToString!R); Write `buffer` to file `name`. Creates the file if it does not already exist. Parameters: | | | | --- | --- | | R `name` | string or range of characters representing the file name | | void[] `buffer` | data to be written to file | Throws: [`FileException`](#FileException) on error. See Also: [`std.stdio.toFile`](std_stdio#toFile) Examples: ``` scope(exit) { assert(exists(deleteme)); remove(deleteme); } int[] a = [ 0, 1, 1, 2, 3, 5, 8 ]; write(deleteme, a); // deleteme is the name of a temporary file writeln(cast(int[])read(deleteme)); // a ``` void **append**(R)(R name, const void[] buffer) Constraints: if ((isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || isSomeString!R) && !isConvertibleToString!R); void **append**(R)(auto ref R name, const void[] buffer) Constraints: if (isConvertibleToString!R); Appends `buffer` to file `name`. Creates the file if it does not already exist. Parameters: | | | | --- | --- | | R `name` | string or range of characters representing the file name | | void[] `buffer` | data to be appended to file | Throws: [`FileException`](#FileException) on error. Examples: ``` scope(exit) { assert(exists(deleteme)); remove(deleteme); } int[] a = [ 0, 1, 1, 2, 3, 5, 8 ]; write(deleteme, a); // deleteme is the name of a temporary file int[] b = [ 13, 21 ]; append(deleteme, b); writeln(cast(int[])read(deleteme)); // a ~ b ``` void **rename**(RF, RT)(RF from, RT to) Constraints: if ((isInputRange!RF && !isInfinite!RF && isSomeChar!(ElementEncodingType!RF) || isSomeString!RF) && !isConvertibleToString!RF && (isInputRange!RT && !isInfinite!RT && isSomeChar!(ElementEncodingType!RT) || isSomeString!RT) && !isConvertibleToString!RT); void **rename**(RF, RT)(auto ref RF from, auto ref RT to) Constraints: if (isConvertibleToString!RF || isConvertibleToString!RT); Rename file `from` to `to`, moving it between directories if required. If the target file exists, it is overwritten. It is not possible to rename a file across different mount points or drives. On POSIX, the operation is atomic. That means, if `to` already exists there will be no time period during the operation where `to` is missing. See [manpage for rename](http://man7.org/linux/man-pages/man2/rename.2.html) for more details. Parameters: | | | | --- | --- | | RF `from` | string or range of characters representing the existing file name | | RT `to` | string or range of characters representing the target file name | Throws: [`FileException`](#FileException) on error. Examples: ``` auto t1 = deleteme, t2 = deleteme~"2"; scope(exit) foreach (t; [t1, t2]) if (t.exists) t.remove(); t1.write("1"); t1.rename(t2); writeln(t2.readText); // "1" t1.write("2"); t1.rename(t2); writeln(t2.readText); // "2" ``` void **remove**(R)(R name) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); void **remove**(R)(auto ref R name) Constraints: if (isConvertibleToString!R); Delete file `name`. Parameters: | | | | --- | --- | | R `name` | string or range of characters representing the file name | Throws: [`FileException`](#FileException) on error. Examples: ``` import std.exception : assertThrown; deleteme.write("Hello"); writeln(deleteme.readText); // "Hello" deleteme.remove; assertThrown!FileException(deleteme.readText); ``` ulong **getSize**(R)(R name) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); ulong **getSize**(R)(auto ref R name) Constraints: if (isConvertibleToString!R); Get size of file `name` in bytes. Parameters: | | | | --- | --- | | R `name` | string or range of characters representing the file name | Returns: The size of file in bytes. Throws: [`FileException`](#FileException) on error (e.g., file not found). Examples: ``` scope(exit) deleteme.remove; // create a file of size 1 write(deleteme, "a"); writeln(getSize(deleteme)); // 1 // create a file of size 3 write(deleteme, "abc"); writeln(getSize(deleteme)); // 3 ``` void **getTimes**(R)(R name, out SysTime accessTime, out SysTime modificationTime) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); void **getTimes**(R)(auto ref R name, out SysTime accessTime, out SysTime modificationTime) Constraints: if (isConvertibleToString!R); Get the access and modified times of file or folder `name`. Parameters: | | | | --- | --- | | R `name` | File/Folder name to get times for. | | SysTime `accessTime` | Time the file/folder was last accessed. | | SysTime `modificationTime` | Time the file/folder was last modified. | Throws: [`FileException`](#FileException) on error. Examples: ``` import std.datetime : abs, SysTime; scope(exit) deleteme.remove; write(deleteme, "a"); SysTime accessTime, modificationTime; getTimes(deleteme, accessTime, modificationTime); import std.datetime : Clock, seconds; auto currTime = Clock.currTime(); enum leeway = 5.seconds; auto diffAccess = accessTime - currTime; auto diffModification = modificationTime - currTime; assert(abs(diffAccess) <= leeway); assert(abs(diffModification) <= leeway); ``` void **getTimesWin**(R)(R name, out SysTime fileCreationTime, out SysTime fileAccessTime, out SysTime fileModificationTime) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); This function is Windows-Only. Get creation/access/modified times of file `name`. This is the same as `getTimes` except that it also gives you the file creation time - which isn't possible on POSIX systems. Parameters: | | | | --- | --- | | R `name` | File name to get times for. | | SysTime `fileCreationTime` | Time the file was created. | | SysTime `fileAccessTime` | Time the file was last accessed. | | SysTime `fileModificationTime` | Time the file was last modified. | Throws: [`FileException`](#FileException) on error. void **setTimes**(R)(R name, SysTime accessTime, SysTime modificationTime) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); void **setTimes**(R)(auto ref R name, SysTime accessTime, SysTime modificationTime) Constraints: if (isConvertibleToString!R); Set access/modified times of file or folder `name`. Parameters: | | | | --- | --- | | R `name` | File/Folder name to get times for. | | SysTime `accessTime` | Time the file/folder was last accessed. | | SysTime `modificationTime` | Time the file/folder was last modified. | Throws: [`FileException`](#FileException) on error. Examples: ``` import std.datetime : DateTime, hnsecs, SysTime; scope(exit) deleteme.remove; write(deleteme, "a"); SysTime accessTime = SysTime(DateTime(2010, 10, 4, 0, 0, 30)); SysTime modificationTime = SysTime(DateTime(2018, 10, 4, 0, 0, 30)); setTimes(deleteme, accessTime, modificationTime); SysTime accessTimeResolved, modificationTimeResolved; getTimes(deleteme, accessTimeResolved, modificationTimeResolved); writeln(accessTime); // accessTimeResolved writeln(modificationTime); // modificationTimeResolved ``` SysTime **timeLastModified**(R)(R name) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); SysTime **timeLastModified**(R)(auto ref R name) Constraints: if (isConvertibleToString!R); Returns the time that the given file was last modified. Parameters: | | | | --- | --- | | R `name` | the name of the file to check | Returns: A [`std.datetime.systime.SysTime`](std_datetime_systime#SysTime). Throws: [`FileException`](#FileException) if the given file does not exist. Examples: ``` import std.datetime : abs, DateTime, hnsecs, SysTime; scope(exit) deleteme.remove; import std.datetime : Clock, seconds; auto currTime = Clock.currTime(); enum leeway = 5.seconds; deleteme.write("bb"); assert(abs(deleteme.timeLastModified - currTime) <= leeway); ``` SysTime **timeLastModified**(R)(R name, SysTime returnIfMissing) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R)); Returns the time that the given file was last modified. If the file does not exist, returns `returnIfMissing`. A frequent usage pattern occurs in build automation tools such as [make](http://gnu.org/software/make) or [ant](http://%20%20%20%20en.wikipedia.org/wiki/Apache_Ant). To check whether file `target` must be rebuilt from file `source` (i.e., `target` is older than `source` or does not exist), use the comparison below. The code throws a [`FileException`](#FileException) if `source` does not exist (as it should). On the other hand, the `SysTime.min` default makes a non-existing `target` seem infinitely old so the test correctly prompts building it. Parameters: | | | | --- | --- | | R `name` | The name of the file to get the modification time for. | | SysTime `returnIfMissing` | The time to return if the given file does not exist. | Returns: A [`std.datetime.systime.SysTime`](std_datetime_systime#SysTime). Example ``` if (source.timeLastModified >= target.timeLastModified(SysTime.min)) { // must (re)build } else { // target is up-to-date } ``` Examples: ``` import std.datetime : SysTime; writeln("file.does.not.exist".timeLastModified(SysTime.min)); // SysTime.min auto source = deleteme ~ "source"; auto target = deleteme ~ "target"; scope(exit) source.remove, target.remove; source.write("."); assert(target.timeLastModified(SysTime.min) < source.timeLastModified); target.write("."); assert(target.timeLastModified(SysTime.min) >= source.timeLastModified); ``` pure nothrow SysTime **timeLastModified**()(auto ref stat\_t statbuf); This function is POSIX-Only. Returns the time that the given file was last modified. Parameters: | | | | --- | --- | | stat\_t `statbuf` | stat\_t retrieved from file. | pure nothrow SysTime **timeLastAccessed**()(auto ref stat\_t statbuf); This function is POSIX-Only. Returns the time that the given file was last accessed. Parameters: | | | | --- | --- | | stat\_t `statbuf` | stat\_t retrieved from file. | pure nothrow SysTime **timeStatusChanged**()(auto ref stat\_t statbuf); This function is POSIX-Only. Returns the time that the given file was last changed. Parameters: | | | | --- | --- | | stat\_t `statbuf` | stat\_t retrieved from file. | bool **exists**(R)(R name) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); bool **exists**(R)(auto ref R name) Constraints: if (isConvertibleToString!R); Determine whether the given file (or directory) exists. Parameters: | | | | --- | --- | | R `name` | string or range of characters representing the file name | Returns: true if the file name specified as input exists Examples: ``` auto f = deleteme ~ "does.not.exist"; assert(!f.exists); f.write("hello"); assert(f.exists); f.remove; assert(!f.exists); ``` uint **getAttributes**(R)(R name) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); uint **getAttributes**(R)(auto ref R name) Constraints: if (isConvertibleToString!R); Returns the attributes of the given file. Note that the file attributes on Windows and POSIX systems are completely different. On Windows, they're what is returned by [GetFileAttributes](http://msdn.microsoft.com/en-us/library/aa364944(v=vs.85).aspx), whereas on POSIX systems, they're the `st_mode` value which is part of the `stat struct` gotten by calling the [`stat`](http://en.wikipedia.org/wiki/Stat_%28Unix%29) function. On POSIX systems, if the given file is a symbolic link, then attributes are the attributes of the file pointed to by the symbolic link. Parameters: | | | | --- | --- | | R `name` | The file to get the attributes of. | Returns: The attributes of the file as a `uint`. Throws: [`FileException`](#FileException) on error. Examples: getAttributes with a file ``` import std.exception : assertThrown; auto f = deleteme ~ "file"; scope(exit) f.remove; assert(!f.exists); assertThrown!FileException(f.getAttributes); f.write("."); auto attributes = f.getAttributes; assert(!attributes.attrIsDir); assert(attributes.attrIsFile); ``` Examples: getAttributes with a directory ``` import std.exception : assertThrown; auto dir = deleteme ~ "dir"; scope(exit) dir.rmdir; assert(!dir.exists); assertThrown!FileException(dir.getAttributes); dir.mkdir; auto attributes = dir.getAttributes; assert(attributes.attrIsDir); assert(!attributes.attrIsFile); ``` uint **getLinkAttributes**(R)(R name) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); uint **getLinkAttributes**(R)(auto ref R name) Constraints: if (isConvertibleToString!R); If the given file is a symbolic link, then this returns the attributes of the symbolic link itself rather than file that it points to. If the given file is *not* a symbolic link, then this function returns the same result as getAttributes. On Windows, getLinkAttributes is identical to getAttributes. It exists on Windows so that you don't have to special-case code for Windows when dealing with symbolic links. Parameters: | | | | --- | --- | | R `name` | The file to get the symbolic link attributes of. | Returns: the attributes Throws: [`FileException`](#FileException) on error. Examples: ``` import std.exception : assertThrown; auto source = deleteme ~ "source"; auto target = deleteme ~ "target"; assert(!source.exists); assertThrown!FileException(source.getLinkAttributes); // symlinking isn't available on Windows version (Posix) { scope(exit) source.remove, target.remove; target.write("target"); target.symlink(source); writeln(source.readText); // "target" assert(source.isSymlink); assert(source.getLinkAttributes.attrIsSymlink); } ``` Examples: if the file is no symlink, getLinkAttributes behaves like getAttributes ``` import std.exception : assertThrown; auto f = deleteme ~ "file"; scope(exit) f.remove; assert(!f.exists); assertThrown!FileException(f.getLinkAttributes); f.write("."); auto attributes = f.getLinkAttributes; assert(!attributes.attrIsDir); assert(attributes.attrIsFile); ``` Examples: if the file is no symlink, getLinkAttributes behaves like getAttributes ``` import std.exception : assertThrown; auto dir = deleteme ~ "dir"; scope(exit) dir.rmdir; assert(!dir.exists); assertThrown!FileException(dir.getLinkAttributes); dir.mkdir; auto attributes = dir.getLinkAttributes; assert(attributes.attrIsDir); assert(!attributes.attrIsFile); ``` void **setAttributes**(R)(R name, uint attributes) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); void **setAttributes**(R)(auto ref R name, uint attributes) Constraints: if (isConvertibleToString!R); Set the attributes of the given file. For example, a programmatic equivalent of Unix's `chmod +x name` to make a file executable is `name.setAttributes(name.getAttributes | octal!700)`. Parameters: | | | | --- | --- | | R `name` | the file name | | uint `attributes` | the attributes to set the file to | Throws: [`FileException`](#FileException) if the given file does not exist. Examples: setAttributes with a file ``` import std.exception : assertThrown; import std.conv : octal; auto f = deleteme ~ "file"; version (Posix) { scope(exit) f.remove; assert(!f.exists); assertThrown!FileException(f.setAttributes(octal!777)); f.write("."); auto attributes = f.getAttributes; assert(!attributes.attrIsDir); assert(attributes.attrIsFile); f.setAttributes(octal!777); attributes = f.getAttributes; writeln((attributes & 1023)); // octal!777 } ``` Examples: setAttributes with a directory ``` import std.exception : assertThrown; import std.conv : octal; auto dir = deleteme ~ "dir"; version (Posix) { scope(exit) dir.rmdir; assert(!dir.exists); assertThrown!FileException(dir.setAttributes(octal!777)); dir.mkdir; auto attributes = dir.getAttributes; assert(attributes.attrIsDir); assert(!attributes.attrIsFile); dir.setAttributes(octal!777); attributes = dir.getAttributes; writeln((attributes & 1023)); // octal!777 } ``` @property bool **isDir**(R)(R name) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); @property bool **isDir**(R)(auto ref R name) Constraints: if (isConvertibleToString!R); Returns whether the given file is a directory. Parameters: | | | | --- | --- | | R `name` | The path to the file. | Returns: true if name specifies a directory Throws: [`FileException`](#FileException) if the given file does not exist. Examples: ``` import std.exception : assertThrown; auto dir = deleteme ~ "dir"; auto f = deleteme ~ "f"; scope(exit) dir.rmdir, f.remove; assert(!dir.exists); assertThrown!FileException(dir.isDir); dir.mkdir; assert(dir.isDir); f.write("."); assert(!f.isDir); ``` pure nothrow @nogc @safe bool **attrIsDir**(uint attributes); Returns whether the given file attributes are for a directory. Parameters: | | | | --- | --- | | uint `attributes` | The file attributes. | Returns: true if attributes specifies a directory Examples: ``` import std.exception : assertThrown; auto dir = deleteme ~ "dir"; auto f = deleteme ~ "f"; scope(exit) dir.rmdir, f.remove; assert(!dir.exists); assertThrown!FileException(dir.getAttributes.attrIsDir); dir.mkdir; assert(dir.isDir); assert(dir.getAttributes.attrIsDir); f.write("."); assert(!f.isDir); assert(!f.getAttributes.attrIsDir); ``` @property bool **isFile**(R)(R name) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); @property bool **isFile**(R)(auto ref R name) Constraints: if (isConvertibleToString!R); Returns whether the given file (or directory) is a file. On Windows, if a file is not a directory, then it's a file. So, either `isFile` or `isDir` will return true for any given file. On POSIX systems, if `isFile` is `true`, that indicates that the file is a regular file (e.g. not a block not device). So, on POSIX systems, it's possible for both `isFile` and `isDir` to be `false` for a particular file (in which case, it's a special file). You can use `getAttributes` to get the attributes to figure out what type of special it is, or you can use `DirEntry` to get at its `statBuf`, which is the result from `stat`. In either case, see the man page for `stat` for more information. Parameters: | | | | --- | --- | | R `name` | The path to the file. | Returns: true if name specifies a file Throws: [`FileException`](#FileException) if the given file does not exist. Examples: ``` import std.exception : assertThrown; auto dir = deleteme ~ "dir"; auto f = deleteme ~ "f"; scope(exit) dir.rmdir, f.remove; dir.mkdir; assert(!dir.isFile); assert(!f.exists); assertThrown!FileException(f.isFile); f.write("."); assert(f.isFile); ``` pure nothrow @nogc @safe bool **attrIsFile**(uint attributes); Returns whether the given file attributes are for a file. On Windows, if a file is not a directory, it's a file. So, either `attrIsFile` or `attrIsDir` will return `true` for the attributes of any given file. On POSIX systems, if `attrIsFile` is `true`, that indicates that the file is a regular file (e.g. not a block not device). So, on POSIX systems, it's possible for both `attrIsFile` and `attrIsDir` to be `false` for a particular file (in which case, it's a special file). If a file is a special file, you can use the attributes to check what type of special file it is (see the man page for `stat` for more information). Parameters: | | | | --- | --- | | uint `attributes` | The file attributes. | Returns: true if the given file attributes are for a file Example ``` assert(attrIsFile(getAttributes("/etc/fonts/fonts.conf"))); assert(attrIsFile(getLinkAttributes("/etc/fonts/fonts.conf"))); ``` Examples: ``` import std.exception : assertThrown; auto dir = deleteme ~ "dir"; auto f = deleteme ~ "f"; scope(exit) dir.rmdir, f.remove; dir.mkdir; assert(!dir.isFile); assert(!dir.getAttributes.attrIsFile); assert(!f.exists); assertThrown!FileException(f.getAttributes.attrIsFile); f.write("."); assert(f.isFile); assert(f.getAttributes.attrIsFile); ``` @property bool **isSymlink**(R)(R name) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); @property bool **isSymlink**(R)(auto ref R name) Constraints: if (isConvertibleToString!R); Returns whether the given file is a symbolic link. On Windows, returns `true` when the file is either a symbolic link or a junction point. Parameters: | | | | --- | --- | | R `name` | The path to the file. | Returns: true if name is a symbolic link Throws: [`FileException`](#FileException) if the given file does not exist. Examples: ``` import std.exception : assertThrown; auto source = deleteme ~ "source"; auto target = deleteme ~ "target"; assert(!source.exists); assertThrown!FileException(source.isSymlink); // symlinking isn't available on Windows version (Posix) { scope(exit) source.remove, target.remove; target.write("target"); target.symlink(source); writeln(source.readText); // "target" assert(source.isSymlink); assert(source.getLinkAttributes.attrIsSymlink); } ``` pure nothrow @nogc @safe bool **attrIsSymlink**(uint attributes); Returns whether the given file attributes are for a symbolic link. On Windows, return `true` when the file is either a symbolic link or a junction point. Parameters: | | | | --- | --- | | uint `attributes` | The file attributes. | Returns: true if attributes are for a symbolic link Example ``` core.sys.posix.unistd.symlink("/etc/fonts/fonts.conf", "/tmp/alink"); assert(!getAttributes("/tmp/alink").isSymlink); assert(getLinkAttributes("/tmp/alink").isSymlink); ``` Examples: ``` import std.exception : assertThrown; auto source = deleteme ~ "source"; auto target = deleteme ~ "target"; assert(!source.exists); assertThrown!FileException(source.getLinkAttributes.attrIsSymlink); // symlinking isn't available on Windows version (Posix) { scope(exit) source.remove, target.remove; target.write("target"); target.symlink(source); writeln(source.readText); // "target" assert(source.isSymlink); assert(source.getLinkAttributes.attrIsSymlink); } ``` void **chdir**(R)(R pathname) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); void **chdir**(R)(auto ref R pathname) Constraints: if (isConvertibleToString!R); Change directory to `pathname`. Equivalent to `cd` on Windows and POSIX. Parameters: | | | | --- | --- | | R `pathname` | the directory to step into | Throws: [`FileException`](#FileException) on error. Examples: ``` import std.algorithm.comparison : equal; import std.path : buildPath; auto cwd = getcwd; auto dir = deleteme ~ "dir"; dir.mkdir; scope(exit) cwd.chdir, dir.rmdirRecurse; dir.buildPath("a").write("."); dir.chdir; // step into dir "b".write("."); dirEntries(".", SpanMode.shallow).equal( [".".buildPath("b"), ".".buildPath("a")] ); ``` void **mkdir**(R)(R pathname) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); void **mkdir**(R)(auto ref R pathname) Constraints: if (isConvertibleToString!R); Make a new directory `pathname`. Parameters: | | | | --- | --- | | R `pathname` | the path of the directory to make | Throws: [`FileException`](#FileException) on POSIX or [`WindowsException`](#WindowsException) on Windows if an error occured. Examples: ``` import std.file : mkdir; auto dir = deleteme ~ "dir"; scope(exit) dir.rmdir; dir.mkdir; assert(dir.exists); ``` Examples: ``` import std.exception : assertThrown; assertThrown("a/b/c/d/e".mkdir); ``` @safe void **mkdirRecurse**(scope const(char)[] pathname); Make directory and all parent directories as needed. Does nothing if the directory specified by `pathname` already exists. Parameters: | | | | --- | --- | | const(char)[] `pathname` | the full path of the directory to create | Throws: [`FileException`](#FileException) on error. Examples: ``` import std.path : buildPath; auto dir = deleteme ~ "dir"; scope(exit) dir.rmdirRecurse; dir.mkdir; assert(dir.exists); dir.mkdirRecurse; // does nothing // creates all parent directories as needed auto nested = dir.buildPath("a", "b", "c"); nested.mkdirRecurse; assert(nested.exists); ``` Examples: ``` import std.exception : assertThrown; scope(exit) deleteme.remove; deleteme.write("a"); // cannot make directory as it's already a file assertThrown!FileException(deleteme.mkdirRecurse); ``` void **rmdir**(R)(R pathname) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); void **rmdir**(R)(auto ref R pathname) Constraints: if (isConvertibleToString!R); Remove directory `pathname`. Parameters: | | | | --- | --- | | R `pathname` | Range or string specifying the directory name | Throws: [`FileException`](#FileException) on error. Examples: ``` auto dir = deleteme ~ "dir"; dir.mkdir; assert(dir.exists); dir.rmdir; assert(!dir.exists); ``` void **symlink**(RO, RL)(RO original, RL link) Constraints: if ((isInputRange!RO && !isInfinite!RO && isSomeChar!(ElementEncodingType!RO) || isConvertibleToString!RO) && (isInputRange!RL && !isInfinite!RL && isSomeChar!(ElementEncodingType!RL) || isConvertibleToString!RL)); This function is POSIX-Only. Creates a symbolic link (symlink). Parameters: | | | | --- | --- | | RO `original` | The file that is being linked. This is the target path that's stored in the symlink. A relative path is relative to the created symlink. | | RL `link` | The symlink to create. A relative path is relative to the current working directory. | Throws: [`FileException`](#FileException) on error (which includes if the symlink already exists). string **readLink**(R)(R link) Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || isConvertibleToString!R); This function is POSIX-Only. Returns the path to the file pointed to by a symlink. Note that the path could be either relative or absolute depending on the symlink. If the path is relative, it's relative to the symlink, not the current working directory. Throws: [`FileException`](#FileException) on error. @trusted string **getcwd**(); Get the current working directory. Throws: [`FileException`](#FileException) on error. Examples: ``` auto s = getcwd(); assert(s.length); ``` @trusted string **thisExePath**(); Returns the full path of the current executable. Returns: The path of the executable as a `string`. Throws: [`Exception`](object#Exception) Examples: ``` import std.path : isAbsolute; auto path = thisExePath(); assert(path.exists); assert(path.isAbsolute); assert(path.isFile); ``` struct **DirEntry**; Info on a file, similar to what you'd get from stat on a POSIX system. @safe this(string path); Constructs a `DirEntry` for the given file (or directory). Parameters: | | | | --- | --- | | string `path` | The file (or directory) to get a DirEntry for. | Throws: [`FileException`](#FileException) if the file does not exist. const @property @safe string **name**(); Returns the path to the file represented by this `DirEntry`. Example ``` auto de1 = DirEntry("/etc/fonts/fonts.conf"); assert(de1.name == "/etc/fonts/fonts.conf"); auto de2 = DirEntry("/usr/share/include"); assert(de2.name == "/usr/share/include"); ``` @property @safe bool **isDir**(); Returns whether the file represented by this `DirEntry` is a directory. Example ``` auto de1 = DirEntry("/etc/fonts/fonts.conf"); assert(!de1.isDir); auto de2 = DirEntry("/usr/share/include"); assert(de2.isDir); ``` @property @safe bool **isFile**(); Returns whether the file represented by this `DirEntry` is a file. On Windows, if a file is not a directory, then it's a file. So, either `isFile` or `isDir` will return `true`. On POSIX systems, if `isFile` is `true`, that indicates that the file is a regular file (e.g. not a block not device). So, on POSIX systems, it's possible for both `isFile` and `isDir` to be `false` for a particular file (in which case, it's a special file). You can use `attributes` or `statBuf` to get more information about a special file (see the stat man page for more details). Example ``` auto de1 = DirEntry("/etc/fonts/fonts.conf"); assert(de1.isFile); auto de2 = DirEntry("/usr/share/include"); assert(!de2.isFile); ``` @property @safe bool **isSymlink**(); Returns whether the file represented by this `DirEntry` is a symbolic link. On Windows, return `true` when the file is either a symbolic link or a junction point. @property @safe ulong **size**(); Returns the size of the the file represented by this `DirEntry` in bytes. const @property @safe SysTime **timeCreated**(); This function is Windows-Only. Returns the creation time of the file represented by this `DirEntry`. @property @safe SysTime **timeLastAccessed**(); Returns the time that the file represented by this `DirEntry` was last accessed. Note that many file systems do not update the access time for files (generally for performance reasons), so there's a good chance that `timeLastAccessed` will return the same value as `timeLastModified`. @property @safe SysTime **timeLastModified**(); Returns the time that the file represented by this `DirEntry` was last modified. const @property @safe SysTime **timeStatusChanged**(); This function is POSIX-Only. Returns the time that the file represented by this `DirEntry` was last changed (not only in contents, but also in permissions or ownership). @property @safe uint **attributes**(); Returns the attributes of the file represented by this `DirEntry`. Note that the file attributes on Windows and POSIX systems are completely different. On, Windows, they're what is returned by `GetFileAttributes` [GetFileAttributes](http://msdn.microsoft.com/en-us/library/aa364944(v=vs.85).aspx) Whereas, an POSIX systems, they're the `st_mode` value which is part of the `stat` struct gotten by calling `stat`. On POSIX systems, if the file represented by this `DirEntry` is a symbolic link, then attributes are the attributes of the file pointed to by the symbolic link. @property @safe uint **linkAttributes**(); On POSIX systems, if the file represented by this `DirEntry` is a symbolic link, then `linkAttributes` are the attributes of the symbolic link itself. Otherwise, `linkAttributes` is identical to `attributes`. On Windows, `linkAttributes` is identical to `attributes`. It exists on Windows so that you don't have to special-case code for Windows when dealing with symbolic links. @property @safe stat\_t **statBuf**(); This function is POSIX-Only. The `stat` struct gotten from calling `stat`. PreserveAttributes **preserveAttributesDefault**; Defaults to `Yes.preserveAttributes` on Windows, and the opposite on all other platforms. void **copy**(RF, RT)(RF from, RT to, PreserveAttributes preserve = preserveAttributesDefault) Constraints: if (isInputRange!RF && !isInfinite!RF && isSomeChar!(ElementEncodingType!RF) && !isConvertibleToString!RF && isInputRange!RT && !isInfinite!RT && isSomeChar!(ElementEncodingType!RT) && !isConvertibleToString!RT); void **copy**(RF, RT)(auto ref RF from, auto ref RT to, PreserveAttributes preserve = preserveAttributesDefault) Constraints: if (isConvertibleToString!RF || isConvertibleToString!RT); Copy file `from` to file `to`. File timestamps are preserved. File attributes are preserved, if `preserve` equals `Yes.preserveAttributes`. On Windows only `Yes.preserveAttributes` (the default on Windows) is supported. If the target file exists, it is overwritten. Parameters: | | | | --- | --- | | RF `from` | string or range of characters representing the existing file name | | RT `to` | string or range of characters representing the target file name | | PreserveAttributes `preserve` | whether to preserve the file attributes | Throws: [`FileException`](#FileException) on error. Examples: ``` auto source = deleteme ~ "source"; auto target = deleteme ~ "target"; auto targetNonExistent = deleteme ~ "target2"; scope(exit) source.remove, target.remove, targetNonExistent.remove; source.write("source"); target.write("target"); writeln(target.readText); // "target" source.copy(target); writeln(target.readText); // "source" source.copy(targetNonExistent); writeln(targetNonExistent.readText); // "source" ``` @safe void **rmdirRecurse**(scope const(char)[] pathname); @safe void **rmdirRecurse**(ref DirEntry de); @safe void **rmdirRecurse**(DirEntry de); Remove directory and all of its content and subdirectories, recursively. Parameters: | | | | --- | --- | | const(char)[] `pathname` | the path of the directory to completely remove | | DirEntry `de` | The [`DirEntry`](#DirEntry) to remove | Throws: [`FileException`](#FileException) if there is an error (including if the given file is not a directory). Examples: ``` import std.path : buildPath; auto dir = deleteme.buildPath("a", "b", "c"); dir.mkdirRecurse; assert(dir.exists); deleteme.rmdirRecurse; assert(!dir.exists); assert(!deleteme.exists); ``` enum **SpanMode**: int; Dictates directory spanning policy for dirEntries (see below). Examples: ``` import std.algorithm.comparison : equal; import std.algorithm.iteration : map; import std.path : buildPath, relativePath; auto root = deleteme ~ "root"; scope(exit) root.rmdirRecurse; root.mkdir; root.buildPath("animals").mkdir; root.buildPath("animals", "cat").mkdir; root.buildPath("animals", "dog").mkdir; root.buildPath("plants").mkdir; alias removeRoot = (e) => e.relativePath(root); root.dirEntries(SpanMode.shallow).map!removeRoot.equal( ["plants", "animals"]); root.dirEntries(SpanMode.depth).map!removeRoot.equal( ["plants", "animals/dog", "animals/cat", "animals"]); root.dirEntries(SpanMode.breadth).map!removeRoot.equal( ["plants", "animals", "animals/dog", "animals/cat"]); ``` **shallow** Only spans one directory. **depth** Spans the directory in [depth-first **post**-order](https://en.wikipedia.org/wiki/Tree_traversal#Post-order), i.e. the content of any subdirectory is spanned before that subdirectory itself. Useful e.g. when recursively deleting files. **breadth** Spans the directory in [depth-first **pre**-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order), i.e. the content of any subdirectory is spanned right after that subdirectory itself. Note that `SpanMode.breadth` will not result in all directory members occurring before any subdirectory members, i.e. it is not true [breadth-first traversal](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search). auto **dirEntries**(string path, SpanMode mode, bool followSymlink = true); auto **dirEntries**(string path, string pattern, SpanMode mode, bool followSymlink = true); Returns an [input range](std_range_primitives#isInputRange) of `DirEntry` that lazily iterates a given directory, also provides two ways of foreach iteration. The iteration variable can be of type `string` if only the name is needed, or `DirEntry` if additional details are needed. The span mode dictates how the directory is traversed. The name of each iterated directory entry contains the absolute or relative path (depending on pathname). Parameters: | | | | --- | --- | | string `path` | The directory to iterate over. If empty, the current directory will be iterated. | | string `pattern` | Optional string with wildcards, such as "\*.d". When present, it is used to filter the results by their file name. The supported wildcard strings are described under [`std.path.globMatch`](std_path#globMatch). | | SpanMode `mode` | Whether the directory's sub-directories should be iterated in depth-first post-order ([`depth`](#depth)), depth-first pre-order ([`breadth`](#breadth)), or not at all ([`shallow`](#shallow)). | | bool `followSymlink` | Whether symbolic links which point to directories should be treated as directories and their contents iterated over. | Returns: An [input range](std_range_primitives#isInputRange) of [`DirEntry`](#DirEntry). Throws: [`FileException`](#FileException) if the directory does not exist. Example ``` // Iterate a directory in depth foreach (string name; dirEntries("destroy/me", SpanMode.depth)) { remove(name); } // Iterate the current directory in breadth foreach (string name; dirEntries("", SpanMode.breadth)) { writeln(name); } // Iterate a directory and get detailed info about it foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth)) { writeln(e.name, "\t", e.size); } // Iterate over all *.d files in current directory and all its subdirectories auto dFiles = dirEntries("", SpanMode.depth).filter!(f => f.name.endsWith(".d")); foreach (d; dFiles) writeln(d.name); // Hook it up with std.parallelism to compile them all in parallel: foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread { string cmd = "dmd -c " ~ d.name; writeln(cmd); std.process.executeShell(cmd); } // Iterate over all D source files in current directory and all its // subdirectories auto dFiles = dirEntries("","*.{d,di}",SpanMode.depth); foreach (d; dFiles) writeln(d.name); ``` Examples: Duplicate functionality of D1's `std.file.listdir()`: ``` string[] listdir(string pathname) { import std.algorithm; import std.array; import std.file; import std.path; return std.file.dirEntries(pathname, SpanMode.shallow) .filter!(a => a.isFile) .map!(a => std.path.baseName(a.name)) .array; } void main(string[] args) { import std.stdio; string[] files = listdir(args[1]); writefln("%s", files); } ``` Select!(Types.length == 1, Types[0][], Tuple!Types[]) **slurp**(Types...)(string filename, scope const(char)[] format); Reads a file line by line and parses the line into a single value or a [`std.typecons.Tuple`](std_typecons#Tuple) of values depending on the length of `Types`. The lines are parsed using the specified format string. The format string is passed to [`std.format.formattedRead`](std_format#formattedRead), and therefore must conform to the format string specification outlined in [`std.format`](std_format). Parameters: | | | | --- | --- | | Types | the types that each of the elements in the line should be returned as | | string `filename` | the name of the file to read | | const(char)[] `format` | the format string to use when reading | Returns: If only one type is passed, then an array of that type. Otherwise, an array of [`std.typecons.Tuple`](std_typecons#Tuple)s. Throws: `Exception` if the format string is malformed. Also, throws `Exception` if any of the lines in the file are not fully consumed by the call to [`std.format.formattedRead`](std_format#formattedRead). Meaning that no empty lines or lines with extra characters are allowed. Examples: ``` import std.typecons : tuple; scope(exit) { assert(exists(deleteme)); remove(deleteme); } write(deleteme, "12 12.25\n345 1.125"); // deleteme is the name of a temporary file // Load file; each line is an int followed by comma, whitespace and a // double. auto a = slurp!(int, double)(deleteme, "%s %s"); writeln(a.length); // 2 writeln(a[0]); // tuple(12, 12.25) writeln(a[1]); // tuple(345, 1.125) ``` @trusted string **tempDir**(); Returns the path to a directory for temporary files. The return value of the function is cached, so the procedures described below will only be performed the first time the function is called. All subsequent runs will return the same string, regardless of whether environment variables and directory structures have changed in the meantime. The POSIX `tempDir` algorithm is inspired by Python's [`tempfile.tempdir`](http://docs.python.org/library/tempfile.html#tempfile.tempdir). Returns: On Windows, this function returns the result of calling the Windows API function [`GetTempPath`](http://msdn.microsoft.com/en-us/library/windows/desktop/aa364992.aspx). On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist: 1. The directory given by the `TMPDIR` environment variable. 2. The directory given by the `TEMP` environment variable. 3. The directory given by the `TMP` environment variable. 4. `/tmp` 5. `/var/tmp` 6. `/usr/tmp` On all platforms, `tempDir` returns `"."` on failure, representing the current working directory. Examples: ``` import std.ascii : letters; import std.conv : to; import std.path : buildPath; import std.random : randomSample; import std.utf : byCodeUnit; // random id with 20 letters auto id = letters.byCodeUnit.randomSample(20).to!string; auto myFile = tempDir.buildPath(id ~ "my_tmp_file"); scope(exit) myFile.remove; myFile.write("hello"); writeln(myFile.readText); // "hello" ``` @safe ulong **getAvailableDiskSpace**(scope const(char)[] path); Returns the available disk space based on a given path. On Windows, `path` must be a directory; on POSIX systems, it can be a file or directory. Parameters: | | | | --- | --- | | const(char)[] `path` | on Windows, it must be a directory; on POSIX it can be a file or directory | Returns: Available space in bytes Throws: [`FileException`](#FileException) in case of failure Examples: ``` import std.exception : assertThrown; auto space = getAvailableDiskSpace("."); assert(space > 0); assertThrown!FileException(getAvailableDiskSpace("ThisFileDoesNotExist123123")); ```
programming_docs
d std.algorithm std.algorithm ============= This package implements generic algorithms oriented towards the processing of sequences. Sequences processed by these functions define range-based interfaces. See also [Reference on ranges](std_range) and [tutorial on ranges](http://ddili.org/ders/d.en/ranges.html). Algorithms are categorized into the following submodules: | Submodule | Functions | | --- | --- | | [Searching](std_algorithm_searching) | [*all*](std_algorithm_searching#all) [*any*](std_algorithm_searching#any) [*balancedParens*](std_algorithm_searching#balancedParens) [*boyerMooreFinder*](std_algorithm_searching#boyerMooreFinder) [*canFind*](std_algorithm_searching#canFind) [*commonPrefix*](std_algorithm_searching#commonPrefix) [*count*](std_algorithm_searching#count) [*countUntil*](std_algorithm_searching#countUntil) [*endsWith*](std_algorithm_searching#endsWith) [*find*](std_algorithm_searching#find) [*findAdjacent*](std_algorithm_searching#findAdjacent) [*findAmong*](std_algorithm_searching#findAmong) [*findSkip*](std_algorithm_searching#findSkip) [*findSplit*](std_algorithm_searching#findSplit) [*findSplitAfter*](std_algorithm_searching#findSplitAfter) [*findSplitBefore*](std_algorithm_searching#findSplitBefore) [*minCount*](std_algorithm_searching#minCount) [*maxCount*](std_algorithm_searching#maxCount) [*minElement*](std_algorithm_searching#minElement) [*maxElement*](std_algorithm_searching#maxElement) [*minIndex*](std_algorithm_searching#minIndex) [*maxIndex*](std_algorithm_searching#maxIndex) [*minPos*](std_algorithm_searching#minPos) [*maxPos*](std_algorithm_searching#maxPos) [*skipOver*](std_algorithm_searching#skipOver) [*startsWith*](std_algorithm_searching#startsWith) [*until*](std_algorithm_searching#until) | | [Comparison](std_algorithm_comparison) | [*among*](std_algorithm_comparison#among) [*castSwitch*](std_algorithm_comparison#castSwitch) [*clamp*](std_algorithm_comparison#clamp) [*cmp*](std_algorithm_comparison#cmp) [*either*](std_algorithm_comparison#either) [*equal*](std_algorithm_comparison#equal) [*isPermutation*](std_algorithm_comparison#isPermutation) [*isSameLength*](std_algorithm_comparison#isSameLength) [*levenshteinDistance*](std_algorithm_comparison#levenshteinDistance) [*levenshteinDistanceAndPath*](std_algorithm_comparison#levenshteinDistanceAndPath) [*max*](std_algorithm_comparison#max) [*min*](std_algorithm_comparison#min) [*mismatch*](std_algorithm_comparison#mismatch) [*predSwitch*](std_algorithm_comparison#predSwitch) | | [Iteration](std_algorithm_iteration) | [*cache*](std_algorithm_iteration#cache) [*cacheBidirectional*](std_algorithm_iteration#cacheBidirectional) [*chunkBy*](std_algorithm_iteration#chunkBy) [*cumulativeFold*](std_algorithm_iteration#cumulativeFold) [*each*](std_algorithm_iteration#each) [*filter*](std_algorithm_iteration#filter) [*filterBidirectional*](std_algorithm_iteration#filterBidirectional) [*fold*](std_algorithm_iteration#fold) [*group*](std_algorithm_iteration#group) [*joiner*](std_algorithm_iteration#joiner) [*map*](std_algorithm_iteration#map) [*mean*](std_algorithm_iteration#mean) [*permutations*](std_algorithm_iteration#permutations) [*reduce*](std_algorithm_iteration#reduce) [*splitter*](std_algorithm_iteration#splitter) [*substitute*](std_algorithm_iteration#substitute) [*sum*](std_algorithm_iteration#sum) [*uniq*](std_algorithm_iteration#uniq) | | [Sorting](std_algorithm_sorting) | [*completeSort*](std_algorithm_sorting#completeSort) [*isPartitioned*](std_algorithm_sorting#isPartitioned) [*isSorted*](std_algorithm_sorting#isSorted) [*isStrictlyMonotonic*](std_algorithm_sorting#isStrictlyMonotonic) [*ordered*](std_algorithm_sorting#ordered) [*strictlyOrdered*](std_algorithm_sorting#strictlyOrdered) [*makeIndex*](std_algorithm_sorting#makeIndex) [*merge*](std_algorithm_sorting#merge) [*multiSort*](std_algorithm_sorting#multiSort) [*nextEvenPermutation*](std_algorithm_sorting#nextEvenPermutation) [*nextPermutation*](std_algorithm_sorting#nextPermutation) [*partialSort*](std_algorithm_sorting#partialSort) [*partition*](std_algorithm_sorting#partition) [*partition3*](std_algorithm_sorting#partition3) [*schwartzSort*](std_algorithm_sorting#schwartzSort) [*sort*](std_algorithm_sorting#sort) [*topN*](std_algorithm_sorting#topN) [*topNCopy*](std_algorithm_sorting#topNCopy) [*topNIndex*](std_algorithm_sorting#topNIndex) | | Set operations ([setops](std_algorithm_setops)) | [*cartesianProduct*](std_algorithm_setops#cartesianProduct) [*largestPartialIntersection*](std_algorithm_setops#largestPartialIntersection) [*largestPartialIntersectionWeighted*](std_algorithm_setops#largestPartialIntersectionWeighted) [*multiwayMerge*](std_algorithm_setops#multiwayMerge) [*multiwayUnion*](std_algorithm_setops#multiwayUnion) [*setDifference*](std_algorithm_setops#setDifference) [*setIntersection*](std_algorithm_setops#setIntersection) [*setSymmetricDifference*](std_algorithm_setops#setSymmetricDifference) | | [Mutation](std_algorithm_mutation) | [*bringToFront*](std_algorithm_mutation#bringToFront) [*copy*](std_algorithm_mutation#copy) [*fill*](std_algorithm_mutation#fill) [*initializeAll*](std_algorithm_mutation#initializeAll) [*move*](std_algorithm_mutation#move) [*moveAll*](std_algorithm_mutation#moveAll) [*moveSome*](std_algorithm_mutation#moveSome) [*moveEmplace*](std_algorithm_mutation#moveEmplace) [*moveEmplaceAll*](std_algorithm_mutation#moveEmplaceAll) [*moveEmplaceSome*](std_algorithm_mutation#moveEmplaceSome) [*remove*](std_algorithm_mutation#remove) [*reverse*](std_algorithm_mutation#reverse) [*strip*](std_algorithm_mutation#strip) [*stripLeft*](std_algorithm_mutation#stripLeft) [*stripRight*](std_algorithm_mutation#stripRight) [*swap*](std_algorithm_mutation#swap) [*swapRanges*](std_algorithm_mutation#swapRanges) [*uninitializedFill*](std_algorithm_mutation#uninitializedFill) | Many functions in this package are parameterized with a [predicate](http://dlang.org/glossary.html#predicate). The predicate may be any suitable callable type (a function, a delegate, a [functor](http://dlang.org/glossary.html#functor), or a lambda), or a compile-time string. The string may consist of **any** legal D expression that uses the symbol `a` (for unary functions) or the symbols `a` and `b` (for binary functions). These names will NOT interfere with other homonym symbols in user code because they are evaluated in a different context. The default for all binary comparison predicates is `"a == b"` for unordered operations and `"a < b"` for ordered operations. Example ``` int[] a = ...; static bool greater(int a, int b) { return a > b; } sort!greater(a); // predicate as alias sort!((a, b) => a > b)(a); // predicate as a lambda. sort!"a > b"(a); // predicate as string // (no ambiguity with array name) sort(a); // no predicate, "a < b" is implicit ``` License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: [Andrei Alexandrescu](http://erdani.com) Source [std/algorithm/package.d](https://github.com/dlang/phobos/blob/master/std/algorithm/package.d) d rt.trace rt.trace ======== Contains support code for code profiling. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright, Sean Kelly, the LDC team Source [rt/trace.d](https://github.com/dlang/druntime/blob/master/src/rt/trace.d) void **trace\_setlogfilename**(string name); Set the file path for profile reports (`-profile`) This function is a public API, exposed in `core.runtime`. Since we are calling C functions under the hood, and we might need to open and close files during the runtime tear-down we copy the parameter via malloc to ensure NUL-termination. Parameters: | | | | --- | --- | | string `name` | Path to the output file. Empty means stdout. | void **trace\_setdeffilename**(string name); Set the file path for the optimized profile linker DEF file (`-profile`) This function is a public API, exposed in `core.runtime`. Since we are calling C functions under the hood, and we might need to open and close files during the runtime tear-down we copy the parameter via malloc to ensure NUL-termination. Parameters: | | | | --- | --- | | string `name` | Path to the output file. Empty means stdout. | d core.sync.rwmutex core.sync.rwmutex ================= The read/write mutex module provides a primitive for maintaining shared read access and mutually exclusive write access. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) Authors: Sean Kelly Source [core/sync/rwmutex.d](https://github.com/dlang/druntime/blob/master/src/core/sync/rwmutex.d) class **ReadWriteMutex**; This class represents a mutex that allows any number of readers to enter, but when a writer enters, all other readers and writers are blocked. Please note that this mutex is not recursive and is intended to guard access to data only. Also, no deadlock checking is in place because doing so would require dynamic memory allocation, which would reduce performance by an unacceptable amount. As a result, any attempt to recursively acquire this mutex may well deadlock the caller, particularly if a write lock is acquired while holding a read lock, or vice-versa. In practice, this should not be an issue however, because it is uncommon to call deeply into unknown code while holding a lock that simply protects data. Examples: ``` import core.atomic, core.thread, core.sync.semaphore; static void runTest(ReadWriteMutex.Policy policy) { scope mutex = new ReadWriteMutex(policy); scope rdSemA = new Semaphore, rdSemB = new Semaphore, wrSemA = new Semaphore, wrSemB = new Semaphore; shared size_t numReaders, numWriters; void readerFn() { synchronized (mutex.reader) { atomicOp!"+="(numReaders, 1); rdSemA.notify(); rdSemB.wait(); atomicOp!"-="(numReaders, 1); } } void writerFn() { synchronized (mutex.writer) { atomicOp!"+="(numWriters, 1); wrSemA.notify(); wrSemB.wait(); atomicOp!"-="(numWriters, 1); } } void waitQueued(size_t queuedReaders, size_t queuedWriters) { for (;;) { synchronized (mutex.m_commonMutex) { if (mutex.m_numQueuedReaders == queuedReaders && mutex.m_numQueuedWriters == queuedWriters) break; } Thread.yield(); } } scope group = new ThreadGroup; // 2 simultaneous readers group.create(&readerFn); group.create(&readerFn); rdSemA.wait(); rdSemA.wait(); assert(numReaders == 2); rdSemB.notify(); rdSemB.notify(); group.joinAll(); assert(numReaders == 0); foreach (t; group) group.remove(t); // 1 writer at a time group.create(&writerFn); group.create(&writerFn); wrSemA.wait(); assert(!wrSemA.tryWait()); assert(numWriters == 1); wrSemB.notify(); wrSemA.wait(); assert(numWriters == 1); wrSemB.notify(); group.joinAll(); assert(numWriters == 0); foreach (t; group) group.remove(t); // reader and writer are mutually exclusive group.create(&readerFn); rdSemA.wait(); group.create(&writerFn); waitQueued(0, 1); assert(!wrSemA.tryWait()); assert(numReaders == 1 && numWriters == 0); rdSemB.notify(); wrSemA.wait(); assert(numReaders == 0 && numWriters == 1); wrSemB.notify(); group.joinAll(); assert(numReaders == 0 && numWriters == 0); foreach (t; group) group.remove(t); // writer and reader are mutually exclusive group.create(&writerFn); wrSemA.wait(); group.create(&readerFn); waitQueued(1, 0); assert(!rdSemA.tryWait()); assert(numReaders == 0 && numWriters == 1); wrSemB.notify(); rdSemA.wait(); assert(numReaders == 1 && numWriters == 0); rdSemB.notify(); group.joinAll(); assert(numReaders == 0 && numWriters == 0); foreach (t; group) group.remove(t); // policy determines whether queued reader or writers progress first group.create(&writerFn); wrSemA.wait(); group.create(&readerFn); group.create(&writerFn); waitQueued(1, 1); assert(numReaders == 0 && numWriters == 1); wrSemB.notify(); if (policy == ReadWriteMutex.Policy.PREFER_READERS) { rdSemA.wait(); assert(numReaders == 1 && numWriters == 0); rdSemB.notify(); wrSemA.wait(); assert(numReaders == 0 && numWriters == 1); wrSemB.notify(); } else if (policy == ReadWriteMutex.Policy.PREFER_WRITERS) { wrSemA.wait(); assert(numReaders == 0 && numWriters == 1); wrSemB.notify(); rdSemA.wait(); assert(numReaders == 1 && numWriters == 0); rdSemB.notify(); } group.joinAll(); assert(numReaders == 0 && numWriters == 0); foreach (t; group) group.remove(t); } runTest(ReadWriteMutex.Policy.PREFER_READERS); runTest(ReadWriteMutex.Policy.PREFER_WRITERS); ``` enum **Policy**: int; Defines the policy used by this mutex. Currently, two policies are defined. The first will queue writers until no readers hold the mutex, then pass the writers through one at a time. If a reader acquires the mutex while there are still writers queued, the reader will take precedence. The second will queue readers if there are any writers queued. Writers are passed through one at a time, and once there are no writers present, all queued readers will be alerted. Future policies may offer a more even balance between reader and writer precedence. **PREFER\_READERS** Readers get preference. This may starve writers. **PREFER\_WRITERS** Writers get preference. This may starve readers. this(Policy policy = Policy.PREFER\_WRITERS); Initializes a read/write mutex object with the supplied policy. Parameters: | | | | --- | --- | | Policy `policy` | The policy to use. | Throws: SyncError on error. @property Policy **policy**(); Gets the policy used by this mutex. Returns: The policy used by this mutex. @property Reader **reader**(); Gets an object representing the reader lock for the associated mutex. Returns: A reader sub-mutex. @property Writer **writer**(); Gets an object representing the writer lock for the associated mutex. Returns: A writer sub-mutex. class **Reader**: object.Object.Monitor; This class can be considered a mutex in its own right, and is used to negotiate a read lock for the enclosing mutex. this(); Initializes a read/write mutex reader proxy object. @trusted void **lock**(); Acquires a read lock on the enclosing mutex. @trusted void **unlock**(); Releases a read lock on the enclosing mutex. bool **tryLock**(); Attempts to acquire a read lock on the enclosing mutex. If one can be obtained without blocking, the lock is acquired and true is returned. If not, the lock is not acquired and false is returned. Returns: true if the lock was acquired and false if not. bool **tryLock**(Duration timeout); Attempts to acquire a read lock on the enclosing mutex. If one can be obtained without blocking, the lock is acquired and true is returned. If not, the function blocks until either the lock can be obtained or the time elapsed exceeds timeout, returning true if the lock was acquired and false if the function timed out. Parameters: | | | | --- | --- | | Duration `timeout` | maximum amount of time to wait for the lock | Returns: true if the lock was acquired and false if not. class **Writer**: object.Object.Monitor; This class can be considered a mutex in its own right, and is used to negotiate a write lock for the enclosing mutex. this(); Initializes a read/write mutex writer proxy object. @trusted void **lock**(); Acquires a write lock on the enclosing mutex. @trusted void **unlock**(); Releases a write lock on the enclosing mutex. bool **tryLock**(); Attempts to acquire a write lock on the enclosing mutex. If one can be obtained without blocking, the lock is acquired and true is returned. If not, the lock is not acquired and false is returned. Returns: true if the lock was acquired and false if not. bool **tryLock**(Duration timeout); Attempts to acquire a write lock on the enclosing mutex. If one can be obtained without blocking, the lock is acquired and true is returned. If not, the function blocks until either the lock can be obtained or the time elapsed exceeds timeout, returning true if the lock was acquired and false if the function timed out. Parameters: | | | | --- | --- | | Duration `timeout` | maximum amount of time to wait for the lock | Returns: true if the lock was acquired and false if not. d core.stdcpp.allocator core.stdcpp.allocator ===================== D binding to C++ std::allocator. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Manu Evans Source [core/stdcpp/allocator.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/allocator.d) struct **allocator**(T); Allocators are classes that define memory models to be used by some parts of the C++ Standard Library, and most specifically, by STL containers. this(U)(ref allocator!U); alias **size\_type** = size\_t; alias **difference\_type** = ptrdiff\_t; alias **pointer** = T\*; alias **value\_type** = T; enum auto **propagate\_on\_container\_move\_assignment**; enum auto **is\_always\_equal**; template **rebind**(U) @nogc T\* **allocate**(size\_t count); @nogc void **deallocate**(T\* ptr, size\_t count); enum size\_t **max\_size**; struct **allocator\_traits**(Alloc); alias **allocator\_type** = Alloc; alias **value\_type** = allocator\_type.**value\_type**; alias **size\_type** = allocator\_type.**size\_type**; alias **difference\_type** = allocator\_type.**difference\_type**; alias **pointer** = allocator\_type.**pointer**; enum auto **propagate\_on\_container\_copy\_assignment**; enum auto **propagate\_on\_container\_move\_assignment**; enum auto **propagate\_on\_container\_swap**; enum auto **is\_always\_equal**; template **rebind\_alloc**(U) template **rebind\_traits**(U) size\_type **max\_size**()(auto ref allocator\_type a); allocator\_type **select\_on\_container\_copy\_construction**()(auto ref allocator\_type a); d std.math std.math ======== Contains the elementary mathematical functions (powers, roots, and trigonometric functions), and low-level floating-point operations. Mathematical special functions are available in `std.mathspecial`. | Category | Members | | --- | --- | | Constants | [*E*](#E) [*PI*](#PI) [*PI\_2*](#PI_2) [*PI\_4*](#PI_4) [*M\_1\_PI*](#M_1_PI) [*M\_2\_PI*](#M_2_PI) [*M\_2\_SQRTPI*](#M_2_SQRTPI) [*LN10*](#LN10) [*LN2*](#LN2) [*LOG2*](#LOG2) [*LOG2E*](#LOG2E) [*LOG2T*](#LOG2T) [*LOG10E*](#LOG10E) [*SQRT2*](#SQRT2) [*SQRT1\_2*](#SQRT1_2) | | Classics | [*abs*](#abs) [*fabs*](#fabs) [*sqrt*](#sqrt) [*cbrt*](#cbrt) [*hypot*](#hypot) [*poly*](#poly) [*nextPow2*](#nextPow2) [*truncPow2*](#truncPow2) | | Trigonometry | [*sin*](#sin) [*cos*](#cos) [*tan*](#tan) [*asin*](#asin) [*acos*](#acos) [*atan*](#atan) [*atan2*](#atan2) [*sinh*](#sinh) [*cosh*](#cosh) [*tanh*](#tanh) [*asinh*](#asinh) [*acosh*](#acosh) [*atanh*](#atanh) | | Rounding | [*ceil*](#ceil) [*floor*](#floor) [*round*](#round) [*lround*](#lround) [*trunc*](#trunc) [*rint*](#rint) [*lrint*](#lrint) [*nearbyint*](#nearbyint) [*rndtol*](#rndtol) [*quantize*](#quantize) | | Exponentiation & Logarithms | [*pow*](#pow) [*exp*](#exp) [*exp2*](#exp2) [*expm1*](#expm1) [*ldexp*](#ldexp) [*frexp*](#frexp) [*log*](#log) [*log2*](#log2) [*log10*](#log10) [*logb*](#logb) [*ilogb*](#ilogb) [*log1p*](#log1p) [*scalbn*](#scalbn) | | Modulus | [*fmod*](#fmod) [*modf*](#modf) [*remainder*](#remainder) | | Floating-point operations | [*approxEqual*](#approxEqual) [*feqrel*](#feqrel) [*fdim*](#fdim) [*fmax*](#fmax) [*fmin*](#fmin) [*fma*](#fma) [*isClose*](#isClose) [*nextDown*](#nextDown) [*nextUp*](#nextUp) [*nextafter*](#nextafter) [*NaN*](#NaN) [*getNaNPayload*](#getNaNPayload) [*cmp*](#cmp) | | Introspection | [*isFinite*](#isFinite) [*isIdentical*](#isIdentical) [*isInfinity*](#isInfinity) [*isNaN*](#isNaN) [*isNormal*](#isNormal) [*isSubnormal*](#isSubnormal) [*signbit*](#signbit) [*sgn*](#sgn) [*copysign*](#copysign) [*isPowerOf2*](#isPowerOf2) | | Hardware Control | [*IeeeFlags*](#IeeeFlags) [*FloatingPointControl*](#FloatingPointControl) | The functionality closely follows the IEEE754-2008 standard for floating-point arithmetic, including the use of camelCase names rather than C99-style lower case names. All of these functions behave correctly when presented with an infinity or NaN. The following IEEE 'real' formats are currently supported: * 64 bit Big-endian 'double' (eg PowerPC) * 128 bit Big-endian 'quadruple' (eg SPARC) * 64 bit Little-endian 'double' (eg x86-SSE2) * 80 bit Little-endian, with implied bit 'real80' (eg x87, Itanium) * 128 bit Little-endian 'quadruple' (not implemented on any known processor!) * Non-IEEE 128 bit Big-endian 'doubledouble' (eg PowerPC) has partial support Unlike C, there is no global 'errno' variable. Consequently, almost all of these functions are pure nothrow. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com), Don Clugston, Conversion of CEPHES math library to D by Iain Buclaw and David Nadlinger Source [std/math.d](https://github.com/dlang/phobos/blob/master/std/math.d) enum real **E**; e = 2.718281... enum real **LOG2T**; log210 = 3.321928... enum real **LOG2E**; log2e = 1.442695... enum real **LOG2**; log102 = 0.301029... enum real **LOG10E**; log10e = 0.434294... enum real **LN2**; ln 2 = 0.693147... enum real **LN10**; ln 10 = 2.302585... enum real **PI**; π = 3.141592... enum real **PI\_2**; π / 2 = 1.570796... enum real **PI\_4**; π / 4 = 0.785398... enum real **M\_1\_PI**; 1 / π = 0.318309... enum real **M\_2\_PI**; 2 / π = 0.636619... enum real **M\_2\_SQRTPI**; 2 / √π = 1.128379... enum real **SQRT2**; √2 = 1.414213... enum real **SQRT1\_2**; √½ = 0.707106... pure nothrow @nogc auto **abs**(Num)(Num x) Constraints: if (is(immutable(Num) == immutable(short)) || is(immutable(Num) == immutable(byte)) || is(typeof(Num.init >= 0)) && is(typeof(-Num.init))); Calculates the absolute value of a number. Parameters: | | | | --- | --- | | Num | (template parameter) type of number | | Num `x` | real number value | Returns: The absolute value of the number. If floating-point or integral, the return type will be the same as the input. Limitations Does not work correctly for signed intergal types and value `Num`.min. Examples: ditto ``` assert(isIdentical(abs(-0.0L), 0.0L)); assert(isNaN(abs(real.nan))); writeln(abs(-real.infinity)); // real.infinity writeln(abs(-56)); // 56 writeln(abs(2321312L)); // 2321312L ``` pure nothrow @nogc @safe real **cos**(real x); pure nothrow @nogc @safe double **cos**(double x); pure nothrow @nogc @safe float **cos**(float x); Returns cosine of x. x is in radians. Special Values| x | cos(x) | invalid? | | NAN | NAN | yes | | ±∞ | NAN | yes | Bugs: Results are undefined if |x| >= 264. Examples: ``` writeln(cos(0.0)); // 1.0 assert(cos(1.0).approxEqual(0.540)); assert(cos(3.0).approxEqual(-0.989)); ``` pure nothrow @nogc @safe real **sin**(real x); pure nothrow @nogc @safe double **sin**(double x); pure nothrow @nogc @safe float **sin**(float x); Returns [sine](http://en.wikipedia.org/wiki/Sine) of x. x is in [radians](http://en.wikipedia.org/wiki/Radian). Special Values| x | sin(x) | invalid? | | NAN | NAN | yes | | ±0.0 | ±0.0 | no | | ±∞ | NAN | yes | Parameters: | | | | --- | --- | | real `x` | angle in radians (not degrees) | Returns: sine of x See Also: [*cos*](#cos) , [*tan*](#tan) , [*asin*](#asin) Bugs: Results are undefined if |x| >= 264. Examples: ``` import std.math : sin, PI; import std.stdio : writefln; void someFunc() { real x = 30.0; auto result = sin(x * (PI / 180)); // convert degrees to radians writefln("The sine of %s degrees is %s", x, result); } ``` pure nothrow @nogc @safe real **tan**(real x); pure nothrow @nogc @safe double **tan**(double x); pure nothrow @nogc @safe float **tan**(float x); Returns tangent of x. x is in radians. Special Values| x | tan(x) | invalid? | | NAN | NAN | yes | | ±0.0 | ±0.0 | no | | ±∞ | NAN | yes | Examples: ``` assert(isIdentical(tan(0.0), 0.0)); assert(tan(PI).approxEqual(0)); assert(tan(PI / 3).approxEqual(sqrt(3.0))); ``` pure nothrow @nogc @safe real **acos**(real x); pure nothrow @nogc @safe double **acos**(double x); pure nothrow @nogc @safe float **acos**(float x); Calculates the arc cosine of x, returning a value ranging from 0 to π. Special Values| x | acos(x) | invalid? | | >1.0 | NAN | yes | | <-1.0 | NAN | yes | | NAN | NAN | yes | Examples: ``` assert(acos(0.0).approxEqual(1.570)); assert(acos(0.5).approxEqual(std.math.PI / 3)); assert(acos(PI).isNaN); ``` pure nothrow @nogc @safe real **asin**(real x); pure nothrow @nogc @safe double **asin**(double x); pure nothrow @nogc @safe float **asin**(float x); Calculates the arc sine of x, returning a value ranging from -π/2 to π/2. Special Values| x | asin(x) | invalid? | | ±0.0 | ±0.0 | no | | >1.0 | NAN | yes | | <-1.0 | NAN | yes | Examples: ``` assert(isIdentical(asin(0.0), 0.0)); assert(asin(0.5).approxEqual(PI / 6)); assert(asin(PI).isNaN); ``` pure nothrow @nogc @safe real **atan**(real x); pure nothrow @nogc @safe double **atan**(double x); pure nothrow @nogc @safe float **atan**(float x); Calculates the arc tangent of x, returning a value ranging from -π/2 to π/2. Special Values| x | atan(x) | invalid? | | ±0.0 | ±0.0 | no | | ±∞ | NAN | yes | Examples: ``` assert(isIdentical(atan(0.0), 0.0)); assert(atan(sqrt(3.0)).approxEqual(PI / 3)); ``` pure nothrow @nogc @trusted real **atan2**(real y, real x); pure nothrow @nogc @safe double **atan2**(double y, double x); pure nothrow @nogc @safe float **atan2**(float y, float x); Calculates the arc tangent of y / x, returning a value ranging from -π to π. Special Values| y | x | atan(y, x) | | NAN | anything | NAN | | anything | NAN | NAN | | ±0.0 | >0.0 | ±0.0 | | ±0.0 | +0.0 | ±0.0 | | ±0.0 | <0.0 | ±π | | ±0.0 | -0.0 | ±π | | >0.0 | ±0.0 | π/2 | | <0.0 | ±0.0 | -π/2 | | >0.0 | ∞ | ±0.0 | | ±∞ | anything | ±π/2 | | >0.0 | -∞ | ±π | | ±∞ | ∞ | ±π/4 | | ±∞ | -∞ | ±3π/4 | Examples: ``` assert(atan2(1.0, sqrt(3.0)).approxEqual(PI / 6)); ``` pure nothrow @nogc @safe real **cosh**(real x); pure nothrow @nogc @safe double **cosh**(double x); pure nothrow @nogc @safe float **cosh**(float x); Calculates the hyperbolic cosine of x. Special Values| x | cosh(x) | invalid? | | ±∞ | ±0.0 | no | Examples: ``` writeln(cosh(0.0)); // 1.0 assert(cosh(1.0).approxEqual((E + 1.0 / E) / 2)); ``` pure nothrow @nogc @safe real **sinh**(real x); pure nothrow @nogc @safe double **sinh**(double x); pure nothrow @nogc @safe float **sinh**(float x); Calculates the hyperbolic sine of x. Special Values| x | sinh(x) | invalid? | | ±0.0 | ±0.0 | no | | ±∞ | ±∞ | no | Examples: ``` enum sinh1 = (E - 1.0 / E) / 2; import std.meta : AliasSeq; static foreach (F; AliasSeq!(float, double, real)) { assert(isIdentical(sinh(F(0.0)), F(0.0))); assert(sinh(F(1.0)).approxEqual(F(sinh1))); } ``` pure nothrow @nogc @safe real **tanh**(real x); pure nothrow @nogc @safe double **tanh**(double x); pure nothrow @nogc @safe float **tanh**(float x); Calculates the hyperbolic tangent of x. Special Values| x | tanh(x) | invalid? | | ±0.0 | ±0.0 | no | | ±∞ | ±1.0 | no | Examples: ``` assert(isIdentical(tanh(0.0), 0.0)); assert(tanh(1.0).approxEqual(sinh(1.0) / cosh(1.0))); ``` pure nothrow @nogc @safe real **acosh**(real x); pure nothrow @nogc @safe double **acosh**(double x); pure nothrow @nogc @safe float **acosh**(float x); Calculates the inverse hyperbolic cosine of x. Mathematically, acosh(x) = log(x + sqrt( x\*x - 1)) | Domain X | Range Y | | --- | --- | | 1..∞ | 0..∞ | Special Values| x | acosh(x) | | NAN | NAN | | <1 | NAN | | 1 | 0 | | +∞ | +∞ | Examples: ``` assert(isNaN(acosh(0.9))); assert(isNaN(acosh(real.nan))); assert(isIdentical(acosh(1.0), 0.0)); writeln(acosh(real.infinity)); // real.infinity assert(isNaN(acosh(0.5))); ``` pure nothrow @nogc @safe real **asinh**(real x); pure nothrow @nogc @safe double **asinh**(double x); pure nothrow @nogc @safe float **asinh**(float x); Calculates the inverse hyperbolic sine of x. Mathematically, ``` asinh(x) = log( x + sqrt( x*x + 1 )) // if x >= +0 asinh(x) = -log(-x + sqrt( x*x + 1 )) // if x <= -0 ``` Special Values| x | asinh(x) | | NAN | NAN | | ±0 | ±0 | | ±∞ | ±∞ | Examples: ``` assert(isIdentical(asinh(0.0), 0.0)); assert(isIdentical(asinh(-0.0), -0.0)); writeln(asinh(real.infinity)); // real.infinity writeln(asinh(-real.infinity)); // -real.infinity assert(isNaN(asinh(real.nan))); ``` pure nothrow @nogc @safe real **atanh**(real x); pure nothrow @nogc @safe double **atanh**(double x); pure nothrow @nogc @safe float **atanh**(float x); Calculates the inverse hyperbolic tangent of x, returning a value from ranging from -1 to 1. Mathematically, atanh(x) = log( (1+x)/(1-x) ) / 2 | Domain X | Range Y | | --- | --- | | -∞..∞ | -1 .. 1 | Special Values| x | acosh(x) | | NAN | NAN | | ±0 | ±0 | | -∞ | -0 | Examples: ``` assert(isIdentical(atanh(0.0), 0.0)); assert(isIdentical(atanh(-0.0),-0.0)); assert(isNaN(atanh(real.nan))); assert(isNaN(atanh(-real.infinity))); writeln(atanh(0.0)); // 0 ``` pure nothrow @nogc @safe long **rndtol**(real x); pure nothrow @nogc @safe long **rndtol**(double x); pure nothrow @nogc @safe long **rndtol**(float x); Returns x rounded to a long value using the current rounding mode. If the integer value of x is greater than long.max, the result is indeterminate. Examples: ``` writeln(rndtol(1.0)); // 1L writeln(rndtol(1.2)); // 1L writeln(rndtol(1.7)); // 2L writeln(rndtol(1.0001)); // 1L ``` pure nothrow @nogc @safe float **sqrt**(float x); pure nothrow @nogc @safe double **sqrt**(double x); pure nothrow @nogc @safe real **sqrt**(real x); Compute square root of x. Special Values| x | sqrt(x) | invalid? | | -0.0 | -0.0 | no | | <0.0 | NAN | yes | | +∞ | +∞ | no | Examples: ``` assert(sqrt(2.0).feqrel(1.4142) > 16); assert(sqrt(9.0).feqrel(3.0) > 16); assert(isNaN(sqrt(-1.0f))); assert(isNaN(sqrt(-1.0))); assert(isNaN(sqrt(-1.0L))); ``` pure nothrow @nogc @trusted real **exp**(real x); pure nothrow @nogc @safe double **exp**(double x); pure nothrow @nogc @safe float **exp**(float x); Calculates ex. Special Values| x | ex | | +∞ | +∞ | | -∞ | +0.0 | | NAN | NAN | Examples: ``` writeln(exp(0.0)); // 1.0 assert(exp(3.0).feqrel(E * E * E) > 16); ``` pure nothrow @nogc @trusted real **expm1**(real x); pure nothrow @nogc @safe double **expm1**(double x); pure nothrow @nogc @safe float **expm1**(float x); Calculates the value of the natural logarithm base (e) raised to the power of x, minus 1. For very small x, expm1(x) is more accurate than exp(x)-1. Special Values| x | ex-1 | | ±0.0 | ±0.0 | | +∞ | +∞ | | -∞ | -1.0 | | NAN | NAN | Examples: ``` assert(isIdentical(expm1(0.0), 0.0)); assert(expm1(1.0).feqrel(1.71828) > 16); assert(expm1(2.0).feqrel(6.3890) > 16); ``` pure nothrow @nogc @trusted real **exp2**(real x); pure nothrow @nogc @safe double **exp2**(double x); pure nothrow @nogc @safe float **exp2**(float x); Calculates 2x. Special Values| x | exp2(x) | | +∞ | +∞ | | -∞ | +0.0 | | NAN | NAN | Examples: ``` assert(isIdentical(exp2(0.0), 1.0)); assert(exp2(2.0).feqrel(4.0) > 16); assert(exp2(8.0).feqrel(256.0) > 16); ``` pure nothrow @nogc @trusted T **frexp**(T)(const T value, out int exp) Constraints: if (isFloatingPoint!T); Separate floating point value into significand and exponent. Returns: Calculate and return *x* and *exp* such that value =*x*\*2exp and .5 <= |*x*| < 1.0 *x* has same sign as value. Special Values| value | returns | exp | | ±0.0 | ±0.0 | 0 | | +∞ | +∞ | int.max | | -∞ | -∞ | int.min | | ±NAN | ±NAN | int.min | Examples: ``` int exp; real mantissa = frexp(123.456L, exp); assert(approxEqual(mantissa * pow(2.0L, cast(real) exp), 123.456L)); assert(frexp(-real.nan, exp) && exp == int.min); assert(frexp(real.nan, exp) && exp == int.min); assert(frexp(-real.infinity, exp) == -real.infinity && exp == int.min); assert(frexp(real.infinity, exp) == real.infinity && exp == int.max); assert(frexp(-0.0, exp) == -0.0 && exp == 0); assert(frexp(0.0, exp) == 0.0 && exp == 0); ``` pure nothrow @nogc @trusted int **ilogb**(T)(const T x) Constraints: if (isFloatingPoint!T); pure nothrow @nogc @safe int **ilogb**(T)(const T x) Constraints: if (isIntegral!T && isUnsigned!T); pure nothrow @nogc @safe int **ilogb**(T)(const T x) Constraints: if (isIntegral!T && isSigned!T); Extracts the exponent of x as a signed integral value. If x is not a special value, the result is the same as `cast(int) logb(x)`. Special Values| x | ilogb(x) | Range error? | | 0 | FP\_ILOGB0 | yes | | ±∞ | int.max | no | | NAN | FP\_ILOGBNAN | no | Examples: ``` writeln(ilogb(1)); // 0 writeln(ilogb(3)); // 1 writeln(ilogb(3.0)); // 1 writeln(ilogb(100_000_000)); // 26 writeln(ilogb(0)); // FP_ILOGB0 writeln(ilogb(0.0)); // FP_ILOGB0 writeln(ilogb(double.nan)); // FP_ILOGBNAN writeln(ilogb(double.infinity)); // int.max ``` alias **FP\_ILOGB0** = core.stdc.math.**FP\_ILOGB0**; alias **FP\_ILOGBNAN** = core.stdc.math.**FP\_ILOGBNAN**; Special return values of [`ilogb`](#ilogb). Examples: ``` writeln(ilogb(0)); // FP_ILOGB0 writeln(ilogb(0.0)); // FP_ILOGB0 writeln(ilogb(double.nan)); // FP_ILOGBNAN ``` pure nothrow @nogc @safe real **ldexp**(real n, int exp); pure nothrow @nogc @safe double **ldexp**(double n, int exp); pure nothrow @nogc @safe float **ldexp**(float n, int exp); Compute n \* 2exp References frexp Examples: ``` import std.meta : AliasSeq; static foreach (T; AliasSeq!(float, double, real)) {{ T r; r = ldexp(3.0L, 3); writeln(r); // 24 r = ldexp(cast(T) 3.0, cast(int) 3); writeln(r); // 24 T n = 3.0; int exp = 3; r = ldexp(n, exp); writeln(r); // 24 }} ``` pure nothrow @nogc @safe real **log**(real x); Calculate the natural logarithm of x. Special Values| x | log(x) | divide by 0? | invalid? | | ±0.0 | -∞ | yes | no | | <0.0 | NAN | no | yes | | +∞ | +∞ | no | no | Examples: ``` assert(feqrel(log(E), 1) >= real.mant_dig - 1); ``` pure nothrow @nogc @safe real **log10**(real x); Calculate the base-10 logarithm of x. Special Values| x | log10(x) | divide by 0? | invalid? | | ±0.0 | -∞ | yes | no | | <0.0 | NAN | no | yes | | +∞ | +∞ | no | no | Examples: ``` assert(fabs(log10(1000) - 3) < .000001); ``` pure nothrow @nogc @safe real **log1p**(real x); Calculates the natural logarithm of 1 + x. For very small x, log1p(x) will be more accurate than log(1 + x). Special Values| x | log1p(x) | divide by 0? | invalid? | | ±0.0 | ±0.0 | no | no | | -1.0 | -∞ | yes | no | | <-1.0 | -NAN | no | yes | | +∞ | +∞ | no | no | Examples: ``` assert(isIdentical(log1p(0.0), 0.0)); assert(log1p(1.0).feqrel(0.69314) > 16); writeln(log1p(-1.0)); // -real.infinity assert(isNaN(log1p(-2.0))); assert(log1p(real.nan) is real.nan); assert(log1p(-real.nan) is -real.nan); writeln(log1p(real.infinity)); // real.infinity ``` pure nothrow @nogc @safe real **log2**(real x); Calculates the base-2 logarithm of x: log2x Special Values| x | log2(x) | divide by 0? | invalid? | | ±0.0 | -∞ | yes | no | | <0.0 | NAN | no | yes | | +∞ | +∞ | no | no | Examples: ``` assert(approxEqual(log2(1024.0L), 10)); ``` nothrow @nogc @trusted real **logb**(real x); Extracts the exponent of x as a signed integral value. If x is subnormal, it is treated as if it were normalized. For a positive, finite x: 1 <= *x* \* FLT\_RADIX-logb(x) < FLT\_RADIX Special Values| x | logb(x) | divide by 0? | | ±∞ | +∞ | no | | ±0.0 | -∞ | yes | Examples: ``` writeln(logb(1.0)); // 0 writeln(logb(100.0)); // 6 writeln(logb(0.0)); // -real.infinity writeln(logb(real.infinity)); // real.infinity writeln(logb(-real.infinity)); // real.infinity ``` nothrow @nogc @trusted real **fmod**(real x, real y); Calculates the remainder from the calculation x/y. Returns: The value of x - i \* y, where i is the number of times that y can be completely subtracted from x. The result has the same sign as x. Special Values| x | y | fmod(x, y) | invalid? | | ±0.0 | not 0.0 | ±0.0 | no | | ±∞ | anything | NAN | yes | | anything | ±0.0 | NAN | yes | | !=±∞ | ±∞ | x | no | Examples: ``` assert(isIdentical(fmod(0.0, 1.0), 0.0)); assert(fmod(5.0, 3.0).feqrel(2.0) > 16); assert(isNaN(fmod(5.0, 0.0))); ``` nothrow @nogc @trusted real **modf**(real x, ref real i); Breaks x into an integral part and a fractional part, each of which has the same sign as x. The integral part is stored in i. Returns: The fractional part of x. Special Values| x | i (on input) | modf(x, i) | i (on return) | | ±∞ | anything | ±0.0 | ±∞ | Examples: ``` real frac; real intpart; frac = modf(3.14159, intpart); assert(intpart.feqrel(3.0) > 16); assert(frac.feqrel(0.14159) > 16); ``` pure nothrow @nogc @safe real **scalbn**(real x, int n); pure nothrow @nogc @safe double **scalbn**(double x, int n); pure nothrow @nogc @safe float **scalbn**(float x, int n); Efficiently calculates x \* 2n. scalbn handles underflow and overflow in the same fashion as the basic arithmetic operators. Special Values| x | scalb(x) | | ±∞ | ±∞ | | ±0.0 | ±0.0 | Examples: ``` writeln(scalbn(0x1.2345678abcdefp0L, 999)); // 0x1.2345678abcdefp999L writeln(scalbn(-real.infinity, 5)); // -real.infinity writeln(scalbn(2.0, 10)); // 2048.0 writeln(scalbn(2048.0f, -10)); // 2.0f ``` nothrow @nogc @trusted real **cbrt**(real x); Calculates the cube root of x. Special Values| *x* | cbrt(x) | invalid? | | ±0.0 | ±0.0 | no | | NAN | NAN | yes | | ±∞ | ±∞ | no | Examples: ``` assert(cbrt(1.0).feqrel(1.0) > 16); assert(cbrt(27.0).feqrel(3.0) > 16); assert(cbrt(15.625).feqrel(2.5) > 16); ``` pure nothrow @nogc @safe real **fabs**(real x); pure nothrow @nogc @trusted double **fabs**(double d); pure nothrow @nogc @trusted float **fabs**(float f); Returns |x| Special Values| x | fabs(x) | | ±0.0 | +0.0 | | ±∞ | +∞ | Examples: ``` assert(isIdentical(fabs(0.0f), 0.0f)); assert(isIdentical(fabs(-0.0f), 0.0f)); writeln(fabs(-10.0f)); // 10.0f assert(isIdentical(fabs(0.0), 0.0)); assert(isIdentical(fabs(-0.0), 0.0)); writeln(fabs(-10.0)); // 10.0 assert(isIdentical(fabs(0.0L), 0.0L)); assert(isIdentical(fabs(-0.0L), 0.0L)); writeln(fabs(-10.0L)); // 10.0L ``` pure nothrow @nogc @safe real **hypot**(real x, real y); Calculates the length of the hypotenuse of a right-angled triangle with sides of length x and y. The hypotenuse is the value of the square root of the sums of the squares of x and y: sqrt(x2 + y2) Note that hypot(x, y), hypot(y, x) and hypot(x, -y) are equivalent. Special Values| x | y | hypot(x, y) | invalid? | | x | ±0.0 | |x| | no | | ±∞ | y | +∞ | no | | ±∞ | NAN | +∞ | no | Examples: ``` assert(hypot(1.0, 1.0).feqrel(1.4142) > 16); assert(hypot(3.0, 4.0).feqrel(5.0) > 16); writeln(hypot(real.infinity, 1.0)); // real.infinity writeln(hypot(real.infinity, real.nan)); // real.infinity ``` pure nothrow @nogc @trusted real **ceil**(real x); pure nothrow @nogc @trusted double **ceil**(double x); pure nothrow @nogc @trusted float **ceil**(float x); Returns the value of x rounded upward to the next integer (toward positive infinity). Examples: ``` writeln(ceil(+123.456L)); // +124 writeln(ceil(-123.456L)); // -123 writeln(ceil(-1.234L)); // -1 writeln(ceil(-0.123L)); // 0 writeln(ceil(0.0L)); // 0 writeln(ceil(+0.123L)); // 1 writeln(ceil(+1.234L)); // 2 writeln(ceil(real.infinity)); // real.infinity assert(isNaN(ceil(real.nan))); assert(isNaN(ceil(real.init))); ``` pure nothrow @nogc @trusted real **floor**(real x); pure nothrow @nogc @trusted double **floor**(double x); pure nothrow @nogc @trusted float **floor**(float x); Returns the value of x rounded downward to the next integer (toward negative infinity). Examples: ``` writeln(floor(+123.456L)); // +123 writeln(floor(-123.456L)); // -124 writeln(floor(+123.0L)); // +123 writeln(floor(-124.0L)); // -124 writeln(floor(-1.234L)); // -2 writeln(floor(-0.123L)); // -1 writeln(floor(0.0L)); // 0 writeln(floor(+0.123L)); // 0 writeln(floor(+1.234L)); // 1 writeln(floor(real.infinity)); // real.infinity assert(isNaN(floor(real.nan))); assert(isNaN(floor(real.init))); ``` Unqual!F **quantize**(alias rfunc = rint, F)(const F val, const F unit) Constraints: if (is(typeof(rfunc(F.init)) : F) && isFloatingPoint!F); Round `val` to a multiple of `unit`. `rfunc` specifies the rounding function to use; by default this is `rint`, which uses the current rounding mode. Examples: ``` writeln(12345.6789L.quantize(0.01L)); // 12345.68L writeln(12345.6789L.quantize!floor(0.01L)); // 12345.67L writeln(12345.6789L.quantize(22.0L)); // 12342.0L ``` Examples: ``` writeln(12345.6789L.quantize(0)); // 12345.6789L assert(12345.6789L.quantize(real.infinity).isNaN); assert(12345.6789L.quantize(real.nan).isNaN); writeln(real.infinity.quantize(0.01L)); // real.infinity assert(real.infinity.quantize(real.nan).isNaN); assert(real.nan.quantize(0.01L).isNaN); assert(real.nan.quantize(real.infinity).isNaN); assert(real.nan.quantize(real.nan).isNaN); ``` Unqual!F **quantize**(real base, alias rfunc = rint, F, E)(const F val, const E exp) Constraints: if (is(typeof(rfunc(F.init)) : F) && isFloatingPoint!F && isIntegral!E); Unqual!F **quantize**(real base, long exp = 1, alias rfunc = rint, F)(const F val) Constraints: if (is(typeof(rfunc(F.init)) : F) && isFloatingPoint!F); Round `val` to a multiple of `pow(base, exp)`. `rfunc` specifies the rounding function to use; by default this is `rint`, which uses the current rounding mode. Examples: ``` writeln(12345.6789L.quantize!10(-2)); // 12345.68L writeln(12345.6789L.quantize!(10, -2)); // 12345.68L writeln(12345.6789L.quantize!(10, floor)(-2)); // 12345.67L writeln(12345.6789L.quantize!(10, -2, floor)); // 12345.67L writeln(12345.6789L.quantize!22(1)); // 12342.0L writeln(12345.6789L.quantize!22); // 12342.0L ``` pure nothrow @nogc @safe real **nearbyint**(real x); Rounds x to the nearest integer value, using the current rounding mode. Unlike the rint functions, nearbyint does not raise the FE\_INEXACT exception. Examples: ``` writeln(nearbyint(0.4)); // 0 writeln(nearbyint(0.5)); // 0 writeln(nearbyint(0.6)); // 1 writeln(nearbyint(100.0)); // 100 assert(isNaN(nearbyint(real.nan))); writeln(nearbyint(real.infinity)); // real.infinity writeln(nearbyint(-real.infinity)); // -real.infinity ``` pure nothrow @nogc @safe real **rint**(real x); pure nothrow @nogc @safe double **rint**(double x); pure nothrow @nogc @safe float **rint**(float x); Rounds x to the nearest integer value, using the current rounding mode. If the return value is not equal to x, the FE\_INEXACT exception is raised. [`nearbyint`](#nearbyint) performs the same operation, but does not set the FE\_INEXACT exception. Examples: ``` version (IeeeFlagsSupport) resetIeeeFlags(); writeln(rint(0.4)); // 0 version (IeeeFlagsSupport) assert(ieeeFlags.inexact); writeln(rint(0.5)); // 0 writeln(rint(0.6)); // 1 writeln(rint(100.0)); // 100 assert(isNaN(rint(real.nan))); writeln(rint(real.infinity)); // real.infinity writeln(rint(-real.infinity)); // -real.infinity ``` pure nothrow @nogc @trusted long **lrint**(real x); Rounds x to the nearest integer value, using the current rounding mode. This is generally the fastest method to convert a floating-point number to an integer. Note that the results from this function depend on the rounding mode, if the fractional part of x is exactly 0.5. If using the default rounding mode (ties round to even integers) lrint(4.5) == 4, lrint(5.5)==6. Examples: ``` writeln(lrint(4.5)); // 4 writeln(lrint(5.5)); // 6 writeln(lrint(-4.5)); // -4 writeln(lrint(-5.5)); // -6 writeln(lrint(int.max - 0.5)); // 2147483646L writeln(lrint(int.max + 0.5)); // 2147483648L writeln(lrint(int.min - 0.5)); // -2147483648L writeln(lrint(int.min + 0.5)); // -2147483648L ``` nothrow @nogc @trusted auto **round**(real x); Return the value of x rounded to the nearest integer. If the fractional part of x is exactly 0.5, the return value is rounded away from zero. Returns: A `real`. Examples: ``` writeln(round(4.5)); // 5 writeln(round(5.4)); // 5 writeln(round(-4.5)); // -5 writeln(round(-5.1)); // -5 ``` nothrow @nogc @trusted long **lround**(real x); Return the value of x rounded to the nearest integer. If the fractional part of x is exactly 0.5, the return value is rounded away from zero. This function is not implemented for Digital Mars C runtime. Examples: ``` version (CRuntime_DigitalMars) {} else { writeln(lround(0.49)); // 0 writeln(lround(0.5)); // 1 writeln(lround(1.5)); // 2 } ``` pure nothrow @nogc @trusted real **trunc**(real x); Returns the integer portion of x, dropping the fractional portion. This is also known as "chop" rounding. `pure` on all platforms. Examples: ``` writeln(trunc(0.01)); // 0 writeln(trunc(0.49)); // 0 writeln(trunc(0.5)); // 0 writeln(trunc(1.5)); // 1 ``` nothrow @nogc @trusted real **remainder**(real x, real y); nothrow @nogc @trusted real **remquo**(real x, real y, out int n); Calculate the remainder x REM y, following IEC 60559. REM is the value of x - y \* n, where n is the integer nearest the exact value of x / y. If |n - x / y| == 0.5, n is even. If the result is zero, it has the same sign as x. Otherwise, the sign of the result is the sign of x / y. Precision mode has no effect on the remainder functions. remquo returns `n` in the parameter `n`. Special Values| x | y | remainder(x, y) | n | invalid? | | ±0.0 | not 0.0 | ±0.0 | 0.0 | no | | ±∞ | anything | -NAN | ? | yes | | anything | ±0.0 | ±NAN | ? | yes | | != ±∞ | ±∞ | x | ? | no | Examples: ``` assert(remainder(5.1, 3.0).feqrel(-0.9) > 16); assert(remainder(-5.1, 3.0).feqrel(0.9) > 16); writeln(remainder(0.0, 3.0)); // 0.0 assert(isNaN(remainder(1.0, 0.0))); assert(isNaN(remainder(-1.0, 0.0))); ``` Examples: ``` int n; assert(remquo(5.1, 3.0, n).feqrel(-0.9) > 16 && n == 2); assert(remquo(-5.1, 3.0, n).feqrel(0.9) > 16 && n == -2); assert(remquo(0.0, 3.0, n) == 0.0 && n == 0); ``` struct **IeeeFlags**; IEEE exception status flags ('sticky bits') These flags indicate that an exceptional floating-point condition has occurred. They indicate that a NaN or an infinity has been generated, that a result is inexact, or that a signalling NaN has been encountered. If floating-point exceptions are enabled (unmasked), a hardware exception will be generated instead of setting these flags. Examples: ``` static void func() { int a = 10 * 10; } pragma(inline, false) static void blockopt(ref real x) {} real a = 3.5; // Set all the flags to zero resetIeeeFlags(); assert(!ieeeFlags.divByZero); blockopt(a); // avoid constant propagation by the optimizer // Perform a division by zero. a /= 0.0L; writeln(a); // real.infinity assert(ieeeFlags.divByZero); blockopt(a); // avoid constant propagation by the optimizer // Create a NaN a *= 0.0L; assert(ieeeFlags.invalid); assert(isNaN(a)); // Check that calling func() has no effect on the // status flags. IeeeFlags f = ieeeFlags; func(); writeln(ieeeFlags); // f ``` const nothrow @nogc @property @safe bool **inexact**(); The result cannot be represented exactly, so rounding occurred. Example `x = sin(0.1);` const nothrow @nogc @property @safe bool **underflow**(); A zero was generated by underflow Example `x = real.min*real.epsilon/2;` const nothrow @nogc @property @safe bool **overflow**(); An infinity was generated by overflow Example `x = real.max*2;` const nothrow @nogc @property @safe bool **divByZero**(); An infinity was generated by division by zero Example `x = 3/0.0;` const nothrow @nogc @property @safe bool **invalid**(); A machine NaN was generated. Example `x = real.infinity * 0.0;` nothrow @nogc @trusted void **resetIeeeFlags**(); Set all of the floating-point status flags to false. Examples: ``` pragma(inline, false) static void blockopt(ref real x) {} resetIeeeFlags(); real a = 3.5; blockopt(a); // avoid constant propagation by the optimizer a /= 0.0L; blockopt(a); // avoid constant propagation by the optimizer writeln(a); // real.infinity assert(ieeeFlags.divByZero); resetIeeeFlags(); assert(!ieeeFlags.divByZero); ``` pure nothrow @nogc @property @trusted IeeeFlags **ieeeFlags**(); Returns: snapshot of the current state of the floating-point status flags Examples: ``` pragma(inline, false) static void blockopt(ref real x) {} resetIeeeFlags(); real a = 3.5; blockopt(a); // avoid constant propagation by the optimizer a /= 0.0L; writeln(a); // real.infinity assert(ieeeFlags.divByZero); blockopt(a); // avoid constant propagation by the optimizer a *= 0.0L; assert(isNaN(a)); assert(ieeeFlags.invalid); ``` struct **FloatingPointControl**; Control the Floating point hardware Change the IEEE754 floating-point rounding mode and the floating-point hardware exceptions. By default, the rounding mode is roundToNearest and all hardware exceptions are disabled. For most applications, debugging is easier if the *division by zero*, *overflow*, and *invalid operation* exceptions are enabled. These three are combined into a *severeExceptions* value for convenience. Note in particular that if *invalidException* is enabled, a hardware trap will be generated whenever an uninitialized floating-point variable is used. All changes are temporary. The previous state is restored at the end of the scope. Example ``` { FloatingPointControl fpctrl; // Enable hardware exceptions for division by zero, overflow to infinity, // invalid operations, and uninitialized floating-point variables. fpctrl.enableExceptions(FloatingPointControl.severeExceptions); // This will generate a hardware exception, if x is a // default-initialized floating point variable: real x; // Add `= 0` or even `= real.nan` to not throw the exception. real y = x * 3.0; // The exception is only thrown for default-uninitialized NaN-s. // NaN-s with other payload are valid: real z = y * real.nan; // ok // The set hardware exceptions and rounding modes will be disabled when // leaving this scope. } ``` Examples: ``` FloatingPointControl fpctrl; fpctrl.rounding = FloatingPointControl.roundDown; writeln(lrint(1.5)); // 1.0 fpctrl.rounding = FloatingPointControl.roundUp; writeln(lrint(1.4)); // 2.0 fpctrl.rounding = FloatingPointControl.roundToNearest; writeln(lrint(1.5)); // 2.0 ``` alias **RoundingMode** = uint; **roundToNearest** **roundDown** **roundUp** **roundToZero** **roundingMask** IEEE rounding modes. The default mode is roundToNearest. roundingMask = A mask of all rounding modes. nothrow @nogc @property @trusted void **rounding**(RoundingMode newMode); Change the floating-point hardware rounding mode Changing the rounding mode in the middle of a function can interfere with optimizations of floating point expressions, as the optimizer assumes that the rounding mode does not change. It is best to change the rounding mode only at the beginning of the function, and keep it until the function returns. It is also best to add the line: ``` pragma(inline, false); ``` as the first line of the function so it will not get inlined. Parameters: | | | | --- | --- | | RoundingMode `newMode` | the new rounding mode | static pure nothrow @nogc @property @trusted RoundingMode **rounding**(); Returns: the currently active rounding mode alias **ExceptionMask** = uint; **subnormalException** **inexactException** **underflowException** **overflowException** **divByZeroException** **invalidException** **severeExceptions** **allExceptions** IEEE hardware exceptions. By default, all exceptions are masked (disabled). severeExceptions = The overflow, division by zero, and invalid exceptions. static pure nothrow @nogc @property @safe bool **hasExceptionTraps**(); Returns: true if the current FPU supports exception trapping nothrow @nogc @trusted void **enableExceptions**(ExceptionMask exceptions); Enable (unmask) specific hardware exceptions. Multiple exceptions may be ORed together. nothrow @nogc @trusted void **disableExceptions**(ExceptionMask exceptions); Disable (mask) specific hardware exceptions. Multiple exceptions may be ORed together. static pure nothrow @nogc @property @trusted ExceptionMask **enabledExceptions**(); Returns: the exceptions which are currently enabled (unmasked) pure nothrow @nogc @trusted bool **isNaN**(X)(X x) Constraints: if (isFloatingPoint!X); Determines if x is NaN. Parameters: | | | | --- | --- | | X `x` | a floating point number. | Returns: `true` if x is Nan. Examples: ``` assert( isNaN(float.init)); assert( isNaN(-double.init)); assert( isNaN(real.nan)); assert( isNaN(-real.nan)); assert(!isNaN(cast(float) 53.6)); assert(!isNaN(cast(real)-53.6)); ``` pure nothrow @nogc @trusted bool **isFinite**(X)(X x); Determines if x is finite. Parameters: | | | | --- | --- | | X `x` | a floating point number. | Returns: `true` if x is finite. Examples: ``` assert( isFinite(1.23f)); assert( isFinite(float.max)); assert( isFinite(float.min_normal)); assert(!isFinite(float.nan)); assert(!isFinite(float.infinity)); ``` pure nothrow @nogc @trusted bool **isNormal**(X)(X x); Determines if x is normalized. A normalized number must not be zero, subnormal, infinite nor NAN. Parameters: | | | | --- | --- | | X `x` | a floating point number. | Returns: `true` if x is normalized. Examples: ``` float f = 3; double d = 500; real e = 10e+48; assert(isNormal(f)); assert(isNormal(d)); assert(isNormal(e)); f = d = e = 0; assert(!isNormal(f)); assert(!isNormal(d)); assert(!isNormal(e)); assert(!isNormal(real.infinity)); assert(isNormal(-real.max)); assert(!isNormal(real.min_normal/4)); ``` pure nothrow @nogc @trusted bool **isSubnormal**(X)(X x); Determines if x is subnormal. Subnormals (also known as "denormal number"), have a 0 exponent and a 0 most significant mantissa bit. Parameters: | | | | --- | --- | | X `x` | a floating point number. | Returns: `true` if x is a denormal number. Examples: ``` import std.meta : AliasSeq; static foreach (T; AliasSeq!(float, double, real)) {{ T f; for (f = 1.0; !isSubnormal(f); f /= 2) assert(f != 0); }} ``` pure nothrow @nogc @trusted bool **isInfinity**(X)(X x) Constraints: if (isFloatingPoint!X); Determines if x is ±∞. Parameters: | | | | --- | --- | | X `x` | a floating point number. | Returns: `true` if x is ±∞. Examples: ``` assert(!isInfinity(float.init)); assert(!isInfinity(-float.init)); assert(!isInfinity(float.nan)); assert(!isInfinity(-float.nan)); assert(isInfinity(float.infinity)); assert(isInfinity(-float.infinity)); assert(isInfinity(-1.0f / 0.0f)); ``` pure nothrow @nogc @trusted bool **isIdentical**(real x, real y); Is the binary representation of x identical to y? Examples: ``` assert( isIdentical(0.0, 0.0)); assert( isIdentical(1.0, 1.0)); assert( isIdentical(real.infinity, real.infinity)); assert( isIdentical(-real.infinity, -real.infinity)); assert(!isIdentical(0.0, -0.0)); assert(!isIdentical(real.nan, -real.nan)); assert(!isIdentical(real.infinity, -real.infinity)); ``` pure nothrow @nogc @trusted int **signbit**(X)(X x); Return 1 if sign bit of e is set, 0 if not. Examples: ``` assert(!signbit(float.nan)); assert(signbit(-float.nan)); assert(!signbit(168.1234f)); assert(signbit(-168.1234f)); assert(!signbit(0.0f)); assert(signbit(-0.0f)); assert(signbit(-float.max)); assert(!signbit(float.max)); assert(!signbit(double.nan)); assert(signbit(-double.nan)); assert(!signbit(168.1234)); assert(signbit(-168.1234)); assert(!signbit(0.0)); assert(signbit(-0.0)); assert(signbit(-double.max)); assert(!signbit(double.max)); assert(!signbit(real.nan)); assert(signbit(-real.nan)); assert(!signbit(168.1234L)); assert(signbit(-168.1234L)); assert(!signbit(0.0L)); assert(signbit(-0.0L)); assert(signbit(-real.max)); assert(!signbit(real.max)); ``` pure nothrow @nogc @trusted R **copysign**(R, X)(R to, X from) Constraints: if (isFloatingPoint!R && isFloatingPoint!X); pure nothrow @nogc @trusted R **copysign**(R, X)(X to, R from) Constraints: if (isIntegral!X && isFloatingPoint!R); Parameters: | | | | --- | --- | | R `to` | the numeric value to use | | X `from` | the sign value to use | Returns: a value composed of to with from's sign bit. Examples: ``` writeln(copysign(1.0, 1.0)); // 1.0 writeln(copysign(1.0, -0.0)); // -1.0 writeln(copysign(1UL, -1.0)); // -1.0 writeln(copysign(-1.0, -1.0)); // -1.0 writeln(copysign(real.infinity, -1.0)); // -real.infinity assert(copysign(real.nan, 1.0) is real.nan); assert(copysign(-real.nan, 1.0) is real.nan); assert(copysign(real.nan, -1.0) is -real.nan); ``` pure nothrow @nogc @safe F **sgn**(F)(F x) Constraints: if (isFloatingPoint!F || isIntegral!F); Returns `-1` if `x < 0`, `x` if `x == 0`, `1` if `x > 0`, and NAN if x==NAN. Examples: ``` writeln(sgn(168.1234)); // 1 writeln(sgn(-168.1234)); // -1 writeln(sgn(0.0)); // 0 writeln(sgn(-0.0)); // 0 ``` pure nothrow @nogc @trusted real **NaN**(ulong payload); Create a quiet NAN, storing an integer inside the payload. For floats, the largest possible payload is 0x3F\_FFFF. For doubles, it is 0x3\_FFFF\_FFFF\_FFFF. For 80-bit or 128-bit reals, it is 0x3FFF\_FFFF\_FFFF\_FFFF. Examples: ``` real a = NaN(1_000_000); assert(isNaN(a)); writeln(getNaNPayload(a)); // 1_000_000 ``` pure nothrow @nogc @trusted ulong **getNaNPayload**(real x); Extract an integral payload from a NAN. Returns: the integer payload as a ulong. For floats, the largest possible payload is 0x3F\_FFFF. For doubles, it is 0x3\_FFFF\_FFFF\_FFFF. For 80-bit or 128-bit reals, it is 0x3FFF\_FFFF\_FFFF\_FFFF. Examples: ``` real a = NaN(1_000_000); assert(isNaN(a)); writeln(getNaNPayload(a)); // 1_000_000 ``` pure nothrow @nogc @trusted real **nextUp**(real x); pure nothrow @nogc @trusted double **nextUp**(double x); pure nothrow @nogc @trusted float **nextUp**(float x); Calculate the next largest floating point value after x. Return the least number greater than x that is representable as a real; thus, it gives the next point on the IEEE number line. Special Values| x | nextUp(x) | | -∞ | -real.max | | ±0.0 | real.min\_normal\*real.epsilon | | real.max | ∞ | | ∞ | ∞ | | NAN | NAN | Examples: ``` assert(nextUp(1.0 - 1.0e-6).feqrel(0.999999) > 16); assert(nextUp(1.0 - real.epsilon).feqrel(1.0) > 16); ``` pure nothrow @nogc @safe real **nextDown**(real x); pure nothrow @nogc @safe double **nextDown**(double x); pure nothrow @nogc @safe float **nextDown**(float x); Calculate the next smallest floating point value before x. Return the greatest number less than x that is representable as a real; thus, it gives the previous point on the IEEE number line. Special Values| x | nextDown(x) | | ∞ | real.max | | ±0.0 | -real.min\_normal\*real.epsilon | | -real.max | -∞ | | -∞ | -∞ | | NAN | NAN | Examples: ``` writeln(nextDown(1.0 + real.epsilon)); // 1.0 ``` pure nothrow @nogc @safe T **nextafter**(T)(const T x, const T y); Calculates the next representable value after x in the direction of y. If y > x, the result will be the next largest floating-point value; if y < x, the result will be the next smallest value. If x == y, the result is y. If x or y is a NaN, the result is a NaN. Remarks This function is not generally very useful; it's almost always better to use the faster functions nextUp() or nextDown() instead. The FE\_INEXACT and FE\_OVERFLOW exceptions will be raised if x is finite and the function result is infinite. The FE\_INEXACT and FE\_UNDERFLOW exceptions will be raised if the function value is subnormal, and x is not equal to y. Examples: ``` float a = 1; assert(is(typeof(nextafter(a, a)) == float)); assert(nextafter(a, a.infinity) > a); assert(isNaN(nextafter(a, a.nan))); assert(isNaN(nextafter(a.nan, a))); double b = 2; assert(is(typeof(nextafter(b, b)) == double)); assert(nextafter(b, b.infinity) > b); assert(isNaN(nextafter(b, b.nan))); assert(isNaN(nextafter(b.nan, b))); real c = 3; assert(is(typeof(nextafter(c, c)) == real)); assert(nextafter(c, c.infinity) > c); assert(isNaN(nextafter(c, c.nan))); assert(isNaN(nextafter(c.nan, c))); ``` pure nothrow @nogc @safe real **fdim**(real x, real y); Returns the positive difference between x and y. Equivalent to `fmax(x-y, 0)`. Returns: Special Values| x, y | fdim(x, y) | | x > y | x - y | | x <= y | +0.0 | Examples: ``` writeln(fdim(2.0, 0.0)); // 2.0 writeln(fdim(-2.0, 0.0)); // 0.0 writeln(fdim(real.infinity, 2.0)); // real.infinity assert(isNaN(fdim(real.nan, 2.0))); assert(isNaN(fdim(2.0, real.nan))); assert(isNaN(fdim(real.nan, real.nan))); ``` pure nothrow @nogc @safe F **fmax**(F)(const F x, const F y) Constraints: if (\_\_traits(isFloating, F)); Returns the larger of `x` and `y`. If one of the arguments is a `NaN`, the other is returned. See Also: [`std.algorithm.comparison.max`](std_algorithm_comparison#max) is faster because it does not perform the `isNaN` test. Examples: ``` import std.meta : AliasSeq; static foreach (F; AliasSeq!(float, double, real)) { writeln(fmax(F(0.0), F(2.0))); // 2.0 writeln(fmax(F(-2.0), 0.0)); // F(0.0) writeln(fmax(F.infinity, F(2.0))); // F.infinity writeln(fmax(F.nan, F(2.0))); // F(2.0) writeln(fmax(F(2.0), F.nan)); // F(2.0) } ``` pure nothrow @nogc @safe F **fmin**(F)(const F x, const F y) Constraints: if (\_\_traits(isFloating, F)); Returns the smaller of `x` and `y`. If one of the arguments is a `NaN`, the other is returned. See Also: [`std.algorithm.comparison.min`](std_algorithm_comparison#min) is faster because it does not perform the `isNaN` test. Examples: ``` import std.meta : AliasSeq; static foreach (F; AliasSeq!(float, double, real)) { writeln(fmin(F(0.0), F(2.0))); // 0.0 writeln(fmin(F(-2.0), F(0.0))); // -2.0 writeln(fmin(F.infinity, F(2.0))); // 2.0 writeln(fmin(F.nan, F(2.0))); // 2.0 writeln(fmin(F(2.0), F.nan)); // 2.0 } ``` pure nothrow @nogc @safe real **fma**(real x, real y, real z); Returns (x \* y) + z, rounding only once according to the current rounding mode. Bugs: Not currently implemented - rounds twice. Examples: ``` writeln(fma(0.0, 2.0, 2.0)); // 2.0 writeln(fma(2.0, 2.0, 2.0)); // 6.0 writeln(fma(real.infinity, 2.0, 2.0)); // real.infinity assert(fma(real.nan, 2.0, 2.0) is real.nan); assert(fma(2.0, 2.0, real.nan) is real.nan); ``` pure nothrow @nogc @trusted Unqual!F **pow**(F, G)(F x, G n) Constraints: if (isFloatingPoint!F && isIntegral!G); Compute the value of x n, where n is an integer Examples: ``` writeln(pow(2.0, 5)); // 32.0 assert(pow(1.5, 9).feqrel(38.4433) > 16); assert(pow(real.nan, 2) is real.nan); writeln(pow(real.infinity, 2)); // real.infinity ``` pure nothrow @nogc @trusted typeof(Unqual!F.init \* Unqual!G.init) **pow**(F, G)(F x, G n) Constraints: if (isIntegral!F && isIntegral!G); Compute the power of two integral numbers. Parameters: | | | | --- | --- | | F `x` | base | | G `n` | exponent | Returns: x raised to the power of n. If n is negative the result is 1 / pow(x, -n), which is calculated as integer division with remainder. This may result in a division by zero error. If both x and n are 0, the result is 1. Throws: If x is 0 and n is negative, the result is the same as the result of a division by zero. Examples: ``` writeln(pow(2, 3)); // 8 writeln(pow(3, 2)); // 9 writeln(pow(2, 10)); // 1_024 writeln(pow(2, 20)); // 1_048_576 writeln(pow(2, 30)); // 1_073_741_824 writeln(pow(0, 0)); // 1 writeln(pow(1, -5)); // 1 writeln(pow(1, -6)); // 1 writeln(pow(-1, -5)); // -1 writeln(pow(-1, -6)); // 1 writeln(pow(-2, 5)); // -32 writeln(pow(-2, -5)); // 0 writeln(pow(cast(double)-2, -5)); // -0.03125 ``` pure nothrow @nogc @trusted real **pow**(I, F)(I x, F y) Constraints: if (isIntegral!I && isFloatingPoint!F); Computes integer to floating point powers. Examples: ``` writeln(pow(2, 5.0)); // 32.0 writeln(pow(7, 3.0)); // 343.0 assert(pow(2, real.nan) is real.nan); writeln(pow(2, real.infinity)); // real.infinity ``` pure nothrow @nogc @trusted Unqual!(Largest!(F, G)) **pow**(F, G)(F x, G y) Constraints: if (isFloatingPoint!F && isFloatingPoint!G); Calculates xy. Special Values| x | y | pow(x, y) | div 0 | invalid? | | anything | ±0.0 | 1.0 | no | no | | |x| > 1 | +∞ | +∞ | no | no | | |x| < 1 | +∞ | +0.0 | no | no | | |x| > 1 | -∞ | +0.0 | no | no | | |x| < 1 | -∞ | +∞ | no | no | | +∞ | > 0.0 | +∞ | no | no | | +∞ | < 0.0 | +0.0 | no | no | | -∞ | odd integer > 0.0 | -∞ | no | no | | -∞ | > 0.0, not odd integer | +∞ | no | no | | -∞ | odd integer < 0.0 | -0.0 | no | no | | -∞ | < 0.0, not odd integer | +0.0 | no | no | | ±1.0 | ±∞ | -NAN | no | yes | | < 0.0 | finite, nonintegral | NAN | no | yes | | ±0.0 | odd integer < 0.0 | ±∞ | yes | no | | ±0.0 | < 0.0, not odd integer | +∞ | yes | no | | ±0.0 | odd integer > 0.0 | ±0.0 | no | no | | ±0.0 | > 0.0, not odd integer | +0.0 | no | no | Examples: ``` writeln(pow(1.0, 2.0)); // 1.0 writeln(pow(0.0, 0.0)); // 1.0 assert(pow(1.5, 10.0).feqrel(57.665) > 16); // special values writeln(pow(1.5, real.infinity)); // real.infinity writeln(pow(0.5, real.infinity)); // 0.0 writeln(pow(1.5, -real.infinity)); // 0.0 writeln(pow(0.5, -real.infinity)); // real.infinity writeln(pow(real.infinity, 1.0)); // real.infinity writeln(pow(real.infinity, -1.0)); // 0.0 writeln(pow(-real.infinity, 1.0)); // -real.infinity writeln(pow(-real.infinity, 2.0)); // real.infinity writeln(pow(-real.infinity, -1.0)); // -0.0 writeln(pow(-real.infinity, -2.0)); // 0.0 assert(pow(1.0, real.infinity) is -real.nan); writeln(pow(0.0, -1.0)); // real.infinity writeln(pow(real.nan, 0.0)); // 1.0 ``` Unqual!(Largest!(F, H)) **powmod**(F, G, H)(F x, G n, H m) Constraints: if (isUnsigned!F && isUnsigned!G && isUnsigned!H); Computes the value of a positive integer `x`, raised to the power `n`, modulo `m`. Parameters: | | | | --- | --- | | F `x` | base | | G `n` | exponent | | H `m` | modulus | Returns: `x` to the power `n`, modulo `m`. The return type is the largest of `x`'s and `m`'s type. The function requires that all values have unsigned types. Examples: ``` writeln(powmod(1U, 10U, 3U)); // 1 writeln(powmod(3U, 2U, 6U)); // 3 writeln(powmod(5U, 5U, 15U)); // 5 writeln(powmod(2U, 3U, 5U)); // 3 writeln(powmod(2U, 4U, 5U)); // 1 writeln(powmod(2U, 5U, 5U)); // 2 ``` pure nothrow @nogc @trusted int **feqrel**(X)(const X x, const X y) Constraints: if (isFloatingPoint!X); To what precision is x equal to y? Returns: the number of mantissa bits which are equal in x and y. eg, 0x1.F8p+60 and 0x1.F1p+60 are equal to 5 bits of precision. Special Values| x | y | feqrel(x, y) | | x | x | real.mant\_dig | | x | >= 2\*x | 0 | | x | <= x/2 | 0 | | NAN | any | 0 | | any | NAN | 0 | Examples: ``` writeln(feqrel(2.0, 2.0)); // 53 writeln(feqrel(2.0f, 2.0f)); // 24 writeln(feqrel(2.0, double.nan)); // 0 // Test that numbers are within n digits of each // other by testing if feqrel > n * log2(10) // five digits assert(feqrel(2.0, 2.00001) > 16); // ten digits assert(feqrel(2.0, 2.00000000001) > 33); ``` pure nothrow @nogc @trusted Unqual!(CommonType!(T1, T2)) **poly**(T1, T2)(T1 x, in T2[] A) Constraints: if (isFloatingPoint!T1 && isFloatingPoint!T2); pure nothrow @nogc @safe Unqual!(CommonType!(T1, T2)) **poly**(T1, T2, int N)(T1 x, ref const T2[N] A) Constraints: if (isFloatingPoint!T1 && isFloatingPoint!T2 && (N > 0) && (N <= 10)); Evaluate polynomial A(x) = a0 + a1x + a2x2 + a3x3; ... Uses Horner's rule A(x) = a0 + x(a1 + x(a2 + x(a3 + ...))) Parameters: | | | | --- | --- | | T1 `x` | the value to evaluate. | | T2[] `A` | array of coefficients a0, a1, etc. | Examples: ``` real x = 3.1L; static real[] pp = [56.1L, 32.7L, 6]; writeln(poly(x, pp)); // (56.1L + (32.7L + 6.0L * x) * x) ``` bool **approxEqual**(T, U, V)(T value, U reference, V maxRelDiff = 0.01, V maxAbsDiff = 1e-05); Computes whether a values is approximately equal to a reference value, admitting a maximum relative difference, and a maximum absolute difference. Parameters: | | | | --- | --- | | T `value` | Value to compare. | | U `reference` | Reference value. | | V `maxRelDiff` | Maximum allowable difference relative to `reference`. Setting to 0.0 disables this check. Defaults to `1e-2`. | | V `maxAbsDiff` | Maximum absolute difference. This is mainly usefull for comparing values to zero. Setting to 0.0 disables this check. Defaults to `1e-5`. | Returns: `true` if `value` is approximately equal to `reference` under either criterium. It is sufficient, when `value` satisfies one of the two criteria. If one item is a range, and the other is a single value, then the result is the logical and-ing of calling `approxEqual` on each element of the ranged item against the single item. If both items are ranges, then `approxEqual` returns `true` if and only if the ranges have the same number of elements and if `approxEqual` evaluates to `true` for each pair of elements. See Also: Use [`feqrel`](#feqrel) to get the number of equal bits in the mantissa. Examples: ``` assert(approxEqual(1.0, 1.0099)); assert(!approxEqual(1.0, 1.011)); assert(approxEqual(0.00001, 0.0)); assert(!approxEqual(0.00002, 0.0)); assert(approxEqual(3.0, [3, 3.01, 2.99])); // several reference values is strange assert(approxEqual([3, 3.01, 2.99], 3.0)); // better float[] arr1 = [ 1.0, 2.0, 3.0 ]; double[] arr2 = [ 1.001, 1.999, 3 ]; assert(approxEqual(arr1, arr2)); ``` Examples: ``` // relative comparison depends on reference, make sure proper // side is used when comparing range to single value. Based on // https://issues.dlang.org/show_bug.cgi?id=15763 auto a = [2e-3 - 1e-5]; auto b = 2e-3 + 1e-5; assert(a[0].approxEqual(b)); assert(!b.approxEqual(a[0])); assert(a.approxEqual(b)); assert(!b.approxEqual(a)); ``` Examples: ``` assert(!approxEqual(0.0,1e-15,1e-9,0.0)); assert(approxEqual(0.0,1e-15,1e-9,1e-9)); assert(!approxEqual(1.0,3.0,0.0,1.0)); assert(approxEqual(1.00000000099,1.0,1e-9,0.0)); assert(!approxEqual(1.0000000011,1.0,1e-9,0.0)); ``` Examples: ``` // maybe unintuitive behavior assert(approxEqual(1000.0,1010.0)); assert(approxEqual(9_090_000_000.0,9_000_000_000.0)); assert(approxEqual(0.0,1e30,1.0)); assert(approxEqual(0.00001,1e-30)); assert(!approxEqual(-1e-30,1e-30,1e-2,0.0)); ``` bool **isClose**(T, U, V = CommonType!(FloatingPointBaseType!T, FloatingPointBaseType!U))(T lhs, U rhs, V maxRelDiff = CommonDefaultFor!(T, U), V maxAbsDiff = 0.0); Computes whether two values are approximately equal, admitting a maximum relative difference, and a maximum absolute difference. Parameters: | | | | --- | --- | | T `lhs` | First item to compare. | | U `rhs` | Second item to compare. | | V `maxRelDiff` | Maximum allowable relative difference. Setting to 0.0 disables this check. Default depends on the type of `lhs` and `rhs`: It is approximately half the number of decimal digits of precision of the smaller type. | | V `maxAbsDiff` | Maximum absolute difference. This is mainly usefull for comparing values to zero. Setting to 0.0 disables this check. Defaults to `0.0`. | Returns: `true` if the two items are approximately equal under either criterium. It is sufficient, when `value` satisfies one of the two criteria. If one item is a range, and the other is a single value, then the result is the logical and-ing of calling `isClose` on each element of the ranged item against the single item. If both items are ranges, then `isClose` returns `true` if and only if the ranges have the same number of elements and if `isClose` evaluates to `true` for each pair of elements. See Also: Use [`feqrel`](#feqrel) to get the number of equal bits in the mantissa. Examples: ``` assert(isClose(1.0,0.999_999_999)); assert(isClose(0.001, 0.000_999_999_999)); assert(isClose(1_000_000_000.0,999_999_999.0)); assert(isClose(17.123_456_789, 17.123_456_78)); assert(!isClose(17.123_456_789, 17.123_45)); // use explicit 3rd parameter for less (or more) accuracy assert(isClose(17.123_456_789, 17.123_45, 1e-6)); assert(!isClose(17.123_456_789, 17.123_45, 1e-7)); // use 4th parameter when comparing close to zero assert(!isClose(1e-100, 0.0)); assert(isClose(1e-100, 0.0, 0.0, 1e-90)); assert(!isClose(1e-10, -1e-10)); assert(isClose(1e-10, -1e-10, 0.0, 1e-9)); assert(!isClose(1e-300, 1e-298)); assert(isClose(1e-300, 1e-298, 0.0, 1e-200)); // different default limits for different floating point types assert(isClose(1.0f, 0.999_99f)); assert(!isClose(1.0, 0.999_99)); static if (real.sizeof > double.sizeof) assert(!isClose(1.0L, 0.999_999_999L)); ``` Examples: ``` assert(isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001, 3.0])); assert(!isClose([1.0, 2.0], [0.999_999_999, 2.000_000_001, 3.0])); assert(!isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001])); assert(isClose([2.0, 1.999_999_999, 2.000_000_001], 2.0)); assert(isClose(2.0, [2.0, 1.999_999_999, 2.000_000_001])); ``` pure nothrow @nogc @trusted int **cmp**(T)(const(T) x, const(T) y) Constraints: if (isFloatingPoint!T); Defines a total order on all floating-point numbers. The order is defined as follows: * All numbers in [-∞, +∞] are ordered the same way as by built-in comparison, with the exception of -0.0, which is less than +0.0; * If the sign bit is set (that is, it's 'negative'), NAN is less than any number; if the sign bit is not set (it is 'positive'), NAN is greater than any number; * NANs of the same sign are ordered by the payload ('negative' ones - in reverse order). Returns: negative value if `x` precedes `y` in the order specified above; 0 if `x` and `y` are identical, and positive value otherwise. See Also: [*isIdentical*](#isIdentical) Standards: Conforms to IEEE 754-2008 Examples: Most numbers are ordered naturally. ``` assert(cmp(-double.infinity, -double.max) < 0); assert(cmp(-double.max, -100.0) < 0); assert(cmp(-100.0, -0.5) < 0); assert(cmp(-0.5, 0.0) < 0); assert(cmp(0.0, 0.5) < 0); assert(cmp(0.5, 100.0) < 0); assert(cmp(100.0, double.max) < 0); assert(cmp(double.max, double.infinity) < 0); writeln(cmp(1.0, 1.0)); // 0 ``` Examples: Positive and negative zeroes are distinct. ``` assert(cmp(-0.0, +0.0) < 0); assert(cmp(+0.0, -0.0) > 0); ``` Examples: Depending on the sign, NANs go to either end of the spectrum. ``` assert(cmp(-double.nan, -double.infinity) < 0); assert(cmp(double.infinity, double.nan) < 0); assert(cmp(-double.nan, double.nan) < 0); ``` Examples: NANs of the same sign are ordered by the payload. ``` assert(cmp(NaN(10), NaN(20)) < 0); assert(cmp(-NaN(20), -NaN(10)) < 0); ``` T **nextPow2**(T)(const T val) Constraints: if (isIntegral!T); T **nextPow2**(T)(const T val) Constraints: if (isFloatingPoint!T); Gives the next power of two after `val`. `T` can be any built-in numerical type. If the operation would lead to an over/underflow, this function will return `0`. Parameters: | | | | --- | --- | | T `val` | any number | Returns: the next power of two after `val` Examples: ``` writeln(nextPow2(2)); // 4 writeln(nextPow2(10)); // 16 writeln(nextPow2(4000)); // 4096 writeln(nextPow2(-2)); // -4 writeln(nextPow2(-10)); // -16 writeln(nextPow2(uint.max)); // 0 writeln(nextPow2(uint.min)); // 0 writeln(nextPow2(size_t.max)); // 0 writeln(nextPow2(size_t.min)); // 0 writeln(nextPow2(int.max)); // 0 writeln(nextPow2(int.min)); // 0 writeln(nextPow2(long.max)); // 0 writeln(nextPow2(long.min)); // 0 ``` Examples: ``` writeln(nextPow2(2.1)); // 4.0 writeln(nextPow2(-2.0)); // -4.0 writeln(nextPow2(0.25)); // 0.5 writeln(nextPow2(-4.0)); // -8.0 writeln(nextPow2(double.max)); // 0.0 writeln(nextPow2(double.infinity)); // double.infinity ``` T **truncPow2**(T)(const T val) Constraints: if (isIntegral!T); T **truncPow2**(T)(const T val) Constraints: if (isFloatingPoint!T); Gives the last power of two before `val`. <>> can be any built-in numerical type. Parameters: | | | | --- | --- | | T `val` | any number | Returns: the last power of two before `val` Examples: ``` writeln(truncPow2(3)); // 2 writeln(truncPow2(4)); // 4 writeln(truncPow2(10)); // 8 writeln(truncPow2(4000)); // 2048 writeln(truncPow2(-5)); // -4 writeln(truncPow2(-20)); // -16 writeln(truncPow2(uint.max)); // int.max + 1 writeln(truncPow2(uint.min)); // 0 writeln(truncPow2(ulong.max)); // long.max + 1 writeln(truncPow2(ulong.min)); // 0 writeln(truncPow2(int.max)); // (int.max / 2) + 1 writeln(truncPow2(int.min)); // int.min writeln(truncPow2(long.max)); // (long.max / 2) + 1 writeln(truncPow2(long.min)); // long.min ``` Examples: ``` writeln(truncPow2(2.1)); // 2.0 writeln(truncPow2(7.0)); // 4.0 writeln(truncPow2(-1.9)); // -1.0 writeln(truncPow2(0.24)); // 0.125 writeln(truncPow2(-7.0)); // -4.0 writeln(truncPow2(double.infinity)); // double.infinity ``` pure nothrow @nogc @safe bool **isPowerOf2**(X)(const X x) Constraints: if (isNumeric!X); Check whether a number is an integer power of two. Note that only positive numbers can be integer powers of two. This function always return `false` if `x` is negative or zero. Parameters: | | | | --- | --- | | X `x` | the number to test | Returns: `true` if `x` is an integer power of two. Examples: ``` assert( isPowerOf2(1.0L)); assert( isPowerOf2(2.0L)); assert( isPowerOf2(0.5L)); assert( isPowerOf2(pow(2.0L, 96))); assert( isPowerOf2(pow(2.0L, -77))); assert(!isPowerOf2(-2.0L)); assert(!isPowerOf2(-0.5L)); assert(!isPowerOf2(0.0L)); assert(!isPowerOf2(4.315)); assert(!isPowerOf2(1.0L / 3.0L)); assert(!isPowerOf2(real.nan)); assert(!isPowerOf2(real.infinity)); ``` Examples: ``` assert( isPowerOf2(1)); assert( isPowerOf2(2)); assert( isPowerOf2(1uL << 63)); assert(!isPowerOf2(-4)); assert(!isPowerOf2(0)); assert(!isPowerOf2(1337u)); ```
programming_docs
d Application Binary Interface Application Binary Interface ============================ **Contents** 1. [C ABI](#c_abi) 2. [Endianness](#endianness) 3. [Basic Types](#basic_types) 4. [Delegates](#delegates) 5. [Structs](#structs) 6. [Classes](#classes) 7. [Interfaces](#interfaces) 8. [Arrays](#arrays) 9. [Associative Arrays](#associative_arrays) 10. [Reference Types](#references_types) 11. [Name Mangling](#name_mangling) 1. [Back references](#back_ref) 2. [Type Mangling](#type_mangling) 12. [Function Calling Conventions](#function_calling_conventions) 1. [Register Conventions](#register_conventions) 2. [Return Value](#return_value) 3. [Parameters](#parameters) 13. [Exception Handling](#exception_handling) 1. [Windows](#windows_eh) 2. [Linux, FreeBSD and OS X](#ninux_fbsd_osx_eh) 14. [Garbage Collection](#garbage_collection) 15. [Runtime Helper Functions](#runtime_helper_functions) 16. [Module Initialization and Termination](#module_init_and_fina) 17. [Unit Testing](#unit_testing) 18. [Symbolic Debugging](#symbolic_debugging) 1. [Codeview Debugger Extensions](#codeview) A D implementation that conforms to the D ABI (Application Binary Interface) will be able to generate libraries, DLLs, etc., that can interoperate with D binaries built by other implementations. C ABI ----- The C ABI referred to in this specification means the C Application Binary Interface of the target system. C and D code should be freely linkable together, in particular, D code shall have access to the entire C ABI runtime library. Endianness ---------- The [endianness](https://en.wikipedia.org/wiki/Endianness) (byte order) of the layout of the data will conform to the endianness of the target machine. The Intel x86 CPUs are *little endian* meaning that the value 0x0A0B0C0D is stored in memory as: `0D 0C 0B 0A`. Basic Types ----------- | | | | --- | --- | | bool | 8 bit byte with the values 0 for false and 1 for true | | byte | 8 bit signed value | | ubyte | 8 bit unsigned value | | short | 16 bit signed value | | ushort | 16 bit unsigned value | | int | 32 bit signed value | | uint | 32 bit unsigned value | | long | 64 bit signed value | | ulong | 64 bit unsigned value | | cent | 128 bit signed value | | ucent | 128 bit unsigned value | | float | 32 bit IEEE 754 floating point value | | double | 64 bit IEEE 754 floating point value | | real | implementation defined floating point value, for x86 it is 80 bit IEEE 754 extended real | Delegates --------- Delegates are *fat pointers* with two parts: Delegate Layout| **offset** | **property** | **contents** | | `0` | `.ptr` | context pointer | | *ptrsize* | `.funcptr` | pointer to function | The *context pointer* can be a class *this* reference, a struct *this* pointer, a pointer to a closure (nested functions) or a pointer to an enclosing function's stack frame (nested functions). Structs ------- Conforms to the target's C ABI struct layout. Classes ------- An object consists of: Class Object Layout| **size** | **property** | **contents** | | *ptrsize* | `.__vptr` | pointer to vtable | | *ptrsize* | `.__monitor` | monitor | | *ptrsize*... | | vptrs for any interfaces implemented by this class in left to right, most to least derived, order | | `...` | `...` | super's non-static fields and super's interface vptrs, from least to most derived | | `...` | named fields | non-static fields | The vtable consists of: Virtual Function Pointer Table Layout| **size** | **contents** | | *ptrsize* | pointer to instance of TypeInfo | | *ptrsize*... | pointers to virtual member functions | Casting a class object to an interface consists of adding the offset of the interface's corresponding vptr to the address of the base of the object. Casting an interface ptr back to the class type it came from involves getting the correct offset to subtract from it from the object.Interface entry at vtbl[0]. Adjustor thunks are created and pointers to them stored in the method entries in the vtbl[] in order to set the this pointer to the start of the object instance corresponding to the implementing method. An adjustor thunk looks like: ``` ADD EAX,offset JMP method ``` The leftmost side of the inheritance graph of the interfaces all share their vptrs, this is the single inheritance model. Every time the inheritance graph forks (for multiple inheritance) a new vptr is created and stored in the class' instance. Every time a virtual method is overridden, a new vtbl[] must be created with the updated method pointers in it. The class definition: ``` class XXXX { .... }; ``` Generates the following: * An instance of Class called ClassXXXX. * A type called StaticClassXXXX which defines all the static members. * An instance of StaticClassXXXX called StaticXXXX for the static members. Interfaces ---------- An interface is a pointer to a pointer to a vtbl[]. The vtbl[0] entry is a pointer to the corresponding instance of the object.Interface class. The rest of the `vtbl[1..$]` entries are pointers to the virtual functions implemented by that interface, in the order that they were declared. A COM interface differs from a regular interface in that there is no object.Interface entry in `vtbl[0]`; the entries `vtbl[0..$]` are all the virtual function pointers, in the order that they were declared. This matches the COM object layout used by Windows. A C++ interface differs from a regular interface in that it matches the layout of a C++ class using single inheritance on the target machine. Arrays ------ A dynamic array consists of: Dynamic Array Layout| **offset** | **property** | **contents** | | `0` | `.length` | array dimension | | `size_t` | `.ptr` | pointer to array data | A dynamic array is declared as: ``` type[] array; ``` whereas a static array is declared as: ``` type[dimension] array; ``` Thus, a static array always has the dimension statically available as part of the type, and so it is implemented like in C. Static arrays and Dynamic arrays can be easily converted back and forth to each other. Associative Arrays ------------------ Associative arrays consist of a pointer to an opaque, implementation defined type. The current implementation is contained in and defined by [rt/aaA.d](https://github.com/dlang/druntime/blob/master/src/rt/aaA.d). Reference Types --------------- D has reference types, but they are implicit. For example, classes are always referred to by reference; this means that class instances can never reside on the stack or be passed as function parameters. Name Mangling ------------- D accomplishes typesafe linking by *mangling* a D identifier to include scope and type information. ``` MangledName: _D QualifiedName Type _D QualifiedName Z // Internal ``` The [*Type*](#Type) above is the type of a variable or the return type of a function. This is never a [*TypeFunction*](#TypeFunction), as the latter can only be bound to a value via a pointer to a function or a delegate. ``` QualifiedName: SymbolFunctionName SymbolFunctionName QualifiedName SymbolFunctionName: SymbolName SymbolName TypeFunctionNoReturn SymbolName M TypeModifiersopt TypeFunctionNoReturn ``` The **M** means that the symbol is a function that requires a `this` pointer. Class or struct fields are mangled without **M**. To disambiguate **M** from being a [*Parameter*](#Parameter) with modifier `scope`, the following type needs to be checked for being a [*TypeFunction*](#TypeFunction). ``` SymbolName: LName TemplateInstanceName IdentifierBackRef 0 // anonymous symbols ``` Template Instance Names have the types and values of its parameters encoded into it: ``` TemplateInstanceName: TemplateID LName TemplateArgs Z TemplateID: __T __U // for symbols declared inside template constraint TemplateArgs: TemplateArg TemplateArg TemplateArgs TemplateArg: TemplateArgX H TemplateArgX ``` If a template argument matches a specialized template parameter, the argument is mangled with prefix **H**. ``` TemplateArgX: T Type V Type Value S QualifiedName X Number ExternallyMangledName ``` *ExternallyMangledName* can be any series of characters allowed on the current platform, e.g. generated by functions with C++ linkage or annotated with `pragma(mangle,...)`. ``` Value: n i Number N Number e HexFloat c HexFloat c HexFloat CharWidth Number _ HexDigits A Number Value... S Number Value... HexFloat: NAN INF NINF N HexDigits P Exponent HexDigits P Exponent Exponent: N Number Number HexDigits: HexDigit HexDigit HexDigits HexDigit: Digit A B C D E F CharWidth: a w d ``` **n** is for **null** arguments. **i** [*Number*](#Number) is for positive numeric literals (including character literals). **N** [*Number*](#Number) is for negative numeric literals. **e** [*HexFloat*](#HexFloat) is for real and imaginary floating point literals. **c** [*HexFloat*](#HexFloat) **c** [*HexFloat*](#HexFloat) is for complex floating point literals. [*CharWidth*](#CharWidth) [*Number*](#Number) `_` [*HexDigits*](#HexDigits) [*CharWidth*](#CharWidth) is whether the characters are 1 byte (**a**), 2 bytes (**w**) or 4 bytes (**d**) in size. [*Number*](#Number) is the number of characters in the string. The [*HexDigits*](#HexDigits) are the hex data for the string. **A** [*Number*](#Number) [*Value*](#Value)... An array or asssociative array literal. [*Number*](#Number) is the length of the array. [*Value*](#Value) is repeated [*Number*](#Number) times for a normal array, and 2 \* [*Number*](#Number) times for an associative array. **S** [*Number*](#Number) [*Value*](#Value)... A struct literal. [*Value*](#Value) is repeated [*Number*](#Number) times. ``` Name: Namestart Namestart Namechars Namestart: _ Alpha Namechar: Namestart Digit Namechars: Namechar Namechar Namechars ``` A [*Name*](#Name) is a standard D [identifier](lex#identifiers). ``` LName: Number Name Number: Digit Digit Number Digit: 0 1 2 3 4 5 6 7 8 9 ``` An [*LName*](#LName) is a name preceded by a [*Number*](#Number) giving the number of characters in the [*Name*](#Name). ### Back references Any [*LName*](#LName) or non-basic [*Type*](#Type) (i.e. any type that does not encode as a fixed one or two character sequence) that has been emitted to the mangled symbol before will not be emitted again, but is referenced by a special sequence encoding the relative position of the original occurrence in the mangled symbol name. Numbers in back references are encoded with base 26 by upper case letters **A** - **Z** for higher digits but lower case letters **a** - **z** for the last digit. ``` TypeBackRef: Q NumberBackRef IdentifierBackRef: Q NumberBackRef NumberBackRef: lower-case-letter upper-case-letter NumberBackRef ``` To distinguish between the type of the back reference a look-up of the back referenced character is necessary: An identifier back reference always points to a digit **0** to **9**, while a type back reference always points to a letter. ### Type Mangling Types are mangled using a simple linear scheme: ``` Type: TypeModifiersopt TypeX TypeBackRef TypeX: TypeArray TypeStaticArray TypeAssocArray TypePointer TypeFunction TypeIdent TypeClass TypeStruct TypeEnum TypeTypedef TypeDelegate TypeVoid TypeByte TypeUbyte TypeShort TypeUshort TypeInt TypeUint TypeLong TypeUlong TypeCent TypeUcent TypeFloat TypeDouble TypeReal TypeIfloat TypeIdouble TypeIreal TypeCfloat TypeCdouble TypeCreal TypeBool TypeChar TypeWchar TypeDchar TypeNull TypeTuple TypeVector TypeModifiers: Const Wild Wild Const Shared Shared Const Shared Wild Shared Wild Const Immutable Shared: O Const: x Immutable: y Wild: Ng TypeArray: A Type TypeStaticArray: G Number Type TypeAssocArray: H Type Type TypePointer: P Type TypeVector: Nh Type TypeFunction: TypeFunctionNoReturn Type TypeFunctionNoReturn: CallConvention FuncAttrsopt Parametersopt ParamClose CallConvention: F // D U // C W // Windows R // C++ Y // Objective-C FuncAttrs: FuncAttr FuncAttr FuncAttrs FuncAttr: FuncAttrPure FuncAttrNothrow FuncAttrRef FuncAttrProperty FuncAttrNogc FuncAttrReturn FuncAttrScope FuncAttrTrusted FuncAttrSafe FuncAttrLive ``` Function attributes are emitted in the order as listed above. ``` FuncAttrPure: Na FuncAttrNogc: Ni FuncAttrNothrow: Nb FuncAttrProperty: Nd FuncAttrRef: Nc FuncAttrReturn: Nj FuncAttrScope: Nl FuncAttrTrusted: Ne FuncAttrSafe: Nf FuncAttrLive: Nm Parameters: Parameter Parameter Parameters Parameter: Parameter2 M Parameter2 // scope Nk Parameter2 // return Parameter2: Type I Type // in J Type // out K Type // ref L Type // lazy ParamClose X // variadic T t...) style Y // variadic T t,...) style Z // not variadic TypeIdent: I QualifiedName TypeClass: C QualifiedName TypeStruct: S QualifiedName TypeEnum: E QualifiedName TypeTypedef: T QualifiedName TypeDelegate: D TypeModifiersopt TypeFunction TypeVoid: v TypeByte: g TypeUbyte: h TypeShort: s TypeUshort: t TypeInt: i TypeUint: k TypeLong: l TypeUlong: m TypeCent: zi TypeUcent: zk TypeFloat: f TypeDouble: d TypeReal: e TypeIfloat: o TypeIdouble: p TypeIreal: j TypeCfloat: q TypeCdouble: r TypeCreal: c TypeBool: b TypeChar: a TypeWchar: u TypeDchar: w TypeNull: n TypeTuple: B Parameters Z ``` Function Calling Conventions ---------------------------- The `extern (C)` and `extern (D)` calling convention matches the C calling convention used by the supported C compiler on the host system. Except that the extern (D) calling convention for Windows x86 is described here. ### Register Conventions * EAX, ECX, EDX are scratch registers and can be destroyed by a function. * EBX, ESI, EDI, EBP must be preserved across function calls. * EFLAGS is assumed destroyed across function calls, except for the direction flag which must be forward. * The FPU stack must be empty when calling a function. * The FPU control word must be preserved across function calls. * Floating point return values are returned on the FPU stack. These must be cleaned off by the caller, even if they are not used. ### Return Value * The types bool, byte, ubyte, short, ushort, int, uint, pointer, Object, and interfaces are returned in EAX. * long and ulong are returned in EDX,EAX, where EDX gets the most significant half. * float, double, real, ifloat, idouble, ireal are returned in ST0. * cfloat, cdouble, creal are returned in ST1,ST0 where ST1 is the real part and ST0 is the imaginary part. * Dynamic arrays are returned with the pointer in EDX and the length in EAX. * Associative arrays are returned in EAX. * References are returned as pointers in EAX. * Delegates are returned with the pointer to the function in EDX and the context pointer in EAX. * 1, 2 and 4 byte structs and static arrays are returned in EAX. * 8 byte structs and static arrays are returned in EDX,EAX, where EDX gets the most significant half. * For other sized structs and static arrays, the return value is stored through a hidden pointer passed as an argument to the function. * Constructors return the this pointer in EAX. ### Parameters The parameters to the non-variadic function: ``` foo(a1, a2, ..., an); ``` are passed as follows: | | | --- | | a1 | | a2 | | ... | | an | | hidden | | this | where *hidden* is present if needed to return a struct value, and *this* is present if needed as the this pointer for a member function or the context pointer for a nested function. The last parameter is passed in EAX rather than being pushed on the stack if the following conditions are met: * It fits in EAX. * It is not a 3 byte struct. * It is not a floating point type. Parameters are always pushed as multiples of 4 bytes, rounding upwards, so the stack is always aligned on 4 byte boundaries. They are pushed most significant first. **out** and **ref** are passed as pointers. Static arrays are passed as pointers to their first element. On Windows, a real is pushed as a 10 byte quantity, a creal is pushed as a 20 byte quantity. On Linux, a real is pushed as a 12 byte quantity, a creal is pushed as two 12 byte quantities. The extra two bytes of pad occupy the ‘most significant’ position. The callee cleans the stack. The parameters to the variadic function: ``` void foo(int p1, int p2, int[] p3...) foo(a1, a2, ..., an); ``` are passed as follows: | | | --- | | p1 | | p2 | | a3 | | hidden | | this | The variadic part is converted to a dynamic array and the rest is the same as for non-variadic functions. The parameters to the variadic function: ``` void foo(int p1, int p2, ...) foo(a1, a2, a3, ..., an); ``` are passed as follows: | | | --- | | an | | ... | | a3 | | a2 | | a1 | | `_`arguments | | hidden | | this | The caller is expected to clean the stack. `_argptr` is not passed, it is computed by the callee. Exception Handling ------------------ ### Windows Conforms to the Microsoft Windows Structured Exception Handling conventions. ### Linux, FreeBSD and OS X Uses static address range/handler tables. It is not compatible with the ELF/Mach-O exception handling tables. The stack is walked assuming it uses the EBP/RBP stack frame convention. The EBP/RBP convention must be used for every function that has an associated EH (Exception Handler) table. For each function that has exception handlers, an EH table entry is generated. EH Table Entry| **field** | **description** | | `void*` | pointer to start of function | | `DHandlerTable*` | pointer to corresponding EH data | | `uint` | size in bytes of the function | The EH table entries are placed into the following special segments, which are concatenated by the linker. EH Table Segment| **Operating System** | **Segment Name** | | Windows | `FI` | | Linux | `.deh_eh` | | FreeBSD | `.deh_eh` | | OS X | `__deh_eh`, `__DATA` | The rest of the EH data can be placed anywhere, it is immutable. DHandlerTable| **field** | **description** | | `void*` | pointer to start of function | | `uint` | offset of ESP/RSP from EBP/RBP | | `uint` | offset from start of function to return code | | `uint` | number of entries in `DHandlerInfo[]` | | `DHandlerInfo[]` | array of handler information | DHandlerInfo| **field** | **description** | | `uint` | offset from function address to start of guarded section | | `uint` | offset of end of guarded section | | `int` | previous table index | | `uint` | if != 0 offset to DCatchInfo data from start of table | | `void*` | if not null, pointer to finally code to execute | DCatchInfo| **field** | **description** | | `uint` | number of entries in `DCatchBlock[]` | | `DCatchBlock[]` | array of catch information | DCatchBlock| **field** | **description** | | `ClassInfo` | catch type | | `uint` | offset from EBP/RBP to catch variable | |`void*`, catch handler code Garbage Collection ------------------ The interface to this is found in Druntime's [gc/gcinterface.d](https://github.com/dlang/druntime/blob/master/src/gc/gcinterface.d). Runtime Helper Functions ------------------------ These are found in Druntime's [rt/](https://github.com/dlang/druntime/blob/master/src/rt/). Module Initialization and Termination ------------------------------------- All the static constructors for a module are aggregated into a single function, and a pointer to that function is inserted into the ctor member of the ModuleInfo instance for that module. All the static denstructors for a module are aggregated into a single function, and a pointer to that function is inserted into the dtor member of the ModuleInfo instance for that module. Unit Testing ------------ All the unit tests for a module are aggregated into a single function, and a pointer to that function is inserted into the unitTest member of the ModuleInfo instance for that module. Symbolic Debugging ------------------ D has types that are not represented in existing C or C++ debuggers. These are dynamic arrays, associative arrays, and delegates. Representing these types as structs causes problems because function calling conventions for structs are often different than that for these types, which causes C/C++ debuggers to misrepresent things. For these debuggers, they are represented as a C type which does match the calling conventions for the type. Types for C Debuggers| **D type** | **C representation** | | dynamic array | `unsigned long long` | | associative array | `void*` | | delegate | `long long` | | `dchar` | `unsigned long` | For debuggers that can be modified to accept new types, the following extensions help them fully support the types. ### Codeview Debugger Extensions The D **dchar** type is represented by the special primitive type 0x78. D makes use of the Codeview OEM generic type record indicated by `LF_OEM` (0x0015). The format is: Codeview OEM Extensions for D| field size | 2 | 2 | 2 | 2 | 2 | 2 | | **D Type** | **Leaf Index** | **OEM Identifier** | **recOEM** | **num indices** | **type index** | **type index** | | dynamic array | `LF_OEM` | *OEM* | 1 | 2 | @*index* | @*element* | | associative array | `LF_OEM` | *OEM* | 2 | 2 | @*key* | @*element* | | delegate | `LF_OEM` | *OEM* | 3 | 2 | @*this* | @*function* | where: | | | | --- | --- | | *OEM* | 0x42 | | *index* | type index of array index | | *key* | type index of key | | *element* | type index of array element | | *this* | type index of context pointer | | *function* | type index of function | These extensions can be pretty-printed by [obj2asm](http://www.digitalmars.com/ctg/obj2asm.html). The [Ddbg](http://ddbg.mainia.de/releases.html) debugger supports them.
programming_docs
d Documentation Generator Documentation Generator ======================= **Contents** 1. [Specification](#specifications) 1. [Phases of Processing](#phases_of_processing) 2. [Lexical](#lexical) 3. [Parsing](#parsing) 4. [Sections](#sections) 5. [Standard Sections](#standard_sections) 6. [Special Sections](#special_sections) 2. [Highlighting](#highlighting) 1. [Embedded Comments](#embedded_comments) 2. [Embedded Code](#embedded_code) 3. [Inline Code](#inline_code) 4. [Embedded HTML](#embedded_html) 5. [Headings](#headings) 6. [Links](#links) 7. [Lists](#lists) 8. [Tables](#tables) 9. [Quotes](#quotes) 10. [Horizontal Rules](#hrules) 11. [Text Emphasis](#text_emphasis) 12. [Identifier Emphasis](#emphasis) 13. [Character Entities](#character_entities) 14. [Punctuation Escapes](#punctuation_escapes) 15. [No Documentation](#no_documentation) 3. [Macros](#macros) 1. [Predefined Macros](#predefined_macros) 2. [Macro Definitions from `sc.ini`'s DDOCFILE](#macro_def_scini) 3. [Macro Definitions from .ddoc Files on the Command Line](#macro_def_ddoc_file) 4. [Macro Definitions Generated by Ddoc](#macro_def_ddocgenerated) 4. [Using Ddoc to generate examples from unit tests](#using_ddoc_to_generate_examples) 5. [Using Ddoc for other Documentation](#using_ddoc_for_other_documentation) 6. [Security considerations](#security) 7. [Links to D documentation generators](#links_to_d_documentation_generators) The D programming language enables embedding both contracts and test code along side the actual code, which helps to keep them all consistent with each other. One thing lacking is the documentation, as ordinary comments are usually unsuitable for automated extraction and formatting into manual pages. Embedding the user documentation into the source code has important advantages, such as not having to write the documentation twice, and the likelihood of the documentation staying consistent with the code. Some existing approaches to this are: * [Doxygen](http://www.stack.nl/~dimitri/doxygen) which already has some support for D * Java's [Javadoc](https://docs.oracle.com/javase/7/docs/technotes/guides/javadoc/index.html), probably the most well-known * C#'s [embedded XML](https://msdn.microsoft.com/en-us/library/b2s063f7.aspx) * Other [documentation tools](https://python.org/sigs/doc-sig/otherlangs.html) D's goals for embedded documentation are: 1. It looks good as embedded documentation, not just after it is extracted and processed. 2. It's easy and natural to write, i.e. minimal reliance on <tags> and other clumsy forms one would never see in a finished document. 3. It does not repeat information that the compiler already knows from parsing the code. 4. It doesn't rely on embedded HTML, as such will impede extraction and formatting for other purposes. 5. It's based on existing D comment forms, so it is completely independent of parsers only interested in D code. 6. It should look and feel different from code, so it won't be visually confused with code. 7. It should be possible for the user to use Doxygen or other documentation extractor if desired. Specification ------------- The specification for the form of embedded documentation comments only specifies how information is to be presented to the compiler. It is implementation-defined how that information is used and the form of the final presentation. Whether the final presentation form is an HTML web page, a man page, a PDF file, etc. is not specified as part of the D Programming Language. ### Phases of Processing Embedded documentation comments are processed in a series of phases: 1. Lexical - documentation comments are identified and attached to tokens. 2. Parsing - documentation comments are associated with specific declarations and combined. 3. Sections - each documentation comment is divided up into a sequence of sections. 4. Special sections are processed. 5. Highlighting of non-special sections is done. 6. All sections for the module are combined. 7. Macro and Escape text substitution is performed to produce the final result. ### Lexical Embedded documentation comments are one of the following forms: 1. /\*\* ... \*/ The two \*'s after the opening / 2. /++ ... +/ The two +'s after the opening / 3. /// The three slashes The following are all embedded documentation comments: ``` /// This is a one line documentation comment. /** So is this. */ /++ And this. +/ /** This is a brief documentation comment. */ /** * The leading * on this line is not part of the documentation comment. */ /********************************* The extra *'s immediately following the /** are not part of the documentation comment. */ /++ This is a brief documentation comment. +/ /++ + The leading + on this line is not part of the documentation comment. +/ /+++++++++++++++++++++++++++++++++ The extra +'s immediately following the / ++ are not part of the documentation comment. +/ /**************** Closing *'s are not part *****************/ ``` The extra \*'s and +'s on the comment opening, closing and left margin are ignored and are not part of the embedded documentation. Comments not following one of those forms are not documentation comments. ### Parsing Each documentation comment is associated with a declaration. If the documentation comment is on a line by itself or with only whitespace to the left, it refers to the next declaration. Multiple documentation comments applying to the same declaration are concatenated. Documentation comments not associated with a declaration are ignored. Documentation comments preceding the *ModuleDeclaration* apply to the entire module. If the documentation comment appears on the same line to the right of a declaration, it applies to that. If a documentation comment for a declaration consists only of the identifier `ditto` then the documentation comment for the previous declaration at the same declaration scope is applied to this declaration as well. If there is no documentation comment for a declaration, that declaration may not appear in the output. To ensure it does appear in the output, put an empty declaration comment for it. ``` int a; /// documentation for a; b has no documentation int b; /** documentation for c and d */ /** more documentation for c and d */ int c; /** ditto */ int d; /** documentation for e and f */ int e; int f; /// ditto /** documentation for g */ int g; /// more documentation for g /// documentation for C and D class C { int x; /// documentation for C.x /** documentation for C.y and C.z */ int y; int z; /// ditto } /// ditto class D { } ``` ### Sections The document comment is a series of *Section*s. A *Section* is a name that is the first non-blank character on a line immediately followed by a ':'. This name forms the section name. The section name is not case sensitive. Section names starting with 'http://' or 'https://' are not recognized as section names. #### Summary The first section is the *Summary*, and does not have a section name. It is first paragraph, up to a blank line or a section name. While the summary can be any length, try to keep it to one line. The *Summary* section is optional. #### Description The next unnamed section is the *Description*. It consists of all the paragraphs following the *Summary* until a section name is encountered or the end of the comment. While the *Description* section is optional, there cannot be a *Description* without a *Summary* section. ``` /*********************************** * Brief summary of what * myfunc does, forming the summary section. * * First paragraph of synopsis description. * * Second paragraph of * synopsis description. */ void myfunc() { } ``` Named sections follow the *Summary* and *Description* unnamed sections. ### Standard Sections For consistency and predictability, there are several standard sections. None of these are required to be present. **Authors:** Lists the author(s) of the declaration. ``` /** * Authors: Melvin D. Nerd, [email protected] */ ``` **Bugs:** Lists any known bugs. ``` /** * Bugs: Doesn't work for negative values. */ ``` **Date:** Specifies the date of the current revision. The date should be in a form parseable by std.date. ``` /** * Date: March 14, 2003 */ ``` **Deprecated:** Provides an explanation for and corrective action to take if the associated declaration is marked as deprecated. ``` /** * Deprecated: superseded by function bar(). */ deprecated void foo() { ... } ``` **Examples:** Any usage examples ``` /** * Examples: * -------------------- * writeln("3"); // writes '3' to stdout * -------------------- */ ``` **History:** Revision history. ``` /** * History: * V1 is initial version * * V2 added feature X */ ``` **License:** Any license information for copyrighted code. ``` /** * License: use freely for any purpose */ void bar() { ... } ``` **Returns:** Explains the return value of the function. If the function returns **void**, don't redundantly document it. ``` /** * Read the file. * Returns: The contents of the file. */ void[] readFile(const(char)[] filename) { ... } ``` **See\_Also:** List of other symbols and URLs to related items. ``` /** * See_Also: * foo, bar, http://www.digitalmars.com/d/phobos/index.html */ ``` **Standards:** If this declaration is compliant with any particular standard, the description of it goes here. ``` /** * Standards: Conforms to DSPEC-1234 */ ``` **Throws:** Lists exceptions thrown and under what circumstances they are thrown. ``` /** * Write the file. * Throws: WriteException on failure. */ void writeFile(string filename) { ... } ``` **Version:** Specifies the current version of the declaration. ``` /** * Version: 1.6a */ ``` ### Special Sections Some sections have specialized meanings and syntax. **Copyright:** This contains the copyright notice. The macro COPYRIGHT is set to the contents of the section when it documents the module declaration. The copyright section only gets this special treatment when it is for the module declaration. ``` /** Copyright: Public Domain */ module foo; ``` **Params:** Function parameters can be documented by listing them in a params section. Each line that starts with an identifier followed by an '=' starts a new parameter description. A description can span multiple lines. ``` /*********************************** * foo does this. * Params: * x = is for this * and not for that * y = is for that */ void foo(int x, int y) { } ``` **Macros:** The macros section follows the same syntax as the **Params:** section. It's a series of *NAME*=*value* pairs. The *NAME* is the macro name, and *value* is the replacement text. ``` /** * Macros: * FOO = now is the time for * all good men * BAR = bar * MAGENTA = <font color="magenta">&dollar;0</font> */ ``` **Escapes=** The escapes section is a series of substitutions which replace special characters with a string. It's useful when the output format requires escaping of certain characters, for example in HTML **&** should be escaped with **&amp;**. The syntax is **/c/string/**, where **c** is either a single character, or multiple characters separated by whitespace or commas, and **string** is the replacement text. ``` /** * ESCAPES = /&/AddressOf!/ * /!/Exclamation/ * /?/QuestionMark/ * /,/Comma/ * /{ }/Parens/ * /<,>/Arrows/ */ ``` Highlighting ------------ ### Embedded Comments The documentation comments can themselves be commented using the &dollar;`(DDOC_COMMENT comment text)` syntax. These comments do not nest. ### Embedded Code D code can be embedded using lines beginning with at least three hyphens `-`, backticks ``` or tildes `~` (ignoring whitespace) to delineate the code section: ``` /++ + Our function. + + Example: + --- + import std.stdio; + + void foo() + { + writeln("foo!"); /* print the string */ + } + --- +/ ``` Note that in the above example the documentation comment uses the /++ ... +/ form so that /\* ... \*/ can be used inside the code section. D code gets automatic syntax highlighting. To include code in another language without syntax highlighting, add a language string at the end of the top delimiter line: ``` /++ + Some C++ + ``` cpp + #include <iostream> + + void foo() + { + std::cout << "foo!"; + } + ``` +/ ``` ### Inline Code Inline code can be written between backtick characters (`), similarly to the syntax used on GitHub, Reddit, Stack Overflow, and other websites. Both the opening and closing ` character must appear on the same line to trigger this behavior. Text inside these sections will be escaped according to the rules described above, then wrapped in a `&dollar;(DDOC_BACKQUOTED)` macro. By default, this macro expands to be displayed as an inline text span, formatted as code. A literal backtick character can be output either as a non-paired ` on a single line or by using the `&dollar;(BACKTICK)` macro. ``` /// Returns `true` if `a == b`. void foo() {} /// Backquoted `<html>` will be displayed to the user instead /// of passed through as embedded HTML (see below). void bar() {} ``` ### Embedded HTML HTML can be embedded into the documentation comments, and it will be passed through to the HTML output unchanged. However, since it is not necessarily true that HTML will be the desired output format of the embedded documentation comment extractor, it is best to avoid using it where practical. ``` /** * Example of embedded HTML: * * <ol> * <li><a href="http://www.digitalmars.com">Digital Mars</a></li> * <li><a href="http://www.classicempire.com">Empire</a></li> * </ol> */ ``` ### Headings A long documentation section can be subdivided by adding headings. A heading is a line of text that starts with one to six `#` characters followed by whitespace and then the heading text. The number of `#` characters determines the heading level. Headings may optionally end with any number of trailing `#` characters. ``` /** * # H1 * ## H2 * ### H3 * #### H4 ### * ##### H5 ## * ###### H6 # */ ``` ### Links Documentation may link to other documentation or to a URL. There are four styles of links: ``` /** * Some links: * * 1. A [reference link][ref] and bare reference links: [ref] or [Object] * 2. An [inline link](https://dlang.org) * 3. A bare URL: https://dlang.org * 4. An ![image](https://dlang.org/images/d3.png) * * [ref]: https://dlang.org "The D Language Website" */ ``` #### Reference Links Reference-style links enclose a reference label in square brackets. They may optionally be preceded by some link text, also enclosed in square brackets. The reference label must match a reference defined elsewhere. This may be a D symbol in scope of the source code being documented, like `[Object]` in the example above, or it may be an explicit reference that is defined in the same documentation comment, like `[ref]` in the example above. In the example both instances of `[ref]` in item `1.` will be replaced with the URL and title text from the matching definition at the bottom of the example. The first link will read `reference link` and the second will read `ref`. Reference definitions start with a label in square brackets, followed by a colon, a URL and an optional title wrapped in single or double quotes, or in parentheses. If a reference label would match both a D symbol and a reference definition then the reference definition is used. The generated links to D symbols are relative if they have the same root package as the module being documented. If not, their URLs are preceded by a `&dollar;(DDOC_ROOT_pkg)` macro, where `pkg` is the root package of the symbol being linked to. Links to D symbols are generated with a `&dollar;(DOC_EXTENSION)` macro after the module name. Then the generated URL for `[Object]` in the above example is as if it had been written: ``` &dollar;(DOC_ROOT_object)object&dollar;(DOC_EXTENSION)#.Object ``` `DOC_ROOT_` macros can be defined for any external packages to link to using a [Macros section](#macros). #### Inline Links Inline-style links enclose link text in square brackets and the link URL in parentheses. Like reference links, the URL may optionally be followed by title text wrapped in single or double quotes, or in parentheses: ``` /// [a link with title text](https://dlang.org 'Some title text') ``` #### Bare URLs Bare URLs are sequences of characters that start with `http://` or `https://`, continue with one or more characters from the set of letters, digits and `-_?=%&/+#~.`, and contain at least one period. URL recognition happens before all macro text substitution. The URL is wrapped in a `&dollar;(DDOC_LINK_AUTODETECT)` macro and is otherwise left untouched. #### Images Images have the same form as reference or inline links, but add an exclamation point `!` before the initial square bracket. What would be the link text in a normal link is used as the image's alt text. ### Lists Documentation may contain lists. Start an ordered list with a number followed by a period: ``` /** * 1. First this * 2. Then this * 1. A sub-item */ ``` Start an unordered list with a hyphen (`-`), an asterisk (`*`) or a plus (`+`). Subsequent items in the same list must also start with the same symbol: ``` /** * - A list * - With a second item * * + A different list * - With a sub-item * * * A third list (note the double asterisks) */ ``` Note the double asterisks in the example above. This is because the list is inside a documentation comment that is delimited with asterisks, so the initial asterisk is considered part of the documentation comment, not a list item. This is even true when other lines don't start with an asterisk: ``` /** - A list * Not a list because the asterisk is part of the documentation comment */ /++ + + The caveat also applies to plus-delimited documentation comments +/ ``` List items can include content like new paragraphs, headings, embedded code, or child list items. Simply indent the content to match the indent of the text after the list symbol: ``` /** * - A parent list item * * With a second paragraph * * - A sub-item * --- * // A code example inside the sub-item * --- */ ``` ### Tables Data may be placed into a table. Tables consist of a single header row, a delimiter row, and zero or more data rows. Cells in each row are separated by pipe (`|`) characters. Initial and trailing `|`'s are optional. The number of cells in the delimiter row must match the number of cells in the header row: ``` /** * | Item | Price | * | ---- | ----: | * | Wigs | &dollar;10 | * Wheels | &dollar;13 * | Widgets | &dollar;200 | */ ``` Cells in the delimiter row contain hyphens (`-`) and optional colons (`:`). A `:` to the left of the hyphens creates a left-aligned column, a `:` to the right of the hyphens creates a right-aligned column (like the example above), and `:`'s on both sides of the hyphens create a center-aligned column. ### Quotes Documentation may include a section of quoted material by prefixing each line of the section with a `>`. Quotes may include headings, lists, embedded code, etc. ``` /** * > To D, or not to D. -- Willeam NerdSpeare */ ``` Lines of text that directly follow a quoted line are considered part of the quote: ``` /** * > This line * and this line are both part of the quote * * This line is not part of the quote. */ ``` ### Horizontal Rules Create a horizontal rule by adding a line containing three or more asterisks, underscores or hyphens: ``` /** * *** * ___ */ ``` As with [lists](#lists), note that the initial `*` in the example above will be stripped because it is part of a documentation comment that is delimited with asterisks. At least three subsequent asterisks are needed. To create a horizontal rule with hyphens, add spaces between the hyphens. Without the spaces they would be treated as the start or end of an [embedded code block](#embedded_code). Note that any horizontal rule may contain spaces: ``` /** * - - - * _ _ _ * * * * */ ``` ### Text Emphasis A span of text wrapped in asterisks (`*`) is emphasized, and text wrapped in two asterisks (`**`) is strongly emphasized: `*single asterisks*` is rendered as *single asterisks*. `**double asterisks**` is rendered as **double asterisks**. Insert a literal asterisk by [backslash-escaping](#punctuation_escapes) it: `\*` is rendered as \*. Unlike [Markdown](https://daringfireball.net/projects/markdown/syntax), underscores (`_`) are not supported for emphasizing text because it would break snake\_case names and underscore prefix processing in [identifier emphasis](#emphasis). ### Identifier Emphasis Identifiers in documentation comments that are function parameters or are names that are in scope at the associated declaration are emphasized in the output. This emphasis can take the form of italics, boldface, a hyperlink, etc. How it is emphasized depends on what it is — a function parameter, type, D keyword, etc. To prevent unintended emphasis of an identifier, it can be preceded by an underscore (\_). The underscore will be stripped from the output. ### Character Entities Some characters have special meaning to the documentation processor, to avoid confusion it can be best to replace them with their corresponding character entities: Characters and Entities| **Character** | **Entity** | | `<` | &lt; | | `>` | &gt; | | `&` | &amp; | It is not necessary to do this inside a code section, or if the special character is not immediately followed by a # or a letter. ### Punctuation Escapes Escape any ASCII punctuation symbol with a backslash `\`. Doing so outputs the original character without the backslash, except for the following characters which output predefined macros instead: Characters and Escape Macros| **Character** | **Macro** | | `(` | &dollar;(LPAREN) | | `)` | &dollar;(RPAREN) | | `,` | &dollar;(COMMA) | | `&dollar;` | &dollar;(DOLLAR) | To output a backslash, simply use two backslashes in a row: `\\`. Note that backslashes inside embedded or inline code do *not* escape punctuation and are included in the output as-is. Backslashes before non-punctation are also included in the output as-is. For example, `C:\dmd2\bin\dmd.exe` does not require escaping its embedded backslashes. ### No Documentation No documentation is generated for the following constructs, even if they have a documentation comment: * Invariants * Postblits * Destructors * Static constructors and static destructors * Class info, type info, and module info Macros ------ The documentation comment processor includes a simple macro text preprocessor. When a &dollar;(*NAME*) appears in section text it is replaced with *NAME*s corresponding replacement text. For example: ``` /** Macros: PARAM = <u>&dollar;1</u> MATH_DOCS = <a href="https://dlang.org/phobos/std_math.html">Math Docs</a> */ module math; /** * This function returns the sum of &dollar;(PARAM a) and &dollar;(PARAM b). * See also the &dollar;(MATH_DOCS). */ int sum(int a, int b) { return a + b; } ``` The above would generate the following output: ``` <h1>test</h1> <dl><dt><big><a name="sum"></a>int <u>sum</u>(int <i>a</i>, int <i>b</i>); </big></dt> <dd>This function returns the <u>sum</u> of <u><i>a</i></u> and <u><i>b</i></u>. See also the <a href="https://dlang.org/phobos/std_math.html">Math Docs</a>. </dd> </dl> ``` The replacement text is recursively scanned for more macros. If a macro is recursively encountered, with no argument or with the same argument text as the enclosing macro, it is replaced with no text. Macro invocations that cut across replacement text boundaries are not expanded. If the macro name is undefined, the replacement text has no characters in it. If a &dollar;(NAME) is desired to exist in the output without being macro expanded, the &dollar; should be [backslash-escaped](#punctuation_escapes): `\$`. Macros can have arguments. Any text from the end of the identifier to the closing ‘)’ is the &dollar;0 argument. A &dollar;0 in the replacement text is replaced with the argument text. If there are commas in the argument text, &dollar;1 will represent the argument text up to the first comma, &dollar;2 from the first comma to the second comma, etc., up to &dollar;9. &dollar;+ represents the text from the first comma to the closing ‘)’. The argument text can contain nested parentheses, "" or '' strings, `<``!--` `...` `--``>` comments, or tags. If stray, unnested parentheses are used, they can be [backslash-escaped](#punctuation_escapes): `\(` or `\)`. Macro definitions come from the following sources, in the specified order: 1. Predefined macros. 2. Definitions from file specified by [sc.ini](https://dlang.org/dmd-windows.html)'s or [dmd.conf](https://dlang.org/dmd-linux.html#dmd_conf) DDOCFILE setting. 3. Definitions from \*.ddoc files specified on the command line. 4. Runtime definitions generated by Ddoc. 5. Definitions from any Macros: sections. Macro redefinitions replace previous definitions of the same name. This means that the sequence of macro definitions from the various sources forms a hierarchy. Macro names beginning with "D\_" and "DDOC\_" are reserved. ### Predefined Macros A number of macros are predefined Ddoc, and represent the minimal definitions needed by Ddoc to format and highlight the presentation. The definitions are for simple HTML. The implementations of all predefined macros are implementation-defined. The reference implementation's macro definitions can be found [here](https://github.com/dlang/dmd/blob/master/res/default_ddoc_theme.ddoc). Ddoc does not generate HTML code. It formats into the basic formatting macros, which (in their predefined form) are then expanded into HTML. If output other than HTML is desired, then these macros need to be redefined. Predefined Formatting Macros| **Name** | **Description** | | `B` | boldface the argument | | `I` | italicize the argument | | `U` | underline the argument | | `P` | argument is a paragraph | | `DL` | argument is a definition list | | `DT` | argument is a definition in a definition list | | `DD` | argument is a description of a definition | | `TABLE` | argument is a table | | `TR` | argument is a row in a table | | `TH` | argument is a header entry in a row | | `TD` | argument is a data entry in a row | | `OL` | argument is an ordered list | | `UL` | argument is an unordered list | | `LI` | argument is an item in a list | | `BIG` | argument is one font size bigger | | `SMALL` | argument is one font size smaller | | `BR` | start new line | | `LINK` | generate clickable link on argument | | `LINK2` | generate clickable link, first arg is address | | `RED` | argument is set to be red | | `BLUE` | argument is set to be blue | | `GREEN` | argument is set to be green | | `YELLOW` | argument is set to be yellow | | `BLACK` | argument is set to be black | | `WHITE` | argument is set to be white | | `D_CODE` | argument is D code | | `D_INLINECODE` | argument is inline D code | | `LF` | Insert a line feed (newline) | | `LPAREN` | Insert a left parenthesis | | `RPAREN` | Insert a right parenthesis | | `BACKTICK` | Insert a backtick | | `DOLLAR` | Insert a dollar sign | | `DDOC` | overall template for output | **DDOC** is special in that it specifies the boilerplate into which the entire generated text is inserted (represented by the Ddoc generated macro **BODY**). For example, in order to use a style sheet, **DDOC** would be redefined as: ``` DDOC = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html><head> <META http-equiv="content-type" content="text/html; charset=utf-8"> <title>&dollar;(TITLE)</title> <link rel="stylesheet" type="text/css" href="style.css"> </head><body> <h1>&dollar;(TITLE)</h1> &dollar;(BODY) </body></html> ``` Highlighting of D code is performed by the following macros: D Code Formatting Macros| **Name** | **Description** | | `D_COMMENT` | Highlighting of comments | | `D_STRING` | Highlighting of string literals | | `D_KEYWORD` | Highlighting of D keywords | | `D_PSYMBOL` | Highlighting of current declaration name | | `D_PARAM` | Highlighting of current function declaration parameters | The highlighting macros start with `DDOC_`. They control the formatting of individual parts of the presentation. Ddoc Section Formatting Macros| **Name** | **Description** | | `DDOC_CONSTRAINT` | Highlighting of a template constraint. | | `DDOC_COMMENT` | Inserts a comment in the output. | | `DDOC_DECL` | Highlighting of the declaration. | | `DDOC_DECL_DD` | Highlighting of the description of a declaration. | | `DDOC_DITTO` | Highlighting of ditto declarations. | | `DDOC_SECTIONS` | Highlighting of all the sections. | | `DDOC_SUMMARY` | Highlighting of the summary section. | | `DDOC_DESCRIPTION` | Highlighting of the description section. | | `DDOC_AUTHORS` | Highlighting of the authors section. | | `DDOC_BUGS` | Highlighting of the bugs section. | | `DDOC_COPYRIGHT` | Highlighting of the copyright section. | | `DDOC_DATE` | Highlighting of the date section. | | `DDOC_DEPRECATED` | Highlighting of the deprecated section. | | `DEPRECATED` | Wrapper for deprecated declarations. | | `DDOC_EXAMPLES` | Highlighting of the examples section. | | `DDOC_HISTORY` | Highlighting of the history section. | | `DDOC_LICENSE` | Highlighting of the license section. | | `DDOC_OVERLOAD_SEPARATOR` | Inserts a separator between overloads of a given name. | | `DDOC_RETURNS` | Highlighting of the returns section. | | `DDOC_SEE_ALSO` | Highlighting of the see-also section. | | `DDOC_STANDARDS` | Highlighting of the standards section. | | `DDOC_THROWS` | Highlighting of the throws section. | | `DDOC_VERSION` | Highlighting of the version section. | | `DDOC_SECTION_H` | Highlighting of the section name of a non-standard section. | | `DDOC_SECTION` | Highlighting of the contents of a non-standard section. | | `DDOC_MEMBERS` | Default highlighting of all the members of a class, struct, etc. | | `DDOC_MODULE_MEMBERS` | Highlighting of all the members of a module. | | `DDOC_CLASS_MEMBERS` | Highlighting of all the members of a class. | | `DDOC_STRUCT_MEMBERS` | Highlighting of all the members of a struct. | | `DDOC_ENUM_MEMBERS` | Highlighting of all the members of an enum. | | `DDOC_TEMPLATE_PARAM` | Highlighting of a template's individual parameters. | | `DDOC_TEMPLATE_PARAM_LIST` | Highlighting of a template's parameter list. | | `DDOC_TEMPLATE_MEMBERS` | Highlighting of all the members of a template. | | `DDOC_ENUM_BASETYPE` | Highlighting of the type an enum is based upon | | `DDOC_PARAMS` | Highlighting of a function parameter section. | | `DDOC_PARAM_ROW` | Highlighting of a name=value function parameter. | | `DDOC_PARAM_ID` | Highlighting of the parameter name. | | `DDOC_PARAM_DESC` | Highlighting of the parameter value. | | `DDOC_BLANKLINE` | Inserts a blank line. | | `DDOC_ANCHOR` | Expands to a named anchor used for hyperlinking to a particular declaration section. Argument &dollar;1 expands to the qualified declaration name. | | `DDOC_PSYMBOL` | Highlighting of declaration name to which a particular section is referring. | | `DDOC_PSUPER_SYMBOL` | Highlighting of the base type of a class. | | `DDOC_KEYWORD` | Highlighting of D keywords. | | `DDOC_PARAM` | Highlighting of function parameters. | | `DDOC_BACKQUOTED` | Inserts inline code. | | `DDOC_AUTO_PSYMBOL_SUPPRESS` | Highlighting of auto-detected symbol that starts with underscore | | `DDOC_AUTO_PSYMBOL` | Highlighting of auto-detected symbol | | `DDOC_AUTO_KEYWORD` | Highlighting of auto-detected keywords | | `DDOC_AUTO_PARAM` | Highlighting of auto-detected parameters | For example, one could redefine `DDOC_SUMMARY`: ``` DDOC_SUMMARY = &dollar;(GREEN &dollar;0) ``` And all the summary sections will now be green. ### Macro Definitions from `sc.ini`'s DDOCFILE A text file of macro definitions can be created, and specified in `sc.ini`: ``` DDOCFILE=myproject.ddoc ``` ### Macro Definitions from .ddoc Files on the Command Line File names on the DMD command line with the extension .ddoc are text files that are read and processed in order. ### Macro Definitions Generated by Ddoc Generated Macro Definitions| **Macro Name** | **Content** | | BODY | Set to the generated document text. | | TITLE | Set to the module name. | | DATETIME | Set to the current date and time. | | YEAR | Set to the current year. | | COPYRIGHT | Set to the contents of any Copyright: section that is part of the module comment. | | DOCFILENAME | Set to the name of the generated output file. | | SRCFILENAME | Set to the name of the source file the documentation is being generated from. | Using Ddoc to generate examples from unit tests ----------------------------------------------- Ddoc can automatically generate usage examples for declarations using unit tests. If a declaration is followed by a documented unit test, the code from the test will be inserted into the example section of the declaration. This avoids the frequent problem of having outdated documentation for pieces of code. To create a documented unit test just add three forward slashes before the unittest block, like this: ``` /// unittest { ... } ``` For more information please see the full section on [documented unit tests](unittest#documented-unittests). Using Ddoc for other Documentation ---------------------------------- Ddoc is primarily designed for use in producing documentation from embedded comments. It can also, however, be used for processing other general documentation. The reason for doing this would be to take advantage of the macro capability of Ddoc and the D code syntax highlighting capability. If the .d source file starts with the string "Ddoc" then it is treated as general purpose documentation, not as a D code source file. From immediately after the "Ddoc" string to the end of the file or any "Macros:" section forms the document. No automatic highlighting is done to that text, other than highlighting of D code embedded between lines delineated with --- lines. Only macro processing is done. Much of the D documentation itself is generated this way, including this page. Such documentation is marked at the bottom as being generated by Ddoc. Security considerations ----------------------- Note that DDoc comments may embed raw HTML, including <script> tags. Be careful when publishing or distributing rendered DDoc HTML generated from untrusted sources, as this may allow [cross-site scripting](https://en.wikipedia.org/wiki/Cross-site_scripting). Links to D documentation generators ----------------------------------- A list of current D documentation generators which use Ddoc can be found on our [wiki page](https://wiki.dlang.org/Open_Source_Projects#Documentation_Generators).
programming_docs
d Modules Modules ======= **Contents** 1. [Module Declaration](#module_declaration) 2. [Import Declaration](#import-declaration) 3. [Symbol Name Lookup](#name_lookup) 4. [Public Imports](#public_imports) 5. [Static Imports](#static_imports) 6. [Renamed Imports](#renamed_imports) 7. [Selective Imports](#selective_imports) 8. [Renamed and Selective Imports](#renamed_selective_imports) 9. [Scoped Imports](#scoped_imports) 10. [Module Scope Operator](#module_scope_operators) 11. [Static Construction and Destruction](#staticorder) 12. [Order of Static Construction](#order_of_static_ctor) 13. [Order of Static Construction within a Module](#order_of_static_ctors) 14. [Order of Static Destruction](#order_static_dtor) 15. [Order of Unit tests](#order_of_unittests) 16. [Mixin Declaration](#mixin-declaration) 17. [Package Module](#package-module) ``` Module: ModuleDeclaration DeclDefs DeclDefs DeclDefs: DeclDef DeclDef DeclDefs DeclDef: AttributeSpecifier Declaration Constructor Destructor Postblit Allocator Deallocator ClassInvariant StructInvariant UnitTest AliasThis StaticConstructor StaticDestructor SharedStaticConstructor SharedStaticDestructor ConditionalDeclaration DebugSpecification VersionSpecification StaticAssert TemplateDeclaration TemplateMixinDeclaration TemplateMixin MixinDeclaration ; ``` Modules have a one-to-one correspondence with source files. The module name is, by default, the file name with the path and extension stripped off, and can be set explicitly with the module declaration. Modules automatically provide a namespace scope for their contents. Modules superficially resemble classes, but differ in that: * There's only one instance of each module, and it is statically allocated. * There is no virtual table. * Modules do not inherit, they have no super modules, etc. * A file may contain only one module. * Module symbols can be imported. * Modules are always compiled at global scope, and are unaffected by surrounding attributes or other modifiers. Modules can be grouped together in hierarchies called *packages*. Modules offer several guarantees: * The order in which modules are imported does not affect the semantics. * The semantics of a module are not affected by what imports it. * If a module C imports modules A and B, any modifications to B will not silently change code in C that is dependent on A. Module Declaration ------------------ The *ModuleDeclaration* sets the name of the module and what package it belongs to. If absent, the module name is taken to be the same name (stripped of path and extension) of the source file name. ``` ModuleDeclaration: ModuleAttributesopt module ModuleFullyQualifiedName ; ModuleAttributes: ModuleAttribute ModuleAttribute ModuleAttributes ModuleAttribute: DeprecatedAttribute UserDefinedAttribute ModuleFullyQualifiedName: ModuleName Packages . ModuleName ModuleName: Identifier Packages: PackageName Packages . PackageName PackageName: Identifier ``` The *Identifier*s preceding the rightmost *Identifier* are the *Packages* that the module is in. The packages correspond to directory names in the source file path. Package and module names cannot be [*Keyword*](lex#Keyword)s. If present, the *ModuleDeclaration* must be the first and only such declaration in the source file, and may be preceded only by comments and `#line` directives. Example: ``` module c.stdio; // module stdio in the c package ``` By convention, package and module names are all lower case. This is because these names have a one-to-one correspondence with the operating system's directory and file names, and many file systems are not case sensitive. Using all lower case package and module names will avoid or minimize problems when moving projects between dissimilar file systems. If the file name of a module is an invalid module name (e.g. `foo-bar.d`), use a module declaration to set a valid module name: ``` module foo_bar; ``` A *ModuleDeclaration* can have an optional [*DeprecatedAttribute*](attribute#DeprecatedAttribute). The compiler will produce a message when the deprecated module is imported. ``` deprecated module foo; ``` ``` module bar; import foo; // Deprecated: module foo is deprecated ``` A *DeprecatedAttribute* can have an optional [*AssignExpression*](expression#AssignExpression) argument to provide a more informative message. An *AssignExpression* must evaluate to a string at compile time. ``` deprecated("Please use foo2 instead.") module foo; ``` ``` module bar; import foo; // Deprecated: module foo is deprecated - Please use foo2 instead. ``` **Implementation Defined:** 1. The mapping of package and module identifiers to directory and file names. 2. How the deprecation messages are presented to the user. **Best Practices:** 1. [*PackageName*](#PackageName)s and [*ModuleName*](#ModuleName)s should be composed of the ASCII characters lower case letters, digits or `_` to ensure maximum portability and compatibility with various file systems. 2. The file names for packages and modules should be composed only of the ASCII lower case letters, digits, and `_`s, and should not be a [*Keyword*](lex#Keyword). Import Declaration ------------------ Symbols from one module are made available in another module by using the *ImportDeclaration*: ``` ImportDeclaration: import ImportList ; static import ImportList ; ImportList: Import ImportBindings Import , ImportList Import: ModuleFullyQualifiedName ModuleAliasIdentifier = ModuleFullyQualifiedName ImportBindings: Import : ImportBindList ImportBindList: ImportBind ImportBind , ImportBindList ImportBind: Identifier Identifier = Identifier ModuleAliasIdentifier: Identifier ``` There are several forms of the *ImportDeclaration*, from generalized to fine-grained importing. The order in which *ImportDeclaration*s occur has no significance. *ModuleFullyQualifiedName*s in the *ImportDeclaration* must be fully qualified with whatever packages they are in. They are not considered to be relative to the module that imports them. Symbol Name Lookup ------------------ The simplest form of importing is to just list the modules being imported: ``` module myapp.main; import std.stdio; // import module stdio from package std class Foo : BaseClass { import myapp.foo; // import module myapp.foo in this class' scope void bar () { import myapp.bar; // import module myapp.bar in this function' scope writeln("hello!"); // calls std.stdio.writeln } } ``` When a symbol name is used unqualified, a two-phase lookup is used. First, the module scope is searched, starting from the innermost scope. For example, in the previous example, while looking for `writeln`, the order will be: * Declarations inside `bar`. * Declarations inside `Foo`. * Declarations inside `BaseClass`. * Declarations at module scope. If the first lookup isn't successful, a second one is performed on imports. In the second lookup phase inherited scopes are ignored. This includes the scope of base classes and interfaces (in this example, `BaseClass`'s imports would be ignored), as well as imports in mixed-in `template`. Symbol lookup stops as soon as a matching symbol is found. If two symbols with the same name are found at the same lookup phase, this ambiguity will result in a compilation error. ``` module A; void foo(); void bar(); ``` ``` module B; void foo(); void bar(); ``` ``` module C; import A; void foo(); void test() { foo(); // C.foo() is called, it is found before imports are searched bar(); // A.bar() is called, since imports are searched } ``` ``` module D; import A; import B; void test() { foo(); // error, A.foo() or B.foo() ? A.foo(); // ok, call A.foo() B.foo(); // ok, call B.foo() } ``` ``` module E; import A; import B; alias foo = B.foo; void test() { foo(); // call B.foo() A.foo(); // call A.foo() B.foo(); // call B.foo() } ``` Public Imports -------------- By default, imports are *private*. This means that if module A imports module B, and module B imports module C, then names inside C are visible only inside B and not inside A. An import can be explicitly declared *public*, which will cause names from the imported module to be visible to further imports. So in the above example where module A imports module B, if module B *publicly* imports module C, names from C will be visible in A as well. All symbols from a publicly imported module are also aliased in the importing module. Thus in the above example if C contains the name foo, it will be accessible in A as `foo`, `B.foo` and `C.foo`. For another example: ``` module W; void foo() { } ``` ``` module X; void bar() { } ``` ``` module Y; import W; public import X; ... foo(); // calls W.foo() bar(); // calls X.bar() ``` ``` module Z; import Y; ... foo(); // error, foo() is undefined bar(); // ok, calls X.bar() X.bar(); // ditto Y.bar(); // ok, Y.bar() is an alias to X.bar() ``` Static Imports -------------- A static import requires the use of a fully qualified name to reference the module's names: ``` static import std.stdio; void main() { writeln("hello!"); // error, writeln is undefined std.stdio.writeln("hello!"); // ok, writeln is fully qualified } ``` Renamed Imports --------------- A local name for an import can be given, through which all references to the module's symbols must be qualified with: ``` import io = std.stdio; void main() { io.writeln("hello!"); // ok, calls std.stdio.writeln std.stdio.writeln("hello!"); // error, std is undefined writeln("hello!"); // error, writeln is undefined } ``` **Best Practices:** Renamed imports are handy when dealing with very long import names. Selective Imports ----------------- Specific symbols can be exclusively imported from a module and bound into the current namespace: ``` import std.stdio : writeln, foo = write; void main() { std.stdio.writeln("hello!"); // error, std is undefined writeln("hello!"); // ok, writeln bound into current namespace write("world"); // error, write is undefined foo("world"); // ok, calls std.stdio.write() fwritefln(stdout, "abc"); // error, fwritefln undefined } ``` `static` cannot be used with selective imports. Renamed and Selective Imports ----------------------------- When renaming and selective importing are combined: ``` import io = std.stdio : foo = writeln; void main() { writeln("bar"); // error, writeln is undefined std.stdio.foo("bar"); // error, foo is bound into current namespace std.stdio.writeln("bar"); // error, std is undefined foo("bar"); // ok, foo is bound into current namespace, // FQN not required io.writeln("bar"); // ok, io=std.stdio bound the name io in // the current namespace to refer to the entire // module io.foo("bar"); // error, foo is bound into current namespace, // foo is not a member of io } ``` Scoped Imports -------------- Import declarations may be used at any scope. For example: ``` void main() { import std.stdio; writeln("bar"); } ``` The imports are looked up to satisfy any unresolved symbols at that scope. Imported symbols may hide symbols from outer scopes. In function scopes, imported symbols only become visible after the import declaration lexically appears in the function body. In other words, imported symbols at function scope cannot be forward referenced. ``` void main() { void writeln(string) {} void foo() { writeln("bar"); // calls main.writeln import std.stdio; writeln("bar"); // calls std.stdio.writeln void writeln(string) {} writeln("bar"); // calls main.foo.writeln } writeln("bar"); // calls main.writeln std.stdio.writeln("bar"); // error, std is undefined } ``` Module Scope Operator --------------------- A leading `.` causes the identifier to be looked up in the module scope. ``` int x; int foo(int x) { if (y) return x; // returns foo.x, not global x else return .x; // returns global x } ``` Static Construction and Destruction ----------------------------------- Static constructors are executed to initialize a module's state. Static destructors terminate a module's state. A module may have multiple static constructors and static destructors. The static constructors are run in lexical order, the static destructors are run in reverse lexical order. Non-shared static constructors and destructors are run whenever threads are created or destroyed, including the main thread. Shared static constructors are run once before `main()` is called. Shared static destructors are run after the `main()` function returns. ``` import resource; Resource x; shared Resource y; __gshared Resource z; static this() // non-shared static constructor { x = acquireResource(); } shared static this() // shared static constructor { y = acquireSharedResource(); z = acquireSharedResource(); } static ~this() // non-shared static destructor { releaseResource(x); } shared static ~this() // shared static destructor { releaseSharedResource(y); releaseSharedResource(z); } ``` **Best Practices:** 1. Shared static constructors and destructors are used to initialize and terminate shared global data. 2. Non-shared static constructors and destructors are used to initialize and terminate thread local data. Order of Static Construction ---------------------------- Shared static constructors on all modules are run before any non-shared static constructors. The order of static initialization is implicitly determined by the *import* declarations in each module. Each module is assumed to depend on any imported modules being statically constructed first. There is no other order imposed on the execution of module static constructors. Cycles (circular dependencies) in the import declarations are allowed so long as neither, or one, but not both, of the modules, contains static constructors or static destructors. Violation of this rule will result in a runtime exception. **Implementation Defined:** 1. An implementation may provide a means of overriding the cycle detection abort. A typical method uses the D Runtime switch `--DRT-oncycle=...` where the following behaviors are supported: 1. `abort` The default behavior. The normal behavior as described in the previous section. 2. `deprecate` This works just like `abort`, but upon cycle detection the runtime will use a flawed pre-2.072 algorithm to determine if the cycle was previously detected. If no cycles are detected in the old algorithm, execution continues, but a deprecation message is printed. 3. `print` Print all cycles detected, but do not abort execution. When cycles are present, the order of static construction is implementation defined, and not guaranteed to be valid. 4. `ignore` Do not abort execution or print any cycles. When cycles are present, the order of static construction is implementation defined, and not guaranteed to be valid. **Best Practices:** 1. Avoid cyclical imports where practical. They can be an indication of poor decomposition of a program's structure into independent modules. Two modules that import each other can often be reorganized into three modules without cycles, where the third contains the declarations needed by the other two. Order of Static Construction within a Module -------------------------------------------- Within a module, static construction occurs in the lexical order in which they appear. Order of Static Destruction --------------------------- This is defined to be in exactly the reverse order of static construction. Static destructors for individual modules will only be run if the corresponding static constructor successfully completed. Shared static destructors are executed after static destructors. Order of Unit tests ------------------- Unit tests are run in the lexical order in which they appear within a module. Mixin Declaration ----------------- ``` MixinDeclaration: mixin ( ArgumentList ) ; ``` Each [*AssignExpression*](expression#AssignExpression) in the *ArgumentList* is evaluated at compile time, and the result must be representable as a string. The resulting strings are concatenated to form a string. The text contents of the string must be compilable as a valid [*DeclDefs*](#DeclDefs), and is compiled as such. Package Module -------------- A package module can be used to publicly import other modules, while providing a simpler import syntax. This enables the conversion of a module into a package of modules, without breaking existing code which uses that module. Example of a set of library modules: **libweb/client.d:** ``` module libweb.client; void runClient() { } ``` **libweb/server.d:** ``` module libweb.server; void runServer() { } ``` **libweb/package.d:** ``` module libweb; public import libweb.client; public import libweb.server; ``` The package module's file name must be `package.d`. The module name is declared to be the fully qualified name of the package. Package modules can be imported just like any other modules: **test.d:** ``` module test; // import the package module import libweb; void main() { runClient(); runServer(); } ``` A package module can be nested inside of a sub-package: **libweb/utils/package.d:** ``` // must be declared as the fully qualified name of the package, not just 'utils' module libweb.utils; // publicly import modules from within the 'libweb.utils' package. public import libweb.utils.conv; public import libweb.utils.text; ``` The package module can then be imported with the standard module import declaration: **test.d:** ``` module test; // import the package module import libweb.utils; void main() { } ``` d core.stdc.stdio core.stdc.stdio =============== D header file for C99 This module contains bindings to selected types and functions from the standard C header [`<stdio.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdio.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly, Alex Rønne Petersen Source <https://github.com/dlang/druntime/blob/master/src/core/stdc/stdio.d> Standards: ISO/IEC 9899:1999 (E) **BUFSIZ** **EOF** **FOPEN\_MAX** **FILENAME\_MAX** **TMP\_MAX** **L\_tmpnam** **SEEK\_SET** Offset is relative to the beginning **SEEK\_CUR** Offset is relative to the current position **SEEK\_END** Offset is relative to the end struct **fpos\_t**; struct **\_IO\_FILE**; alias **\_iobuf** = \_IO\_FILE; alias **FILE** = \_IO\_FILE; **\_F\_RDWR** **\_F\_READ** **\_F\_WRIT** **\_F\_BUF** **\_F\_LBUF** **\_F\_ERR** **\_F\_EOF** **\_F\_BIN** **\_F\_IN** **\_F\_OUT** **\_F\_TERM** **\_IOFBF** **\_IOLBF** **\_IONBF** shared FILE\* **stdin**; shared FILE\* **stdout**; shared FILE\* **stderr**; nothrow @nogc @system int **remove**(scope const char\* filename); nothrow @nogc @system int **rename**(scope const char\* from, scope const char\* to); nothrow @nogc @trusted FILE\* **tmpfile**(); nothrow @nogc @system char\* **tmpnam**(char\* s); nothrow @nogc @system int **fclose**(FILE\* stream); nothrow @nogc @trusted int **fflush**(FILE\* stream); nothrow @nogc @system FILE\* **fopen**(scope const char\* filename, scope const char\* mode); nothrow @nogc @system FILE\* **freopen**(scope const char\* filename, scope const char\* mode, FILE\* stream); nothrow @nogc @system void **setbuf**(FILE\* stream, char\* buf); nothrow @nogc @system int **setvbuf**(FILE\* stream, char\* buf, int mode, size\_t size); nothrow @nogc @system int **fprintf**(FILE\* stream, scope const char\* format, ...); nothrow @nogc @system int **fscanf**(FILE\* stream, scope const char\* format, ...); nothrow @nogc @system int **sprintf**(scope char\* s, scope const char\* format, ...); nothrow @nogc @system int **sscanf**(scope const char\* s, scope const char\* format, ...); nothrow @nogc @system int **vfprintf**(FILE\* stream, scope const char\* format, va\_list arg); nothrow @nogc @system int **vfscanf**(FILE\* stream, scope const char\* format, va\_list arg); nothrow @nogc @system int **vsprintf**(scope char\* s, scope const char\* format, va\_list arg); nothrow @nogc @system int **vsscanf**(scope const char\* s, scope const char\* format, va\_list arg); nothrow @nogc @system int **vprintf**(scope const char\* format, va\_list arg); nothrow @nogc @system int **vscanf**(scope const char\* format, va\_list arg); nothrow @nogc @system int **printf**(scope const char\* format, ...); nothrow @nogc @system int **scanf**(scope const char\* format, ...); nothrow @nogc @trusted int **fgetc**(FILE\* stream); nothrow @nogc @trusted int **fputc**(int c, FILE\* stream); nothrow @nogc @system char\* **fgets**(char\* s, int n, FILE\* stream); nothrow @nogc @system int **fputs**(scope const char\* s, FILE\* stream); nothrow @nogc @system char\* **gets**(char\* s); nothrow @nogc @system int **puts**(scope const char\* s); int **getchar**()(); int **putchar**()(int c); int **getc**()(FILE\* stream); int **putc**()(int c, FILE\* stream); nothrow @nogc @trusted int **ungetc**(int c, FILE\* stream); nothrow @nogc @system size\_t **fread**(scope void\* ptr, size\_t size, size\_t nmemb, FILE\* stream); nothrow @nogc @system size\_t **fwrite**(scope const void\* ptr, size\_t size, size\_t nmemb, FILE\* stream); nothrow @nogc @trusted int **fgetpos**(FILE\* stream, scope fpos\_t\* pos); nothrow @nogc @trusted int **fsetpos**(FILE\* stream, scope const fpos\_t\* pos); nothrow @nogc @trusted int **fseek**(FILE\* stream, c\_long offset, int whence); nothrow @nogc @trusted c\_long **ftell**(FILE\* stream); nothrow @nogc @trusted void **rewind**(FILE\* stream); pure nothrow @nogc @trusted void **clearerr**(FILE\* stream); pure nothrow @nogc @trusted int **feof**(FILE\* stream); pure nothrow @nogc @trusted int **ferror**(FILE\* stream); nothrow @nogc @trusted int **fileno**(FILE\*); nothrow @nogc @system int **snprintf**(scope char\* s, size\_t n, scope const char\* format, ...); nothrow @nogc @system int **vsnprintf**(scope char\* s, size\_t n, scope const char\* format, va\_list arg); nothrow @nogc @system void **perror**(scope const char\* s);
programming_docs
d std.range.interfaces std.range.interfaces ==================== This module is a submodule of [`std.range`](std_range). The main [`std.range`](std_range) module provides template-based tools for working with ranges, but sometimes an object-based interface for ranges is needed, such as when runtime polymorphism is required. For this purpose, this submodule provides a number of object and `interface` definitions that can be used to wrap around range objects created by the [`std.range`](std_range) templates. | | | | --- | --- | | [`InputRange`](#InputRange) | Wrapper for input ranges. | | [`InputAssignable`](#InputAssignable) | Wrapper for input ranges with assignable elements. | | [`ForwardRange`](#ForwardRange) | Wrapper for forward ranges. | | [`ForwardAssignable`](#ForwardAssignable) | Wrapper for forward ranges with assignable elements. | | [`BidirectionalRange`](#BidirectionalRange) | Wrapper for bidirectional ranges. | | [`BidirectionalAssignable`](#BidirectionalAssignable) | Wrapper for bidirectional ranges with assignable elements. | | [`RandomAccessFinite`](#RandomAccessFinite) | Wrapper for finite random-access ranges. | | [`RandomAccessAssignable`](#RandomAccessAssignable) | Wrapper for finite random-access ranges with assignable elements. | | [`RandomAccessInfinite`](#RandomAccessInfinite) | Wrapper for infinite random-access ranges. | | [`OutputRange`](#OutputRange) | Wrapper for output ranges. | | [`OutputRangeObject`](#OutputRangeObject) | Class that implements the `OutputRange` interface and wraps the `put` methods in virtual functions. | | [`outputRangeObject`](#outputRangeObject) | Convenience function for creating an `OutputRangeObject` with a base range of type R that accepts types E. | | [`InputRangeObject`](#InputRangeObject) | Class that implements the `InputRange` interface and wraps the input range methods in virtual functions. | | [`inputRangeObject`](#inputRangeObject) | Convenience function for creating an `InputRangeObject` of the proper type. | | [`MostDerivedInputRange`](#MostDerivedInputRange) | Returns the interface type that best matches the range. | Source [std/range/interfaces.d](https://github.com/dlang/phobos/blob/master/std/range/interfaces.d) License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: [Andrei Alexandrescu](http://erdani.com), David Simcha, and [Jonathan M Davis](http://jmdavisprog.com). Credit for some of the ideas in building this module goes to [Leonardo Maffi](http://fantascienza.net/leonardo/so/). interface **InputRange**(E); These interfaces are intended to provide virtual function-based wrappers around input ranges with element type E. This is useful where a well-defined binary interface is required, such as when a DLL function or virtual function needs to accept a generic range as a parameter. Note that [isInputRange](std_range_primitives#isInputRange) and friends check for conformance to structural interfaces not for implementation of these `interface` types. Limitations These interfaces are not capable of forwarding `ref` access to elements. Infiniteness of the wrapped range is not propagated. Length is not propagated in the case of non-random access ranges. See Also: [`inputRangeObject`](#inputRangeObject) Examples: ``` import std.algorithm.iteration : map; import std.range : iota; void useRange(InputRange!int range) { // Function body. } // Create a range type. auto squares = map!"a * a"(iota(10)); // Wrap it in an interface. auto squaresWrapped = inputRangeObject(squares); // Use it. useRange(squaresWrapped); ``` @property E **front**(); E **moveFront**(); void **popFront**(); @property bool **empty**(); int **opApply**(scope int delegate(E)); int **opApply**(scope int delegate(size\_t, E)); `foreach` iteration uses opApply, since one delegate call per loop iteration is faster than three virtual function calls. interface **ForwardRange**(E): InputRange!E; Interface for a forward range of type `E`. @property ForwardRange!E **save**(); interface **BidirectionalRange**(E): ForwardRange!E; Interface for a bidirectional range of type `E`. @property BidirectionalRange!E **save**(); @property E **back**(); E **moveBack**(); void **popBack**(); interface **RandomAccessFinite**(E): BidirectionalRange!E; Interface for a finite random access range of type `E`. @property RandomAccessFinite!E **save**(); E **opIndex**(size\_t); E **moveAt**(size\_t); @property size\_t **length**(); alias **opDollar** = length; RandomAccessFinite!E **opSlice**(size\_t, size\_t); interface **RandomAccessInfinite**(E): ForwardRange!E; Interface for an infinite random access range of type `E`. E **moveAt**(size\_t); @property RandomAccessInfinite!E **save**(); E **opIndex**(size\_t); interface **InputAssignable**(E): InputRange!E; Adds assignable elements to InputRange. @property void **front**(E newVal); interface **ForwardAssignable**(E): InputAssignable!E, ForwardRange!E; Adds assignable elements to ForwardRange. @property ForwardAssignable!E **save**(); interface **BidirectionalAssignable**(E): ForwardAssignable!E, BidirectionalRange!E; Adds assignable elements to BidirectionalRange. @property BidirectionalAssignable!E **save**(); @property void **back**(E newVal); interface **RandomFiniteAssignable**(E): RandomAccessFinite!E, BidirectionalAssignable!E; Adds assignable elements to RandomAccessFinite. @property RandomFiniteAssignable!E **save**(); void **opIndexAssign**(E val, size\_t index); interface **OutputRange**(E); Interface for an output range of type `E`. Usage is similar to the `InputRange` interface and descendants. void **put**(E); class **OutputRangeObject**(R, E...): staticMap!(OutputRange, E); Implements the `OutputRange` interface for all types E and wraps the `put` method for each type `E` in a virtual function. this(R range); template **MostDerivedInputRange**(R) if (isInputRange!(Unqual!R)) Returns the interface type that best matches `R`. template **InputRangeObject**(R) if (isInputRange!(Unqual!R)) Implements the most derived interface that `R` works with and wraps all relevant range primitives in virtual functions. If `R` is already derived from the `InputRange` interface, aliases itself away. InputRangeObject!R **inputRangeObject**(R)(R range) Constraints: if (isInputRange!R); Convenience function for creating an `InputRangeObject` of the proper type. See [`InputRange`](#InputRange) for an example. template **outputRangeObject**(E...) Convenience function for creating an `OutputRangeObject` with a base range of type `R` that accepts types `E`. Examples: ``` import std.array; auto app = appender!(uint[])(); auto appWrapped = outputRangeObject!(uint, uint[])(app); static assert(is(typeof(appWrapped) : OutputRange!(uint[]))); static assert(is(typeof(appWrapped) : OutputRange!(uint))); ``` OutputRangeObject!(R, E) **outputRangeObject**(R)(R range); d std.range std.range ========= This module defines the notion of a range. Ranges generalize the concept of arrays, lists, or anything that involves sequential access. This abstraction enables the same set of algorithms (see [`std.algorithm`](std_algorithm)) to be used with a vast variety of different concrete types. For example, a linear search algorithm such as [`std.algorithm.searching.find`](std_algorithm_searching#find) works not just for arrays, but for linked-lists, input files, incoming network data, etc. Guides There are many articles available that can bolster understanding ranges: * Ali Çehreli's [tutorial on ranges](http://ddili.org/ders/d.en/ranges.html) for the basics of working with and creating range-based code. * Jonathan M. Davis [*Introduction to Ranges*](http://dconf.org/2015/talks/davis.html) talk at DConf 2015 a vivid introduction from its core constructs to practical advice. * The DLang Tour's [chapter on ranges](http://tour.dlang.org/tour/en/basics/ranges) for an interactive introduction. * H. S. Teoh's [tutorial on component programming with ranges](http://wiki.dlang.org/Component_programming_with_ranges) for a real-world showcase of the influence of range-based programming on complex algorithms. * Andrei Alexandrescu's article [*On Iteration*](http://www.informit.com/articles/printerfriendly.aspx?p=1407357&rll=1) for conceptual aspect of ranges and the motivation Submodules This module has two submodules: The [`std.range.primitives`](std_range_primitives) submodule provides basic range functionality. It defines several templates for testing whether a given object is a range, what kind of range it is, and provides some common range operations. The [`std.range.interfaces`](std_range_interfaces) submodule provides object-based interfaces for working with ranges via runtime polymorphism. The remainder of this module provides a rich set of range creation and composition templates that let you construct new ranges out of existing ranges: | | | | --- | --- | | [`chain`](#chain) | Concatenates several ranges into a single range. | | [`choose`](#choose) | Chooses one of two ranges at runtime based on a boolean condition. | | [`chooseAmong`](#chooseAmong) | Chooses one of several ranges at runtime based on an index. | | [`chunks`](#chunks) | Creates a range that returns fixed-size chunks of the original range. | | [`cycle`](#cycle) | Creates an infinite range that repeats the given forward range indefinitely. Good for implementing circular buffers. | | [`drop`](#drop) | Creates the range that results from discarding the first *n* elements from the given range. | | [`dropBack`](#dropBack) | Creates the range that results from discarding the last *n* elements from the given range. | | [`dropExactly`](#dropExactly) | Creates the range that results from discarding exactly *n* of the first elements from the given range. | | [`dropBackExactly`](#dropBackExactly) | Creates the range that results from discarding exactly *n* of the last elements from the given range. | | [`dropOne`](#dropOne) | Creates the range that results from discarding the first element from the given range. | | `[dropBackOne](#dropBackOne)` | Creates the range that results from discarding the last element from the given range. | | [`enumerate`](#enumerate) | Iterates a range with an attached index variable. | | [`evenChunks`](#evenChunks) | Creates a range that returns a number of chunks of approximately equal length from the original range. | | [`frontTransversal`](#frontTransversal) | Creates a range that iterates over the first elements of the given ranges. | | [`generate`](#generate) | Creates a range by successive calls to a given function. This allows to create ranges as a single delegate. | | [`indexed`](#indexed) | Creates a range that offers a view of a given range as though its elements were reordered according to a given range of indices. | | [`iota`](#iota) | Creates a range consisting of numbers between a starting point and ending point, spaced apart by a given interval. | | [`lockstep`](#lockstep) | Iterates *n* ranges in lockstep, for use in a `foreach` loop. Similar to `zip`, except that `lockstep` is designed especially for `foreach` loops. | | [`nullSink`](#nullSink) | An output range that discards the data it receives. | | [`only`](#only) | Creates a range that iterates over the given arguments. | | [`padLeft`](#padLeft) | Pads a range to a specified length by adding a given element to the front of the range. Is lazy if the range has a known length. | | [`padRight`](#padRight) | Lazily pads a range to a specified length by adding a given element to the back of the range. | | [`radial`](#radial) | Given a random-access range and a starting point, creates a range that alternately returns the next left and next right element to the starting point. | | [`recurrence`](#recurrence) | Creates a forward range whose values are defined by a mathematical recurrence relation. | | [`refRange`](#refRange) | Pass a range by reference. Both the original range and the RefRange will always have the exact same elements. Any operation done on one will affect the other. | | [`repeat`](#repeat) | Creates a range that consists of a single element repeated *n* times, or an infinite range repeating that element indefinitely. | | [`retro`](#retro) | Iterates a bidirectional range backwards. | | [`roundRobin`](#roundRobin) | Given *n* ranges, creates a new range that return the *n* first elements of each range, in turn, then the second element of each range, and so on, in a round-robin fashion. | | [`sequence`](#sequence) | Similar to `recurrence`, except that a random-access range is created. | | `[slide](#slide)` | Creates a range that returns a fixed-size sliding window over the original range. Unlike chunks, it advances a configurable number of items at a time, not one chunk at a time. | | [`stride`](#stride) | Iterates a range with stride *n*. | | [`tail`](#tail) | Return a range advanced to within `n` elements of the end of the given range. | | [`take`](#take) | Creates a sub-range consisting of only up to the first *n* elements of the given range. | | [`takeExactly`](#takeExactly) | Like `take`, but assumes the given range actually has *n* elements, and therefore also defines the `length` property. | | [`takeNone`](#takeNone) | Creates a random-access range consisting of zero elements of the given range. | | [`takeOne`](#takeOne) | Creates a random-access range consisting of exactly the first element of the given range. | | [`tee`](#tee) | Creates a range that wraps a given range, forwarding along its elements while also calling a provided function with each element. | | [`transposed`](#transposed) | Transposes a range of ranges. | | [`transversal`](#transversal) | Creates a range that iterates over the *n*'th elements of the given random-access ranges. | | [`zip`](#zip) | Given *n* ranges, creates a range that successively returns a tuple of all the first elements, a tuple of all the second elements, etc. | Sortedness Ranges whose elements are sorted afford better efficiency with certain operations. For this, the [`assumeSorted`](#assumeSorted) function can be used to construct a [`SortedRange`](#SortedRange) from a pre-sorted range. The [`std.algorithm.sorting.sort`](std_algorithm_sorting#sort) function also conveniently returns a [`SortedRange`](#SortedRange). [`SortedRange`](#SortedRange) objects provide some additional range operations that take advantage of the fact that the range is sorted. Source [std/range/package.d](https://github.com/dlang/phobos/blob/master/std/range/package.d) License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: [Andrei Alexandrescu](http://erdani.com), David Simcha, [Jonathan M Davis](http://jmdavisprog.com), and Jack Stouffer. Credit for some of the ideas in building this module goes to [Leonardo Maffi](http://fantascienza.net/leonardo/so/). auto **retro**(Range)(Range r) Constraints: if (isBidirectionalRange!(Unqual!Range)); Iterates a bidirectional range backwards. The original range can be accessed by using the `source` property. Applying retro twice to the same range yields the original range. Parameters: | | | | --- | --- | | Range `r` | the bidirectional range to iterate backwards | Returns: A bidirectional range with length if `r` also provides a length. Or, if `r` is a random access range, then the return value will be random access as well. See Also: [`std.algorithm.mutation.reverse`](std_algorithm_mutation#reverse) for mutating the source range directly. Examples: ``` import std.algorithm.comparison : equal; int[5] a = [ 1, 2, 3, 4, 5 ]; int[5] b = [ 5, 4, 3, 2, 1 ]; assert(equal(retro(a[]), b[])); assert(retro(a[]).source is a[]); assert(retro(retro(a[])) is a[]); ``` auto **stride**(Range)(Range r, size\_t n) Constraints: if (isInputRange!(Unqual!Range)); Iterates range `r` with stride `n`. If the range is a random-access range, moves by indexing into the range; otherwise, moves by successive calls to `popFront`. Applying stride twice to the same range results in a stride with a step that is the product of the two applications. It is an error for `n` to be 0. Parameters: | | | | --- | --- | | Range `r` | the [input range](std_range_primitives#isInputRange) to stride over | | size\_t `n` | the number of elements to skip over | Returns: At minimum, an input range. The resulting range will adopt the range primitives of the underlying range as long as [`std.range.primitives.hasLength`](std_range_primitives#hasLength) is `true`. Examples: ``` import std.algorithm.comparison : equal; int[] a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]; assert(equal(stride(a, 3), [ 1, 4, 7, 10 ][])); writeln(stride(stride(a, 2), 3)); // stride(a, 6) ``` auto **chain**(Ranges...)(Ranges rs) Constraints: if (Ranges.length > 0 && allSatisfy!(isInputRange, staticMap!(Unqual, Ranges)) && !is(CommonType!(staticMap!(ElementType, staticMap!(Unqual, Ranges))) == void)); Spans multiple ranges in sequence. The function `chain` takes any number of ranges and returns a `Chain!(R1, R2,...)` object. The ranges may be different, but they must have the same element type. The result is a range that offers the `front`, `popFront`, and `empty` primitives. If all input ranges offer random access and `length`, `Chain` offers them as well. If only one range is offered to `Chain` or `chain`, the `Chain` type exits the picture by aliasing itself directly to that range's type. Parameters: | | | | --- | --- | | Ranges `rs` | the [input ranges](std_range_primitives#isInputRange) to chain together | Returns: An input range at minimum. If all of the ranges in `rs` provide a range primitive, the returned range will also provide that range primitive. See Also: [`only`](#only) to chain values to a range Examples: ``` import std.algorithm.comparison : equal; int[] arr1 = [ 1, 2, 3, 4 ]; int[] arr2 = [ 5, 6 ]; int[] arr3 = [ 7 ]; auto s = chain(arr1, arr2, arr3); writeln(s.length); // 7 writeln(s[5]); // 6 assert(equal(s, [1, 2, 3, 4, 5, 6, 7][])); ``` Examples: Range primitives are carried over to the returned range if all of the ranges provide them ``` import std.algorithm.comparison : equal; import std.algorithm.sorting : sort; int[] arr1 = [5, 2, 8]; int[] arr2 = [3, 7, 9]; int[] arr3 = [1, 4, 6]; // in-place sorting across all of the arrays auto s = arr1.chain(arr2, arr3).sort; assert(s.equal([1, 2, 3, 4, 5, 6, 7, 8, 9])); assert(arr1.equal([1, 2, 3])); assert(arr2.equal([4, 5, 6])); assert(arr3.equal([7, 8, 9])); ``` Examples: Due to safe type promotion in D, chaining together different character ranges results in a `uint` range. Use [byChar](std_utf#byChar), [byWchar](std_utf#byWchar), and [byDchar](std_utf#byDchar) on the ranges to get the type you need. ``` import std.utf : byChar, byCodeUnit; auto s1 = "string one"; auto s2 = "string two"; // s1 and s2 front is dchar because of auto-decoding static assert(is(typeof(s1.front) == dchar) && is(typeof(s2.front) == dchar)); auto r1 = s1.chain(s2); // chains of ranges of the same character type give that same type static assert(is(typeof(r1.front) == dchar)); auto s3 = "string three".byCodeUnit; static assert(is(typeof(s3.front) == immutable char)); auto r2 = s1.chain(s3); // chaining ranges of mixed character types gives `dchar` static assert(is(typeof(r2.front) == dchar)); // use byChar on character ranges to correctly convert them to UTF-8 auto r3 = s1.byChar.chain(s3); static assert(is(typeof(r3.front) == immutable char)); ``` auto **choose**(R1, R2)(bool condition, return scope R1 r1, return scope R2 r2) Constraints: if (isInputRange!(Unqual!R1) && isInputRange!(Unqual!R2) && !is(CommonType!(ElementType!(Unqual!R1), ElementType!(Unqual!R2)) == void)); Choose one of two ranges at runtime depending on a Boolean condition. The ranges may be different, but they must have compatible element types (i.e. `CommonType` must exist for the two element types). The result is a range that offers the weakest capabilities of the two (e.g. `ForwardRange` if `R1` is a random-access range and `R2` is a forward range). Parameters: | | | | --- | --- | | bool `condition` | which range to choose: `r1` if `true`, `r2` otherwise | | R1 `r1` | the "true" range | | R2 `r2` | the "false" range | Returns: A range type dependent on `R1` and `R2`. Examples: ``` import std.algorithm.comparison : equal; import std.algorithm.iteration : filter, map; auto data1 = only(1, 2, 3, 4).filter!(a => a != 3); auto data2 = only(5, 6, 7, 8).map!(a => a + 1); // choose() is primarily useful when you need to select one of two ranges // with different types at runtime. static assert(!is(typeof(data1) == typeof(data2))); auto chooseRange(bool pickFirst) { // The returned range is a common wrapper type that can be used for // returning or storing either range without running into a type error. return choose(pickFirst, data1, data2); // Simply returning the chosen range without using choose() does not // work, because map() and filter() return different types. //return pickFirst ? data1 : data2; // does not compile } auto result = chooseRange(true); assert(result.equal(only(1, 2, 4))); result = chooseRange(false); assert(result.equal(only(6, 7, 8, 9))); ``` auto **chooseAmong**(Ranges...)(size\_t index, return scope Ranges rs) Constraints: if (Ranges.length >= 2 && allSatisfy!(isInputRange, staticMap!(Unqual, Ranges)) && !is(CommonType!(staticMap!(ElementType, Ranges)) == void)); Choose one of multiple ranges at runtime. The ranges may be different, but they must have compatible element types. The result is a range that offers the weakest capabilities of all `Ranges`. Parameters: | | | | --- | --- | | size\_t `index` | which range to choose, must be less than the number of ranges | | Ranges `rs` | two or more ranges | Returns: The indexed range. If rs consists of only one range, the return type is an alias of that range's type. Examples: ``` auto test() { import std.algorithm.comparison : equal; int[4] sarr1 = [1, 2, 3, 4]; int[2] sarr2 = [5, 6]; int[1] sarr3 = [7]; auto arr1 = sarr1[]; auto arr2 = sarr2[]; auto arr3 = sarr3[]; { auto s = chooseAmong(0, arr1, arr2, arr3); auto t = s.save; writeln(s.length); // 4 writeln(s[2]); // 3 s.popFront(); assert(equal(t, only(1, 2, 3, 4))); } { auto s = chooseAmong(1, arr1, arr2, arr3); writeln(s.length); // 2 s.front = 8; assert(equal(s, only(8, 6))); } { auto s = chooseAmong(1, arr1, arr2, arr3); writeln(s.length); // 2 s[1] = 9; assert(equal(s, only(8, 9))); } { auto s = chooseAmong(1, arr2, arr1, arr3)[1 .. 3]; writeln(s.length); // 2 assert(equal(s, only(2, 3))); } { auto s = chooseAmong(0, arr1, arr2, arr3); writeln(s.length); // 4 writeln(s.back); // 4 s.popBack(); s.back = 5; assert(equal(s, only(1, 2, 5))); s.back = 3; assert(equal(s, only(1, 2, 3))); } { uint[5] foo = [1, 2, 3, 4, 5]; uint[5] bar = [6, 7, 8, 9, 10]; auto c = chooseAmong(1, foo[], bar[]); writeln(c[3]); // 9 c[3] = 42; writeln(c[3]); // 42 writeln(c.moveFront()); // 6 writeln(c.moveBack()); // 10 writeln(c.moveAt(4)); // 10 } { import std.range : cycle; auto s = chooseAmong(0, cycle(arr2), cycle(arr3)); assert(isInfinite!(typeof(s))); assert(!s.empty); writeln(s[100]); // 8 writeln(s[101]); // 9 assert(s[0 .. 3].equal(only(8, 9, 8))); } return 0; } // works at runtime auto a = test(); // and at compile time static b = test(); ``` auto **roundRobin**(Rs...)(Rs rs) Constraints: if (Rs.length > 1 && allSatisfy!(isInputRange, staticMap!(Unqual, Rs))); `roundRobin(r1, r2, r3)` yields `r1.front`, then `r2.front`, then `r3.front`, after which it pops off one element from each and continues again from `r1`. For example, if two ranges are involved, it alternately yields elements off the two ranges. `roundRobin` stops after it has consumed all ranges (skipping over the ones that finish early). Examples: ``` import std.algorithm.comparison : equal; int[] a = [ 1, 2, 3 ]; int[] b = [ 10, 20, 30, 40 ]; auto r = roundRobin(a, b); assert(equal(r, [ 1, 10, 2, 20, 3, 30, 40 ])); ``` Examples: roundRobin can be used to create "interleave" functionality which inserts an element between each element in a range. ``` import std.algorithm.comparison : equal; auto interleave(R, E)(R range, E element) if ((isInputRange!R && hasLength!R) || isForwardRange!R) { static if (hasLength!R) immutable len = range.length; else immutable len = range.save.walkLength; return roundRobin( range, element.repeat(len - 1) ); } assert(interleave([1, 2, 3], 0).equal([1, 0, 2, 0, 3])); ``` auto **radial**(Range, I)(Range r, I startingIndex) Constraints: if (isRandomAccessRange!(Unqual!Range) && hasLength!(Unqual!Range) && hasSlicing!(Unqual!Range) && isIntegral!I); auto **radial**(R)(R r) Constraints: if (isRandomAccessRange!(Unqual!R) && hasLength!(Unqual!R) && hasSlicing!(Unqual!R)); Iterates a random-access range starting from a given point and progressively extending left and right from that point. If no initial point is given, iteration starts from the middle of the range. Iteration spans the entire range. When `startingIndex` is 0 the range will be fully iterated in order and in reverse order when `r.length` is given. Parameters: | | | | --- | --- | | Range `r` | a random access range with length and slicing | | I `startingIndex` | the index to begin iteration from | Returns: A forward range with length Examples: ``` import std.algorithm.comparison : equal; int[] a = [ 1, 2, 3, 4, 5 ]; assert(equal(radial(a), [ 3, 4, 2, 5, 1 ])); a = [ 1, 2, 3, 4 ]; assert(equal(radial(a), [ 2, 3, 1, 4 ])); // If the left end is reached first, the remaining elements on the right // are concatenated in order: a = [ 0, 1, 2, 3, 4, 5 ]; assert(equal(radial(a, 1), [ 1, 2, 0, 3, 4, 5 ])); // If the right end is reached first, the remaining elements on the left // are concatenated in reverse order: assert(equal(radial(a, 4), [ 4, 5, 3, 2, 1, 0 ])); ``` Take!R **take**(R)(R input, size\_t n) Constraints: if (isInputRange!(Unqual!R)); struct **Take**(Range) if (isInputRange!(Unqual!Range) && !(!isInfinite!(Unqual!Range) && hasSlicing!(Unqual!Range) || is(Range T == **Take**!T))); template **Take**(R) if (isInputRange!(Unqual!R) && (!isInfinite!(Unqual!R) && hasSlicing!(Unqual!R) || is(R T == **Take**!T))) Lazily takes only up to `n` elements of a range. This is particularly useful when using with infinite ranges. Unlike [`takeExactly`](#takeExactly), `take` does not require that there are `n` or more elements in `input`. As a consequence, length information is not applied to the result unless `input` also has length information. Parameters: | | | | --- | --- | | R `input` | an [input range](std_range_primitives#isInputRange) to iterate over up to `n` times | | size\_t `n` | the number of elements to take | Returns: At minimum, an input range. If the range offers random access and `length`, `take` offers them as well. Examples: ``` import std.algorithm.comparison : equal; int[] arr1 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; auto s = take(arr1, 5); writeln(s.length); // 5 writeln(s[4]); // 5 assert(equal(s, [ 1, 2, 3, 4, 5 ][])); ``` Examples: If the range runs out before `n` elements, `take` simply returns the entire range (unlike [`takeExactly`](#takeExactly), which will cause an assertion failure if the range ends prematurely): ``` import std.algorithm.comparison : equal; int[] arr2 = [ 1, 2, 3 ]; auto t = take(arr2, 5); writeln(t.length); // 3 assert(equal(t, [ 1, 2, 3 ])); ``` auto **takeExactly**(R)(R range, size\_t n) Constraints: if (isInputRange!R); Similar to [`take`](#take), but assumes that `range` has at least `n` elements. Consequently, the result of `takeExactly(range, n)` always defines the `length` property (and initializes it to `n`) even when `range` itself does not define `length`. The result of `takeExactly` is identical to that of [`take`](#take) in cases where the original range defines `length` or is infinite. Unlike [`take`](#take), however, it is illegal to pass a range with less than `n` elements to `takeExactly`; this will cause an assertion failure. Examples: ``` import std.algorithm.comparison : equal; auto a = [ 1, 2, 3, 4, 5 ]; auto b = takeExactly(a, 3); assert(equal(b, [1, 2, 3])); static assert(is(typeof(b.length) == size_t)); writeln(b.length); // 3 writeln(b.front); // 1 writeln(b.back); // 3 ``` auto **takeOne**(R)(R source) Constraints: if (isInputRange!R); Returns a range with at most one element; for example, `takeOne([42, 43, 44])` returns a range consisting of the integer `42`. Calling `popFront()` off that range renders it empty. In effect `takeOne(r)` is somewhat equivalent to `take(r, 1)` but in certain interfaces it is important to know statically that the range may only have at most one element. The type returned by `takeOne` is a random-access range with length regardless of `R`'s capabilities, as long as it is a forward range. (another feature that distinguishes `takeOne` from `take`). If (D R) is an input range but not a forward range, return type is an input range with all random-access capabilities except save. Examples: ``` auto s = takeOne([42, 43, 44]); static assert(isRandomAccessRange!(typeof(s))); writeln(s.length); // 1 assert(!s.empty); writeln(s.front); // 42 s.front = 43; writeln(s.front); // 43 writeln(s.back); // 43 writeln(s[0]); // 43 s.popFront(); writeln(s.length); // 0 assert(s.empty); ``` auto **takeNone**(R)() Constraints: if (isInputRange!R); Returns an empty range which is statically known to be empty and is guaranteed to have `length` and be random access regardless of `R`'s capabilities. Examples: ``` auto range = takeNone!(int[])(); writeln(range.length); // 0 assert(range.empty); ``` auto **takeNone**(R)(R range) Constraints: if (isInputRange!R); Creates an empty range from the given range in Ο(`1`). If it can, it will return the same range type. If not, it will return `takeExactly(range, 0)`. Examples: ``` import std.algorithm.iteration : filter; assert(takeNone([42, 27, 19]).empty); assert(takeNone("dlang.org").empty); assert(takeNone(filter!"true"([42, 27, 19])).empty); ``` auto **tail**(Range)(Range range, size\_t n) Constraints: if (isInputRange!Range && !isInfinite!Range && (hasLength!Range || isForwardRange!Range)); Return a range advanced to within `_n` elements of the end of `range`. Intended as the range equivalent of the Unix [tail](http://en.wikipedia.org/wiki/Tail_%28Unix%29) utility. When the length of `range` is less than or equal to `_n`, `range` is returned as-is. Completes in Ο(`1`) steps for ranges that support slicing and have length. Completes in Ο(`range.length`) time for all other ranges. Parameters: | | | | --- | --- | | Range `range` | range to get tail of | | size\_t `n` | maximum number of elements to include in tail | Returns: Returns the tail of `range` augmented with length information Examples: ``` // tail -c n writeln([1, 2, 3].tail(1)); // [3] writeln([1, 2, 3].tail(2)); // [2, 3] writeln([1, 2, 3].tail(3)); // [1, 2, 3] writeln([1, 2, 3].tail(4)); // [1, 2, 3] writeln([1, 2, 3].tail(0).length); // 0 // tail --lines=n import std.algorithm.comparison : equal; import std.algorithm.iteration : joiner; import std.exception : assumeWontThrow; import std.string : lineSplitter; assert("one\ntwo\nthree" .lineSplitter .tail(2) .joiner("\n") .equal("two\nthree") .assumeWontThrow); ``` R **drop**(R)(R range, size\_t n) Constraints: if (isInputRange!R); R **dropBack**(R)(R range, size\_t n) Constraints: if (isBidirectionalRange!R); Convenience function which calls [`std.range.primitives.popFrontN`](std_range_primitives#popFrontN)`(range, n)` and returns `range`. `drop` makes it easier to pop elements from a range and then pass it to another function within a single expression, whereas `popFrontN` would require multiple statements. `dropBack` provides the same functionality but instead calls [`std.range.primitives.popBackN`](std_range_primitives#popBackN)`(range, n)` Note `drop` and `dropBack` will only pop *up to* `n` elements but will stop if the range is empty first. In other languages this is sometimes called `skip`. Parameters: | | | | --- | --- | | R `range` | the [input range](std_range_primitives#isInputRange) to drop from | | size\_t `n` | the number of elements to drop | Returns: `range` with up to `n` elements dropped See Also: [`std.range.primitives.popFront`](std_range_primitives#popFront), [`std.range.primitives.popBackN`](std_range_primitives#popBackN) Examples: ``` import std.algorithm.comparison : equal; writeln([0, 2, 1, 5, 0, 3].drop(3)); // [5, 0, 3] writeln("hello world".drop(6)); // "world" assert("hello world".drop(50).empty); assert("hello world".take(6).drop(3).equal("lo ")); ``` Examples: ``` import std.algorithm.comparison : equal; writeln([0, 2, 1, 5, 0, 3].dropBack(3)); // [0, 2, 1] writeln("hello world".dropBack(6)); // "hello" assert("hello world".dropBack(50).empty); assert("hello world".drop(4).dropBack(4).equal("o w")); ``` R **dropExactly**(R)(R range, size\_t n) Constraints: if (isInputRange!R); R **dropBackExactly**(R)(R range, size\_t n) Constraints: if (isBidirectionalRange!R); Similar to [`drop`](#drop) and `dropBack` but they call `range.[popFrontExactly](#popFrontExactly)(n)` and `range.popBackExactly(n)` instead. Note Unlike `drop`, `dropExactly` will assume that the range holds at least `n` elements. This makes `dropExactly` faster than `drop`, but it also means that if `range` does not contain at least `n` elements, it will attempt to call `popFront` on an empty range, which is undefined behavior. So, only use `popFrontExactly` when it is guaranteed that `range` holds at least `n` elements. Parameters: | | | | --- | --- | | R `range` | the [input range](std_range_primitives#isInputRange) to drop from | | size\_t `n` | the number of elements to drop | Returns: `range` with `n` elements dropped See Also: [`std.range.primitives.popFrontExcatly`](std_range_primitives#popFrontExcatly), [`std.range.primitives.popBackExcatly`](std_range_primitives#popBackExcatly) Examples: ``` import std.algorithm.comparison : equal; import std.algorithm.iteration : filterBidirectional; auto a = [1, 2, 3]; writeln(a.dropExactly(2)); // [3] writeln(a.dropBackExactly(2)); // [1] string s = "日本語"; writeln(s.dropExactly(2)); // "語" writeln(s.dropBackExactly(2)); // "日" auto bd = filterBidirectional!"true"([1, 2, 3]); assert(bd.dropExactly(2).equal([3])); assert(bd.dropBackExactly(2).equal([1])); ``` R **dropOne**(R)(R range) Constraints: if (isInputRange!R); R **dropBackOne**(R)(R range) Constraints: if (isBidirectionalRange!R); Convenience function which calls `range.popFront()` and returns `range`. `dropOne` makes it easier to pop an element from a range and then pass it to another function within a single expression, whereas `popFront` would require multiple statements. `dropBackOne` provides the same functionality but instead calls `range.popBack()`. Examples: ``` import std.algorithm.comparison : equal; import std.algorithm.iteration : filterBidirectional; import std.container.dlist : DList; auto dl = DList!int(9, 1, 2, 3, 9); assert(dl[].dropOne().dropBackOne().equal([1, 2, 3])); auto a = [1, 2, 3]; writeln(a.dropOne()); // [2, 3] writeln(a.dropBackOne()); // [1, 2] string s = "日本語"; import std.exception : assumeWontThrow; assert(assumeWontThrow(s.dropOne() == "本語")); assert(assumeWontThrow(s.dropBackOne() == "日本")); auto bd = filterBidirectional!"true"([1, 2, 3]); assert(bd.dropOne().equal([2, 3])); assert(bd.dropBackOne().equal([1, 2])); ``` struct **Repeat**(T); Repeat!T **repeat**(T)(T value); Take!(Repeat!T) **repeat**(T)(T value, size\_t n); Create a range which repeats one value. Parameters: | | | | --- | --- | | T `value` | the value to repeat | | size\_t `n` | the number of times to repeat `value` | Returns: If `n` is not defined, an infinite random access range with slicing. If `n` is defined, a random access range with slicing. Examples: ``` import std.algorithm.comparison : equal; assert(5.repeat().take(4).equal([5, 5, 5, 5])); ``` Examples: ``` import std.algorithm.comparison : equal; assert(5.repeat(4).equal([5, 5, 5, 5])); ``` inout @property inout(T) **front**(); inout @property inout(T) **back**(); enum bool **empty**; void **popFront**(); void **popBack**(); inout @property auto **save**(); inout inout(T) **opIndex**(size\_t); auto **opSlice**(size\_t i, size\_t j); enum auto **opDollar**; inout auto **opSlice**(size\_t, DollarToken); Range primitives auto **generate**(Fun)(Fun fun) Constraints: if (isCallable!fun); auto **generate**(alias fun)() Constraints: if (isCallable!fun); Given callable ([`std.traits.isCallable`](std_traits#isCallable)) `fun`, create as a range whose front is defined by successive calls to `fun()`. This is especially useful to call function with global side effects (random functions), or to create ranges expressed as a single delegate, rather than an entire `front`/`popFront`/`empty` structure. `fun` maybe be passed either a template alias parameter (existing function, delegate, struct type defining `static opCall`) or a run-time value argument (delegate, function object). The result range models an InputRange ([`std.range.primitives.isInputRange`](std_range_primitives#isInputRange)). The resulting range will call `fun()` on construction, and every call to `popFront`, and the cached value will be returned when `front` is called. Returns: an `inputRange` where each element represents another call to fun. Examples: ``` import std.algorithm.comparison : equal; import std.algorithm.iteration : map; int i = 1; auto powersOfTwo = generate!(() => i *= 2)().take(10); assert(equal(powersOfTwo, iota(1, 11).map!"2^^a"())); ``` Examples: ``` import std.algorithm.comparison : equal; //Returns a run-time delegate auto infiniteIota(T)(T low, T high) { T i = high; return (){if (i == high) i = low; return i++;}; } //adapted as a range. assert(equal(generate(infiniteIota(1, 4)).take(10), [1, 2, 3, 1, 2, 3, 1, 2, 3, 1])); ``` Examples: ``` import std.format : format; import std.random : uniform; auto r = generate!(() => uniform(0, 6)).take(10); format("%(%s %)", r); ``` struct **Cycle**(R) if (isForwardRange!R && !isInfinite!R); template **Cycle**(R) if (isInfinite!R) struct **Cycle**(R) if (isStaticArray!R); auto **cycle**(R)(R input) Constraints: if (isInputRange!R); Cycle!R **cycle**(R)(R input, size\_t index = 0) Constraints: if (isRandomAccessRange!R && !isInfinite!R); @system Cycle!R **cycle**(R)(ref R input, size\_t index = 0) Constraints: if (isStaticArray!R); Repeats the given forward range ad infinitum. If the original range is infinite (fact that would make `Cycle` the identity application), `Cycle` detects that and aliases itself to the range type itself. That works for non-forward ranges too. If the original range has random access, `Cycle` offers random access and also offers a constructor taking an initial position `index`. `Cycle` works with static arrays in addition to ranges, mostly for performance reasons. Note The input range must not be empty. Tip This is a great way to implement simple circular buffers. Examples: ``` import std.algorithm.comparison : equal; import std.range : cycle, take; // Here we create an infinitive cyclic sequence from [1, 2] // (i.e. get here [1, 2, 1, 2, 1, 2 and so on]) then // take 5 elements of this sequence (so we have [1, 2, 1, 2, 1]) // and compare them with the expected values for equality. assert(cycle([1, 2]).take(5).equal([ 1, 2, 1, 2, 1 ])); ``` this(R input, size\_t index = 0); @property ref auto **front**(); const @property ref auto **front**(); @property void **front**(ElementType!R val); enum bool **empty**; void **popFront**(); ref auto **opIndex**(size\_t n); const ref auto **opIndex**(size\_t n); void **opIndexAssign**(ElementType!R val, size\_t n); @property Cycle **save**(); enum auto **opDollar**; auto **opSlice**(size\_t i, size\_t j); auto **opSlice**(size\_t i, DollarToken); Range primitives struct **Zip**(Ranges...) if (Ranges.length && allSatisfy!(isInputRange, Ranges)); auto **zip**(Ranges...)(Ranges ranges) Constraints: if (Ranges.length && allSatisfy!(isInputRange, Ranges)); auto **zip**(Ranges...)(StoppingPolicy sp, Ranges ranges) Constraints: if (Ranges.length && allSatisfy!(isInputRange, Ranges)); Iterate several ranges in lockstep. The element type is a proxy tuple that allows accessing the current element in the `n`th range by using `e[n]`. `zip` is similar to [`lockstep`](#lockstep), but `lockstep` doesn't bundle its elements and uses the `opApply` protocol. `lockstep` allows reference access to the elements in `foreach` iterations. Parameters: | | | | --- | --- | | StoppingPolicy `sp` | controls what `zip` will do if the ranges are different lengths | | Ranges `ranges` | the ranges to zip together | Returns: At minimum, an input range. `Zip` offers the lowest range facilities of all components, e.g. it offers random access iff all ranges offer random access, and also offers mutation and swapping if all ranges offer it. Due to this, `Zip` is extremely powerful because it allows manipulating several ranges in lockstep. Throws: An `Exception` if all of the ranges are not the same length and `sp` is set to `StoppingPolicy.requireSameLength`. Limitations The `@nogc` and `nothrow` attributes cannot be inferred for the `Zip` struct because [`StoppingPolicy`](#StoppingPolicy) can vary at runtime. This limitation is not shared by the anonymous range returned by the `zip` function when not given an explicit `StoppingPolicy` as an argument. Examples: ``` import std.algorithm.comparison : equal; import std.algorithm.iteration : map; // pairwise sum auto arr = only(0, 1, 2); auto part1 = zip(arr, arr.dropOne).map!"a[0] + a[1]"; assert(part1.equal(only(1, 3))); ``` Examples: ``` import std.conv : to; int[] a = [ 1, 2, 3 ]; string[] b = [ "a", "b", "c" ]; string[] result; foreach (tup; zip(a, b)) { result ~= tup[0].to!string ~ tup[1]; } writeln(result); // ["1a", "2b", "3c"] size_t idx = 0; // unpacking tuple elements with foreach foreach (e1, e2; zip(a, b)) { writeln(e1); // a[idx] writeln(e2); // b[idx] ++idx; } ``` Examples: `zip` is powerful - the following code sorts two arrays in parallel: ``` import std.algorithm.sorting : sort; int[] a = [ 1, 2, 3 ]; string[] b = [ "a", "c", "b" ]; zip(a, b).sort!((t1, t2) => t1[0] > t2[0]); writeln(a); // [3, 2, 1] // b is sorted according to a's sorting writeln(b); // ["b", "c", "a"] ``` this(R rs, StoppingPolicy s = StoppingPolicy.shortest); Builds an object. Usually this is invoked indirectly by using the [`zip`](#zip) function. enum bool **empty**; Returns `true` if the range is at end. The test depends on the stopping policy. @property Zip **save**(); @property ElementType **front**(); Returns the current iterated element. @property void **front**(ElementType v); Sets the front of all iterated ranges. ElementType **moveFront**(); Moves out the front. @property ElementType **back**(); Returns the rightmost element. ElementType **moveBack**(); Moves out the back. Returns the rightmost element. @property void **back**(ElementType v); Returns the current iterated element. Returns the rightmost element. void **popFront**(); Advances to the next element in all controlled ranges. void **popBack**(); Calls `popBack` for all controlled ranges. @property auto **length**(); Returns the length of this range. Defined only if all ranges define `length`. alias **opDollar** = length; Returns the length of this range. Defined only if all ranges define `length`. auto **opSlice**(size\_t from, size\_t to); Returns a slice of the range. Defined only if all range define slicing. ElementType **opIndex**(size\_t n); Returns the `n`th element in the composite range. Defined if all ranges offer random access. void **opIndexAssign**(ElementType v, size\_t n); Assigns to the `n`th element in the composite range. Defined if all ranges offer random access. Returns the `n`th element in the composite range. Defined if all ranges offer random access. ElementType **moveAt**(size\_t n); Destructively reads the `n`th element in the composite range. Defined if all ranges offer random access. Returns the `n`th element in the composite range. Defined if all ranges offer random access. enum **StoppingPolicy**: int; Dictates how iteration in a [`zip`](#zip) and [`lockstep`](#lockstep) should stop. By default stop at the end of the shortest of all ranges. Examples: ``` import std.algorithm.comparison : equal; import std.exception : assertThrown; import std.range.primitives; import std.typecons : tuple; auto a = [1, 2, 3]; auto b = [4, 5, 6, 7]; auto shortest = zip(StoppingPolicy.shortest, a, b); assert(shortest.equal([ tuple(1, 4), tuple(2, 5), tuple(3, 6) ])); auto longest = zip(StoppingPolicy.longest, a, b); assert(longest.equal([ tuple(1, 4), tuple(2, 5), tuple(3, 6), tuple(0, 7) ])); auto same = zip(StoppingPolicy.requireSameLength, a, b); same.popFrontN(3); assertThrown!Exception(same.popFront); ``` **shortest** Stop when the shortest range is exhausted **longest** Stop when the longest range is exhausted **requireSameLength** Require that all ranges are equal struct **Lockstep**(Ranges...) if (Ranges.length > 1 && allSatisfy!(isInputRange, Ranges)); Lockstep!Ranges **lockstep**(Ranges...)(Ranges ranges) Constraints: if (allSatisfy!(isInputRange, Ranges)); Lockstep!Ranges **lockstep**(Ranges...)(Ranges ranges, StoppingPolicy s) Constraints: if (allSatisfy!(isInputRange, Ranges)); Iterate multiple ranges in lockstep using a `foreach` loop. In contrast to [`zip`](#zip) it allows reference access to its elements. If only a single range is passed in, the `Lockstep` aliases itself away. If the ranges are of different lengths and `s` == `StoppingPolicy.shortest` stop after the shortest range is empty. If the ranges are of different lengths and `s` == `StoppingPolicy.requireSameLength`, throw an exception. `s` may not be `StoppingPolicy.longest`, and passing this will throw an exception. Iterating over `Lockstep` in reverse and with an index is only possible when `s` == `StoppingPolicy.requireSameLength`, in order to preserve indexes. If an attempt is made at iterating in reverse when `s` == `StoppingPolicy.shortest`, an exception will be thrown. By default `StoppingPolicy` is set to `StoppingPolicy.shortest`. Limitations The `pure`, `@safe`, `@nogc`, or `nothrow` attributes cannot be inferred for `lockstep` iteration. [`zip`](#zip) can infer the first two due to a different implementation. See Also: [`zip`](#zip) `lockstep` is similar to [`zip`](#zip), but `zip` bundles its elements and returns a range. `lockstep` also supports reference access. Use `zip` if you want to pass the result to a range function. Examples: ``` auto arr1 = [1,2,3,4,5,100]; auto arr2 = [6,7,8,9,10]; foreach (ref a, b; lockstep(arr1, arr2)) { a += b; } writeln(arr1); // [7, 9, 11, 13, 15, 100] /// Lockstep also supports iterating with an index variable: foreach (index, a, b; lockstep(arr1, arr2)) { writeln(arr1[index]); // a writeln(arr2[index]); // b } ``` this(R ranges, StoppingPolicy sp = StoppingPolicy.shortest); struct **Recurrence**(alias fun, StateType, size\_t stateSize); Recurrence!(fun, CommonType!State, State.length) **recurrence**(alias fun, State...)(State initial); Creates a mathematical sequence given the initial values and a recurrence function that computes the next value from the existing values. The sequence comes in the form of an infinite forward range. The type `Recurrence` itself is seldom used directly; most often, recurrences are obtained by calling the function `recurrence`. When calling `recurrence`, the function that computes the next value is specified as a template argument, and the initial values in the recurrence are passed as regular arguments. For example, in a Fibonacci sequence, there are two initial values (and therefore a state size of 2) because computing the next Fibonacci value needs the past two values. The signature of this function should be: ``` auto fun(R)(R state, size_t n) ``` where `n` will be the index of the current value, and `state` will be an opaque state vector that can be indexed with array-indexing notation `state[i]`, where valid values of `i` range from `(n - 1)` to `(n - State.length)`. If the function is passed in string form, the state has name `"a"` and the zero-based index in the recurrence has name `"n"`. The given string must return the desired value for `a[n]` given `a[n - 1]`, `a[n - 2]`, `a[n - 3]`,..., `a[n - stateSize]`. The state size is dictated by the number of arguments passed to the call to `recurrence`. The `Recurrence` struct itself takes care of managing the recurrence's state and shifting it appropriately. Examples: ``` import std.algorithm.comparison : equal; // The Fibonacci numbers, using function in string form: // a[0] = 1, a[1] = 1, and compute a[n+1] = a[n-1] + a[n] auto fib = recurrence!("a[n-1] + a[n-2]")(1, 1); assert(fib.take(10).equal([1, 1, 2, 3, 5, 8, 13, 21, 34, 55])); // The factorials, using function in lambda form: auto fac = recurrence!((a,n) => a[n-1] * n)(1); assert(take(fac, 10).equal([ 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 ])); // The triangular numbers, using function in explicit form: static size_t genTriangular(R)(R state, size_t n) { return state[n-1] + n; } auto tri = recurrence!genTriangular(0); assert(take(tri, 10).equal([0, 1, 3, 6, 10, 15, 21, 28, 36, 45])); ``` struct **Sequence**(alias fun, State); auto **sequence**(alias fun, State...)(State args); `Sequence` is similar to `Recurrence` except that iteration is presented in the so-called [closed form](http://en.wikipedia.org/wiki/Closed_form). This means that the `n`th element in the series is computable directly from the initial values and `n` itself. This implies that the interface offered by `Sequence` is a random-access range, as opposed to the regular `Recurrence`, which only offers forward iteration. The state of the sequence is stored as a `Tuple` so it can be heterogeneous. Examples: Odd numbers, using function in string form: ``` auto odds = sequence!("a[0] + n * a[1]")(1, 2); writeln(odds.front); // 1 odds.popFront(); writeln(odds.front); // 3 odds.popFront(); writeln(odds.front); // 5 ``` Examples: Triangular numbers, using function in lambda form: ``` auto tri = sequence!((a,n) => n*(n+1)/2)(); // Note random access writeln(tri[0]); // 0 writeln(tri[3]); // 6 writeln(tri[1]); // 1 writeln(tri[4]); // 10 writeln(tri[2]); // 3 ``` Examples: Fibonacci numbers, using function in explicit form: ``` import std.math : pow, round, sqrt; static ulong computeFib(S)(S state, size_t n) { // Binet's formula return cast(ulong)(round((pow(state[0], n+1) - pow(state[1], n+1)) / state[2])); } auto fib = sequence!computeFib( (1.0 + sqrt(5.0)) / 2.0, // Golden Ratio (1.0 - sqrt(5.0)) / 2.0, // Conjugate of Golden Ratio sqrt(5.0)); // Note random access with [] operator writeln(fib[1]); // 1 writeln(fib[4]); // 5 writeln(fib[3]); // 3 writeln(fib[2]); // 2 writeln(fib[9]); // 55 ``` auto **iota**(B, E, S)(B begin, E end, S step) Constraints: if ((isIntegral!(CommonType!(B, E)) || isPointer!(CommonType!(B, E))) && isIntegral!S); auto **iota**(B, E)(B begin, E end) Constraints: if (isFloatingPoint!(CommonType!(B, E))); auto **iota**(B, E)(B begin, E end) Constraints: if (isIntegral!(CommonType!(B, E)) || isPointer!(CommonType!(B, E))); auto **iota**(E)(E end) Constraints: if (is(typeof(iota(E(0), end)))); auto **iota**(B, E, S)(B begin, E end, S step) Constraints: if (isFloatingPoint!(CommonType!(B, E, S))); auto **iota**(B, E)(B begin, E end) Constraints: if (!isIntegral!(CommonType!(B, E)) && !isFloatingPoint!(CommonType!(B, E)) && !isPointer!(CommonType!(B, E)) && is(typeof((ref B b) { ++b; } )) && (is(typeof(B.init < E.init)) || is(typeof(B.init == E.init)))); Creates a range of values that span the given starting and stopping values. Parameters: | | | | --- | --- | | B `begin` | The starting value. | | E `end` | The value that serves as the stopping criterion. This value is not included in the range. | | S `step` | The value to add to the current value at each iteration. | Returns: A range that goes through the numbers `begin`, `begin + step`, `begin + 2 * step`, `...`, up to and excluding `end`. The two-argument overloads have `step = 1`. If `begin < end && step < 0` or `begin > end && step > 0` or `begin == end`, then an empty range is returned. If `step == 0` then `begin == end` is an error. For built-in types, the range returned is a random access range. For user-defined types that support `++`, the range is an input range. An integral iota also supports `in` operator from the right. It takes the stepping into account, the integral won't be considered contained if it falls between two consecutive values of the range. `contains` does the same as in, but from lefthand side. Example ``` void main() { import std.stdio; // The following groups all produce the same output of: // 0 1 2 3 4 foreach (i; 0 .. 5) writef("%s ", i); writeln(); import std.range : iota; foreach (i; iota(0, 5)) writef("%s ", i); writeln(); writefln("%(%s %|%)", iota(0, 5)); import std.algorithm.iteration : map; import std.algorithm.mutation : copy; import std.format; iota(0, 5).map!(i => format("%s ", i)).copy(stdout.lockingTextWriter()); writeln(); } ``` Examples: ``` import std.algorithm.comparison : equal; import std.math : approxEqual; auto r = iota(0, 10, 1); assert(equal(r, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])); assert(equal(r, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])); assert(3 in r); assert(r.contains(3)); //Same as above assert(!(10 in r)); assert(!(-8 in r)); r = iota(0, 11, 3); assert(equal(r, [0, 3, 6, 9])); writeln(r[2]); // 6 assert(!(2 in r)); auto rf = iota(0.0, 0.5, 0.1); assert(approxEqual(rf, [0.0, 0.1, 0.2, 0.3, 0.4])); ``` enum **TransverseOptions**: int; Options for the [`FrontTransversal`](#FrontTransversal) and [`Transversal`](#Transversal) ranges (below). Examples: ``` import std.algorithm.comparison : equal; import std.exception : assertThrown; auto arr = [[1, 2], [3, 4, 5]]; auto r1 = arr.frontTransversal!(TransverseOptions.assumeJagged); assert(r1.equal([1, 3])); // throws on construction assertThrown!Exception(arr.frontTransversal!(TransverseOptions.enforceNotJagged)); auto r2 = arr.frontTransversal!(TransverseOptions.assumeNotJagged); assert(r2.equal([1, 3])); // either assuming or checking for equal lengths makes // the result a random access range writeln(r2[0]); // 1 static assert(!__traits(compiles, r1[0])); ``` **assumeJagged** When transversed, the elements of a range of ranges are assumed to have different lengths (e.g. a jagged array). **enforceNotJagged** The transversal enforces that the elements of a range of ranges have all the same length (e.g. an array of arrays, all having the same length). Checking is done once upon construction of the transversal range. **assumeNotJagged** The transversal assumes, without verifying, that the elements of a range of ranges have all the same length. This option is useful if checking was already done from the outside of the range. struct **FrontTransversal**(Ror, TransverseOptions opt = TransverseOptions.assumeJagged); FrontTransversal!(RangeOfRanges, opt) **frontTransversal**(TransverseOptions opt = TransverseOptions.assumeJagged, RangeOfRanges)(RangeOfRanges rr); Given a range of ranges, iterate transversally through the first elements of each of the enclosed ranges. Examples: ``` import std.algorithm.comparison : equal; int[][] x = new int[][2]; x[0] = [1, 2]; x[1] = [3, 4]; auto ror = frontTransversal(x); assert(equal(ror, [ 1, 3 ][])); ``` this(RangeOfRanges input); Construction from an input. enum bool **empty**; @property ref auto **front**(); ElementType **moveFront**(); void **popFront**(); Forward range primitives. @property FrontTransversal **save**(); Duplicates this `frontTransversal`. Note that only the encapsulating range of range will be duplicated. Underlying ranges will not be duplicated. @property ref auto **back**(); void **popBack**(); ElementType **moveBack**(); Bidirectional primitives. They are offered if `isBidirectionalRange!RangeOfRanges`. ref auto **opIndex**(size\_t n); ElementType **moveAt**(size\_t n); void **opIndexAssign**(ElementType val, size\_t n); Random-access primitive. It is offered if `isRandomAccessRange!RangeOfRanges && (opt == TransverseOptions.assumeNotJagged || opt == TransverseOptions.enforceNotJagged)`. typeof(this) **opSlice**(size\_t lower, size\_t upper); Slicing if offered if `RangeOfRanges` supports slicing and all the conditions for supporting indexing are met. struct **Transversal**(Ror, TransverseOptions opt = TransverseOptions.assumeJagged); Transversal!(RangeOfRanges, opt) **transversal**(TransverseOptions opt = TransverseOptions.assumeJagged, RangeOfRanges)(RangeOfRanges rr, size\_t n); Given a range of ranges, iterate transversally through the `n`th element of each of the enclosed ranges. This function is similar to `unzip` in other languages. Parameters: | | | | --- | --- | | opt | Controls the assumptions the function makes about the lengths of the ranges | | RangeOfRanges `rr` | An input range of random access ranges | Returns: At minimum, an input range. Range primitives such as bidirectionality and random access are given if the element type of `rr` provides them. Examples: ``` import std.algorithm.comparison : equal; int[][] x = new int[][2]; x[0] = [1, 2]; x[1] = [3, 4]; auto ror = transversal(x, 1); assert(equal(ror, [ 2, 4 ])); ``` Examples: The following code does a full unzip ``` import std.algorithm.comparison : equal; import std.algorithm.iteration : map; int[][] y = [[1, 2, 3], [4, 5, 6]]; auto z = y.front.walkLength.iota.map!(i => transversal(y, i)); assert(equal!equal(z, [[1, 4], [2, 5], [3, 6]])); ``` this(RangeOfRanges input, size\_t n); Construction from an input and an index. enum bool **empty**; @property ref auto **front**(); E **moveFront**(); @property void **front**(E val); void **popFront**(); @property typeof(this) **save**(); Forward range primitives. @property ref auto **back**(); void **popBack**(); E **moveBack**(); @property void **back**(E val); Bidirectional primitives. They are offered if `isBidirectionalRange!RangeOfRanges`. ref auto **opIndex**(size\_t n); E **moveAt**(size\_t n); void **opIndexAssign**(E val, size\_t n); Random-access primitive. It is offered if `isRandomAccessRange!RangeOfRanges && (opt == TransverseOptions.assumeNotJagged || opt == TransverseOptions.enforceNotJagged)`. typeof(this) **opSlice**(size\_t lower, size\_t upper); Slicing if offered if `RangeOfRanges` supports slicing and all the conditions for supporting indexing are met. Transposed!(RangeOfRanges, opt) **transposed**(TransverseOptions opt = TransverseOptions.assumeJagged, RangeOfRanges)(RangeOfRanges rr) Constraints: if (isForwardRange!RangeOfRanges && isInputRange!(ElementType!RangeOfRanges) && hasAssignableElements!RangeOfRanges); Given a range of ranges, returns a range of ranges where the *i*'th subrange contains the *i*'th elements of the original subranges. `Transposed` currently defines `save`, but does not work as a forward range. Consuming a copy made with `save` will consume all copies, even the original sub-ranges fed into `Transposed`. Parameters: | | | | --- | --- | | opt | Controls the assumptions the function makes about the lengths of the ranges (i.e. jagged or not) | | RangeOfRanges `rr` | Range of ranges | Examples: ``` import std.algorithm.comparison : equal; int[][] ror = [ [1, 2, 3], [4, 5, 6] ]; auto xp = transposed(ror); assert(equal!"a.equal(b)"(xp, [ [1, 4], [2, 5], [3, 6] ])); ``` Examples: ``` int[][] x = new int[][2]; x[0] = [1, 2]; x[1] = [3, 4]; auto tr = transposed(x); int[][] witness = [ [ 1, 3 ], [ 2, 4 ] ]; uint i; foreach (e; tr) { writeln(array(e)); // witness[i++] } ``` struct **Indexed**(Source, Indices) if (isRandomAccessRange!Source && isInputRange!Indices && is(typeof(Source.init[ElementType!Indices.init]))); Indexed!(Source, Indices) **indexed**(Source, Indices)(Source source, Indices indices); This struct takes two ranges, `source` and `indices`, and creates a view of `source` as if its elements were reordered according to `indices`. `indices` may include only a subset of the elements of `source` and may also repeat elements. `Source` must be a random access range. The returned range will be bidirectional or random-access if `Indices` is bidirectional or random-access, respectively. Examples: ``` import std.algorithm.comparison : equal; auto source = [1, 2, 3, 4, 5]; auto indices = [4, 3, 1, 2, 0, 4]; auto ind = indexed(source, indices); assert(equal(ind, [5, 4, 2, 3, 1, 5])); assert(equal(retro(ind), [5, 1, 3, 2, 4, 5])); ``` @property ref auto **front**(); void **popFront**(); @property typeof(this) **save**(); @property ref auto **front**(ElementType!Source newVal); auto **moveFront**(); @property ref auto **back**(); void **popBack**(); @property ref auto **back**(ElementType!Source newVal); auto **moveBack**(); ref auto **opIndex**(size\_t index); typeof(this) **opSlice**(size\_t a, size\_t b); auto **opIndexAssign**(ElementType!Source newVal, size\_t index); auto **moveAt**(size\_t index); Range primitives @property Source **source**(); Returns the source range. @property Indices **indices**(); Returns the indices range. size\_t **physicalIndex**(size\_t logicalIndex); Returns the physical index into the source range corresponding to a given logical index. This is useful, for example, when indexing an `Indexed` without adding another layer of indirection. Examples: ``` auto ind = indexed([1, 2, 3, 4, 5], [1, 3, 4]); writeln(ind.physicalIndex(0)); // 1 ``` struct **Chunks**(Source) if (isInputRange!Source); Chunks!Source **chunks**(Source)(Source source, size\_t chunkSize) Constraints: if (isInputRange!Source); This range iterates over fixed-sized chunks of size `chunkSize` of a `source` range. `Source` must be an [input range](std_range_primitives#isInputRange). `chunkSize` must be greater than zero. If `!isInfinite!Source` and `source.walkLength` is not evenly divisible by `chunkSize`, the back element of this range will contain fewer than `chunkSize` elements. If `Source` is a forward range, the resulting range will be forward ranges as well. Otherwise, the resulting chunks will be input ranges consuming the same input: iterating over `front` will shrink the chunk such that subsequent invocations of `front` will no longer return the full chunk, and calling `popFront` on the outer range will invalidate any lingering references to previous values of `front`. Parameters: | | | | --- | --- | | Source `source` | Range from which the chunks will be selected | | size\_t `chunkSize` | Chunk size | See Also: [`slide`](#slide) Returns: Range of chunks. Examples: ``` import std.algorithm.comparison : equal; auto source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; auto chunks = chunks(source, 4); writeln(chunks[0]); // [1, 2, 3, 4] writeln(chunks[1]); // [5, 6, 7, 8] writeln(chunks[2]); // [9, 10] writeln(chunks.back); // chunks[2] writeln(chunks.front); // chunks[0] writeln(chunks.length); // 3 assert(equal(retro(array(chunks)), array(retro(chunks)))); ``` Examples: Non-forward input ranges are supported, but with limited semantics. ``` import std.algorithm.comparison : equal; int i; // The generator doesn't save state, so it cannot be a forward range. auto inputRange = generate!(() => ++i).take(10); // We can still process it in chunks, but it will be single-pass only. auto chunked = inputRange.chunks(2); assert(chunked.front.equal([1, 2])); assert(chunked.front.empty); // Iterating the chunk has consumed it chunked.popFront; assert(chunked.front.equal([3, 4])); ``` this(Source source, size\_t chunkSize); Standard constructor @property auto **front**(); void **popFront**(); @property bool **empty**(); Input range primitives. Always present. @property typeof(this) **save**(); Forward range primitives. Only present if `Source` is a forward range. @property size\_t **length**(); Length. Only if `hasLength!Source` is `true` auto **opIndex**(size\_t index); typeof(this) **opSlice**(size\_t lower, size\_t upper); Indexing and slicing operations. Provided only if `hasSlicing!Source` is `true`. @property auto **back**(); void **popBack**(); Bidirectional range primitives. Provided only if both `hasSlicing!Source` and `hasLength!Source` are `true`. struct **EvenChunks**(Source) if (isForwardRange!Source && hasLength!Source); EvenChunks!Source **evenChunks**(Source)(Source source, size\_t chunkCount) Constraints: if (isForwardRange!Source && hasLength!Source); This range splits a `source` range into `chunkCount` chunks of approximately equal length. `Source` must be a forward range with known length. Unlike [`chunks`](#chunks), `evenChunks` takes a chunk count (not size). The returned range will contain zero or more `source.length / chunkCount + 1` elements followed by `source.length / chunkCount` elements. If `source.length < chunkCount`, some chunks will be empty. `chunkCount` must not be zero, unless `source` is also empty. Examples: ``` import std.algorithm.comparison : equal; auto source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; auto chunks = evenChunks(source, 3); writeln(chunks[0]); // [1, 2, 3, 4] writeln(chunks[1]); // [5, 6, 7] writeln(chunks[2]); // [8, 9, 10] ``` this(Source source, size\_t chunkCount); Standard constructor @property auto **front**(); void **popFront**(); @property bool **empty**(); @property typeof(this) **save**(); Forward range primitives. Always present. const @property size\_t **length**(); Length auto **opIndex**(size\_t index); typeof(this) **opSlice**(size\_t lower, size\_t upper); @property auto **back**(); void **popBack**(); Indexing, slicing and bidirectional operations and range primitives. Provided only if `hasSlicing!Source` is `true`. auto **slide**(Flag!"withPartial" f = Yes.withPartial, Source)(Source source, size\_t windowSize, size\_t stepSize = 1) Constraints: if (isForwardRange!Source); A fixed-sized sliding window iteration of size `windowSize` over a `source` range by a custom `stepSize`. The `Source` range must be at least a [ForwardRange](std_range_primitives#isForwardRange) and the `windowSize` must be greater than zero. For `windowSize = 1` it splits the range into single element groups (aka `unflatten`) For `windowSize = 2` it is similar to `zip(source, source.save.dropOne)`. Parameters: | | | | --- | --- | | f | Whether the last element has fewer elements than `windowSize` it should be be ignored (`No.withPartial`) or added (`Yes.withPartial`) | | Source `source` | Range from which the slide will be selected | | size\_t `windowSize` | Sliding window size | | size\_t `stepSize` | Steps between the windows (by default 1) | Returns: Range of all sliding windows with propagated bi-directionality, forwarding, random access, and slicing. Note To avoid performance overhead, [bi-directionality](std_range_primitives#isBidirectionalRange) is only available when [`std.range.primitives.hasSlicing`](std_range_primitives#hasSlicing) and [`std.range.primitives.hasLength`](std_range_primitives#hasLength) are true. See Also: [`chunks`](#chunks) Examples: Iterate over ranges with windows ``` import std.algorithm.comparison : equal; assert([0, 1, 2, 3].slide(2).equal!equal( [[0, 1], [1, 2], [2, 3]] )); assert(5.iota.slide(3).equal!equal( [[0, 1, 2], [1, 2, 3], [2, 3, 4]] )); ``` Examples: set a custom stepsize (default 1) ``` import std.algorithm.comparison : equal; assert(6.iota.slide(1, 2).equal!equal( [[0], [2], [4]] )); assert(6.iota.slide(2, 4).equal!equal( [[0, 1], [4, 5]] )); assert(iota(7).slide(2, 2).equal!equal( [[0, 1], [2, 3], [4, 5], [6]] )); assert(iota(12).slide(2, 4).equal!equal( [[0, 1], [4, 5], [8, 9]] )); ``` Examples: Allow the last slide to have fewer elements than windowSize ``` import std.algorithm.comparison : equal; assert(3.iota.slide!(No.withPartial)(4).empty); assert(3.iota.slide!(Yes.withPartial)(4).equal!equal( [[0, 1, 2]] )); ``` Examples: Count all the possible substrings of length 2 ``` import std.algorithm.iteration : each; int[dstring] d; "AGAGA"d.slide!(Yes.withPartial)(2).each!(a => d[a]++); writeln(d); // ["AG"d:2, "GA"d:2] ``` Examples: withPartial only has an effect if last element in the range doesn't have the full size ``` import std.algorithm.comparison : equal; assert(5.iota.slide!(Yes.withPartial)(3, 4).equal!equal([[0, 1, 2], [4]])); assert(6.iota.slide!(Yes.withPartial)(3, 4).equal!equal([[0, 1, 2], [4, 5]])); assert(7.iota.slide!(Yes.withPartial)(3, 4).equal!equal([[0, 1, 2], [4, 5, 6]])); assert(5.iota.slide!(No.withPartial)(3, 4).equal!equal([[0, 1, 2]])); assert(6.iota.slide!(No.withPartial)(3, 4).equal!equal([[0, 1, 2]])); assert(7.iota.slide!(No.withPartial)(3, 4).equal!equal([[0, 1, 2], [4, 5, 6]])); ``` auto **only**(Values...)(return scope Values values) Constraints: if (!is(CommonType!Values == void) || Values.length == 0); Assemble `values` into a range that carries all its elements in-situ. Useful when a single value or multiple disconnected values must be passed to an algorithm expecting a range, without having to perform dynamic memory allocation. As copying the range means copying all elements, it can be safely returned from functions. For the same reason, copying the returned range may be expensive for a large number of arguments. Parameters: | | | | --- | --- | | Values `values` | the values to assemble together | Returns: A `RandomAccessRange` of the assembled values. See Also: [`chain`](#chain) to chain ranges Examples: ``` import std.algorithm.comparison : equal; import std.algorithm.iteration : filter, joiner, map; import std.algorithm.searching : findSplitBefore; import std.uni : isUpper; assert(equal(only('♡'), "♡")); writeln([1, 2, 3, 4].findSplitBefore(only(3))[0]); // [1, 2] assert(only("one", "two", "three").joiner(" ").equal("one two three")); string title = "The D Programming Language"; assert(title .filter!isUpper // take the upper case letters .map!only // make each letter its own range .joiner(".") // join the ranges together lazily .equal("T.D.P.L")); ``` auto **enumerate**(Enumerator = size\_t, Range)(Range range, Enumerator start = 0) Constraints: if (isIntegral!Enumerator && isInputRange!Range); Iterate over `range` with an attached index variable. Each element is a [`std.typecons.Tuple`](std_typecons#Tuple) containing the index and the element, in that order, where the index member is named `index` and the element member is named `value`. The index starts at `start` and is incremented by one on every iteration. Overflow If `range` has length, then it is an error to pass a value for `start` so that `start + range.length` is bigger than `Enumerator.max`, thus it is ensured that overflow cannot happen. If `range` does not have length, and `popFront` is called when `front.index == Enumerator.max`, the index will overflow and continue from `Enumerator.min`. Parameters: | | | | --- | --- | | Range `range` | the [input range](std_range_primitives#isInputRange) to attach indexes to | | Enumerator `start` | the number to start the index counter from | Returns: At minimum, an input range. All other range primitives are given in the resulting range if `range` has them. The exceptions are the bidirectional primitives, which are propagated only if `range` has length. Example Useful for using `foreach` with an index loop variable: ``` import std.stdio : stdin, stdout; import std.range : enumerate; foreach (lineNum, line; stdin.byLine().enumerate(1)) stdout.writefln("line #%s: %s", lineNum, line); ``` Examples: Can start enumeration from a negative position: ``` import std.array : assocArray; import std.range : enumerate; bool[int] aa = true.repeat(3).enumerate(-1).assocArray(); assert(aa[-1]); assert(aa[0]); assert(aa[1]); ``` enum auto **isTwoWayCompatible**(alias fn, T1, T2); Returns true if `fn` accepts variables of type T1 and T2 in any order. The following code should compile: ``` (ref T1 a, ref T2 b) { fn(a, b); fn(b, a); } ``` Examples: ``` void func1(int a, int b); void func2(int a, float b); static assert(isTwoWayCompatible!(func1, int, int)); static assert(isTwoWayCompatible!(func1, short, int)); static assert(!isTwoWayCompatible!(func2, int, float)); void func3(ref int a, ref int b); static assert( isTwoWayCompatible!(func3, int, int)); static assert(!isTwoWayCompatible!(func3, short, int)); ``` enum **SearchPolicy**: int; Policy used with the searching primitives `lowerBound`, `upperBound`, and `equalRange` of [`SortedRange`](#SortedRange) below. Examples: ``` import std.algorithm.comparison : equal; auto a = assumeSorted([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); auto p1 = a.upperBound!(SearchPolicy.binarySearch)(3); assert(p1.equal([4, 5, 6, 7, 8, 9])); auto p2 = a.lowerBound!(SearchPolicy.gallop)(4); assert(p2.equal([0, 1, 2, 3])); ``` **linear** Searches in a linear fashion. **trot** Searches with a step that is grows linearly (1, 2, 3,...) leading to a quadratic search schedule (indexes tried are 0, 1, 3, 6, 10, 15, 21, 28,...) Once the search overshoots its target, the remaining interval is searched using binary search. The search is completed in Ο(`sqrt(n)`) time. Use it when you are reasonably confident that the value is around the beginning of the range. **gallop** Performs a [galloping search algorithm](https://en.wikipedia.org/wiki/Exponential_search), i.e. searches with a step that doubles every time, (1, 2, 4, 8, ...) leading to an exponential search schedule (indexes tried are 0, 1, 3, 7, 15, 31, 63,...) Once the search overshoots its target, the remaining interval is searched using binary search. A value is found in Ο(`log(n)`) time. **binarySearch** Searches using a classic interval halving policy. The search starts in the middle of the range, and each search step cuts the range in half. This policy finds a value in Ο(`log(n)`) time but is less cache friendly than `gallop` for large ranges. The `binarySearch` policy is used as the last step of `trot`, `gallop`, `trotBackwards`, and `gallopBackwards` strategies. **trotBackwards** Similar to `trot` but starts backwards. Use it when confident that the value is around the end of the range. **gallopBackwards** Similar to `gallop` but starts backwards. Use it when confident that the value is around the end of the range. enum **SortedRangeOptions**: int; Options for [`SortedRange`](#SortedRange) ranges (below). Examples: ``` // create a SortedRange, that's checked strictly SortedRange!(int[],"a < b", SortedRangeOptions.checkStrictly)([ 1, 3, 5, 7, 9 ]); ``` **assumeSorted** Assume, that the range is sorted without checking. **checkStrictly** All elements of the range are checked to be sorted. The check is performed in O(n) time. **checkRoughly** Some elements of the range are checked to be sorted. For ranges with random order, this will almost surely detect, that it is not sorted. For almost sorted ranges it's more likely to fail. The checked elements are choosen in a deterministic manner, which makes this check reproducable. The check is performed in O(log(n)) time. struct **SortedRange**(Range, alias pred = "a < b", SortedRangeOptions opt = SortedRangeOptions.assumeSorted) if (isInputRange!Range && !isInstanceOf!(**SortedRange**, Range)); template **SortedRange**(Range, alias pred = "a < b", SortedRangeOptions opt = SortedRangeOptions.assumeSorted) if (isInstanceOf!(**SortedRange**, Range)) Represents a sorted range. In addition to the regular range primitives, supports additional operations that take advantage of the ordering, such as merge and binary search. To obtain a `SortedRange` from an unsorted range `r`, use [`std.algorithm.sorting.sort`](std_algorithm_sorting#sort) which sorts `r` in place and returns the corresponding `SortedRange`. To construct a `SortedRange` from a range `r` that is known to be already sorted, use [`assumeSorted`](#assumeSorted). Parameters: Examples: ``` import std.algorithm.sorting : sort; auto a = [ 1, 2, 3, 42, 52, 64 ]; auto r = assumeSorted(a); assert(r.contains(3)); assert(!(32 in r)); auto r1 = sort!"a > b"(a); assert(3 in r1); assert(!r1.contains(32)); writeln(r1.release()); // [64, 52, 42, 3, 2, 1] ``` Examples: `SortedRange` could accept ranges weaker than random-access, but it is unable to provide interesting functionality for them. Therefore, `SortedRange` is currently restricted to random-access ranges. No copy of the original range is ever made. If the underlying range is changed concurrently with its corresponding `SortedRange` in ways that break its sorted-ness, `SortedRange` will work erratically. ``` import std.algorithm.mutation : swap; auto a = [ 1, 2, 3, 42, 52, 64 ]; auto r = assumeSorted(a); assert(r.contains(42)); swap(a[3], a[5]); // illegal to break sortedness of original range assert(!r.contains(42)); // passes although it shouldn't ``` @property bool **empty**(); @property auto **save**(); @property ref auto **front**(); void **popFront**(); @property ref auto **back**(); void **popBack**(); ref auto **opIndex**(size\_t i); scope auto **opSlice**(size\_t a, size\_t b) return; Range primitives. auto **release**(); Releases the controlled range and returns it. auto **lowerBound**(SearchPolicy sp = SearchPolicy.binarySearch, V)(V value) Constraints: if (isTwoWayCompatible!(predFun, ElementType!Range, V) && hasSlicing!Range); This function uses a search with policy `sp` to find the largest left subrange on which `pred(x, value)` is `true` for all `x` (e.g., if `pred` is "less than", returns the portion of the range with elements strictly smaller than `value`). The search schedule and its complexity are documented in [`SearchPolicy`](#SearchPolicy). Examples: ``` import std.algorithm.comparison : equal; auto a = assumeSorted([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]); auto p = a.lowerBound(4); assert(equal(p, [ 0, 1, 2, 3 ])); ``` auto **upperBound**(SearchPolicy sp = SearchPolicy.binarySearch, V)(V value) Constraints: if (isTwoWayCompatible!(predFun, ElementType!Range, V)); This function searches with policy `sp` to find the largest right subrange on which `pred(value, x)` is `true` for all `x` (e.g., if `pred` is "less than", returns the portion of the range with elements strictly greater than `value`). The search schedule and its complexity are documented in [`SearchPolicy`](#SearchPolicy). For ranges that do not offer random access, `SearchPolicy.linear` is the only policy allowed (and it must be specified explicitly lest it exposes user code to unexpected inefficiencies). For random-access searches, all policies are allowed, and `SearchPolicy.binarySearch` is the default. Examples: ``` import std.algorithm.comparison : equal; auto a = assumeSorted([ 1, 2, 3, 3, 3, 4, 4, 5, 6 ]); auto p = a.upperBound(3); assert(equal(p, [4, 4, 5, 6])); ``` auto **equalRange**(V)(V value) Constraints: if (isTwoWayCompatible!(predFun, ElementType!Range, V) && isRandomAccessRange!Range); Returns the subrange containing all elements `e` for which both `pred(e, value)` and `pred(value, e)` evaluate to `false` (e.g., if `pred` is "less than", returns the portion of the range with elements equal to `value`). Uses a classic binary search with interval halving until it finds a value that satisfies the condition, then uses `SearchPolicy.gallopBackwards` to find the left boundary and `SearchPolicy.gallop` to find the right boundary. These policies are justified by the fact that the two boundaries are likely to be near the first found value (i.e., equal ranges are relatively small). Completes the entire search in Ο(`log(n)`) time. Examples: ``` import std.algorithm.comparison : equal; auto a = [ 1, 2, 3, 3, 3, 4, 4, 5, 6 ]; auto r = a.assumeSorted.equalRange(3); assert(equal(r, [ 3, 3, 3 ])); ``` auto **trisect**(V)(V value) Constraints: if (isTwoWayCompatible!(predFun, ElementType!Range, V) && isRandomAccessRange!Range && hasLength!Range); Returns a tuple `r` such that `r[0]` is the same as the result of `lowerBound(value)`, `r[1]` is the same as the result of `equalRange(value)`, and `r[2]` is the same as the result of `upperBound(value)`. The call is faster than computing all three separately. Uses a search schedule similar to `equalRange`. Completes the entire search in Ο(`log(n)`) time. Examples: ``` import std.algorithm.comparison : equal; auto a = [ 1, 2, 3, 3, 3, 4, 4, 5, 6 ]; auto r = assumeSorted(a).trisect(3); assert(equal(r[0], [ 1, 2 ])); assert(equal(r[1], [ 3, 3, 3 ])); assert(equal(r[2], [ 4, 4, 5, 6 ])); ``` bool **contains**(V)(V value) Constraints: if (isRandomAccessRange!Range); Returns `true` if and only if `value` can be found in `range`, which is assumed to be sorted. Performs Ο(`log(r.length)`) evaluations of `pred`. bool **opBinaryRight**(string op, V)(V value) Constraints: if (op == "in" && isRandomAccessRange!Range); Like `contains`, but the value is specified before the range. auto **groupBy**()(); Returns a range of subranges of elements that are equivalent according to the sorting relation. auto **assumeSorted**(alias pred = "a < b", R)(R r) Constraints: if (isInputRange!(Unqual!R)); Assumes `r` is sorted by predicate `pred` and returns the corresponding `SortedRange!(pred, R)` having `r` as support. To check for sorted-ness at cost Ο(`n`), use [`std.algorithm.sorting.isSorted`](std_algorithm_sorting#isSorted). Examples: ``` import std.algorithm.comparison : equal; int[] a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; auto p = assumeSorted(a); assert(equal(p.lowerBound(4), [0, 1, 2, 3])); assert(equal(p.lowerBound(5), [0, 1, 2, 3, 4])); assert(equal(p.lowerBound(6), [0, 1, 2, 3, 4, 5])); assert(equal(p.lowerBound(6.9), [0, 1, 2, 3, 4, 5, 6])); ``` struct **RefRange**(R) if (isInputRange!R); auto **refRange**(R)(R\* range) Constraints: if (isInputRange!R); Wrapper which effectively makes it possible to pass a range by reference. Both the original range and the RefRange will always have the exact same elements. Any operation done on one will affect the other. So, for instance, if it's passed to a function which would implicitly copy the original range if it were passed to it, the original range is *not* copied but is consumed as if it were a reference type. Note `save` works as normal and operates on a new range, so if `save` is ever called on the `RefRange`, then no operations on the saved range will affect the original. Parameters: | | | | --- | --- | | R\* `range` | the range to construct the `RefRange` from | Returns: A `RefRange`. If the given range is a class type (and thus is already a reference type), then the original range is returned rather than a `RefRange`. Examples: Basic Example ``` import std.algorithm.searching : find; ubyte[] buffer = [1, 9, 45, 12, 22]; auto found1 = find(buffer, 45); writeln(found1); // [45, 12, 22] writeln(buffer); // [1, 9, 45, 12, 22] auto wrapped1 = refRange(&buffer); auto found2 = find(wrapped1, 45); writeln(*found2.ptr); // [45, 12, 22] writeln(buffer); // [45, 12, 22] auto found3 = find(wrapped1.save, 22); writeln(*found3.ptr); // [22] writeln(buffer); // [45, 12, 22] string str = "hello world"; auto wrappedStr = refRange(&str); writeln(str.front); // 'h' str.popFrontN(5); writeln(str); // " world" writeln(wrappedStr.front); // ' ' writeln(*wrappedStr.ptr); // " world" ``` Examples: opAssign Example. ``` ubyte[] buffer1 = [1, 2, 3, 4, 5]; ubyte[] buffer2 = [6, 7, 8, 9, 10]; auto wrapped1 = refRange(&buffer1); auto wrapped2 = refRange(&buffer2); assert(wrapped1.ptr is &buffer1); assert(wrapped2.ptr is &buffer2); assert(wrapped1.ptr !is wrapped2.ptr); assert(buffer1 != buffer2); wrapped1 = wrapped2; //Everything points to the same stuff as before. assert(wrapped1.ptr is &buffer1); assert(wrapped2.ptr is &buffer2); assert(wrapped1.ptr !is wrapped2.ptr); //But buffer1 has changed due to the assignment. writeln(buffer1); // [6, 7, 8, 9, 10] writeln(buffer2); // [6, 7, 8, 9, 10] buffer2 = [11, 12, 13, 14, 15]; //Everything points to the same stuff as before. assert(wrapped1.ptr is &buffer1); assert(wrapped2.ptr is &buffer2); assert(wrapped1.ptr !is wrapped2.ptr); //But buffer2 has changed due to the assignment. writeln(buffer1); // [6, 7, 8, 9, 10] writeln(buffer2); // [11, 12, 13, 14, 15] wrapped2 = null; //The pointer changed for wrapped2 but not wrapped1. assert(wrapped1.ptr is &buffer1); assert(wrapped2.ptr is null); assert(wrapped1.ptr !is wrapped2.ptr); //buffer2 is not affected by the assignment. writeln(buffer1); // [6, 7, 8, 9, 10] writeln(buffer2); // [11, 12, 13, 14, 15] ``` pure nothrow @safe this(R\* range); auto **opAssign**(RefRange rhs); This does not assign the pointer of `rhs` to this `RefRange`. Rather it assigns the range pointed to by `rhs` to the range pointed to by this `RefRange`. This is because *any* operation on a `RefRange` is the same is if it occurred to the original range. The one exception is when a `RefRange` is assigned `null` either directly or because `rhs` is `null`. In that case, `RefRange` no longer refers to the original range but is `null`. void **opAssign**(typeof(null) rhs); inout pure nothrow @property @safe inout(R\*) **ptr**(); A pointer to the wrapped range. @property auto **front**(); const @property auto **front**(); @property auto **front**(ElementType!R value); @property bool **empty**(); const @property bool **empty**(); void **popFront**(); @property auto **save**(); const @property auto **save**(); auto **opSlice**(); const auto **opSlice**(); Only defined if `isForwardRange!R` is `true`. @property auto **back**(); const @property auto **back**(); @property auto **back**(ElementType!R value); void **popBack**(); Only defined if `isBidirectionalRange!R` is `true`. ref auto **opIndex**(IndexType)(IndexType index); const ref auto **opIndex**(IndexType)(IndexType index); Only defined if `isRandomAccesRange!R` is `true`. auto **moveFront**(); Only defined if `hasMobileElements!R` and `isForwardRange!R` are `true`. auto **moveBack**(); Only defined if `hasMobileElements!R` and `isBidirectionalRange!R` are `true`. auto **moveAt**(size\_t index); Only defined if `hasMobileElements!R` and `isRandomAccessRange!R` are `true`. @property size\_t **length**(); const @property size\_t **length**(); alias **opDollar** = length; Only defined if `hasLength!R` is `true`. auto **opSlice**(IndexType1, IndexType2)(IndexType1 begin, IndexType2 end); const auto **opSlice**(IndexType1, IndexType2)(IndexType1 begin, IndexType2 end); Only defined if `hasSlicing!R` is `true`. auto **bitwise**(R)(auto ref R range) Constraints: if (isInputRange!R && isIntegral!(ElementType!R)); Bitwise adapter over an integral type range. Consumes the range elements bit by bit, from the least significant bit to the most significant bit. Parameters: | | | | --- | --- | | R | an integral [input range](std_range_primitives#isInputRange) to iterate over | | R `range` | range to consume bit by by | Returns: A `Bitwise` input range with propagated forward, bidirectional and random access capabilities Examples: ``` import std.algorithm.comparison : equal; import std.format : format; // 00000011 00001001 ubyte[] arr = [3, 9]; auto r = arr.bitwise; // iterate through it as with any other range writeln(format("%(%d%)", r)); // "1100000010010000" assert(format("%(%d%)", r.retro).equal("1100000010010000".retro)); auto r2 = r[5 .. $]; // set a bit r[2] = 1; writeln(arr[0]); // 7 writeln(r[5]); // r2[0] ``` Examples: You can use bitwise to implement an uniform bool generator ``` import std.algorithm.comparison : equal; import std.random : rndGen; auto rb = rndGen.bitwise; static assert(isInfinite!(typeof(rb))); auto rb2 = rndGen.bitwise; // Don't forget that structs are passed by value assert(rb.take(10).equal(rb2.take(10))); ``` struct **NullSink**; ref auto **nullSink**(); An OutputRange that discards the data it receives. Examples: ``` import std.algorithm.iteration : map; import std.algorithm.mutation : copy; [4, 5, 6].map!(x => x * 2).copy(nullSink); // data is discarded ``` Examples: ``` import std.csv : csvNextToken; string line = "a,b,c"; // ignore the first column line.csvNextToken(nullSink, ',', '"'); line.popFront; // look at the second column Appender!string app; line.csvNextToken(app, ',', '"'); writeln(app.data); // "b" ``` auto **tee**(Flag!"pipeOnPop" pipeOnPop = Yes.pipeOnPop, R1, R2)(R1 inputRange, R2 outputRange) Constraints: if (isInputRange!R1 && isOutputRange!(R2, ElementType!R1)); auto **tee**(alias fun, Flag!"pipeOnPop" pipeOnPop = Yes.pipeOnPop, R1)(R1 inputRange) Constraints: if (is(typeof(fun) == void) || isSomeFunction!fun); Implements a "tee" style pipe, wrapping an input range so that elements of the range can be passed to a provided function or [`OutputRange`](#OutputRange) as they are iterated over. This is useful for printing out intermediate values in a long chain of range code, performing some operation with side-effects on each call to `front` or `popFront`, or diverting the elements of a range into an auxiliary [`OutputRange`](#OutputRange). It is important to note that as the resultant range is evaluated lazily, in the case of the version of `tee` that takes a function, the function will not actually be executed until the range is "walked" using functions that evaluate ranges, such as [`std.array.array`](std_array#array) or [`std.algorithm.iteration.fold`](std_algorithm_iteration#fold). Parameters: | | | | --- | --- | | pipeOnPop | If `Yes.pipeOnPop`, simply iterating the range without ever calling `front` is enough to have `tee` mirror elements to `outputRange` (or, respectively, `fun`). Note that each `popFront()` call will mirror the old `front` value, not the new one. This means that the last value will not be forwarded if the range isn't iterated until empty. If `No.pipeOnPop`, only elements for which `front` does get called will be also sent to `outputRange`/`fun`. If `front` is called twice for the same element, it will still be sent only once. If this caching is undesired, consider using [`std.algorithm.iteration.map`](std_algorithm_iteration#map) instead. | | R1 `inputRange` | The input range being passed through. | | R2 `outputRange` | This range will receive elements of `inputRange` progressively as iteration proceeds. | | fun | This function will be called with elements of `inputRange` progressively as iteration proceeds. | Returns: An input range that offers the elements of `inputRange`. Regardless of whether `inputRange` is a more powerful range (forward, bidirectional etc), the result is always an input range. Reading this causes `inputRange` to be iterated and returns its elements in turn. In addition, the same elements will be passed to `outputRange` or `fun` as well. See Also: [`std.algorithm.iteration.each`](std_algorithm_iteration#each) Examples: ``` import std.algorithm.comparison : equal; import std.algorithm.iteration : filter, map; // Sum values while copying int[] values = [1, 4, 9, 16, 25]; int sum = 0; auto newValues = values.tee!(a => sum += a).array; assert(equal(newValues, values)); writeln(sum); // 1 + 4 + 9 + 16 + 25 // Count values that pass the first filter int count = 0; auto newValues4 = values.filter!(a => a < 10) .tee!(a => count++) .map!(a => a + 1) .filter!(a => a < 10); //Fine, equal also evaluates any lazy ranges passed to it. //count is not 3 until equal evaluates newValues4 assert(equal(newValues4, [2, 5])); writeln(count); // 3 ``` auto **padLeft**(R, E)(R r, E e, size\_t n) Constraints: if ((isInputRange!R && hasLength!R || isForwardRange!R) && !is(CommonType!(ElementType!R, E) == void)); Extends the length of the input range `r` by padding out the start of the range with the element `e`. The element `e` must be of a common type with the element type of the range `r` as defined by [`std.traits.CommonType`](std_traits#CommonType). If `n` is less than the length of of `r`, then `r` is returned unmodified. If `r` is a string with Unicode characters in it, `padLeft` follows D's rules about length for strings, which is not the number of characters, or graphemes, but instead the number of encoding units. If you want to treat each grapheme as only one encoding unit long, then call [`std.uni.byGrapheme`](std_uni#byGrapheme) before calling this function. If `r` has a length, then this is Ο(`1`). Otherwise, it's Ο(`r.length`). Parameters: | | | | --- | --- | | R `r` | an [input range](std_range_primitives#isInputRange) with a length, or a forward range | | E `e` | element to pad the range with | | size\_t `n` | the length to pad to | Returns: A range containing the elements of the original range with the extra padding See Also: [`std.string.leftJustifier`](std_string#leftJustifier) Examples: ``` import std.algorithm.comparison : equal; assert([1, 2, 3, 4].padLeft(0, 6).equal([0, 0, 1, 2, 3, 4])); assert([1, 2, 3, 4].padLeft(0, 3).equal([1, 2, 3, 4])); assert("abc".padLeft('_', 6).equal("___abc")); ``` auto **padRight**(R, E)(R r, E e, size\_t n) Constraints: if (isInputRange!R && !isInfinite!R && !is(CommonType!(ElementType!R, E) == void)); Extend the length of the input range `r` by padding out the end of the range with the element `e`. The element `e` must be of a common type with the element type of the range `r` as defined by [`std.traits.CommonType`](std_traits#CommonType). If `n` is less than the length of of `r`, then the contents of `r` are returned. The range primitives that the resulting range provides depends whether or not `r` provides them. Except the functions `back` and `popBack`, which also require the range to have a length as well as `back` and `popBack` Parameters: | | | | --- | --- | | R `r` | an [input range](std_range_primitives#isInputRange) with a length | | E `e` | element to pad the range with | | size\_t `n` | the length to pad to | Returns: A range containing the elements of the original range with the extra padding See Also: [`std.string.rightJustifier`](std_string#rightJustifier) Examples: ``` import std.algorithm.comparison : equal; assert([1, 2, 3, 4].padRight(0, 6).equal([1, 2, 3, 4, 0, 0])); assert([1, 2, 3, 4].padRight(0, 4).equal([1, 2, 3, 4])); assert("abc".padRight('_', 6).equal("abc___")); ```
programming_docs
d std.digest.crc std.digest.crc ============== Cyclic Redundancy Check (32-bit) implementation. | Category | Functions | | --- | --- | | Template API | [*CRC*](#CRC) [*CRC32*](#CRC32) [*CRC64ECMA*](#CRC64ECMA) [*CRC64ISO*](#CRC64ISO) | | OOP API | [*CRC32Digest*](#CRC32Digest) [*CRC64ECMADigest*](#CRC64ECMADigest) [*CRC64ISODigest*](#CRC64ISODigest) | | Helpers | [*crcHexString*](#crcHexString) [*crc32Of*](#crc32Of) [*crc64ECMAOf*](#crc64ECMAOf) [*crc64ISOOf*](#crc64ISOOf) | This module conforms to the APIs defined in `std.digest`. To understand the differences between the template and the OOP API, see [`std.digest`](std_digest). This module publicly imports [`std.digest`](std_digest) and can be used as a stand-alone module. Note CRCs are usually printed with the MSB first. When using [`std.digest.toHexString`](std_digest#toHexString) the result will be in an unexpected order. Use [`std.digest.toHexString`](std_digest#toHexString)'s optional order parameter to specify decreasing order for the correct result. The [`crcHexString`](#crcHexString) alias can also be used for this purpose. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Pavel "EvilOne" Minayev, Alex Rønne Petersen, Johannes Pfau References [Wikipedia on CRC](http://en.wikipedia.org/wiki/Cyclic_redundancy_check) Source [std/digest/crc.d](https://github.com/dlang/phobos/blob/master/std/digest/crc.d) Standards: Implements the 'common' IEEE CRC32 variant (LSB-first order, Initial value uint.max, complement result) CTFE Digests do not work in CTFE Examples: ``` //Template API import std.digest.crc; ubyte[4] hash = crc32Of("The quick brown fox jumps over the lazy dog"); writeln(crcHexString(hash)); // "414FA339" //Feeding data ubyte[1024] data; CRC32 crc; crc.put(data[]); crc.start(); //Start again crc.put(data[]); hash = crc.finish(); ``` Examples: ``` //OOP API import std.digest.crc; auto crc = new CRC32Digest(); ubyte[] hash = crc.digest("The quick brown fox jumps over the lazy dog"); assert(crcHexString(hash) == "414FA339"); //352441c2 //Feeding data ubyte[1024] data; crc.put(data[]); crc.reset(); //Start again crc.put(data[]); hash = crc.finish(); ``` alias **CRC32** = CRC!(32u, 3988292384LU).CRC; Template API CRC32 implementation. See `std.digest` for differences between template and OOP API. alias **CRC64ECMA** = CRC!(64u, 14514072000185962306LU).CRC; Template API CRC64-ECMA implementation. See `std.digest` for differences between template and OOP API. alias **CRC64ISO** = CRC!(64u, 15564440312192434176LU).CRC; Template API CRC64-ISO implementation. See `std.digest` for differences between template and OOP API. struct **CRC**(uint N, ulong P) if (N == 32 || N == 64); Generic Template API used for CRC32 and CRC64 implementations. The N parameter indicate the size of the hash in bits. The parameter P specify the polynomial to be used for reduction. You may want to use the CRC32, CRC65ECMA and CRC64ISO aliases for convenience. See `std.digest` for differences between template and OOP API. Examples: ``` //Simple example, hashing a string using crc32Of helper function ubyte[4] hash32 = crc32Of("abc"); //Let's get a hash string writeln(crcHexString(hash32)); // "352441C2" // Repeat for CRC64 ubyte[8] hash64ecma = crc64ECMAOf("abc"); writeln(crcHexString(hash64ecma)); // "2CD8094A1A277627" ubyte[8] hash64iso = crc64ISOOf("abc"); writeln(crcHexString(hash64iso)); // "3776C42000000000" ``` Examples: ``` ubyte[1024] data; //Using the basic API CRC32 hash32; CRC64ECMA hash64ecma; CRC64ISO hash64iso; //Initialize data here... hash32.put(data); ubyte[4] result32 = hash32.finish(); hash64ecma.put(data); ubyte[8] result64ecma = hash64ecma.finish(); hash64iso.put(data); ubyte[8] result64iso = hash64iso.finish(); ``` Examples: ``` //Let's use the template features: //Note: When passing a CRC32 to a function, it must be passed by reference! void doSomething(T)(ref T hash) if (isDigest!T) { hash.put(cast(ubyte) 0); } CRC32 crc32; crc32.start(); doSomething(crc32); writeln(crcHexString(crc32.finish())); // "D202EF8D" // repeat for CRC64 CRC64ECMA crc64ecma; crc64ecma.start(); doSomething(crc64ecma); writeln(crcHexString(crc64ecma.finish())); // "1FADA17364673F59" CRC64ISO crc64iso; crc64iso.start(); doSomething(crc64iso); writeln(crcHexString(crc64iso.finish())); // "6F90000000000000" ``` pure nothrow @nogc @trusted void **put**(scope const(ubyte)[] data...); Use this to feed the digest with data. Also implements the [`std.range.primitives.isOutputRange`](std_range_primitives#isOutputRange) interface for `ubyte` and `const(ubyte)[]`. pure nothrow @nogc @safe void **start**(); Used to initialize the CRC32 digest. Note For this CRC32 Digest implementation calling start after default construction is not necessary. Calling start is only necessary to reset the Digest. Generic code which deals with different Digest types should always call start though. pure nothrow @nogc @safe R **finish**(); Returns the finished CRC hash. This also calls [`start`](#start) to reset the internal state. const pure nothrow @nogc @safe R **peek**(); Works like `finish` but does not reset the internal state, so it's possible to continue putting data into this CRC after a call to peek. ubyte[4] **crc32Of**(T...)(T data); This is a convenience alias for [`std.digest.digest`](std_digest#digest) using the CRC32 implementation. Parameters: | | | | --- | --- | | T `data` | `InputRange` of `ElementType` implicitly convertible to `ubyte`, `ubyte[]` or `ubyte[num]` or one or more arrays of any type. | Returns: CRC32 of data Examples: ``` ubyte[] data = [4,5,7,25]; writeln(data.crc32Of); // [167, 180, 199, 131] import std.utf : byChar; writeln("hello"d.byChar.crc32Of); // [134, 166, 16, 54] ubyte[4] hash = "abc".crc32Of(); writeln(hash); // digest!CRC32("ab", "c") import std.range : iota; enum ubyte S = 5, F = 66; writeln(iota(S, F).crc32Of); // [59, 140, 234, 154] ``` ubyte[8] **crc64ECMAOf**(T...)(T data); This is a convenience alias for [`std.digest.digest`](std_digest#digest) using the CRC64-ECMA implementation. Parameters: | | | | --- | --- | | T `data` | `InputRange` of `ElementType` implicitly convertible to `ubyte`, `ubyte[]` or `ubyte[num]` or one or more arrays of any type. | Returns: CRC64-ECMA of data Examples: ``` ubyte[] data = [4,5,7,25]; writeln(data.crc64ECMAOf); // [58, 142, 220, 214, 118, 98, 105, 69] import std.utf : byChar; writeln("hello"d.byChar.crc64ECMAOf); // [177, 55, 185, 219, 229, 218, 30, 155] ubyte[8] hash = "abc".crc64ECMAOf(); writeln("abc".crc64ECMAOf); // [39, 118, 39, 26, 74, 9, 216, 44] writeln(hash); // digest!CRC64ECMA("ab", "c") import std.range : iota; enum ubyte S = 5, F = 66; writeln(iota(S, F).crc64ECMAOf); // [6, 184, 91, 238, 46, 213, 127, 188] ``` ubyte[8] **crc64ISOOf**(T...)(T data); This is a convenience alias for [`std.digest.digest.digest`](std_digest_digest#digest) using the CRC64-ISO implementation. Parameters: | | | | --- | --- | | T `data` | `InputRange` of `ElementType` implicitly convertible to `ubyte`, `ubyte[]` or `ubyte[num]` or one or more arrays of any type. | Returns: CRC64-ISO of data Examples: ``` ubyte[] data = [4,5,7,25]; writeln(data.crc64ISOOf); // [0, 0, 0, 80, 137, 232, 203, 120] import std.utf : byChar; writeln("hello"d.byChar.crc64ISOOf); // [0, 0, 16, 216, 226, 238, 62, 60] ubyte[8] hash = "abc".crc64ISOOf(); writeln("abc".crc64ISOOf); // [0, 0, 0, 0, 32, 196, 118, 55] writeln(hash); // digest!CRC64ISO("ab", "c") import std.range : iota; enum ubyte S = 5, F = 66; writeln(iota(S, F).crc64ISOOf); // [21, 185, 116, 95, 219, 11, 54, 7] ``` alias **crcHexString** = **crcHexString**; alias **crcHexString** = std.digest.toHexString!(Order.decreasing, 16LU, LetterCase.upper).toHexString; producing the usual CRC32 string output. alias **CRC32Digest** = std.digest.WrapperDigest!(CRC!(32u, 3988292384LU)).WrapperDigest; OOP API CRC32 implementation. See `std.digest` for differences between template and OOP API. This is an alias for `[std.digest.WrapperDigest](std_digest#WrapperDigest)!CRC32`, see there for more information. alias **CRC64ECMADigest** = std.digest.WrapperDigest!(CRC!(64u, 14514072000185962306LU)).WrapperDigest; OOP API CRC64-ECMA implementation. See `std.digest` for differences between template and OOP API. This is an alias for `[std.digest.digest.WrapperDigest](std_digest_digest#WrapperDigest)!CRC64ECMA`, see there for more information. alias **CRC64ISODigest** = std.digest.WrapperDigest!(CRC!(64u, 15564440312192434176LU)).WrapperDigest; OOP API CRC64-ISO implementation. See `std.digest` for differences between template and OOP API. This is an alias for `[std.digest.digest.WrapperDigest](std_digest_digest#WrapperDigest)!CRC64ISO`, see there for more information. Examples: ``` //Simple example, hashing a string using Digest.digest helper function auto crc = new CRC32Digest(); ubyte[] hash = crc.digest("abc"); //Let's get a hash string writeln(crcHexString(hash)); // "352441C2" ``` Examples: ``` //Let's use the OOP features: void test(Digest dig) { dig.put(cast(ubyte) 0); } auto crc = new CRC32Digest(); test(crc); //Let's use a custom buffer: ubyte[4] buf; ubyte[] result = crc.finish(buf[]); writeln(crcHexString(result)); // "D202EF8D" ``` Examples: ``` //Simple example auto hash = new CRC32Digest(); hash.put(cast(ubyte) 0); ubyte[] result = hash.finish(); ``` Examples: ``` //using a supplied buffer ubyte[4] buf; auto hash = new CRC32Digest(); hash.put(cast(ubyte) 0); ubyte[] result = hash.finish(buf[]); //The result is now in result (and in buf. If you pass a buffer which is bigger than //necessary, result will have the correct length, but buf will still have it's original //length) ``` d rt.sections_win32 rt.sections\_win32 ================== Written in the D programming language. This module provides Win32-specific support for sections. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright, Sean Kelly, Martin Nowak Source [rt/sections\_win32.d](https://github.com/dlang/druntime/blob/master/src/rt/sections_win32.d) d Pragmas Pragmas ======= **Contents** 1. [Predefined Pragmas](#predefined-pragmas) 1. [`pragma crt_constructor`](#crtctor) 2. [`pragma crt_destructor`](#crtdtor) 3. [`pragma inline`](#inline) 4. [`pragma lib`](#lib) 5. [`pragma linkerDirective`](#linkerDirective) 6. [`pragma mangle`](#mangle) 7. [`pragma msg`](#msg) 8. [`pragma printf`](#printf) 9. [`pragma scanf`](#scanf) 10. [`pragma startaddress`](#startaddress) 2. [Vendor Specific Pragmas](#vendor_specific_pragmas) ``` PragmaDeclaration: Pragma; Pragma DeclarationBlock PragmaStatement: Pragma; Pragma NoScopeStatement Pragma: pragma ( Identifier ) pragma ( Identifier , ArgumentList ) ``` Pragmas pass special information to the implementation and can add vendor specific extensions. Pragmas can be used by themselves terminated with a *;*, and can apply to a statement, a block of statements, a declaration, or a block of declarations. Pragmas can be either a [*PragmaDeclaration*](#PragmaDeclaration) or a [*PragmaStatement*](#PragmaStatement). ``` pragma(ident); // just by itself pragma(ident) declaration; // influence one declaration pragma(ident): // influence subsequent declarations declaration; declaration; pragma(ident) // influence block of declarations { declaration; declaration; } pragma(ident) statement; // influence one statement pragma(ident) // influence block of statements { statement; statement; } ``` The kind of pragma it is determined by the *Identifier*. [*ArgumentList*](expression#ArgumentList) is a comma-separated list of [*AssignExpression*](expression#AssignExpression)s. The [*AssignExpression*](expression#AssignExpression)s must be parsable as expressions, but their meaning is up to the individual pragma semantics. Predefined Pragmas ------------------ All implementations must support these, even if by just ignoring them: * [pragma crt\_constructor](#crtctor) * [pragma crt\_destructor](#crtdtor) * [pragma inline](#inline) * [pragma lib](#lib) * [pragma linkerDirective](#linkerDirective) * [pragma mangle](#mangle) * [pragma msg](#msg) * [pragma printf](#printf) * [pragma scanf](#scanf) * [pragma startaddress](#startaddress) **Implementation Defined:** An implementation may ignore these pragmas. ### `pragma crt_constructor` Annotates a function so it is run after the C runtime library is initialized and before the D runtime library is initialized. The function must: 1. be `extern (C)` 2. not have any parameters 3. not be a non-static member function 4. be a function definition, not a declaration (i.e. it must have a function body) 5. not return a type that has a destructor 6. not be a nested function ``` __gshared int initCount; pragma(crt_constructor) extern(C) void initializer() { initCount += 1; } ``` No arguments to the pragma are allowed. A function may be annotated with both `pragma(crt_constructor)` and `pragma(crt_destructor)`. Annotating declarations other than function definitions has no effect. Annotating a struct or class definition does not affect the members of the aggregate. **Best Practices:** Use for system programming and interfacing with C/C++, for example to allow for initialization of the runtime when loading a DSO, or as a simple replacement for `shared static this` in [betterC mode](betterc). **Implementation Defined:** The order in which functions annotated with `pragma(crt_constructor)` are run is implementation defined. **Best Practices:** to control the order in which the functions are called within one module, write a single function that calls them in the desired order, and only annotate that function. **Implementation Defined:** This uses the mechanism C compilers use to run code before `main()` is called. C++ compilers use it to run static constructors and destructors. For example, GCC's [`__attribute__((constructor))`](https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html) is equivalent. Digital Mars C uses *\_STI* and *\_STD* identifier prefixes to mark crt\_constructor and crt\_destructor functions. **Implementation Defined:** A reference to the annotated function will be inserted in the *.init\_array* section for Elf systems, the *XI* section for Win32 OMF systems, the *.CRT$XCU* section for Windows MSCOFF systems, and the *\_\_mod\_init\_func* section for OSX systems. **Note:** `crt_constructor` and `crt_destructor` were implemented in [v2.078.0 (2018-01-01)](https://dlang.org/changelog/2.078.0.html). Some compilers exposed non-standard, compiler-specific mechanism before. ### `pragma crt_destructor` `pragma(crt_destructor)` works the same as `pragma(crt_destructor)` except: Annotates a function so it is run after the D runtime library is terminated and before the C runtime library is terminated. Calling C's `exit()` function also causes the annotated functions to run. The order in which the annotated functions are run is the reverse of those functions annotated with `pragma(crt_constructor)`. **Implementation Defined:** This uses the mechanism C compilers use to run code after `main()` returns or `exit()` is called. C++ compilers use it to run static destructors. For example, GCC's [`__attribute__((destructor))`](https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html) is equivalent. Digital Mars C uses *\_STI* and *\_STD* identifier prefixes to mark crt\_constructor and crt\_destructor functions. **Implementation Defined:** A reference to the annotated function will be inserted in the *.fini\_array* section for Elf systems, the *XC* section for Win32 OMF systems, the *.CRT$XPU* section for Windows MSCOFF systems, and the *\_\_mod\_term\_func* section for OSX systems. ``` __gshared int initCount; pragma(crt_constructor) extern(C) void initialize() { initCount += 1; } pragma(crt_destructor) extern(C) void deinitialize() { initCount -= 1; } pragma(crt_constructor) pragma(crt_destructor) extern(C) void innuendo() { printf("Inside a constructor... Or destructor?\n"); } ``` ### `pragma inline` Affects whether functions are inlined or not. If at the declaration level, it affects the functions declared in the block it controls. If inside a function, it affects the function it is enclosed by. It takes two forms: 1. ``` pragma(inline) ``` Sets the behavior to match the implementation's default behavior. 2. ``` pragma(inline, AssignExpression) ``` The [*AssignExpression*](expression#AssignExpression) is evaluated and must have a type that can be converted to a boolean. If the result is false the functions are never inlined, otherwise they are always inlined. More than one *AssignExpression* is not allowed. If there are multiple pragma inlines in a function, the lexically last one takes effect. ``` pragma(inline): int foo(int x) // foo() is never inlined { pragma(inline, true); ++x; pragma(inline, false); // supercedes the others return x + 3; } ``` **Implementation Defined:** 1. The default inline behavior is typically selectable with a compiler switch such as [*-inline*.](https://dlang.org/dmd.html#switch-inline) 2. Whether a particular function can be inlined or not is implementation defined. 3. What happens for `pragma(inline, true)` if the function cannot be inlined. An error message is typical. ### `pragma lib` There must be one [*AssignExpression*](expression#AssignExpression) and it must evaluate at compile time to a string literal. ``` pragma(lib, "foo.lib"); ``` **Implementation Defined:** The string literal specifies the file name of a library file. This name is inserted into the generated object file, or otherwise passed to the linker, so the linker automatically links in that library. ### `pragma linkerDirective` There must be one [*AssignExpression*](expression#AssignExpression) and it must evaluate at compile time to a string literal. ``` pragma(linkerDirective, "/FAILIFMISMATCH:_ITERATOR_DEBUG_LEVEL=2"); ``` **Implementation Defined:** The string literal specifies a linker directive to be embedded in the generated object file. Linker directives are only supported for MS-COFF output. ### `pragma mangle` Overrides the default mangling for a symbol. There must be one [*AssignExpression*](expression#AssignExpression) and it must evaluate at compile time to a string literal. It only applies to function and variable symbols. Other symbols are ignored. **Implementation Defined:** On macOS and Win32, an extra underscore (`_`) is prepended to the string since 2.079, as is done by the C/C++ toolchain. This allows using the same `pragma(mangle)` for all compatible (POSIX in one case, win64 in another) platforms instead of having to special-case. **Rationale:** * Enables linking to symbol names that D cannot represent. * Enables linking to a symbol which is a D keyword, since an [*Identifier*](lex#Identifier) cannot be a keyword. ``` pragma(mangle, "body") extern(C) void body_func(); ``` ### `pragma msg` Each [*AssignExpression*](expression#AssignExpression) is evaluated at compile time and then all are combined into a message. ``` pragma(msg, "compiling...", 6, 1.0); // prints "compiling...61.0" at compile time ``` **Implementation Defined:** The form the message takes and how it is presented to the user. One way is by printing them to the standard error stream. **Rationale:** Analogously to how `writeln()` performs a role of writing informational messages during runtime, `pragma(msg)` performs the equivalent role at compile time. For example, ``` static if (kilroy) pragma(msg, "Kilroy was here"); else pragma(msg, "Kilroy got lost"); ``` ### `pragma printf` `pragma(printf)` specifies that a function declaration is a printf-like function, meaning it is an `extern (C)` or `extern (C++)` function with a `format` parameter accepting a pointer to a 0-terminated `char` string conforming to the C99 Standard 7.19.6.1, immediately followed by either a `...` variadic argument list or a parameter of type `va_list` as the last parameter. If the `format` argument is a string literal, it is verified to be a valid format string per the C99 Standard. If the `format` parameter is followed by `...`, the number and types of the variadic arguments are checked against the format string. Diagnosed incompatibilities are: * incompatible sizes which may cause argument misalignment * deferencing arguments that are not pointers * insufficient number of arguments * struct arguments * array and slice arguments * non-pointer arguments to `s` specifier * non-standard formats * undefined behavior per C99 Per the C99 Standard, extra arguments are ignored. Ignored mismatches are: * sign mismatches, such as printing an `int` with a `%u` format * integral promotion mismatches, where the format specifies a smaller integral type than `int` or `uint`, such as printing a `short` with the `%d` format rather than `%hd` ``` printf("%k\n", value); // error: non-Standard format k printf("%d\n"); // error: not enough arguments printf("%d\n", 1, 2); // ok, extra arguments ignored ``` **Best Practices:** In order to use non-Standard printf/scanf formats, an easy workaround is: ``` const format = "%k\n"; printf(format.ptr, value); // no error ``` **Best Practices:** Most of the errors detected are portability issues. For instance, ``` string s; printf("%.*s\n", s.length, s.ptr); printf("%d\n", s.sizeof); ulong u; scanf("%lld%*c\n", &u); ``` should be replaced with: ``` string s; printf("%.*s\n", cast(int) s.length, s.ptr); printf("%zd\n", s.sizeof); ulong u; scanf("%llu%*c\n", &u); ``` `pragma(printf)` applied to declarations that are not functions are ignored. In particular, it has no effect on the declaration of a pointer to function type. ### `pragma scanf` `pragma(scanf)` specifies that a function declaration is a scanf-like function, meaning it is an `extern (C)` or `extern (C++)` function with a `format` parameter accepting a pointer to a 0-terminated `char` string conforming to the C99 Standard 7.19.6.2, immediately followed by either a `...` variadic argument list or a parameter of type `va_list` as the last parameter. If the `format` argument is a string literal, it is verified to be a valid format string per the C99 Standard. If the `format` parameter is followed by `...`, the number and types of the variadic arguments are checked against the format string. Diagnosed incompatibilities are: * argument is not a pointer to the format specified type * insufficient number of arguments * non-standard formats * undefined behavior per C99 Per the C99 Standard, extra arguments are ignored. `pragma(scanf)` applied to declarations that are not functions are ignored. In particular, it has no effect on the declaration of a pointer to function type. ### `pragma startaddress` There must be one [*AssignExpression*](expression#AssignExpression) and it must evaluate at compile time to a function symbol. **Implementation Defined:** The function symbol specifies the start address for the program. The symbol is inserted into the object file or is otherwise presented to the linker to set the start address. This is not normally used for application level programming, but is for specialized systems work. For applications code, the start address is taken care of by the runtime library. ``` void foo() { ... } pragma(startaddress, foo); ``` Vendor Specific Pragmas ----------------------- Vendor specific pragma *Identifier*s can be defined if they are prefixed by the vendor's trademarked name, in a similar manner to version identifiers: ``` pragma(DigitalMars_extension) { ... } ``` Implementations must diagnose an error for unrecognized *Pragma*s, even if they are vendor specific ones. **Implementation Defined:** Vendor specific pragmas. **Best Practices:** vendor specific pragmas should be wrapped in version statements ``` version (DigitalMars) { pragma(DigitalMars_extension) { ... } } ```
programming_docs
d core.sync.exception core.sync.exception =================== Define base class for synchronization exceptions. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) Authors: Sean Kelly Source [core/sync/exception.d](https://github.com/dlang/druntime/blob/master/src/core/sync/exception.d) class **SyncError**: object.Error; Base class for synchronization errors. d core.stdc.signal core.stdc.signal ================ D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<signal.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/signal.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly Source [core/stdc/signal.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/signal.d) Standards: ISO/IEC 9899:1999 (E) alias **sig\_atomic\_t** = int; enum void function(int) nothrow @nogc @system **SIG\_ERR**; enum void function(int) nothrow @nogc @system **SIG\_DFL**; enum void function(int) nothrow @nogc @system **SIG\_IGN**; enum int **SIGABRT**; enum int **SIGFPE**; enum int **SIGILL**; enum int **SIGINT**; enum int **SIGSEGV**; enum int **SIGTERM**; nothrow @nogc @system sigfn\_t **signal**(int sig, sigfn\_t func); nothrow @nogc @system int **raise**(int sig); d std.experimental.logger std.experimental.logger ======================= Implements logging facilities. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Robert burner Schadek](http://www.svs.informatik.uni-oldenburg.de/60865.html) ### Basic Logging Message logging is a common approach to expose runtime information of a program. Logging should be easy, but also flexible and powerful, therefore `D` provides a standard interface for logging. The easiest way to create a log message is to write: ``` import std.experimental.logger; void main() { log("Hello World"); } ``` This will print a message to the `stderr` device. The message will contain the filename, the line number, the name of the surrounding function, the time and the message. More complex log call can go along the lines like: ``` log("Logging to the sharedLog with its default LogLevel"); logf(LogLevel.info, 5 < 6, "%s to the sharedLog with its LogLevel.info", "Logging"); info("Logging to the sharedLog with its info LogLevel"); warning(5 < 6, "Logging to the sharedLog with its LogLevel.warning if 5 is less than 6"); error("Logging to the sharedLog with its error LogLevel"); errorf("Logging %s the sharedLog %s its error LogLevel", "to", "with"); critical("Logging to the"," sharedLog with its error LogLevel"); fatal("Logging to the sharedLog with its fatal LogLevel"); auto fLogger = new FileLogger("NameOfTheLogFile"); fLogger.log("Logging to the fileLogger with its default LogLevel"); fLogger.info("Logging to the fileLogger with its default LogLevel"); fLogger.warning(5 < 6, "Logging to the fileLogger with its LogLevel.warning if 5 is less than 6"); fLogger.warningf(5 < 6, "Logging to the fileLogger with its LogLevel.warning if %s is %s than 6", 5, "less"); fLogger.critical("Logging to the fileLogger with its info LogLevel"); fLogger.log(LogLevel.trace, 5 < 6, "Logging to the fileLogger"," with its default LogLevel if 5 is less than 6"); fLogger.fatal("Logging to the fileLogger with its warning LogLevel"); ``` Additionally, this example shows how a new `FileLogger` is created. Individual `Logger` and the global log functions share commonly named functions to log data. The names of the functions are as follows: * `log` * `trace` * `info` * `warning` * `critical` * `fatal` The default `Logger` will by default log to `stderr` and has a default `LogLevel` of `LogLevel.all`. The default Logger can be accessed by using the property called `sharedLog`. This property is a reference to the current default `Logger`. This reference can be used to assign a new default `Logger`. ``` sharedLog = new FileLogger("New_Default_Log_File.log"); ``` Additional `Logger` can be created by creating a new instance of the required `Logger`. ### Logging Fundamentals #### LogLevel The `LogLevel` of a log call can be defined in two ways. The first is by calling `log` and passing the `LogLevel` explicitly as the first argument. The second way of setting the `LogLevel` of a log call, is by calling either `trace`, `info`, `warning`, `critical`, or `fatal`. The log call will then have the respective `LogLevel`. If no `LogLevel` is defined the log call will use the current `LogLevel` of the used `Logger`. If data is logged with `LogLevel` `fatal` by default an `Error` will be thrown. This behaviour can be modified by using the member `fatalHandler` to assign a custom delegate to handle log call with `LogLevel` `fatal`. #### Conditional Logging Conditional logging can be achieved be passing a `bool` as first argument to a log function. If conditional logging is used the condition must be `true` in order to have the log message logged. In order to combine an explicit `LogLevel` passing with conditional logging, the `LogLevel` has to be passed as first argument followed by the `bool`. #### Filtering Log Messages Messages are logged if the `LogLevel` of the log message is greater than or equal to the `LogLevel` of the used `Logger` and additionally if the `LogLevel` of the log message is greater than or equal to the global `LogLevel`. If a condition is passed into the log call, this condition must be true. The global `LogLevel` is accessible by using `globalLogLevel`. To assign a `LogLevel` of a `Logger` use the `logLevel` property of the logger. #### Printf Style Logging If `printf`-style logging is needed add a **f** to the logging call, such as `myLogger.infof("Hello %s", "world");` or `fatalf("errno %d", 1337)`. The additional **f** appended to the function name enables `printf`-style logging for all combinations of explicit `LogLevel` and conditional logging functions and methods. #### Thread Local Redirection Calls to the free standing log functions are not directly forwarded to the global `Logger` `sharedLog`. Actually, a thread local `Logger` of type `StdForwardLogger` processes the log call and then, by default, forwards the created `Logger.LogEntry` to the `sharedLog` `Logger`. The thread local `Logger` is accessible by the `stdThreadLocalLog` property. This property allows to assign user defined `Logger`. The default `LogLevel` of the `stdThreadLocalLog` `Logger` is `LogLevel.all` and it will therefore forward all messages to the `sharedLog` `Logger`. The `LogLevel` of the `stdThreadLocalLog` can be used to filter log calls before they reach the `sharedLog` `Logger`. ### User Defined Logger To customize the `Logger` behavior, create a new `class` that inherits from the abstract `Logger` `class`, and implements the `writeLogMsg` method. ``` class MyCustomLogger : Logger { this(LogLevel lv) @safe { super(lv); } override void writeLogMsg(ref LogEntry payload) { // log message in my custom way } } auto logger = new MyCustomLogger(LogLevel.info); logger.log("Awesome log message with LogLevel.info"); ``` To gain more precise control over the logging process, additionally to overriding the `writeLogMsg` method the methods `beginLogMsg`, `logMsgPart` and `finishLogMsg` can be overridden. ### Compile Time Disabling of `Logger` In order to disable logging at compile time, pass `StdLoggerDisableLogging` as a version argument to the `D` compiler when compiling your program code. This will disable all logging functionality. Specific `LogLevel` can be disabled at compile time as well. In order to disable logging with the `trace` `LogLevel` pass `StdLoggerDisableTrace` as a version. The following table shows which version statement disables which `LogLevel`. | | | | --- | --- | | `LogLevel.trace` | StdLoggerDisableTrace | | `LogLevel.info` | StdLoggerDisableInfo | | `LogLevel.warning` | StdLoggerDisableWarning | | `LogLevel.error` | StdLoggerDisableError | | `LogLevel.critical` | StdLoggerDisableCritical | | `LogLevel.fatal` | StdLoggerDisableFatal | Such a version statement will only disable logging in the associated compile unit. ### Provided Logger By default four `Logger` implementations are given. The `FileLogger` logs data to files. It can also be used to log to `stdout` and `stderr` as these devices are files as well. A `Logger` that logs to `stdout` can therefore be created by `new FileLogger(stdout)`. The `MultiLogger` is basically an associative array of `string`s to `Logger`. It propagates log calls to its stored `Logger`. The `ArrayLogger` contains an array of `Logger` and also propagates log calls to its stored `Logger`. The `NullLogger` does not do anything. It will never log a message and will never throw on a log call with `LogLevel` `error`. Source [std/experimental/logger/package.d](https://github.com/dlang/phobos/blob/master/std/experimental/logger/package.d) d Operator Overloading Operator Overloading ==================== **Contents** 1. [Unary Operator Overloading](#unary) 1. [Postincrement *e*`++` and Postdecrement *e*`--` Operators](#postincrement_postdecrement_operators) 2. [Overloading Index Unary Operators](#index_unary_operators) 3. [Overloading Slice Unary Operators](#slice_unary_operators) 2. [Cast Operator Overloading](#cast) 1. [Boolean Operations](#boolean_operators) 3. [Binary Operator Overloading](#binary) 4. [Overloading the Comparison Operators](#eqcmp) 1. [Overloading `==` and `!=`](#equals) 2. [Overloading `<`, `<``=`, `>`, and `>``=`](#compare) 5. [Function Call Operator Overloading `f()`](#function-call) 1. [Static opCall](#static-opcall) 6. [Assignment Operator Overloading](#assignment) 1. [Index Assignment Operator Overloading](#index_assignment_operator) 2. [Slice Assignment Operator Overloading](#slice_assignment_operator) 7. [Op Assignment Operator Overloading](#op-assign) 1. [Index Op Assignment Operator Overloading](#index_op_assignment) 2. [Slice Op Assignment Operator Overloading](#slice_op_assignment) 8. [Array Indexing and Slicing Operators Overloading](#array-ops) 1. [Index Operator Overloading](#array) 2. [Slice Operator Overloading](#slice) 3. [Dollar Operator Overloading](#dollar) 9. [Forwarding](#dispatch) 10. [D1 style operator overloading](#old-style) Operator overloading is accomplished by rewriting operators whose operands are class or struct objects into calls to specially named members. No additional syntax is used. * [Unary Operator Overloading](#unary) * [Cast Operator Overloading](#cast) * [Binary Operator Overloading](#binary) * [Overloading the Comparison Operators](#eqcmp) + [Overloading `==` and `!=`](#equals) + [Overloading `<`, `<=`, `>`, and `>=`](#compare) * [Function Call Operator Overloading](#function-call) * [Assignment Operator Overloading](#assignment) * [Op Assignment Operator Overloading](#op-assign) * [Array Indexing and Slicing Operators Overloading](#array-ops) + [Index Operator Overloading](#array) + [Slice Operator Overloading](#slice) + [Dollar Operator Overloading](#dollar) * [Forwarding](#dispatch) * [D1 style operator overloading](#old-style) Unary Operator Overloading -------------------------- Overloadable Unary Operators| ***op*** | ***rewrite*** | | `-`*e* | *e*`.opUnary!("-")()` | | `+`*e* | *e*`.opUnary!("+")()` | | `~`*e* | *e*`.opUnary!("~")()` | | `*`*e* | *e*`.opUnary!("*")()` | | `++`*e* | *e*`.opUnary!("++")()` | | `--`*e* | *e*`.opUnary!("--")()` | For example, in order to overload the `-` (negation) operator for struct S, and no other operator: ``` struct S { int m; int opUnary(string s)() if (s == "-") { return -m; } } int foo(S s) { return -s; } ``` ### Postincrement *e*`++` and Postdecrement *e*`--` Operators These are not directly overloadable, but instead are rewritten in terms of the ++*e* and --*e* prefix operators: Postfix Operator Rewrites| ***op*** | ***rewrite*** | | *e*`--` | `(auto t =` *e*`, --`*e*`, t)` | | *e*`++` | `(auto t =` *e*`, ++`*e*`, t)` | ### Overloading Index Unary Operators Overloadable Index Unary Operators| ***op*** | ***rewrite*** | | `-`*a*`[`*b*1, *b*2, ... *b*n`]` | *a*`.opIndexUnary!("-")(`*b*1, *b*2, ... *b*n`)` | | `+`*a*`[`*b*1, *b*2, ... *b*n`]` | *a*`.opIndexUnary!("+")(`*b*1, *b*2, ... *b*n`)` | | `~`*a*`[`*b*1, *b*2, ... *b*n`]` | *a*`.opIndexUnary!("~")(`*b*1, *b*2, ... *b*n`)` | | `*`*a*`[`*b*1, *b*2, ... *b*n`]` | *a*`.opIndexUnary!("*")(`*b*1, *b*2, ... *b*n`)` | | `++`*a*`[`*b*1, *b*2, ... *b*n`]` | *a*`.opIndexUnary!("++")(`*b*1, *b*2, ... *b*n`)` | | `--`*a*`[`*b*1, *b*2, ... *b*n`]` | *a*`.opIndexUnary!("--")(`*b*1, *b*2, ... *b*n`)` | ### Overloading Slice Unary Operators Overloadable Slice Unary Operators| ***op*** | ***rewrite*** | | `-`*a*`[`*i*..*j*`]` | *a*`.opIndexUnary!("-")(`*a*`.opSlice(`*i*, *j*`))` | | `+`*a*`[`*i*..*j*`]` | *a*`.opIndexUnary!("+")(`*a*`.opSlice(`*i*, *j*`))` | | `~`*a*`[`*i*..*j*`]` | *a*`.opIndexUnary!("~")(`*a*`.opSlice(`*i*, *j*`))` | | `*`*a*`[`*i*..*j*`]` | *a*`.opIndexUnary!("*")(`*a*`.opSlice(`*i*, *j*`))` | | `++`*a*`[`*i*..*j*`]` | *a*`.opIndexUnary!("++")(`*a*`.opSlice(`*i*, *j*`))` | | `--`*a*`[`*i*..*j*`]` | *a*`.opIndexUnary!("--")(`*a*`.opSlice(`*i*, *j*`))` | | `-`*a*`[ ]` | *a*`.opIndexUnary!("-")()` | | `+`*a*`[ ]` | *a*`.opIndexUnary!("+")()` | | `~`*a*`[ ]` | *a*`.opIndexUnary!("~")()` | | `*`*a*`[ ]` | *a*`.opIndexUnary!("*")()` | | `++`*a*`[ ]` | *a*`.opIndexUnary!("++")()` | | `--`*a*`[ ]` | *a*`.opIndexUnary!("--")()` | For backward compatibility, if the above rewrites fail to compile and `opSliceUnary` is defined, then the rewrites `a.opSliceUnary!(op)(i, j)` and `a.opSliceUnary!(op)` are tried instead, respectively. Cast Operator Overloading ------------------------- To define how one type can be cast to another, define the `opCast` template method, which is used as follows: Cast Operators| ***op*** | ***rewrite*** | | `cast(`*type*`)` *e* | *e*`.opCast!(`*type*`)()` | Note that `opCast` is only ever used with an explicit `cast` expression, except in the case of boolean operations (see next section) ### Boolean Operations Notably absent from the list of overloaded unary operators is the ! logical negation operator. More obscurely absent is a unary operator to convert to a bool result. Instead, these are covered by a rewrite to: ``` opCast!(bool)(e) ``` So, ``` if (e) => if (e.opCast!(bool)) if (!e) => if (!e.opCast!(bool)) ``` etc., whenever a bool result is expected. This only happens, however, for instances of structs. Class references are converted to bool by checking to see if the class reference is null or not. Binary Operator Overloading --------------------------- The following binary operators are overloadable: Overloadable Binary Operators| `+` | `-` | `*` | `/` | `%` | `^^` | `&` | | `|` | `^` | `<``<` | `>``>` | `>``>``>` | `~` | `in` | The expression: ``` a op b ``` is rewritten as both: ``` a.opBinary!("op")(b) b.opBinaryRight!("op")(a) ``` and the one with the ‘better’ match is selected. It is an error for both to equally match. Operator overloading for a number of operators can be done at the same time. For example, if only the + or - operators are supported: ``` T opBinary(string op)(T rhs) { static if (op == "+") return data + rhs.data; else static if (op == "-") return data - rhs.data; else static assert(0, "Operator "~op~" not implemented"); } ``` To do them all en masse: ``` T opBinary(string op)(T rhs) { return mixin("data "~op~" rhs.data"); } ``` Note that `opIn` and `opIn_r` have been deprecated in favor of `opBinary!"in"` and `opBinaryRight!"in"` respectively. Overloading the Comparison Operators ------------------------------------ D allows overloading of the comparison operators `==`, `!=`, `<`, `<=`, `>=`, `>` via two functions, `opEquals` and `opCmp`. The equality and inequality operators are treated separately because while practically all user-defined types can be compared for equality, only a subset of types have a meaningful ordering. For example, while it makes sense to determine if two RGB color vectors are equal, it is not meaningful to say that one color is greater than another, because colors do not have an ordering. Thus, one would define `opEquals` for a `Color` type, but not `opCmp`. Furthermore, even with orderable types, the order relation may not be linear. For example, one may define an ordering on sets via the subset relation, such that `x < y` is true if `x` is a (strict) subset of `y`. If `x` and `y` are disjoint sets, then neither `x < y` nor `y < x` holds, but that does not imply that `x == y`. Thus, it is insufficient to determine equality purely based on `opCmp` alone. For this reason, `opCmp` is only used for the inequality operators `<`, `<=`, `>=`, and `>`. The equality operators `==` and `!=` always employ `opEquals` instead. Therefore, it is the programmer's responsibility to ensure that `opCmp` and `opEquals` are consistent with each other. If `opEquals` is not specified, the compiler provides a default version that does member-wise comparison. If this suffices, one may define only `opCmp` to customize the behaviour of the inequality operators. But if not, then a custom version of `opEquals` should be defined as well, in order to preserve consistent semantics between the two kinds of comparison operators. Finally, if the user-defined type is to be used as a key in the built-in associative arrays, then the programmer must ensure that the semantics of `opEquals` and `toHash` are consistent. If not, the associative array may not work in the expected manner. ### Overloading `==` and `!=` Expressions of the form `a != b` are rewritten as `!(a == b)`. Given `a == b` : 1. If a and b are both class objects, then the expression is rewritten as: ``` .object.opEquals(a, b) ``` and that function is implemented as: ``` bool opEquals(Object a, Object b) { if (a is b) return true; if (a is null || b is null) return false; if (typeid(a) == typeid(b)) return a.opEquals(b); return a.opEquals(b) && b.opEquals(a); } ``` 2. Otherwise the expressions `a.opEquals(b)` and `b.opEquals(a)` are tried. If both resolve to the same `opEquals` function, then the expression is rewritten to be `a.opEquals(b)`. 3. If one is a better match than the other, or one compiles and the other does not, the first is selected. 4. Otherwise, an error results. If overridding `Object.opEquals()` for classes, the class member function signature should look like: ``` class C { override bool opEquals(Object o) { ... } } ``` If structs declare an `opEquals` member function for the identity comparison, it could have several forms, such as: ``` struct S { // lhs should be mutable object bool opEquals(const S s) { ... } // for r-values (e.g. temporaries) bool opEquals(ref const S s) { ... } // for l-values (e.g. variables) // both hand side can be const object bool opEquals(const S s) const { ... } // for r-values (e.g. temporaries) } ``` Alternatively, declare a single templated `opEquals` function with an [auto ref](template#auto-ref-parameters) parameter: ``` struct S { // for l-values and r-values, // with converting both hand side implicitly to const bool opEquals()(auto ref const S s) const { ... } } ``` ### Overloading `<`, `<``=`, `>`, and `>``=` Comparison operations are rewritten as follows: Rewriting of comparison operations| **comparison** | **rewrite 1** | **rewrite 2** | | `a` `<` `b` | `a.opCmp(b)` `<` `0` | `b.opCmp(a)` `>` `0` | | `a` `<``= b` | `a.opCmp(b)` `<``= 0` | `b.opCmp(a)` `>``= 0` | | `a` `>``b` | `a.opCmp(b)` `>` `0` | `b.opCmp(a)` `<` `0` | | `a` `>``= b` | `a.opCmp(b)` `>``= 0` | `b.opCmp(a)` `<``= 0` | Both rewrites are tried. If only one compiles, that one is taken. If they both resolve to the same function, the first rewrite is done. If they resolve to different functions, the best matching one is used. If they both match the same, but are different functions, an ambiguity error results. If overriding `Object.opCmp()` for classes, the class member function signature should look like: ``` class C { override int opCmp(Object o) { ... } } ``` If structs declare an `opCmp` member function, it should have the following form: ``` struct S { int opCmp(ref const S s) const { ... } } ``` Note that `opCmp` is only used for the inequality operators; expressions like `a == b` always uses `opEquals`. If `opCmp` is defined but `opEquals` isn't, the compiler will supply a default version of `opEquals` that performs member-wise comparison. If this member-wise comparison is not consistent with the user-defined `opCmp`, then it is up to the programmer to supply an appropriate version of `opEquals`. Otherwise, inequalities like `a <= b` will behave inconsistently with equalities like `a == b`. Function Call Operator Overloading `f()` ---------------------------------------- The function call operator, `()`, can be overloaded by declaring a function named `opCall`: ``` struct F { int opCall(); int opCall(int x, int y, int z); } void test() { F f; int i; i = f(); // same as i = f.opCall(); i = f(3,4,5); // same as i = f.opCall(3,4,5); } ``` In this way a struct or class object can behave as if it were a function. Note that merely declaring `opCall` automatically disables [struct literal](struct#StructLiteral) syntax. To avoid the limitation, declare a [constructor](struct#Struct-Constructor) so that it takes priority over `opCall` in `Type(...)` syntax. ``` struct Multiplier { int factor; this(int num) { factor = num; } int opCall(int value) { return value * factor; } } void test() { Multiplier m = Multiplier(10); // invoke constructor int result = m(5); // invoke opCall assert(result == 50); } ``` ### Static opCall `static opCall` also works as expected for a function call operator with type names. ``` struct Double { static int opCall(int x) { return x * 2; } } void test() { int i = Double(2); assert(i == 4); } ``` Mixing struct constructors and `static opCall` is not allowed. ``` struct S { this(int i) {} static S opCall() // disallowed due to constructor { return S.init; } } ``` Note: `static opCall` can be used to simulate struct constructors with no arguments, but this is not recommended practice. Instead, the preferred solution is to use a factory function to create struct instances. Assignment Operator Overloading ------------------------------- The assignment operator `=` can be overloaded if the left hand side is a struct aggregate, and `opAssign` is a member function of that aggregate. For struct types, operator overloading for the identity assignment is allowed. ``` struct S { // identity assignment, allowed. void opAssign(S rhs); // not identity assignment, also allowed. void opAssign(int); } S s; s = S(); // Rewritten to s.opAssign(S()); s = 1; // Rewritten to s.opAssign(1); ``` However for class types, identity assignment is not allowed. All class types have reference semantics, so identity assignment by default rebinds the left-hand-side to the argument at the right, and this is not overridable. ``` class C { // If X is the same type as C or the type which is // implicitly convertible to C, then opAssign would // accept identity assignment, which is disallowed. // C opAssign(...); // C opAssign(X); // C opAssign(X, ...); // C opAssign(X ...); // C opAssign(X, U = defaultValue, etc.); // not an identity assignment - allowed void opAssign(int); } C c = new C(); c = new C(); // Rebinding referencee c = 1; // Rewritten to c.opAssign(1); ``` ### Index Assignment Operator Overloading If the left hand side of an assignment is an index operation on a struct or class instance, it can be overloaded by providing an `opIndexAssign` member function. Expressions of the form `a[`*b*1, *b*2, ... *b*n`] = c` are rewritten as `a.opIndexAssign(c,` *b*1, *b*2, ... *b*n`)`. ``` struct A { int opIndexAssign(int value, size_t i1, size_t i2); } void test() { A a; a[i,3] = 7; // same as a.opIndexAssign(7,i,3); } ``` ### Slice Assignment Operator Overloading If the left hand side of an assignment is a slice operation on a struct or class instance, it can be overloaded by implementing an `opIndexAssign` member function that takes the return value of the `opSlice` function as parameter(s). Expressions of the form `a[`*i*..*j*`] = c` are rewritten as `a.opIndexAssign(c,` `a.opSlice(`*i*, *j*`))`, and `a[] = c` as `a.opIndexAssign(c)`. See [Array Indexing and Slicing Operators Overloading](#array-ops) for more details. ``` struct A { int opIndexAssign(int v); // overloads a[] = v int opIndexAssign(int v, size_t[2] x); // overloads a[i .. j] = v int[2] opSlice(size_t x, size_t y); // overloads i .. j } void test() { A a; int v; a[] = v; // same as a.opIndexAssign(v); a[3..4] = v; // same as a.opIndexAssign(v, a.opSlice(3,4)); } ``` For backward compatibility, if rewriting `a[`*i*..*j*`]` as `a.opIndexAssign(a.opSlice(`*i*, *j*`))` fails to compile, the legacy rewrite `opSliceAssign(c,` *i*, *j*`)` is used instead. Op Assignment Operator Overloading ---------------------------------- The following op assignment operators are overloadable: Overloadable Op Assignment Operators| `+=` | `-=` | `*=` | `/=` | `%``=` | `^^=` | `&``=` | | `|``=` | `^=` | `<``<``=` | `>``>``=` | `>``>``>``=` | `~=` | | The expression: ``` a op= b ``` is rewritten as: ``` a.opOpAssign!("op")(b) ``` ### Index Op Assignment Operator Overloading If the left hand side of an *op*= is an index expression on a struct or class instance and `opIndexOpAssign` is a member: ``` a[b1, b2, ... bn] op= c ``` it is rewritten as: ``` a.opIndexOpAssign!("op")(c, b1, b2, ... bn) ``` ### Slice Op Assignment Operator Overloading If the left hand side of an *op*= is a slice expression on a struct or class instance and `opIndexOpAssign` is a member: ``` a[i..j] op= c ``` it is rewritten as: ``` a.opIndexOpAssign!("op")(c, a.opSlice(i, j)) ``` and ``` a[] op= c ``` it is rewritten as: ``` a.opIndexOpAssign!("op")(c) ``` For backward compatibility, if the above rewrites fail and `opSliceOpAssign` is defined, then the rewrites `a.opSliceOpAssign(c, i, j)` and `a.opSliceOpAssign(c)` are tried, respectively. Array Indexing and Slicing Operators Overloading ------------------------------------------------ The array indexing and slicing operators are overloaded by implementing the `opIndex`, `opSlice`, and `opDollar` methods. These may be combined to implement multidimensional arrays. The code example below shows a simple implementation of a 2-dimensional array with overloaded indexing and slicing operators. The explanations of the various constructs employed are given in the sections following. ``` struct Array2D(E) { E[] impl; int stride; int width, height; this(int width, int height, E[] initialData = []) { impl = initialData; this.stride = this.width = width; this.height = height; impl.length = width * height; } // Index a single element, e.g., arr[0, 1] ref E opIndex(int i, int j) { return impl[i + stride*j]; } // Array slicing, e.g., arr[1..2, 1..2], arr[2, 0..&dollar;], arr[0..&dollar;, 1]. Array2D opIndex(int[2] r1, int[2] r2) { Array2D result; auto startOffset = r1[0] + r2[0]*stride; auto endOffset = r1[1] + (r2[1] - 1)*stride; result.impl = this.impl[startOffset .. endOffset]; result.stride = this.stride; result.width = r1[1] - r1[0]; result.height = r2[1] - r2[0]; return result; } auto opIndex(int[2] r1, int j) { return opIndex(r1, [j, j+1]); } auto opIndex(int i, int[2] r2) { return opIndex([i, i+1], r2); } // Support for `x..y` notation in slicing operator for the given dimension. int[2] opSlice(size_t dim)(int start, int end) if (dim >= 0 && dim < 2) in { assert(start >= 0 && end <= this.opDollar!dim); } body { return [start, end]; } // Support `&dollar;` in slicing notation, e.g., arr[1..&dollar;, 0..&dollar;-1]. @property int opDollar(size_t dim : 0)() { return width; } @property int opDollar(size_t dim : 1)() { return height; } } unittest { auto arr = Array2D!int(4, 3, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]); // Basic indexing assert(arr[0, 0] == 0); assert(arr[1, 0] == 1); assert(arr[0, 1] == 4); // Use of opDollar assert(arr[$-1, 0] == 3); assert(arr[0, $-1] == 8); // Note the value of &dollar; differs by dimension assert(arr[$-1, $-1] == 11); // Slicing auto slice1 = arr[1..$, 0..$]; assert(slice1[0, 0] == 1 && slice1[1, 0] == 2 && slice1[2, 0] == 3 && slice1[0, 1] == 5 && slice1[1, 1] == 6 && slice1[2, 1] == 7 && slice1[0, 2] == 9 && slice1[1, 2] == 10 && slice1[2, 2] == 11); auto slice2 = slice1[0..2, 1..$]; assert(slice2[0, 0] == 5 && slice2[1, 0] == 6 && slice2[0, 1] == 9 && slice2[1, 1] == 10); // Thin slices auto slice3 = arr[2, 0..$]; assert(slice3[0, 0] == 2 && slice3[0, 1] == 6 && slice3[0, 2] == 10); auto slice4 = arr[0..3, 2]; assert(slice4[0, 0] == 8 && slice4[1, 0] == 9 && slice4[2, 0] == 10); } ``` ### Index Operator Overloading Expressions of the form `arr[`*b*1, *b*2, ... *b*n`]` are translated into `arr.opIndex(`*b*1, *b*2, ... *b*n`)`. For example: ``` struct A { int opIndex(size_t i1, size_t i2, size_t i3); } void test() { A a; int i; i = a[5,6,7]; // same as i = a.opIndex(5,6,7); } ``` In this way a struct or class object can behave as if it were an array. If an index expression can be rewritten using `opIndexAssign` or `opIndexOpAssign`, those are preferred over `opIndex`. ### Slice Operator Overloading Overloading the slicing operator means overloading expressions like `a[]` or `a[`*i*..*j*`]`, where the expressions inside the square brackets contain slice expressions of the form *i*..*j*. To overload `a[]`, simply define `opIndex` with no parameters: ``` struct S { int[] impl; int[] opIndex() { return impl[]; } } void test() { auto s = S([1,2,3]); auto t = s[]; // calls s.opIndex() assert(t == [1,2,3]); } ``` To overload array indexing of the form `a[`*i*..*j*`,` ...`]`, two steps are needed. First, the expressions of the form *i*..*j* are translated via `opSlice` into user-defined objects that encapsulate the endpoints *i* and *j*. Then these user-defined objects are passed to `opIndex` to perform the actual slicing. This design was chosen in order to support mixed indexing and slicing in multidimensional arrays; for example, in translating expressions like `arr[1, 2..3, 4]`. More precisely, an expression of the form `arr[`*b*1, *b*2, ... *b*n`]` is translated into `arr.opIndex(`*c*1, *c*2, ... *c*n`)`. Each argument *b*i can be either a single expression, in which case it is passed directly as the corresponding argument *c*i to `opIndex`; or it can be a slice expression of the form *x*i`..`*y*i, in which case the corresponding argument *c*i to `opIndex` is `arr.opSlice!i(`*x*i`,` *y*i`)`. Namely: | ***op*** | ***rewrite*** | | --- | --- | | `arr[1, 2, 3]` | `arr.opIndex(1, 2, 3)` | | `arr[1..2, 3..4, 5..6]` | `arr.opIndex(arr.opSlice!0(1,2), arr.opSlice!1(3,4), arr.opSlice!2(5,6))` | | `arr[1, 2..3, 4]` | `arr.opIndex(1, arr.opSlice!1(2,3), 4)` | Similar translations are done for assignment operators involving slicing, for example: | ***op*** | ***rewrite*** | | --- | --- | | `arr[1, 2..3, 4] = c` | `arr.opIndexAssign(c, 1, arr.opSlice!1(2, 3), 4)` | | `arr[2, 3..4] += c` | `arr.opIndexOpAssign!"+"(c, 2, arr.opSlice!1(2, 3))` | The intention is that `opSlice!i` should return a user-defined object that represents an interval of indices along the `i`'th dimension of the array. This object is then passed to `opIndex` to perform the actual slicing operation. If only one-dimensional slicing is desired, `opSlice` may be declared without the compile-time parameter `i`. Note that in all cases, `arr` is only evaluated once. Thus, an expression like `getArray()[1, 2..3, $-1]=c` has the effect of: ``` auto __tmp = getArray(); __tmp.opIndexAssign(c, 1, __tmp.opSlice!1(2,3), __tmp.opDollar!2 - 1); ``` where the initial function call to `getArray` is only executed once. For backward compatibility, `a[]` and `a[`*i*..*j*`]` can also be overloaded by implementing `opSlice()` with no arguments and `opSlice(`*i*, *j*`)` with two arguments, respectively. This only applies for one-dimensional slicing, and dates from when D did not have full support for multidimensional arrays. This usage of `opSlice` is discouraged. ### Dollar Operator Overloading Within the arguments to array index and slicing operators, `$` gets translated to `opDollar!i`, where `i` is the position of the expression `$` appears in. For example: | ***op*** | ***rewrite*** | | --- | --- | | `arr[$-1, $-2, 3]` | `arr.opIndex(arr.opDollar!0 - 1, arr.opDollar!1 - 2, 3)` | | `arr[1, 2, 3..$]` | `arr.opIndex(1, 2, arr.opSlice!2(3, arr.opDollar!2))` | The intention is that `opDollar!i` should return the length of the array along its `i`'th dimension, or a user-defined object representing the end of the array along that dimension, that is understood by `opSlice` and `opIndex`. ``` struct Rectangle { int width, height; int[][] impl; this(int w, int h) { width = w; height = h; impl = new int[w][h]; } int opIndex(size_t i1, size_t i2) { return impl[i1][i2]; } int opDollar(size_t pos)() { static if (pos==0) return width; else return height; } } void test() { auto r = Rectangle(10,20); int i = r[$-1, 0]; // same as: r.opIndex(r.opDollar!0, 0), // which is r.opIndex(r.width-1, 0) int j = r[0, $-1]; // same as: r.opIndex(0, r.opDollar!1) // which is r.opIndex(0, r.height-1) } ``` As the above example shows, a different compile-time argument is passed to `opDollar` depending on which argument it appears in. A `$` appearing in the first argument gets translated to `opDollar!0`, a `$` appearing in the second argument gets translated to `opDollar!1`, and so on. Thus, the appropriate value for `$` can be returned to implement multidimensional arrays. Note that `opDollar!i` is only evaluated once for each `i` where `$` occurs in the corresponding position in the indexing operation. Thus, an expression like `arr[$-sqrt($), 0, $-1]` has the effect of: ``` auto __tmp1 = arr.opDollar!0; auto __tmp2 = arr.opDollar!2; arr.opIndex(__tmp1 - sqrt(__tmp1), 0, __tmp2 - 1); ``` If `opIndex` is declared with only one argument, the compile-time argument to `opDollar` may be omitted. In this case, it is illegal to use `$` inside an array indexing expression with more than one argument. Forwarding ---------- Member names not found in a class or struct can be forwarded to a template function named `opDispatch` for resolution. ``` import std.stdio; struct S { void opDispatch(string s, T)(T i) { writefln("S.opDispatch('%s', %s)", s, i); } } class C { void opDispatch(string s)(int i) { writefln("C.opDispatch('%s', %s)", s, i); } } struct D { template opDispatch(string s) { enum int opDispatch = 8; } } void main() { S s; s.opDispatch!("hello")(7); s.foo(7); auto c = new C(); c.foo(8); D d; writefln("d.foo = %s", d.foo); assert(d.foo == 8); } ``` D1 style operator overloading ----------------------------- The [D1 operator overload mechanisms](http://digitalmars.com/d/1.0/operatoroverloading.html) are deprecated.
programming_docs
d core.stdc.assert_ core.stdc.assert\_ ================== D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<assert.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/assert.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Source [core/stdc/assert\_.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/assert_.d) Standards: ISO/IEC 9899:1999 (E) These are the various functions called by the assert() macro. They are all noreturn functions, although D doesn't have a specific attribute for that. nothrow @nogc @trusted void **\_\_assert**(const(char)\* exp, const(char)\* file, uint line); Assert failure functions in the GLIBC library. nothrow @nogc @trusted void **\_\_assert\_fail**(const(char)\* exp, const(char)\* file, uint line, const(char)\* func); nothrow @nogc @trusted void **\_\_assert\_perror\_fail**(int errnum, const(char)\* file, uint line, const(char)\* func); d std.array std.array ========= Functions and types that manipulate built-in arrays and associative arrays. | Function Name | Description | | --- | --- | | [`array`](#array) | Returns a copy of the input in a newly allocated dynamic array. | | [`appender`](#appender) | Returns a new [`Appender`](#Appender) or [`RefAppender`](#RefAppender) initialized with a given array. | | [`assocArray`](#assocArray) | Returns a newly allocated associative array from a range of key/value tuples. | | [`byPair`](#byPair) | Construct a range iterating over an associative array by key/value tuples. | | [`insertInPlace`](#insertInPlace) | Inserts into an existing array at a given position. | | [`join`](#join) | Concatenates a range of ranges into one array. | | [`minimallyInitializedArray`](#minimallyInitializedArray) | Returns a new array of type `T`. | | [`replace`](#replace) | Returns a new array with all occurrences of a certain subrange replaced. | | [`replaceFirst`](#replaceFirst) | Returns a new array with the first occurrence of a certain subrange replaced. | | [`replaceInPlace`](#replaceInPlace) | Replaces all occurrences of a certain subrange and puts the result into a given array. | | [`replaceInto`](#replaceInto) | Replaces all occurrences of a certain subrange and puts the result into an output range. | | [`replaceLast`](#replaceLast) | Returns a new array with the last occurrence of a certain subrange replaced. | | [`replaceSlice`](#replaceSlice) | Returns a new array with a given slice replaced. | | [`replicate`](#replicate) | Creates a new array out of several copies of an input array or range. | | [`sameHead`](#sameHead) | Checks if the initial segments of two arrays refer to the same place in memory. | | [`sameTail`](#sameTail) | Checks if the final segments of two arrays refer to the same place in memory. | | [`split`](#split) | Eagerly split a range or string into an array. | | [`staticArray`](#staticArray) | Creates a new static array from given data. | | [`uninitializedArray`](#uninitializedArray) | Returns a new array of type `T` without initializing its elements. | This module provides all kinds of functions to create, manipulate or convert arrays: License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: [Andrei Alexandrescu](http://erdani.org) and [Jonathan M Davis](http://jmdavisprog.com) Source [std/array.d](https://github.com/dlang/phobos/blob/master/std/array.d) ForeachType!Range[] **array**(Range)(Range r) Constraints: if (isIterable!Range && !isAutodecodableString!Range && !isInfinite!Range); ForeachType!(PointerTarget!Range)[] **array**(Range)(Range r) Constraints: if (isPointer!Range && isIterable!(PointerTarget!Range) && !isAutodecodableString!Range && !isInfinite!Range); Allocates an array and initializes it with copies of the elements of range `r`. Narrow strings are handled as follows: * If autodecoding is turned on (default), then they are handled as a separate overload. * If autodecoding is turned off, then this is equivalent to duplicating the array. Parameters: | | | | --- | --- | | Range `r` | range (or aggregate with `opApply` function) whose elements are copied into the allocated array | Returns: allocated and initialized array Examples: ``` auto a = array([1, 2, 3, 4, 5][]); writeln(a); // [1, 2, 3, 4, 5] ``` CopyTypeQualifiers!(ElementType!String, dchar)[] **array**(String)(scope String str) Constraints: if (isAutodecodableString!String); Convert a narrow autodecoding string to an array type that fully supports random access. This is handled as a special case and always returns an array of `dchar` NOTE This function is never used when autodecoding is turned off. Parameters: | | | | --- | --- | | String `str` | `isNarrowString` to be converted to an array of `dchar` | Returns: a `dchar[]`, `const(dchar)[]`, or `immutable(dchar)[]` depending on the constness of the input. Examples: ``` import std.range.primitives : isRandomAccessRange; import std.traits : isAutodecodableString; // note that if autodecoding is turned off, `array` will not transcode these. static if (isAutodecodableString!string) writeln("Hello D".array); // "Hello D"d else writeln("Hello D".array); // "Hello D" static if (isAutodecodableString!wstring) writeln("Hello D"w.array); // "Hello D"d else writeln("Hello D"w.array); // "Hello D"w static assert(isRandomAccessRange!dstring == true); ``` auto **assocArray**(Range)(Range r) Constraints: if (isInputRange!Range); auto **assocArray**(Keys, Values)(Keys keys, Values values) Constraints: if (isInputRange!Values && isInputRange!Keys); Returns a newly allocated associative array from a range of key/value tuples or from a range of keys and a range of values. Parameters: | | | | --- | --- | | Range `r` | An [input range](std_range_primitives#isInputRange) of tuples of keys and values. | | Keys `keys` | An [input range](std_range_primitives#isInputRange) of keys | | Values `values` | An [input range](std_range_primitives#isInputRange) of values | Returns: A newly allocated associative array out of elements of the input range, which must be a range of tuples (Key, Value) or a range of keys and a range of values. If given two ranges of unequal lengths after the elements of the shorter are exhausted the remaining elements of the longer will not be considered. Returns a null associative array reference when given an empty range. Duplicates Associative arrays have unique keys. If r contains duplicate keys, then the result will contain the value of the last pair for that key in r. See Also: [`std.typecons.Tuple`](std_typecons#Tuple), [`std.range.zip`](std_range#zip) Examples: ``` import std.range : repeat, zip; import std.typecons : tuple; import std.range.primitives : autodecodeStrings; auto a = assocArray(zip([0, 1, 2], ["a", "b", "c"])); // aka zipMap static assert(is(typeof(a) == string[int])); writeln(a); // [0:"a", 1:"b", 2:"c"] auto b = assocArray([ tuple("foo", "bar"), tuple("baz", "quux") ]); static assert(is(typeof(b) == string[string])); writeln(b); // ["foo":"bar", "baz":"quux"] static if (autodecodeStrings) alias achar = dchar; else alias achar = immutable(char); auto c = assocArray("ABCD", true.repeat); static assert(is(typeof(c) == bool[achar])); bool[achar] expected = ['D':true, 'A':true, 'B':true, 'C':true]; writeln(c); // expected ``` auto **byPair**(AA)(AA aa) Constraints: if (isAssociativeArray!AA); Construct a range iterating over an associative array by key/value tuples. Parameters: | | | | --- | --- | | AA `aa` | The associative array to iterate over. | Returns: A [forward range](std_range_primitives#isForwardRange) of Tuple's of key and value pairs from the given associative array. The members of each pair can be accessed by name (`.key` and `.value`). or by integer index (0 and 1 respectively). Examples: ``` import std.algorithm.sorting : sort; import std.typecons : tuple, Tuple; auto aa = ["a": 1, "b": 2, "c": 3]; Tuple!(string, int)[] pairs; // Iteration over key/value pairs. foreach (pair; aa.byPair) { if (pair.key == "b") pairs ~= tuple("B", pair.value); else pairs ~= pair; } // Iteration order is implementation-dependent, so we should sort it to get // a fixed order. pairs.sort(); assert(pairs == [ tuple("B", 2), tuple("a", 1), tuple("c", 3) ]); ``` nothrow @system auto **uninitializedArray**(T, I...)(I sizes) Constraints: if (isDynamicArray!T && allSatisfy!(isIntegral, I) && hasIndirections!(ElementEncodingType!T)); nothrow @trusted auto **uninitializedArray**(T, I...)(I sizes) Constraints: if (isDynamicArray!T && allSatisfy!(isIntegral, I) && !hasIndirections!(ElementEncodingType!T)); Returns a new array of type `T` allocated on the garbage collected heap without initializing its elements. This can be a useful optimization if every element will be immediately initialized. `T` may be a multidimensional array. In this case sizes may be specified for any number of dimensions from 0 to the number in `T`. uninitializedArray is `nothrow` and weakly `pure`. uninitializedArray is `@system` if the uninitialized element type has pointers. Parameters: | | | | --- | --- | | T | The type of the resulting array elements | | I `sizes` | The length dimension(s) of the resulting array | Returns: An array of `T` with `I.length` dimensions. Examples: ``` double[] arr = uninitializedArray!(double[])(100); writeln(arr.length); // 100 double[][] matrix = uninitializedArray!(double[][])(42, 31); writeln(matrix.length); // 42 writeln(matrix[0].length); // 31 char*[] ptrs = uninitializedArray!(char*[])(100); writeln(ptrs.length); // 100 ``` nothrow @trusted auto **minimallyInitializedArray**(T, I...)(I sizes) Constraints: if (isDynamicArray!T && allSatisfy!(isIntegral, I)); Returns a new array of type `T` allocated on the garbage collected heap. Partial initialization is done for types with indirections, for preservation of memory safety. Note that elements will only be initialized to 0, but not necessarily the element type's `.init`. minimallyInitializedArray is `nothrow` and weakly `pure`. Parameters: | | | | --- | --- | | T | The type of the array elements | | I `sizes` | The length dimension(s) of the resulting array | Returns: An array of `T` with `I.length` dimensions. Examples: ``` import std.algorithm.comparison : equal; import std.range : repeat; auto arr = minimallyInitializedArray!(int[])(42); writeln(arr.length); // 42 // Elements aren't necessarily initialized to 0, so don't do this: // assert(arr.equal(0.repeat(42))); // If that is needed, initialize the array normally instead: auto arr2 = new int[42]; assert(arr2.equal(0.repeat(42))); ``` @trusted CommonType!(T[], U[]) **overlap**(T, U)(T[] a, U[] b) Constraints: if (is(typeof(a.ptr < b.ptr) == bool)); Returns the overlapping portion, if any, of two arrays. Unlike `equal`, `overlap` only compares the pointers and lengths in the ranges, not the values referred by them. If `r1` and `r2` have an overlapping slice, returns that slice. Otherwise, returns the null slice. Parameters: | | | | --- | --- | | T[] `a` | The first array to compare | | U[] `b` | The second array to compare | Returns: The overlapping portion of the two arrays. Examples: ``` int[] a = [ 10, 11, 12, 13, 14 ]; int[] b = a[1 .. 3]; writeln(overlap(a, b)); // [11, 12] b = b.dup; // overlap disappears even though the content is the same assert(overlap(a, b).empty); static test()() @nogc { auto a = "It's three o'clock"d; auto b = a[5 .. 10]; return b.overlap(a); } //works at compile-time static assert(test == "three"d); ``` void **insertInPlace**(T, U...)(ref T[] array, size\_t pos, U stuff) Constraints: if (!isSomeString!(T[]) && allSatisfy!(isInputRangeOrConvertible!T, U) && (U.length > 0)); void **insertInPlace**(T, U...)(ref T[] array, size\_t pos, U stuff) Constraints: if (isSomeString!(T[]) && allSatisfy!(isCharOrStringOrDcharRange, U)); Inserts `stuff` (which must be an input range or any number of implicitly convertible items) in `array` at position `pos`. Parameters: | | | | --- | --- | | T[] `array` | The array that `stuff` will be inserted into. | | size\_t `pos` | The position in `array` to insert the `stuff`. | | U `stuff` | An [input range](std_range_primitives#isInputRange), or any number of implicitly convertible items to insert into `array`. | Examples: ``` int[] a = [ 1, 2, 3, 4 ]; a.insertInPlace(2, [ 1, 2 ]); writeln(a); // [1, 2, 1, 2, 3, 4] a.insertInPlace(3, 10u, 11); writeln(a); // [1, 2, 1, 10, 11, 2, 3, 4] ``` pure nothrow @safe bool **sameHead**(T)(in T[] lhs, in T[] rhs); Returns whether the `front`s of `lhs` and `rhs` both refer to the same place in memory, making one of the arrays a slice of the other which starts at index `0`. Parameters: | | | | --- | --- | | T[] `lhs` | the first array to compare | | T[] `rhs` | the second array to compare | Returns: `true` if `lhs.ptr == rhs.ptr`, `false` otherwise. Examples: ``` auto a = [1, 2, 3, 4, 5]; auto b = a[0 .. 2]; assert(a.sameHead(b)); ``` pure nothrow @trusted bool **sameTail**(T)(in T[] lhs, in T[] rhs); Returns whether the `back`s of `lhs` and `rhs` both refer to the same place in memory, making one of the arrays a slice of the other which end at index `$`. Parameters: | | | | --- | --- | | T[] `lhs` | the first array to compare | | T[] `rhs` | the second array to compare | Returns: `true` if both arrays are the same length and `lhs.ptr == rhs.ptr`, `false` otherwise. Examples: ``` auto a = [1, 2, 3, 4, 5]; auto b = a[3..$]; assert(a.sameTail(b)); ``` ElementEncodingType!S[] **replicate**(S)(S s, size\_t n) Constraints: if (isDynamicArray!S); ElementType!S[] **replicate**(S)(S s, size\_t n) Constraints: if (isInputRange!S && !isDynamicArray!S); Parameters: | | | | --- | --- | | S `s` | an [input range](std_range_primitives#isInputRange) or a dynamic array | | size\_t `n` | number of times to repeat `s` | Returns: An array that consists of `s` repeated `n` times. This function allocates, fills, and returns a new array. See Also: For a lazy version, refer to [`std.range.repeat`](std_range#repeat). Examples: ``` auto a = "abc"; auto s = replicate(a, 3); writeln(s); // "abcabcabc" auto b = [1, 2, 3]; auto c = replicate(b, 3); writeln(c); // [1, 2, 3, 1, 2, 3, 1, 2, 3] auto d = replicate(b, 0); writeln(d); // [] ``` pure @safe S[] **split**(S)(S s) Constraints: if (isSomeString!S); auto **split**(Range, Separator)(Range range, Separator sep) Constraints: if (isForwardRange!Range && (is(typeof(ElementType!Range.init == Separator.init)) || is(typeof(ElementType!Range.init == ElementType!Separator.init)) && isForwardRange!Separator)); auto **split**(alias isTerminator, Range)(Range range) Constraints: if (isForwardRange!Range && is(typeof(unaryFun!isTerminator(range.front)))); Eagerly splits `range` into an array, using `sep` as the delimiter. When no delimiter is provided, strings are split into an array of words, using whitespace as delimiter. Runs of whitespace are merged together (no empty words are produced). The `range` must be a [forward range](std_range_primitives#isForwardRange). The separator can be a value of the same type as the elements in `range` or it can be another forward `range`. Parameters: | | | | --- | --- | | S `s` | the string to split by word if no separator is given | | Range `range` | the range to split | | Separator `sep` | a value of the same type as the elements of `range` or another | | isTerminator | a predicate that splits the range when it returns `true`. | Returns: An array containing the divided parts of `range` (or the words of `s`). See Also: [`std.algorithm.iteration.splitter`](std_algorithm_iteration#splitter) for a lazy version without allocating memory. [`std.regex.splitter`](std_regex#splitter) for a version that splits using a regular expression defined separator. Examples: ``` import std.uni : isWhite; writeln("Learning,D,is,fun".split(",")); // ["Learning", "D", "is", "fun"] writeln("Learning D is fun".split!isWhite); // ["Learning", "D", "is", "fun"] writeln("Learning D is fun".split(" D ")); // ["Learning", "is fun"] ``` Examples: ``` string str = "Hello World!"; writeln(str.split); // ["Hello", "World!"] string str2 = "Hello\t\tWorld\t!"; writeln(str2.split); // ["Hello", "World", "!"] ``` Examples: ``` writeln(split("hello world")); // ["hello", "world"] writeln(split("192.168.0.1", ".")); // ["192", "168", "0", "1"] auto a = split([1, 2, 3, 4, 5, 1, 2, 3, 4, 5], [2, 3]); writeln(a); // [[1], [4, 5, 1], [4, 5]] ``` ElementEncodingType!(ElementType!RoR)[] **join**(RoR, R)(RoR ror, scope R sep) Constraints: if (isInputRange!RoR && isInputRange!(Unqual!(ElementType!RoR)) && isInputRange!R && (is(immutable(ElementType!(ElementType!RoR)) == immutable(ElementType!R)) || isSomeChar!(ElementType!(ElementType!RoR)) && isSomeChar!(ElementType!R))); ElementEncodingType!(ElementType!RoR)[] **join**(RoR, E)(RoR ror, scope E sep) Constraints: if (isInputRange!RoR && isInputRange!(Unqual!(ElementType!RoR)) && (is(E : ElementType!(ElementType!RoR)) || !autodecodeStrings && isSomeChar!(ElementType!(ElementType!RoR)) && isSomeChar!E)); ElementEncodingType!(ElementType!RoR)[] **join**(RoR)(RoR ror) Constraints: if (isInputRange!RoR && isInputRange!(Unqual!(ElementType!RoR))); Eagerly concatenates all of the ranges in `ror` together (with the GC) into one array using `sep` as the separator if present. Parameters: | | | | --- | --- | | RoR `ror` | An [input range](std_range_primitives#isInputRange) of input ranges | | R `sep` | An input range, or a single element, to join the ranges on | Returns: An array of elements See Also: For a lazy version, see [`std.algorithm.iteration.joiner`](std_algorithm_iteration#joiner) Examples: ``` writeln(join(["hello", "silly", "world"], " ")); // "hello silly world" writeln(join(["hello", "silly", "world"])); // "hellosillyworld" writeln(join([[1, 2, 3], [4, 5]], [72, 73])); // [1, 2, 3, 72, 73, 4, 5] writeln(join([[1, 2, 3], [4, 5]])); // [1, 2, 3, 4, 5] const string[] arr = ["apple", "banana"]; writeln(arr.join(",")); // "apple,banana" writeln(arr.join()); // "applebanana" ``` E[] **replace**(E, R1, R2)(E[] subject, R1 from, R2 to) Constraints: if (isForwardRange!R1 && isForwardRange!R2 && (hasLength!R2 || isSomeString!R2) || is(Unqual!E : Unqual!R1)); Replace occurrences of `from` with `to` in `subject` in a new array. Parameters: | | | | --- | --- | | E[] `subject` | the array to scan | | R1 `from` | the item to replace | | R2 `to` | the item to replace all instances of `from` with | Returns: A new array without changing the contents of `subject`, or the original array if no match is found. See Also: [`std.algorithm.iteration.substitute`](std_algorithm_iteration#substitute) for a lazy replace. Examples: ``` writeln("Hello Wörld".replace("o Wö", "o Wo")); // "Hello World" writeln("Hello Wörld".replace("l", "h")); // "Hehho Wörhd" ``` void **replaceInto**(E, Sink, R1, R2)(Sink sink, E[] subject, R1 from, R2 to) Constraints: if (isOutputRange!(Sink, E) && (isForwardRange!R1 && isForwardRange!R2 && (hasLength!R2 || isSomeString!R2) || is(Unqual!E : Unqual!R1))); Replace occurrences of `from` with `to` in `subject` and output the result into `sink`. Parameters: | | | | --- | --- | | Sink `sink` | an [output range](std_range_primitives#isOutputRange) | | E[] `subject` | the array to scan | | R1 `from` | the item to replace | | R2 `to` | the item to replace all instances of `from` with | See Also: [`std.algorithm.iteration.substitute`](std_algorithm_iteration#substitute) for a lazy replace. Examples: ``` auto arr = [1, 2, 3, 4, 5]; auto from = [2, 3]; auto to = [4, 6]; auto sink = appender!(int[])(); replaceInto(sink, arr, from, to); writeln(sink.data); // [1, 4, 6, 4, 5] ``` T[] **replace**(T, Range)(T[] subject, size\_t from, size\_t to, Range stuff) Constraints: if (isInputRange!Range && (is(ElementType!Range : T) || isSomeString!(T[]) && is(ElementType!Range : dchar))); Replaces elements from `array` with indices ranging from `from` (inclusive) to `to` (exclusive) with the range `stuff`. Parameters: | | | | --- | --- | | T[] `subject` | the array to scan | | size\_t `from` | the starting index | | size\_t `to` | the ending index | | Range `stuff` | the items to replace in-between `from` and `to` | Returns: A new array without changing the contents of `subject`. See Also: [`std.algorithm.iteration.substitute`](std_algorithm_iteration#substitute) for a lazy replace. Examples: ``` auto a = [ 1, 2, 3, 4 ]; auto b = a.replace(1, 3, [ 9, 9, 9 ]); writeln(a); // [1, 2, 3, 4] writeln(b); // [1, 9, 9, 9, 4] ``` void **replaceInPlace**(T, Range)(ref T[] array, size\_t from, size\_t to, Range stuff) Constraints: if (is(typeof(replace(array, from, to, stuff)))); Replaces elements from `array` with indices ranging from `from` (inclusive) to `to` (exclusive) with the range `stuff`. Expands or shrinks the array as needed. Parameters: | | | | --- | --- | | T[] `array` | the array to scan | | size\_t `from` | the starting index | | size\_t `to` | the ending index | | Range `stuff` | the items to replace in-between `from` and `to` | Examples: ``` int[] a = [1, 4, 5]; replaceInPlace(a, 1u, 2u, [2, 3, 4]); writeln(a); // [1, 2, 3, 4, 5] replaceInPlace(a, 1u, 2u, cast(int[])[]); writeln(a); // [1, 3, 4, 5] replaceInPlace(a, 1u, 3u, a[2 .. 4]); writeln(a); // [1, 4, 5, 5] ``` E[] **replaceFirst**(E, R1, R2)(E[] subject, R1 from, R2 to) Constraints: if (isDynamicArray!(E[]) && isForwardRange!R1 && is(typeof(appender!(E[])().put(from[0..1]))) && isForwardRange!R2 && is(typeof(appender!(E[])().put(to[0..1])))); Replaces the first occurrence of `from` with `to` in `subject`. Parameters: | | | | --- | --- | | E[] `subject` | the array to scan | | R1 `from` | the item to replace | | R2 `to` | the item to replace `from` with | Returns: A new array without changing the contents of `subject`, or the original array if no match is found. Examples: ``` auto a = [1, 2, 2, 3, 4, 5]; auto b = a.replaceFirst([2], [1337]); writeln(b); // [1, 1337, 2, 3, 4, 5] auto s = "This is a foo foo list"; auto r = s.replaceFirst("foo", "silly"); writeln(r); // "This is a silly foo list" ``` E[] **replaceLast**(E, R1, R2)(E[] subject, R1 from, R2 to) Constraints: if (isDynamicArray!(E[]) && isForwardRange!R1 && is(typeof(appender!(E[])().put(from[0..1]))) && isForwardRange!R2 && is(typeof(appender!(E[])().put(to[0..1])))); Replaces the last occurrence of `from` with `to` in `subject`. Parameters: | | | | --- | --- | | E[] `subject` | the array to scan | | R1 `from` | the item to replace | | R2 `to` | the item to replace `from` with | Returns: A new array without changing the contents of `subject`, or the original array if no match is found. Examples: ``` auto a = [1, 2, 2, 3, 4, 5]; auto b = a.replaceLast([2], [1337]); writeln(b); // [1, 2, 1337, 3, 4, 5] auto s = "This is a foo foo list"; auto r = s.replaceLast("foo", "silly"); writeln(r); // "This is a foo silly list" ``` inout(T)[] **replaceSlice**(T)(inout(T)[] s, in T[] slice, in T[] replacement); Creates a new array such that the items in `slice` are replaced with the items in `replacement`. `slice` and `replacement` do not need to be the same length. The result will grow or shrink based on the items given. Parameters: | | | | --- | --- | | inout(T)[] `s` | the base of the new array | | T[] `slice` | the slice of `s` to be replaced | | T[] `replacement` | the items to replace `slice` with | Returns: A new array that is `s` with `slice` replaced by `replacement[]`. See Also: [`std.algorithm.iteration.substitute`](std_algorithm_iteration#substitute) for a lazy replace. Examples: ``` auto a = [1, 2, 3, 4, 5]; auto b = replaceSlice(a, a[1 .. 4], [0, 0, 0]); writeln(b); // [1, 0, 0, 0, 5] ``` struct **Appender**(A) if (isDynamicArray!A); Implements an output range that appends data to an array. This is recommended over `array ~= data` when appending many elements because it is more efficient. `Appender` maintains its own array metadata locally, so it can avoid global locking for each append where [`capacity`](#capacity) is non-zero. Parameters: | | | | --- | --- | | A | the array type to simulate. | See Also: [`appender`](#appender) Examples: ``` auto app = appender!string(); string b = "abcdefg"; foreach (char c; b) app.put(c); writeln(app[]); // "abcdefg" int[] a = [ 1, 2 ]; auto app2 = appender(a); app2.put(3); app2.put([ 4, 5, 6 ]); writeln(app2[]); // [1, 2, 3, 4, 5, 6] ``` pure nothrow @trusted this(A arr); Constructs an `Appender` with a given array. Note that this does not copy the data. If the array has a larger capacity as determined by `arr.capacity`, it will be used by the appender. After initializing an appender on an array, appending to the original array will reallocate. void **reserve**(size\_t newCapacity); Reserve at least newCapacity elements for appending. Note that more elements may be reserved than requested. If `newCapacity <= capacity`, then nothing is done. Parameters: | | | | --- | --- | | size\_t `newCapacity` | the capacity the `Appender` should have | const pure nothrow @property @safe size\_t **capacity**(); Returns: the capacity of the array (the maximum number of elements the managed array can accommodate before triggering a reallocation). If any appending will reallocate, `0` will be returned. inout pure nothrow @property @trusted inout(ElementEncodingType!A)[] **data**(); Use opSlice() from now on. Returns: The managed array. inout pure nothrow @property @trusted inout(ElementEncodingType!A)[] **opSlice**(); Returns: The managed array. void **put**(U)(U item) Constraints: if (canPutItem!U); Appends `item` to the managed array. Performs encoding for `char` types if `A` is a differently typed `char` array. Parameters: | | | | --- | --- | | U `item` | the single item to append | void **put**(Range)(Range items) Constraints: if (canPutRange!Range); Appends an entire range to the managed array. Performs encoding for `char` elements if `A` is a differently typed `char` array. Parameters: | | | | --- | --- | | Range `items` | the range of items to append | template **opOpAssign**(string op : "~") Appends to the managed array. See Also: [`Appender.put`](#Appender.put) pure nothrow @trusted void **clear**(); Clears the managed array. This allows the elements of the array to be reused for appending. Note clear is disabled for immutable or const element types, due to the possibility that `Appender` might overwrite immutable data. pure @trusted void **shrinkTo**(size\_t newlength); Shrinks the managed array to the given length. Throws: `Exception` if newlength is greater than the current array length. Note shrinkTo is disabled for immutable or const element types. const string **toString**()(); const void **toString**(Writer)(ref Writer w, ref scope const std.format.FormatSpec!char fmt) Constraints: if (isOutputRange!(Writer, char)); Gives a string in the form of `Appender!(A)(data)`. Parameters: | | | | --- | --- | | Writer `w` | A `char` accepting [output range](std_range_primitives#isOutputRange). | | std.format.FormatSpec!char `fmt` | A [`std.format.FormatSpec`](std_format#FormatSpec) which controls how the array is formatted. | Returns: A `string` if `writer` is not set; `void` otherwise. struct **RefAppender**(A) if (isDynamicArray!A); A version of [`Appender`](#Appender) that can update an array in-place. It forwards all calls to an underlying appender implementation. Any calls made to the appender also update the pointer to the original array passed in. Tip Use the `arrayPtr` overload of [`appender`](#appender) for construction with type-inference. Parameters: | | | | --- | --- | | A | The array type to simulate | Examples: ``` int[] a = [1, 2]; auto app2 = appender(&a); writeln(app2[]); // [1, 2] writeln(a); // [1, 2] app2 ~= 3; app2 ~= [4, 5, 6]; writeln(app2[]); // [1, 2, 3, 4, 5, 6] writeln(a); // [1, 2, 3, 4, 5, 6] app2.reserve(5); assert(app2.capacity >= 5); ``` this(A\* arr); Constructs a `RefAppender` with a given array reference. This does not copy the data. If the array has a larger capacity as determined by `arr.capacity`, it will be used by the appender. Note Do not use built-in appending (i.e. `~=`) on the original array until you are done with the appender, because subsequent calls to the appender will reallocate the array data without those appends. Parameters: | | | | --- | --- | | A\* `arr` | Pointer to an array. Must not be null. | void **opDispatch**(string fn, Args...)(Args args) Constraints: if (\_\_traits(compiles, (Appender!A a) => mixin("a." ~ fn ~ "(args)"))); Wraps remaining `Appender` methods such as [`put`](#put). Parameters: | | | | --- | --- | | fn | Method name to call. | | Args `args` | Arguments to pass to the method. | void **opOpAssign**(string op : "~", U)(U rhs) Constraints: if (\_\_traits(compiles, (Appender!A a) { a.put(rhs); } )); Appends `rhs` to the managed array. Parameters: | | | | --- | --- | | U `rhs` | Element or range. | const @property size\_t **capacity**(); Returns the capacity of the array (the maximum number of elements the managed array can accommodate before triggering a reallocation). If any appending will reallocate, `capacity` returns `0`. inout @property inout(ElementEncodingType!A)[] **opSlice**(); Returns: the managed array. Appender!A **appender**(A)() Constraints: if (isDynamicArray!A); Appender!(E[]) **appender**(A : E[], E)(auto ref A array); Convenience function that returns an [`Appender`](#Appender) instance, optionally initialized with `array`. Examples: ``` auto w = appender!string; // pre-allocate space for at least 10 elements (this avoids costly reallocations) w.reserve(10); assert(w.capacity >= 10); w.put('a'); // single elements w.put("bc"); // multiple elements // use the append syntax w ~= 'd'; w ~= "ef"; writeln(w[]); // "abcdef" ``` RefAppender!(E[]) **appender**(P : E[]\*, E)(P arrayPtr); Convenience function that returns a [`RefAppender`](#RefAppender) instance initialized with `arrayPtr`. Don't use null for the array pointer, use the other version of `appender` instead. Examples: ``` int[] a = [1, 2]; auto app2 = appender(&a); writeln(app2[]); // [1, 2] writeln(a); // [1, 2] app2 ~= 3; app2 ~= [4, 5, 6]; writeln(app2[]); // [1, 2, 3, 4, 5, 6] writeln(a); // [1, 2, 3, 4, 5, 6] app2.reserve(5); assert(app2.capacity >= 5); ``` T[n] **staticArray**(T, size\_t n)(auto ref T[n] a); auto **staticArray**(size\_t n, T)(scope T a) Constraints: if (isInputRange!T); auto **staticArray**(size\_t n, T)(scope T a, out size\_t rangeLength) Constraints: if (isInputRange!T); auto **staticArray**(Un : U[n], U, size\_t n, T)(scope T a) Constraints: if (isInputRange!T && is(ElementType!T : U)); auto **staticArray**(Un : U[n], U, size\_t n, T)(scope T a, out size\_t rangeLength) Constraints: if (isInputRange!T && is(ElementType!T : U)); auto **staticArray**(alias a)() Constraints: if (isInputRange!(typeof(a))); auto **staticArray**(U, alias a)() Constraints: if (isInputRange!(typeof(a))); Constructs a static array from `a`. The type of elements can be specified implicitly so that `[1, 2].staticArray` results in `int[2]`, or explicitly, e.g. `[1, 2].staticArray!float` returns `float[2]`. When `a` is a range whose length is not known at compile time, the number of elements must be given as template argument (e.g. `myrange.staticArray!2`). Size and type can be combined, if the source range elements are implicitly convertible to the requested element type (eg: `2.iota.staticArray!(long[2])`). When the range `a` is known at compile time, it can also be specified as a template argument to avoid having to specify the number of elements (e.g.: `staticArray!(2.iota)` or `staticArray!(double, 2.iota)`). Note `staticArray` returns by value, so expressions involving large arrays may be inefficient. Parameters: | | | | --- | --- | | T[n] `a` | The input elements. If there are less elements than the specified length of the static array, the rest of it is default-initialized. If there are more than specified, the first elements up to the specified length are used. | | size\_t `rangeLength` | outputs the number of elements used from `a` to it. Optional. | Returns: A static array constructed from `a`. Examples: static array from array literal ``` auto a = [0, 1].staticArray; static assert(is(typeof(a) == int[2])); writeln(a); // [0, 1] ``` Examples: static array from range + size ``` import std.range : iota; auto input = 3.iota; auto a = input.staticArray!2; static assert(is(typeof(a) == int[2])); writeln(a); // [0, 1] auto b = input.staticArray!(long[4]); static assert(is(typeof(b) == long[4])); writeln(b); // [0, 1, 2, 0] ``` Examples: static array from CT range ``` import std.range : iota; enum a = staticArray!(2.iota); static assert(is(typeof(a) == int[2])); writeln(a); // [0, 1] enum b = staticArray!(long, 2.iota); static assert(is(typeof(b) == long[2])); writeln(b); // [0, 1] ```
programming_docs
d core.stdc.float_ core.stdc.float\_ ================= D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<float.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/float.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly Source [core/stdc/float\_.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/float_.d) Standards: ISO/IEC 9899:1999 (E) enum int **FLT\_ROUNDS**; enum int **FLT\_EVAL\_METHOD**; enum int **FLT\_RADIX**; enum int **DECIMAL\_DIG**; enum int **FLT\_DIG**; enum int **DBL\_DIG**; enum int **LDBL\_DIG**; enum int **FLT\_MANT\_DIG**; enum int **DBL\_MANT\_DIG**; enum int **LDBL\_MANT\_DIG**; enum float **FLT\_MIN**; enum double **DBL\_MIN**; enum real **LDBL\_MIN**; enum float **FLT\_MAX**; enum double **DBL\_MAX**; enum real **LDBL\_MAX**; enum float **FLT\_EPSILON**; enum double **DBL\_EPSILON**; enum real **LDBL\_EPSILON**; enum int **FLT\_MIN\_EXP**; enum int **DBL\_MIN\_EXP**; enum int **LDBL\_MIN\_EXP**; enum int **FLT\_MAX\_EXP**; enum int **DBL\_MAX\_EXP**; enum int **LDBL\_MAX\_EXP**; enum int **FLT\_MIN\_10\_EXP**; enum int **DBL\_MIN\_10\_EXP**; enum int **LDBL\_MIN\_10\_EXP**; enum int **FLT\_MAX\_10\_EXP**; enum int **DBL\_MAX\_10\_EXP**; enum int **LDBL\_MAX\_10\_EXP**; d Live Functions Live Functions ============== **Contents** 1. [Ownership/Borrowing](#ob) 1. [Tracked Pointers](#tracked) 2. [Pointer States](#state) 3. [Lifetimes](#lifetime) 4. [Pointer State Transitions](#transition) 5. [Borrowers can be Owners](#borrower) 6. [Exceptions](#exception) 7. [Lazy Parameters](#lazy) 8. [Mixing Memory Pools](#mempool) 9. [Variadic Function Arguments](#vargs) **Experimental, Subject to Change** If a memory object has only one pointer to it, that pointer is the *owner* of the memory object. With the single owner, it becomes straightforward to manage the memory for the object. It also becomes trivial to synchronize access to that memory object among multiple threads, because it can only be accessed by the thread that controls that single pointer. This can be generalized to a graph of memory objects interconnected by pointers, where only a single pointer connects to that graph from elsewhere. That single pointer becomes the *owner* of all the memory objects in that graph. When the owner of the graph is no longer needed, then the graph of memory objects it points to is no longer needed and can be safely disposed of. If the owner itself is no longer in use (i.e. is no longer *live*) and the owned memory objects are not disposed of, an error can be diagnosed. Hence, the following errors can be statically detected: ``` int* allocate(); // allocate a memory object void release(int*); // deallocate a memory object @live void test() { auto p = allocate(); } // error: p is not disposed of @live void test() { auto p = allocate(); release(p); release(p); // error: p was already disposed of } @live void test() { int* p = void; release(p); // error, p does not have a defined value } @live void test() { auto p = allocate(); p = allocate(); // error: p was not disposed of release(p); } ``` Functions with the `@live` attribute enable diagnosing these sorts of errors by tracking the status of owner pointers. Ownership/Borrowing ------------------- Tracking the ownership status of a pointer can be safely extended by adding the capability of temporarilly *borrowing* ownership of a pointer from the *owner*. The *owner* can no longer use the pointer as long as the *borrower* is still using the pointer value (i.e. is *live*). Once the *borrower* is no longer *live*, the *owner* and resume using it. Only one *borrower* can be live at any point. Multiple *borrower* pointers can simultaneously exist if all of them are pointers to read only (`const` or `immutable`) data, i.e. none of them can modify the memory object(s) pointed to. This is collectively called an *Ownership/Borrowing* system. It can be state as: > At any point in the program, for each memory object, there is exactly one live mutable pointer to it or all the live pointers to it are read-only. > > Function declarations annotated with the `@live` attribute are checked for compliance with the Ownership/Borrowing rules. The checks are run after other semantic processing is complete. The checking does not influence code generation. Whether a pointer is allocated memory using the GC or some other storage allocator is immaterial to OB, they are not distinguished and are handled identically. Class references are assumed to be allocated using either the GC or are allocated on the stack as `scope` classes, and are not tracked. If `@live` functions call non-`@live` functions, those called functions are expected to present an `@live` compatible interface, although it is not checked. if non-`@live` functions call `@live` functions, arguments passed are expected to follow `@live` conventions. It will not detect attempts to dereference `null` pointers or possibly `null` pointers. This is unworkable because there is no current method of annotating a type as a non-`null` pointer. ### Tracked Pointers The only pointers that are tracked are those declared in the `@live` function as `this`, function parameters or local variables. Variables from other functions are not tracked, even `@live` ones, as the analysis of interactions with other functions depends entirely on that function signature, not its internals. Parameters that are `const` are not tracked. ### Pointer States Each tracked pointer is in one of the following states: Undefined The pointer is in an invalid state. Dereferencing such a pointer is an error. Owner The owner is the sole pointer to a memory object graph. An Owner pointer normally does not have a `scope` attribute. If a pointer with the `scope` attribute is initialized with an expression not derived from a tracked pointer, it is an Owner. If an Owner pointer is assigned to another Owner pointer, the former enters the Undefined state. Borrowed A Borrowed pointer is one that temporarily becomes the sole pointer to a memory object graph. It enters that state via assignment from an owner pointer, and stays in that state until its last use. A Borrowed pointer must have the `scope` attribute and must be a pointer to mutable. Readonly A Readonly pointer acquires its value from an Owner. While the Readonly pointer is live, only Readonly pointers can be acquired from that Owner. A Readonly pointer must have the `scope` attribute and also must not be a pointer to mutable. ### Lifetimes The lifetime of a Borrowed or Readonly pointer value starts when it is assigned a value from an Owner or another Borrowed pointer, and ends at the last read of that value. This is also known as *Non-Lexical Lifetimes*. ### Pointer State Transitions A pointer changes its state when one of these operations is done to it: * storage is allocated for it (such as a local variable on the stack), which places the pointer in the Undefined state * initialization (treated as assignment) * assignment - the source and target pointers change state based on what states they are in and their types and storage classes * passed to an `out` function parameter (changes state after the function returns), treated the same as initialization * passed by `ref` to a function parameter, treated as an assignment to a Borrow or a Readonly depending on the storage class and type of the parameter * returned from a function * it is passed by value to a function parameter, which is treated as an assignment to that parameter. * it is implicitly passed by ref as a closure variable to a nested function * the address of the pointer is taken, which is treated as assignment to whoever receives the address * the address of any part of the memory object graph is taken, which is treated as assignment to whoever receives that address * a pointer value is read from any part of the memory object graph, which is treated as assignment to whoever receives that pointer * merging of control flow reconciles the state of each variable based on the states they have from each edge ### Borrowers can be Owners Borrowers are considered Owners if they are initialized from other than a pointer. ``` @live void uhoh() { scope p = malloc(); // p is considered an Owner scope const pc = malloc(); // pc is not considered an Owner } // dangling pointer pc is not detected on exit ``` ### Exceptions The analysis assumes no exceptions are thrown. ``` @live void leaky() { auto p = malloc(); pitcher(); // throws exception, p leaks free(p); } ``` One solution is to use `scope(exit)`: ``` @live void waterTight() { auto p = malloc(); scope(exit) free(p); pitcher(); } ``` or use RAII objects or call only `nothrow` functions. ### Lazy Parameters Lazy parameters are not considered. ### Mixing Memory Pools Conflation of different memory pools: ``` void* xmalloc(size_t); void xfree(void*); void* ymalloc(size_t); void yfree(void*); auto p = xmalloc(20); yfree(p); // should call xfree() instead ``` is not detected. This can be mitigated by using type-specific pools: ``` U* umalloc(); void ufree(U*); V* vmalloc(); void vfree(V*); auto p = umalloc(); vfree(p); // type mismatch ``` and perhaps disabling implicit conversions to `void*` in `@live` functions. ### Variadic Function Arguments Arguments to variadic functions (such as `printf`) are considered to be consumed. d rt.ehalloc rt.ehalloc ========== Exception allocation, cloning, and release compiler support routines. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright Source [rt/dwarfeh.d](https://github.com/dlang/druntime/blob/master/src/rt/dwarfeh.d) Throwable **\_d\_newThrowable**(const TypeInfo\_Class ci); Allocate an exception of type `ci` from the exception pool. It has the same interface as `rt.lifetime._d_newclass()`. The class type must be Throwable or derived from it, and cannot be a COM or C++ class. The compiler must enforce this. Returns: default initialized instance of the type nothrow void **\_d\_delThrowable**(Throwable t); Delete exception instance `t` from the exception pool. Must have been allocated with `_d_newThrowable()`. This is meant to be called at the close of a catch block. It's nothrow because otherwise any function with a catch block could not be nothrow. Input t = Throwable d etc.c.odbc.sqlucode etc.c.odbc.sqlucode =================== Declarations for interfacing with the ODBC library. Adapted with minimal changes from the work of David L. Davis (refer to the [original announcement](http://forum.dlang.org/post/cfk7ql&dollar;1p4n&dollar;[email protected])). `etc.c.odbc.sqlucode` corresponds to the `sqlucode.h` C include file. See Also: [ODBC API Reference on MSN Online](https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/odbc-api-reference) d std.experimental.allocator.building_blocks.null_allocator std.experimental.allocator.building\_blocks.null\_allocator =========================================================== Source [std/experimental/allocator/building\_blocks/null\_allocator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/null_allocator.d) struct **NullAllocator**; `NullAllocator` is an emphatically empty implementation of the allocator interface. Although it has no direct use, it is useful as a "terminator" in composite allocators. enum uint **alignment**; `NullAllocator` advertises a relatively large alignment equal to 64 KB. This is because `NullAllocator` never actually needs to honor this alignment and because composite allocators using `NullAllocator` shouldn't be unnecessarily constrained. shared pure nothrow @nogc @safe void[] **allocate**(size\_t); Always returns `null`. shared pure nothrow @nogc @safe void[] **alignedAllocate**(size\_t, uint); Always returns `null`. shared pure nothrow @nogc @safe void[] **allocateAll**(); Always returns `null`. shared pure nothrow @nogc @safe bool **expand**(ref void[] b, size\_t s); shared pure nothrow @nogc @safe bool **reallocate**(ref void[] b, size\_t); shared pure nothrow @nogc @safe bool **alignedReallocate**(ref void[] b, size\_t, uint); These methods return `false`. Precondition `b is null`. This is because there is no other possible legitimate input. shared const pure nothrow @nogc @safe Ternary **owns**(const void[]); Returns `Ternary.no`. shared const pure nothrow @nogc @safe Ternary **resolveInternalPointer**(const void\*, ref void[]); Returns `Ternary.no`. shared pure nothrow @nogc @safe bool **deallocate**(void[] b); No-op. Precondition `b is null` shared pure nothrow @nogc @safe bool **deallocateAll**(); No-op. shared const pure nothrow @nogc @safe Ternary **empty**(); Returns `Ternary.yes`. static shared NullAllocator **instance**; Returns the `shared` global instance of the `NullAllocator`. d std.experimental.allocator.building_blocks.segregator std.experimental.allocator.building\_blocks.segregator ====================================================== Source [std/experimental/allocator/building\_blocks/segregator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/segregator.d) struct **Segregator**(size\_t threshold, SmallAllocator, LargeAllocator); Dispatches allocations (and deallocations) between two allocators (`SmallAllocator` and `LargeAllocator`) depending on the size allocated, as follows. All allocations smaller than or equal to `threshold` will be dispatched to `SmallAllocator`. The others will go to `LargeAllocator`. If both allocators are `shared`, the `Segregator` will also offer `shared` methods. Examples: ``` import std.experimental.allocator.building_blocks.free_list : FreeList; import std.experimental.allocator.gc_allocator : GCAllocator; import std.experimental.allocator.mallocator : Mallocator; alias A = Segregator!( 1024 * 4, Segregator!( 128, FreeList!(Mallocator, 0, 128), GCAllocator), Segregator!( 1024 * 1024, Mallocator, GCAllocator) ); A a; auto b = a.allocate(200); writeln(b.length); // 200 a.deallocate(b); ``` enum uint **alignment**; The alignment offered is the minimum of the two allocators' alignment. static size\_t **goodAllocSize**(size\_t s); This method is defined only if at least one of the allocators defines it. The good allocation size is obtained from `SmallAllocator` if `s <= threshold`, or `LargeAllocator` otherwise. (If one of the allocators does not define `goodAllocSize`, the default implementation in this module applies.) void[] **allocate**(size\_t); The memory is obtained from `SmallAllocator` if `s <= threshold`, or `LargeAllocator` otherwise. void[] **alignedAllocate**(size\_t, uint); This method is defined if both allocators define it, and forwards to `SmallAllocator` or `LargeAllocator` appropriately. bool **expand**(ref void[] b, size\_t delta); This method is defined only if at least one of the allocators defines it. If `SmallAllocator` defines `expand` and `b.length + delta <= threshold`, the call is forwarded to `SmallAllocator`. If `LargeAllocator` defines `expand` and `b.length > threshold`, the call is forwarded to `LargeAllocator`. Otherwise, the call returns `false`. bool **reallocate**(ref void[] b, size\_t s); This method is defined only if at least one of the allocators defines it. If `SmallAllocator` defines `reallocate` and `b.length <= threshold && s <= threshold`, the call is forwarded to `SmallAllocator`. If `LargeAllocator` defines `expand` and `b.length > threshold && s > threshold`, the call is forwarded to `LargeAllocator`. Otherwise, the call returns `false`. bool **alignedReallocate**(ref void[] b, size\_t s, uint a); This method is defined only if at least one of the allocators defines it, and work similarly to `reallocate`. Ternary **owns**(void[] b); This method is defined only if both allocators define it. The call is forwarded to `SmallAllocator` if `b.length <= threshold`, or `LargeAllocator` otherwise. bool **deallocate**(void[] b); This function is defined only if both allocators define it, and forwards appropriately depending on `b.length`. bool **deallocateAll**(); This function is defined only if both allocators define it, and calls `deallocateAll` for them in turn. Ternary **empty**(); This function is defined only if both allocators define it, and returns the conjunction of `empty` calls for the two. ref auto **allocatorForSize**(size\_t s)(); Composite allocators involving nested instantiations of `Segregator` make it difficult to access individual sub-allocators stored within. `allocatorForSize` simplifies the task by supplying the allocator nested inside a `Segregator` that is responsible for a specific size `s`. Example ``` alias A = Segregator!(300, Segregator!(200, A1, A2), A3); A a; static assert(typeof(a.allocatorForSize!10) == A1); static assert(typeof(a.allocatorForSize!250) == A2); static assert(typeof(a.allocatorForSize!301) == A3); ``` template **Segregator**(Args...) if (Args.length > 3) A `Segregator` with more than three arguments expands to a composition of elemental `Segregator`s, as illustrated by the following example: ``` alias A = Segregator!( n1, A1, n2, A2, n3, A3, A4 ); ``` With this definition, allocation requests for `n1` bytes or less are directed to `A1`; requests between `n1 + 1` and `n2` bytes (inclusive) are directed to `A2`; requests between `n2 + 1` and `n3` bytes (inclusive) are directed to `A3`; and requests for more than `n3` bytes are directed to `A4`. If some particular range should not be handled, `NullAllocator` may be used appropriately. Examples: ``` import std.experimental.allocator.building_blocks.free_list : FreeList; import std.experimental.allocator.gc_allocator : GCAllocator; import std.experimental.allocator.mallocator : Mallocator; alias A = Segregator!( 128, FreeList!(Mallocator, 0, 128), 1024 * 4, GCAllocator, 1024 * 1024, Mallocator, GCAllocator ); A a; auto b = a.allocate(201); writeln(b.length); // 201 a.deallocate(b); ``` d std.net.isemail std.net.isemail =============== Validates an email address according to RFCs 5321, 5322 and others. Authors: Dominic Sayers <[email protected]>, Jacob Carlborg License: [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt) Dominic Sayers graciously granted permission to use the Boost license via email on Feb 22, 2011. Version: 3.0.13 - Version 3.0 of the original PHP implementation: <http://www.dominicsayers.com/isemail> Standards: * RFC 5321 * RFC 5322 References * <http://www.dominicsayers.com/isemail> * <http://tools.ietf.org/html/rfc5321> * <http://tools.ietf.org/html/rfc5322> Source [std/net/isemail.d](https://github.com/dlang/phobos/blob/master/std/net/isemail.d) EmailStatus **isEmail**(Char)(const(Char)[] email, CheckDns checkDNS = No.checkDns, EmailStatusCode errorLevel = EmailStatusCode.none) Constraints: if (isSomeChar!Char); Check that an email address conforms to RFCs 5321, 5322 and others. Distinguishes between a Mailbox as defined by RFC 5321 and an addr-spec as defined by RFC 5322. Depending on the context, either can be regarded as a valid email address. Note The DNS check is currently not implemented. Parameters: | | | | --- | --- | | const(Char)[] `email` | The email address to check | | CheckDns `checkDNS` | If `Yes.checkDns` then a DNS check for MX records will be made | | EmailStatusCode `errorLevel` | Determines the boundary between valid and invalid addresses. Status codes above this number will be returned as-is, status codes below will be returned as EmailStatusCode.valid. Thus the calling program can simply look for EmailStatusCode.valid if it is only interested in whether an address is valid or not. The errorLevel will determine how "picky" isEmail() is about the address. If omitted or passed as EmailStatusCode.none then isEmail() will not perform any finer grained error checking and an address is either considered valid or not. Email status code will either be EmailStatusCode.valid or EmailStatusCode.error. | Returns: An [`EmailStatus`](#EmailStatus), indicating the status of the email address. alias **CheckDns** = std.typecons.Flag!"checkDns".Flag; Flag for indicating if the isEmail function should perform a DNS check or not. If set to `CheckDns.no`, isEmail does not perform DNS checking. Otherwise if set to `CheckDns.yes`, isEmail performs DNS checking. struct **EmailStatus**; Represents the status of an email address const pure nothrow @nogc @property @safe bool **valid**(); Returns: If the email address is valid or not. const pure nothrow @nogc @property @safe string **localPart**(); Returns: The local part of the email address, that is, the part before the @ sign. const pure nothrow @nogc @property @safe string **domainPart**(); Returns: The domain part of the email address, that is, the part after the @ sign. const pure nothrow @nogc @property @safe EmailStatusCode **statusCode**(); Returns: The email status code const pure nothrow @nogc @property @safe string **status**(); Returns: A describing string of the status code const pure @safe string **toString**(); Returns: A textual representation of the email status pure nothrow @nogc @safe string **statusCodeDescription**(EmailStatusCode statusCode); Parameters: | | | | --- | --- | | EmailStatusCode `statusCode` | The [`EmailStatusCode`](#EmailStatusCode) to read | Returns: A detailed string describing the given status code enum **EmailStatusCode**: int; An email status code, indicating if an email address is valid or not. If it is invalid it also indicates why. **validCategory** Address is valid **dnsWarning** Address is valid but a DNS check was not successful **rfc5321** Address is valid for SMTP but has unusual elements **cFoldingWhitespace** Address is valid within the message but cannot be used unmodified for the envelope **deprecated\_** Address contains deprecated elements but may still be valid in restricted contexts **rfc5322** The address is only valid according to the broad definition of RFC 5322. It is otherwise invalid **any** All finer grained error checking is turned on. Address containing errors or warnings is considered invalid. A specific email status code will be returned indicating the error/warning of the address. **none** Address is either considered valid or not, no finer grained error checking is performed. Returned email status code will be either Error or Valid. **warning** Address containing warnings is considered valid, that is, any status code below 16 is considered valid. **error** Address is invalid for any purpose **valid** Address is valid **dnsWarningNoMXRecord** Could not find an MX record for this domain but an A-record does exist **dnsWarningNoRecord** Could not find an MX record or an A-record for this domain **rfc5321TopLevelDomain** Address is valid but at a Top Level Domain **rfc5321TopLevelDomainNumeric** Address is valid but the Top Level Domain begins with a number **rfc5321QuotedString** Address is valid but contains a quoted string **rfc5321AddressLiteral** Address is valid but at a literal address not a domain **rfc5321IpV6Deprecated** Address is valid but contains a :: that only elides one zero group **comment** Address contains comments **foldingWhitespace** Address contains Folding White Space **deprecatedLocalPart** The local part is in a deprecated form **deprecatedFoldingWhitespace** Address contains an obsolete form of Folding White Space **deprecatedQuotedText** A quoted string contains a deprecated character **deprecatedQuotedPair** A quoted pair contains a deprecated character **deprecatedComment** Address contains a comment in a position that is deprecated **deprecatedCommentText** A comment contains a deprecated character **deprecatedCommentFoldingWhitespaceNearAt** Address contains a comment or Folding White Space around the @ sign **rfc5322Domain** Address is RFC 5322 compliant but contains domain characters that are not allowed by DNS **rfc5322TooLong** Address is too long **rfc5322LocalTooLong** The local part of the address is too long **rfc5322DomainTooLong** The domain part is too long **rfc5322LabelTooLong** The domain part contains an element that is too long **rfc5322DomainLiteral** The domain literal is not a valid RFC 5321 address literal **rfc5322DomainLiteralObsoleteText** The domain literal is not a valid RFC 5321 address literal and it contains obsolete characters **rfc5322IpV6GroupCount** The IPv6 literal address contains the wrong number of groups **rfc5322IpV6TooManyDoubleColons** The IPv6 literal address contains too many :: sequences **rfc5322IpV6BadChar** The IPv6 address contains an illegal group of characters **rfc5322IpV6MaxGroups** The IPv6 address has too many groups **rfc5322IpV6ColonStart** IPv6 address starts with a single colon **rfc5322IpV6ColonEnd** IPv6 address ends with a single colon **errorExpectingDomainText** A domain literal contains a character that is not allowed **errorNoLocalPart** Address has no local part **errorNoDomain** Address has no domain part **errorConsecutiveDots** The address may not contain consecutive dots **errorTextAfterCommentFoldingWhitespace** Address contains text after a comment or Folding White Space **errorTextAfterQuotedString** Address contains text after a quoted string **errorTextAfterDomainLiteral** Extra characters were found after the end of the domain literal **errorExpectingQuotedPair** The address contains a character that is not allowed in a quoted pair **errorExpectingText** Address contains a character that is not allowed **errorExpectingQuotedText** A quoted string contains a character that is not allowed **errorExpectingCommentText** A comment contains a character that is not allowed **errorBackslashEnd** The address cannot end with a backslash **errorDotStart** Neither part of the address may begin with a dot **errorDotEnd** Neither part of the address may end with a dot **errorDomainHyphenStart** A domain or subdomain cannot begin with a hyphen **errorDomainHyphenEnd** A domain or subdomain cannot end with a hyphen **errorUnclosedQuotedString** Unclosed quoted string **errorUnclosedComment** Unclosed comment **errorUnclosedDomainLiteral** Domain literal is missing its closing bracket **errorFoldingWhitespaceCrflX2** Folding White Space contains consecutive CRLF sequences **errorFoldingWhitespaceCrLfEnd** Folding White Space ends with a CRLF sequence **errorCrNoLf** Address contains a carriage return that is not followed by a line feed
programming_docs
d std.zip std.zip ======= Read and write data in the [zip archive](https://en.wikipedia.org/wiki/Zip_%28file_format%29) format. Standards: The current implementation mostly conforms to [ISO/IEC 21320-1:2015](https://www.iso.org/standard/60101.html), which means, * that files can only be stored uncompressed or using the deflate mechanism, * that encryption features are not used, * that digital signature features are not used, * that patched data features are not used, and * that archives may not span multiple volumes. Additionally, archives are checked for malware attacks and rejected if detected. This includes * [zip bombs](https://news.ycombinator.com/item?id=20352439) which generate gigantic amounts of unpacked data * zip archives that contain overlapping records * chameleon zip archives which generate different unpacked data, depending on the implementation of the unpack algorithm The current implementation makes use of the zlib compression library. Usage There are two main ways of usage: Extracting files from a zip archive and storing files into a zip archive. These can be mixed though (e.g. read an archive, remove some files, add others and write the new archive). Examples: Example for reading an existing zip archive: ``` import std.stdio : writeln, writefln; import std.file : read; import std.zip; void main(string[] args) { // read a zip file into memory auto zip = new ZipArchive(read(args[1])); // iterate over all zip members writefln("%-10s %-8s Name", "Length", "CRC-32"); foreach (name, am; zip.directory) { // print some data about each member writefln("%10s %08x %s", am.expandedSize, am.crc32, name); assert(am.expandedData.length == 0); // decompress the archive member zip.expand(am); assert(am.expandedData.length == am.expandedSize); } } ``` Example for writing files into a zip archive: ``` import std.file : write; import std.string : representation; import std.zip; void main() { // Create an ArchiveMembers for each file. ArchiveMember file1 = new ArchiveMember(); file1.name = "test1.txt"; file1.expandedData("Test data.\n".dup.representation); file1.compressionMethod = CompressionMethod.none; // don't compress ArchiveMember file2 = new ArchiveMember(); file2.name = "test2.txt"; file2.expandedData("More test data.\n".dup.representation); file2.compressionMethod = CompressionMethod.deflate; // compress // Create an archive and add the member. ZipArchive zip = new ZipArchive(); // add ArchiveMembers zip.addMember(file1); zip.addMember(file2); // Build the archive void[] compressed_data = zip.build(); // Write to a file write("test.zip", compressed_data); } ``` License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com) Source [std/zip.d](https://github.com/dlang/phobos/blob/master/std/zip.d) class **ZipException**: object.Exception; Thrown on error. enum **CompressionMethod**: ushort; Compression method used by `ArchiveMember`. **none** No compression, just archiving. **deflate** Deflate algorithm. Use zlib library to compress. class **ArchiveMember**; A single file or directory inside the archive. string **name**; The name of the archive member; it is used to index the archive directory for the member. Each member must have a unique name. Do not change without removing member from the directory first. ubyte[] **extra**; The content of the extra data field for this member. See [original documentation](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) for a description of the general format of this data. May contain undocumented 3rd-party data. string **comment**; Comment associated with this member. ushort **flags**; Contains some information on how to extract this archive. See [original documentation](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) for details. ushort **internalAttributes**; Internal attributes. Bit 1 is set, if the member is apparently in binary format and bit 2 is set, if each record is preceded by the length of the record. const pure nothrow @nogc @property @safe ushort **extractVersion**(); The zip file format version needed to extract this member. Returns: Format version needed to extract this member. const pure nothrow @nogc @property @safe uint **crc32**(); Cyclic redundancy check (CRC) value. Returns: CRC32 value. const pure nothrow @nogc @property @safe uint **compressedSize**(); Size of data of member in compressed form. Returns: Size of the compressed archive. const pure nothrow @nogc @property @safe uint **expandedSize**(); Size of data of member in uncompressed form. Returns: Size of uncompressed archive. deprecated const pure nothrow @nogc @property @safe ushort **diskNumber**(); Should be 0. Returns: The number of the disk where this member can be found. pure nothrow @nogc @property @safe ubyte[] **compressedData**(); Data of member in compressed form. Returns: The file data in compressed form. pure nothrow @nogc @property @safe ubyte[] **expandedData**(); @property @safe void **expandedData**(ubyte[] ed); Get or set data of member in uncompressed form. When an existing archive is read `ZipArchive.expand` needs to be called before this can be accessed. Parameters: | | | | --- | --- | | ubyte[] `ed` | Expanded Data. | Returns: The file data. @property @safe void **fileAttributes**(uint attr); const nothrow @nogc @property uint **fileAttributes**(); Get or set the OS specific file attributes for this archive member. Parameters: | | | | --- | --- | | uint `attr` | Attributes as obtained by [`std.file.getAttributes`](std_file#getAttributes) or [`std.file.DirEntry.attributes`](std_file#DirEntry.attributes). | Returns: The file attributes or 0 if the file attributes were encoded for an incompatible OS (Windows vs. POSIX). const pure nothrow @nogc @property @safe DosFileTime **time**(); @property void **time**(SysTime **time**); pure nothrow @nogc @property @safe void **time**(DosFileTime **time**); Get or set the last modification time for this member. Parameters: | | | | --- | --- | | SysTime `time` | Time to set (will be saved as DosFileTime, which is less accurate). | Returns: The last modification time in DosFileFormat. const pure nothrow @nogc @property @safe CompressionMethod **compressionMethod**(); pure @property @safe void **compressionMethod**(CompressionMethod cm); Get or set compression method used for this member. Parameters: | | | | --- | --- | | CompressionMethod `cm` | Compression method. | Returns: Compression method. See Also: [`CompressionMethod`](#CompressionMethod) pure nothrow @nogc @property @safe uint **index**(uint value); const pure nothrow @nogc @property @safe uint **index**(); The index of this archive member within the archive. Set this to a different value for reordering the members of an archive. Parameters: | | | | --- | --- | | uint `value` | Index value to set. | Returns: The index. class **ZipArchive**; Object representing the entire archive. ZipArchives are collections of ArchiveMembers. string **comment**; The archive comment. Must be less than 65536 bytes in length. pure nothrow @nogc @property @safe ubyte[] **data**(); Array representing the entire contents of the archive. Returns: Data of the entire contents of the archive. deprecated const pure nothrow @nogc @property @safe uint **diskNumber**(); 0 since multi-disk zip archives are not supported. Returns: Number of this disk. deprecated const pure nothrow @nogc @property @safe uint **diskStartDir**(); 0 since multi-disk zip archives are not supported. Returns: Number of the disk, where the central directory starts. deprecated const pure nothrow @nogc @property @safe uint **numEntries**(); const pure nothrow @nogc @property @safe uint **totalEntries**(); Number of ArchiveMembers in the directory. Returns: The number of files in this archive. const pure nothrow @nogc @property @safe bool **isZip64**(); pure nothrow @nogc @property @safe void **isZip64**(bool value); True when the archive is in Zip64 format. Set this to true to force building a Zip64 archive. Parameters: | | | | --- | --- | | bool `value` | True, when the archive is forced to be build in Zip64 format. | Returns: True, when the archive is in Zip64 format. pure nothrow @nogc @property @safe ArchiveMember[string] **directory**(); Associative array indexed by the name of each member of the archive. All the members of the archive can be accessed with a foreach loop: Example ``` ZipArchive archive = new ZipArchive(data); foreach (ArchiveMember am; archive.directory) { writefln("member name is '%s'", am.name); } ``` Returns: Associative array with all archive members. pure nothrow @nogc @safe this(); Constructor to use when creating a new archive. @safe void **addMember**(ArchiveMember de); Add a member to the archive. The file is compressed on the fly. Parameters: | | | | --- | --- | | ArchiveMember `de` | Member to be added. | Throws: ZipException when an unsupported compression method is used or when compression failed. @safe void **deleteMember**(ArchiveMember de); Delete member `de` from the archive. Uses the name of the member to detect which element to delete. Parameters: | | | | --- | --- | | ArchiveMember `de` | Member to be deleted. | pure @safe void[] **build**(); Construct the entire contents of the current members of the archive. Fills in the properties data[], totalEntries, and directory[]. For each ArchiveMember, fills in properties crc32, compressedSize, compressedData[]. Returns: Array representing the entire archive. Throws: ZipException when the archive could not be build. this(void[] buffer); Constructor to use when reading an existing archive. Fills in the properties data[], totalEntries, comment[], and directory[]. For each ArchiveMember, fills in properties madeVersion, extractVersion, flags, compressionMethod, time, crc32, compressedSize, expandedSize, compressedData[], internalAttributes, externalAttributes, name[], extra[], comment[]. Use expand() to get the expanded data for each ArchiveMember. Parameters: | | | | --- | --- | | void[] `buffer` | The entire contents of the archive. | Throws: ZipException when the archive was invalid or when malware was detected. ubyte[] **expand**(ArchiveMember de); Decompress the contents of a member. Fills in properties extractVersion, flags, compressionMethod, time, crc32, compressedSize, expandedSize, expandedData[], name[], extra[]. Parameters: | | | | --- | --- | | ArchiveMember `de` | Member to be decompressed. | Returns: The expanded data. Throws: ZipException when the entry is invalid or the compression method is not supported. d std.demangle std.demangle ============ Demangle D mangled names. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com), Thomas Kühne, Frits van Bommel Source [std/demangle.d](https://github.com/dlang/phobos/blob/master/std/demangle.d) pure nothrow @safe string **demangle**(string name); Demangle D mangled names. Parameters: | | | | --- | --- | | string `name` | the mangled name | Returns: A `string`. If it is not a D mangled name, it returns its argument name. Examples: ``` // int b in module a writeln(demangle("_D1a1bi")); // "int a.b" // char array foo in module test writeln(demangle("_D4test3fooAa")); // "char[] test.foo" ``` Examples: This program reads standard in and writes it to standard out, pretty-printing any found D mangled names. ``` import std.ascii : isAlphaNum; import std.algorithm.iteration : chunkBy, joiner, map; import std.algorithm.mutation : copy; import std.conv : to; import std.demangle : demangle; import std.functional : pipe; import std.stdio : stdin, stdout; void main() { stdin.byLineCopy .map!( l => l.chunkBy!(a => isAlphaNum(a) || a == '_') .map!(a => a[1].pipe!(to!string, demangle)).joiner ) .copy(stdout.lockingTextWriter); } ``` d std.path std.path ======== This module is used to manipulate path strings. All functions, with the exception of [`expandTilde`](#expandTilde) (and in some cases [`absolutePath`](#absolutePath) and [`relativePath`](#relativePath)), are pure string manipulation functions; they don't depend on any state outside the program, nor do they perform any actual file system actions. This has the consequence that the module does not make any distinction between a path that points to a directory and a path that points to a file, and it does not know whether or not the object pointed to by the path actually exists in the file system. To differentiate between these cases, use [`std.file.isDir`](std_file#isDir) and [`std.file.exists`](std_file#exists). Note that on Windows, both the backslash (`\`) and the slash (`/`) are in principle valid directory separators. This module treats them both on equal footing, but in cases where a *new* separator is added, a backslash will be used. Furthermore, the [`buildNormalizedPath`](#buildNormalizedPath) function will replace all slashes with backslashes on that platform. In general, the functions in this module assume that the input paths are well-formed. (That is, they should not contain invalid characters, they should follow the file system's path format, etc.) The result of calling a function on an ill-formed path is undefined. When there is a chance that a path or a file name is invalid (for instance, when it has been input by the user), it may sometimes be desirable to use the [`isValidFilename`](#isValidFilename) and [`isValidPath`](#isValidPath) functions to check this. Most functions do not perform any memory allocations, and if a string is returned, it is usually a slice of an input string. If a function allocates, this is explicitly mentioned in the documentation. | Category | Functions | | --- | --- | | Normalization | [`absolutePath`](#absolutePath) [`asAbsolutePath`](#asAbsolutePath) [`asNormalizedPath`](#asNormalizedPath) [`asRelativePath`](#asRelativePath) [`buildNormalizedPath`](#buildNormalizedPath) [`buildPath`](#buildPath) [`chainPath`](#chainPath) [`expandTilde`](#expandTilde) | | Partitioning | [`baseName`](#baseName) [`dirName`](#dirName) [`dirSeparator`](#dirSeparator) [`driveName`](#driveName) [`pathSeparator`](#pathSeparator) [`pathSplitter`](#pathSplitter) [`relativePath`](#relativePath) [`rootName`](#rootName) [`stripDrive`](#stripDrive) | | Validation | [`isAbsolute`](#isAbsolute) [`isDirSeparator`](#isDirSeparator) [`isRooted`](#isRooted) [`isValidFilename`](#isValidFilename) [`isValidPath`](#isValidPath) | | Extension | [`defaultExtension`](#defaultExtension) [`extension`](#extension) [`setExtension`](#setExtension) [`stripExtension`](#stripExtension) [`withDefaultExtension`](#withDefaultExtension) [`withExtension`](#withExtension) | | Other | [`filenameCharCmp`](#filenameCharCmp) [`filenameCmp`](#filenameCmp) [`globMatch`](#globMatch) [`CaseSensitive`](#CaseSensitive) | Authors: Lars Tandle Kyllingstad, [Walter Bright](http://digitalmars.com), Grzegorz Adam Hankiewicz, Thomas Kühne, [Andrei Alexandrescu](http://erdani.org) License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt) Source [std/path.d](https://github.com/dlang/phobos/blob/master/std/path.d) enum string **dirSeparator**; String used to separate directory names in a path. Under POSIX this is a slash, under Windows a backslash. enum string **pathSeparator**; Path separator string. A colon under POSIX, a semicolon under Windows. pure nothrow @nogc @safe bool **isDirSeparator**(dchar c); Determines whether the given character is a directory separator. On Windows, this includes both `\` and `/`. On POSIX, it's just `/`. Examples: ``` version (Windows) { assert( '/'.isDirSeparator); assert( '\\'.isDirSeparator); } else { assert( '/'.isDirSeparator); assert(!'\\'.isDirSeparator); } ``` enum **CaseSensitive**: bool; This `enum` is used as a template argument to functions which compare file names, and determines whether the comparison is case sensitive or not. Examples: ``` writeln(baseName!(CaseSensitive.no)("dir/file.EXT", ".ext")); // "file" assert(baseName!(CaseSensitive.yes)("dir/file.EXT", ".ext") != "file"); version (Posix) writeln(relativePath!(CaseSensitive.no)("/FOO/bar", "/foo/baz")); // "../bar" else writeln(relativePath!(CaseSensitive.no)(`c:\FOO\bar`, `c:\foo\baz`)); // `..\bar` ``` **no** File names are case insensitive **yes** File names are case sensitive **osDefault** The default (or most common) setting for the current platform. That is, `no` on Windows and Mac OS X, and `yes` on all POSIX systems except Darwin (Linux, \*BSD, etc.). auto **baseName**(R)(R path) Constraints: if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) && !isSomeString!R); auto **baseName**(C)(C[] path) Constraints: if (isSomeChar!C); pure @safe inout(C)[] **baseName**(CaseSensitive cs = CaseSensitive.osDefault, C, C1)(inout(C)[] path, in C1[] suffix) Constraints: if (isSomeChar!C && isSomeChar!C1); Parameters: | | | | --- | --- | | cs | Whether or not suffix matching is case-sensitive. | | R `path` | A path name. It can be a string, or any random-access range of characters. | | C1[] `suffix` | An optional suffix to be removed from the file name. | Returns: The name of the file in the path name, without any leading directory and with an optional suffix chopped off. If `suffix` is specified, it will be compared to `path` using `filenameCmp!cs`, where `cs` is an optional template parameter determining whether the comparison is case sensitive or not. See the [`filenameCmp`](#filenameCmp) documentation for details. Note This function *only* strips away the specified suffix, which doesn't necessarily have to represent an extension. To remove the extension from a path, regardless of what the extension is, use [`stripExtension`](#stripExtension). To obtain the filename without leading directories and without an extension, combine the functions like this: ``` assert(baseName(stripExtension("dir/file.ext")) == "file"); ``` Standards: This function complies with [the POSIX requirements for the 'basename' shell utility](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/basename.html) (with suitable adaptations for Windows paths). Examples: ``` writeln(baseName("dir/file.ext")); // "file.ext" writeln(baseName("dir/file.ext", ".ext")); // "file" writeln(baseName("dir/file.ext", ".xyz")); // "file.ext" writeln(baseName("dir/filename", "name")); // "file" writeln(baseName("dir/subdir/")); // "subdir" version (Windows) { writeln(baseName(`d:file.ext`)); // "file.ext" writeln(baseName(`d:\dir\file.ext`)); // "file.ext" } ``` auto **dirName**(R)(R path) Constraints: if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R); auto **dirName**(C)(C[] path) Constraints: if (isSomeChar!C); Returns the parent directory of `path`. On Windows, this includes the drive letter if present. If `path` is a relative path and the parent directory is the current working directory, returns `"."`. Parameters: | | | | --- | --- | | R `path` | A path name. | Returns: A slice of `path` or `"."`. Standards: This function complies with [the POSIX requirements for the 'dirname' shell utility](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/dirname.html) (with suitable adaptations for Windows paths). Examples: ``` writeln(dirName("")); // "." writeln(dirName("file"w)); // "." writeln(dirName("dir/"d)); // "." writeln(dirName("dir///")); // "." writeln(dirName("dir/file"w.dup)); // "dir" writeln(dirName("dir///file"d.dup)); // "dir" writeln(dirName("dir/subdir/")); // "dir" writeln(dirName("/dir/file"w)); // "/dir" writeln(dirName("/file"d)); // "/" writeln(dirName("/")); // "/" writeln(dirName("///")); // "/" version (Windows) { writeln(dirName(`dir\`)); // `.` writeln(dirName(`dir\\\`)); // `.` writeln(dirName(`dir\file`)); // `dir` writeln(dirName(`dir\\\file`)); // `dir` writeln(dirName(`dir\subdir\`)); // `dir` writeln(dirName(`\dir\file`)); // `\dir` writeln(dirName(`\file`)); // `\` writeln(dirName(`\`)); // `\` writeln(dirName(`\\\`)); // `\` writeln(dirName(`d:`)); // `d:` writeln(dirName(`d:file`)); // `d:` writeln(dirName(`d:\`)); // `d:\` writeln(dirName(`d:\file`)); // `d:\` writeln(dirName(`d:\dir\file`)); // `d:\dir` writeln(dirName(`\\server\share\dir\file`)); // `\\server\share\dir` writeln(dirName(`\\server\share\file`)); // `\\server\share` writeln(dirName(`\\server\share\`)); // `\\server\share` writeln(dirName(`\\server\share`)); // `\\server\share` } ``` auto **rootName**(R)(R path) Constraints: if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R); auto **rootName**(C)(C[] path) Constraints: if (isSomeChar!C); Returns the root directory of the specified path, or `null` if the path is not rooted. Parameters: | | | | --- | --- | | R `path` | A path name. | Returns: A slice of `path`. Examples: ``` assert(rootName("") is null); assert(rootName("foo") is null); writeln(rootName("/")); // "/" writeln(rootName("/foo/bar")); // "/" version (Windows) { assert(rootName("d:foo") is null); writeln(rootName(`d:\foo`)); // `d:\` writeln(rootName(`\\server\share\foo`)); // `\\server\share` writeln(rootName(`\\server\share`)); // `\\server\share` } ``` auto **driveName**(R)(R path) Constraints: if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R); auto **driveName**(C)(C[] path) Constraints: if (isSomeChar!C); Get the drive portion of a path. Parameters: | | | | --- | --- | | R `path` | string or range of characters | Returns: A slice of `path` that is the drive, or an empty range if the drive is not specified. In the case of UNC paths, the network share is returned. Always returns an empty range on POSIX. Examples: ``` import std.range : empty; version (Posix) assert(driveName("c:/foo").empty); version (Windows) { assert(driveName(`dir\file`).empty); writeln(driveName(`d:file`)); // "d:" writeln(driveName(`d:\file`)); // "d:" writeln(driveName("d:")); // "d:" writeln(driveName(`\\server\share\file`)); // `\\server\share` writeln(driveName(`\\server\share\`)); // `\\server\share` writeln(driveName(`\\server\share`)); // `\\server\share` static assert(driveName(`d:\file`) == "d:"); } ``` auto **stripDrive**(R)(R path) Constraints: if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) && !isSomeString!R); auto **stripDrive**(C)(C[] path) Constraints: if (isSomeChar!C); Strips the drive from a Windows path. On POSIX, the path is returned unaltered. Parameters: | | | | --- | --- | | R `path` | A pathname | Returns: A slice of path without the drive component. Examples: ``` version (Windows) { writeln(stripDrive(`d:\dir\file`)); // `\dir\file` writeln(stripDrive(`\\server\share\dir\file`)); // `\dir\file` } ``` auto **extension**(R)(R path) Constraints: if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) || is(StringTypeOf!R)); Parameters: | | | | --- | --- | | R `path` | A path name. | Returns: The extension part of a file name, including the dot. If there is no extension, `null` is returned. Examples: ``` import std.range : empty; assert(extension("file").empty); writeln(extension("file.")); // "." writeln(extension("file.ext"w)); // ".ext" writeln(extension("file.ext1.ext2"d)); // ".ext2" assert(extension(".foo".dup).empty); writeln(extension(".foo.ext"w.dup)); // ".ext" static assert(extension("file").empty); static assert(extension("file.ext") == ".ext"); ``` auto **stripExtension**(R)(R path) Constraints: if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R); auto **stripExtension**(C)(C[] path) Constraints: if (isSomeChar!C); Remove extension from path. Parameters: | | | | --- | --- | | R `path` | string or range to be sliced | Returns: slice of path with the extension (if any) stripped off Examples: ``` writeln(stripExtension("file")); // "file" writeln(stripExtension("file.ext")); // "file" writeln(stripExtension("file.ext1.ext2")); // "file.ext1" writeln(stripExtension("file.")); // "file" writeln(stripExtension(".file")); // ".file" writeln(stripExtension(".file.ext")); // ".file" writeln(stripExtension("dir/file.ext")); // "dir/file" ``` immutable(C1)[] **setExtension**(C1, C2)(in C1[] path, in C2[] ext) Constraints: if (isSomeChar!C1 && !is(C1 == immutable) && is(immutable(C1) == immutable(C2))); immutable(C1)[] **setExtension**(C1, C2)(immutable(C1)[] path, const(C2)[] ext) Constraints: if (isSomeChar!C1 && is(immutable(C1) == immutable(C2))); Sets or replaces an extension. If the filename already has an extension, it is replaced. If not, the extension is simply appended to the filename. Including a leading dot in `ext` is optional. If the extension is empty, this function is equivalent to [`stripExtension`](#stripExtension). This function normally allocates a new string (the possible exception being the case when path is immutable and doesn't already have an extension). Parameters: | | | | --- | --- | | C1[] `path` | A path name | | C2[] `ext` | The new extension | Returns: A string containing the path given by `path`, but where the extension has been set to `ext`. See Also: [`withExtension`](#withExtension) which does not allocate and returns a lazy range. Examples: ``` writeln(setExtension("file", "ext")); // "file.ext" writeln(setExtension("file"w, ".ext"w)); // "file.ext" writeln(setExtension("file."d, "ext"d)); // "file.ext" writeln(setExtension("file.", ".ext")); // "file.ext" writeln(setExtension("file.old"w, "new"w)); // "file.new" writeln(setExtension("file.old"d, ".new"d)); // "file.new" ``` auto **withExtension**(R, C)(R path, C[] ext) Constraints: if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R && isSomeChar!C); auto **withExtension**(C1, C2)(C1[] path, C2[] ext) Constraints: if (isSomeChar!C1 && isSomeChar!C2); Replace existing extension on filespec with new one. Parameters: | | | | --- | --- | | R `path` | string or random access range representing a filespec | | C[] `ext` | the new extension | Returns: Range with `path`'s extension (if any) replaced with `ext`. The element encoding type of the returned range will be the same as `path`'s. See Also: [`setExtension`](#setExtension) Examples: ``` import std.array; writeln(withExtension("file", "ext").array); // "file.ext" writeln(withExtension("file"w, ".ext"w).array); // "file.ext" writeln(withExtension("file.ext"w, ".").array); // "file." import std.utf : byChar, byWchar; writeln(withExtension("file".byChar, "ext").array); // "file.ext" writeln(withExtension("file"w.byWchar, ".ext"w).array); // "file.ext"w writeln(withExtension("file.ext"w.byWchar, ".").array); // "file."w ``` immutable(C1)[] **defaultExtension**(C1, C2)(in C1[] path, in C2[] ext) Constraints: if (isSomeChar!C1 && is(immutable(C1) == immutable(C2))); Parameters: | | | | --- | --- | | C1[] `path` | A path name. | | C2[] `ext` | The default extension to use. | Returns: The path given by `path`, with the extension given by `ext` appended if the path doesn't already have one. Including the dot in the extension is optional. This function always allocates a new string, except in the case when path is immutable and already has an extension. Examples: ``` writeln(defaultExtension("file", "ext")); // "file.ext" writeln(defaultExtension("file", ".ext")); // "file.ext" writeln(defaultExtension("file.", "ext")); // "file." writeln(defaultExtension("file.old", "new")); // "file.old" writeln(defaultExtension("file.old", ".new")); // "file.old" ``` auto **withDefaultExtension**(R, C)(R path, C[] ext) Constraints: if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R && isSomeChar!C); auto **withDefaultExtension**(C1, C2)(C1[] path, C2[] ext) Constraints: if (isSomeChar!C1 && isSomeChar!C2); Set the extension of `path` to `ext` if `path` doesn't have one. Parameters: | | | | --- | --- | | R `path` | filespec as string or range | | C[] `ext` | extension, may have leading '.' | Returns: range with the result Examples: ``` import std.array; writeln(withDefaultExtension("file", "ext").array); // "file.ext" writeln(withDefaultExtension("file"w, ".ext").array); // "file.ext"w writeln(withDefaultExtension("file.", "ext").array); // "file." writeln(withDefaultExtension("file", "").array); // "file." import std.utf : byChar, byWchar; writeln(withDefaultExtension("file".byChar, "ext").array); // "file.ext" writeln(withDefaultExtension("file"w.byWchar, ".ext").array); // "file.ext"w writeln(withDefaultExtension("file.".byChar, "ext"d).array); // "file." writeln(withDefaultExtension("file".byChar, "").array); // "file." ``` immutable(ElementEncodingType!(ElementType!Range))[] **buildPath**(Range)(Range segments) Constraints: if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range)); pure nothrow @safe immutable(C)[] **buildPath**(C)(const(C)[][] paths...) Constraints: if (isSomeChar!C); Combines one or more path segments. This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by [`isAbsolute`](#isAbsolute)), the preceding segments will be dropped. On Windows, if one of the path segments are rooted, but not absolute (e.g. `\foo`), all preceding path segments down to the previous root will be dropped. (See below for an example.) This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if `paths` is a forward range. Parameters: | | | | --- | --- | | Range `segments` | An [input range](std_range_primitives#isInputRange) of segments to assemble the path from. | Returns: The assembled path. Examples: ``` version (Posix) { writeln(buildPath("foo", "bar", "baz")); // "foo/bar/baz" writeln(buildPath("/foo/", "bar/baz")); // "/foo/bar/baz" writeln(buildPath("/foo", "/bar")); // "/bar" } version (Windows) { writeln(buildPath("foo", "bar", "baz")); // `foo\bar\baz` writeln(buildPath(`c:\foo`, `bar\baz`)); // `c:\foo\bar\baz` writeln(buildPath("foo", `d:\bar`)); // `d:\bar` writeln(buildPath("foo", `\bar`)); // `\bar` writeln(buildPath(`c:\foo`, `\bar`)); // `c:\bar` } ``` auto **chainPath**(R1, R2, Ranges...)(R1 r1, R2 r2, Ranges ranges) Constraints: if ((isRandomAccessRange!R1 && hasSlicing!R1 && hasLength!R1 && isSomeChar!(ElementType!R1) || isNarrowString!R1 && !isConvertibleToString!R1) && (isRandomAccessRange!R2 && hasSlicing!R2 && hasLength!R2 && isSomeChar!(ElementType!R2) || isNarrowString!R2 && !isConvertibleToString!R2) && (Ranges.length == 0 || is(typeof(chainPath(r2, ranges))))); Concatenate path segments together to form one path. Parameters: | | | | --- | --- | | R1 `r1` | first segment | | R2 `r2` | second segment | | Ranges `ranges` | 0 or more segments | Returns: Lazy range which is the concatenation of r1, r2 and ranges with path separators. The resulting element type is that of r1. See Also: [`buildPath`](#buildPath) Examples: ``` import std.array; version (Posix) { writeln(chainPath("foo", "bar", "baz").array); // "foo/bar/baz" writeln(chainPath("/foo/", "bar/baz").array); // "/foo/bar/baz" writeln(chainPath("/foo", "/bar").array); // "/bar" } version (Windows) { writeln(chainPath("foo", "bar", "baz").array); // `foo\bar\baz` writeln(chainPath(`c:\foo`, `bar\baz`).array); // `c:\foo\bar\baz` writeln(chainPath("foo", `d:\bar`).array); // `d:\bar` writeln(chainPath("foo", `\bar`).array); // `\bar` writeln(chainPath(`c:\foo`, `\bar`).array); // `c:\bar` } import std.utf : byChar; version (Posix) { writeln(chainPath("foo", "bar", "baz").array); // "foo/bar/baz" writeln(chainPath("/foo/".byChar, "bar/baz").array); // "/foo/bar/baz" writeln(chainPath("/foo", "/bar".byChar).array); // "/bar" } version (Windows) { writeln(chainPath("foo", "bar", "baz").array); // `foo\bar\baz` writeln(chainPath(`c:\foo`.byChar, `bar\baz`).array); // `c:\foo\bar\baz` writeln(chainPath("foo", `d:\bar`).array); // `d:\bar` writeln(chainPath("foo", `\bar`.byChar).array); // `\bar` writeln(chainPath(`c:\foo`, `\bar`w).array); // `c:\bar` } ``` pure nothrow @safe immutable(C)[] **buildNormalizedPath**(C)(const(C[])[] paths...) Constraints: if (isSomeChar!C); Performs the same task as [`buildPath`](#buildPath), while at the same time resolving current/parent directory symbols (`"."` and `".."`) and removing superfluous directory separators. It will return "." if the path leads to the starting directory. On Windows, slashes are replaced with backslashes. Using buildNormalizedPath on null paths will always return null. Note that this function does not resolve symbolic links. This function always allocates memory to hold the resulting path. Use [`asNormalizedPath`](#asNormalizedPath) to not allocate memory. Parameters: | | | | --- | --- | | const(C[])[] `paths` | An array of paths to assemble. | Returns: The assembled path. Examples: ``` writeln(buildNormalizedPath("foo", "..")); // "." version (Posix) { writeln(buildNormalizedPath("/foo/./bar/..//baz/")); // "/foo/baz" writeln(buildNormalizedPath("../foo/.")); // "../foo" writeln(buildNormalizedPath("/foo", "bar/baz/")); // "/foo/bar/baz" writeln(buildNormalizedPath("/foo", "/bar/..", "baz")); // "/baz" writeln(buildNormalizedPath("foo/./bar", "../../", "../baz")); // "../baz" writeln(buildNormalizedPath("/foo/./bar", "../../baz")); // "/baz" } version (Windows) { writeln(buildNormalizedPath(`c:\foo\.\bar/..\\baz\`)); // `c:\foo\baz` writeln(buildNormalizedPath(`..\foo\.`)); // `..\foo` writeln(buildNormalizedPath(`c:\foo`, `bar\baz\`)); // `c:\foo\bar\baz` writeln(buildNormalizedPath(`c:\foo`, `bar/..`)); // `c:\foo` assert(buildNormalizedPath(`\\server\share\foo`, `..\bar`) == `\\server\share\bar`); } ``` auto **asNormalizedPath**(R)(R path) Constraints: if (isSomeChar!(ElementEncodingType!R) && (isRandomAccessRange!R && hasSlicing!R && hasLength!R || isNarrowString!R) && !isConvertibleToString!R); Normalize a path by resolving current/parent directory symbols (`"."` and `".."`) and removing superfluous directory separators. It will return "." if the path leads to the starting directory. On Windows, slashes are replaced with backslashes. Using asNormalizedPath on empty paths will always return an empty path. Does not resolve symbolic links. This function always allocates memory to hold the resulting path. Use [`buildNormalizedPath`](#buildNormalizedPath) to allocate memory and return a string. Parameters: | | | | --- | --- | | R `path` | string or random access range representing the path to normalize | Returns: normalized path as a forward range Examples: ``` import std.array; writeln(asNormalizedPath("foo/..").array); // "." version (Posix) { writeln(asNormalizedPath("/foo/./bar/..//baz/").array); // "/foo/baz" writeln(asNormalizedPath("../foo/.").array); // "../foo" writeln(asNormalizedPath("/foo/bar/baz/").array); // "/foo/bar/baz" writeln(asNormalizedPath("/foo/./bar/../../baz").array); // "/baz" } version (Windows) { writeln(asNormalizedPath(`c:\foo\.\bar/..\\baz\`).array); // `c:\foo\baz` writeln(asNormalizedPath(`..\foo\.`).array); // `..\foo` writeln(asNormalizedPath(`c:\foo\bar\baz\`).array); // `c:\foo\bar\baz` writeln(asNormalizedPath(`c:\foo\bar/..`).array); // `c:\foo` assert(asNormalizedPath(`\\server\share\foo\..\bar`).array == `\\server\share\bar`); } ``` auto **pathSplitter**(R)(R path) Constraints: if ((isRandomAccessRange!R && hasSlicing!R || isNarrowString!R) && !isConvertibleToString!R); Slice up a path into its elements. Parameters: | | | | --- | --- | | R `path` | string or slicable random access range | Returns: bidirectional range of slices of `path` Examples: ``` import std.algorithm.comparison : equal; import std.conv : to; assert(equal(pathSplitter("/"), ["/"])); assert(equal(pathSplitter("/foo/bar"), ["/", "foo", "bar"])); assert(equal(pathSplitter("foo/../bar//./"), ["foo", "..", "bar", "."])); version (Posix) { assert(equal(pathSplitter("//foo/bar"), ["/", "foo", "bar"])); } version (Windows) { assert(equal(pathSplitter(`foo\..\bar\/.\`), ["foo", "..", "bar", "."])); assert(equal(pathSplitter("c:"), ["c:"])); assert(equal(pathSplitter(`c:\foo\bar`), [`c:\`, "foo", "bar"])); assert(equal(pathSplitter(`c:foo\bar`), ["c:foo", "bar"])); } ``` bool **isRooted**(R)(R path) Constraints: if (isRandomAccessRange!R && isSomeChar!(ElementType!R) || is(StringTypeOf!R)); Determines whether a path starts at a root directory. Parameters: | | | | --- | --- | | R `path` | A path name. | Returns: Whether a path starts at a root directory. On POSIX, this function returns true if and only if the path starts with a slash (/). On Windows, this function returns true if the path starts at the root directory of the current drive, of some other drive, or of a network drive. Examples: ``` version (Posix) { assert( isRooted("/")); assert( isRooted("/foo")); assert(!isRooted("foo")); assert(!isRooted("../foo")); } version (Windows) { assert( isRooted(`\`)); assert( isRooted(`\foo`)); assert( isRooted(`d:\foo`)); assert( isRooted(`\\foo\bar`)); assert(!isRooted("foo")); assert(!isRooted("d:foo")); } ``` pure nothrow @safe bool **isAbsolute**(R)(R path) Constraints: if (isRandomAccessRange!R && isSomeChar!(ElementType!R) || is(StringTypeOf!R)); Determines whether a path is absolute or not. Parameters: | | | | --- | --- | | R `path` | A path name. | Returns: Whether a path is absolute or not. Example On POSIX, an absolute path starts at the root directory. (In fact, `_isAbsolute` is just an alias for [`isRooted`](#isRooted).) ``` version (Posix) { assert(isAbsolute("/")); assert(isAbsolute("/foo")); assert(!isAbsolute("foo")); assert(!isAbsolute("../foo")); } ``` On Windows, an absolute path starts at the root directory of a specific drive. Hence, it must start with `d:\` or `d:/`, where `d` is the drive letter. Alternatively, it may be a network path, i.e. a path starting with a double (back)slash. ``` version (Windows) { assert(isAbsolute(`d:\`)); assert(isAbsolute(`d:\foo`)); assert(isAbsolute(`\\foo\bar`)); assert(!isAbsolute(`\`)); assert(!isAbsolute(`\foo`)); assert(!isAbsolute("d:foo")); } ``` pure @safe string **absolutePath**(string path, lazy string base = getcwd()); Transforms `path` into an absolute path. The following algorithm is used: 1. If `path` is empty, return `null`. 2. If `path` is already absolute, return it. 3. Otherwise, append `path` to `base` and return the result. If `base` is not specified, the current working directory is used. The function allocates memory if and only if it gets to the third stage of this algorithm. Parameters: | | | | --- | --- | | string `path` | the relative path to transform | | string `base` | the base directory of the relative path | Returns: string of transformed path Throws: `Exception` if the specified base directory is not absolute. See Also: [`asAbsolutePath`](#asAbsolutePath) which does not allocate Examples: ``` version (Posix) { writeln(absolutePath("some/file", "/foo/bar")); // "/foo/bar/some/file" writeln(absolutePath("../file", "/foo/bar")); // "/foo/bar/../file" writeln(absolutePath("/some/file", "/foo/bar")); // "/some/file" } version (Windows) { writeln(absolutePath(`some\file`, `c:\foo\bar`)); // `c:\foo\bar\some\file` writeln(absolutePath(`..\file`, `c:\foo\bar`)); // `c:\foo\bar\..\file` writeln(absolutePath(`c:\some\file`, `c:\foo\bar`)); // `c:\some\file` writeln(absolutePath(`\`, `c:\`)); // `c:\` writeln(absolutePath(`\some\file`, `c:\foo\bar`)); // `c:\some\file` } ``` auto **asAbsolutePath**(R)(R path) Constraints: if ((isRandomAccessRange!R && isSomeChar!(ElementType!R) || isNarrowString!R) && !isConvertibleToString!R); Transforms `path` into an absolute path. The following algorithm is used: 1. If `path` is empty, return `null`. 2. If `path` is already absolute, return it. 3. Otherwise, append `path` to the current working directory, which allocates memory. Parameters: | | | | --- | --- | | R `path` | the relative path to transform | Returns: the transformed path as a lazy range See Also: [`absolutePath`](#absolutePath) which returns an allocated string Examples: ``` import std.array; writeln(asAbsolutePath(cast(string)null).array); // "" version (Posix) { writeln(asAbsolutePath("/foo").array); // "/foo" } version (Windows) { writeln(asAbsolutePath("c:/foo").array); // "c:/foo" } asAbsolutePath("foo"); ``` string **relativePath**(CaseSensitive cs = CaseSensitive.osDefault)(string path, lazy string base = getcwd()); Translates `path` into a relative path. The returned path is relative to `base`, which is by default taken to be the current working directory. If specified, `base` must be an absolute path, and it is always assumed to refer to a directory. If `path` and `base` refer to the same directory, the function returns `.`. The following algorithm is used: 1. If `path` is a relative directory, return it unaltered. 2. Find a common root between `path` and `base`. If there is no common root, return `path` unaltered. 3. Prepare a string with as many `../` or `..\` as necessary to reach the common root from base path. 4. Append the remaining segments of `path` to the string and return. In the second step, path components are compared using `filenameCmp!cs`, where `cs` is an optional template parameter determining whether the comparison is case sensitive or not. See the [`filenameCmp`](#filenameCmp) documentation for details. This function allocates memory. Parameters: | | | | --- | --- | | cs | Whether matching path name components against the base path should be case-sensitive or not. | | string `path` | A path name. | | string `base` | The base path to construct the relative path from. | Returns: The relative path. See Also: [`asRelativePath`](#asRelativePath) which does not allocate memory Throws: `Exception` if the specified base directory is not absolute. Examples: ``` writeln(relativePath("foo")); // "foo" version (Posix) { writeln(relativePath("foo", "/bar")); // "foo" writeln(relativePath("/foo/bar", "/foo/bar")); // "." writeln(relativePath("/foo/bar", "/foo/baz")); // "../bar" writeln(relativePath("/foo/bar/baz", "/foo/woo/wee")); // "../../bar/baz" writeln(relativePath("/foo/bar/baz", "/foo/bar")); // "baz" } version (Windows) { writeln(relativePath("foo", `c:\bar`)); // "foo" writeln(relativePath(`c:\foo\bar`, `c:\foo\bar`)); // "." writeln(relativePath(`c:\foo\bar`, `c:\foo\baz`)); // `..\bar` writeln(relativePath(`c:\foo\bar\baz`, `c:\foo\woo\wee`)); // `..\..\bar\baz` writeln(relativePath(`c:\foo\bar\baz`, `c:\foo\bar`)); // "baz" writeln(relativePath(`c:\foo\bar`, `d:\foo`)); // `c:\foo\bar` } ``` auto **asRelativePath**(CaseSensitive cs = CaseSensitive.osDefault, R1, R2)(R1 path, R2 base) Constraints: if ((isNarrowString!R1 || isRandomAccessRange!R1 && hasSlicing!R1 && isSomeChar!(ElementType!R1) && !isConvertibleToString!R1) && (isNarrowString!R2 || isRandomAccessRange!R2 && hasSlicing!R2 && isSomeChar!(ElementType!R2) && !isConvertibleToString!R2)); Transforms `path` into a path relative to `base`. The returned path is relative to `base`, which is usually the current working directory. `base` must be an absolute path, and it is always assumed to refer to a directory. If `path` and `base` refer to the same directory, the function returns `'.'`. The following algorithm is used: 1. If `path` is a relative directory, return it unaltered. 2. Find a common root between `path` and `base`. If there is no common root, return `path` unaltered. 3. Prepare a string with as many `../` or `..\` as necessary to reach the common root from base path. 4. Append the remaining segments of `path` to the string and return. In the second step, path components are compared using `filenameCmp!cs`, where `cs` is an optional template parameter determining whether the comparison is case sensitive or not. See the [`filenameCmp`](#filenameCmp) documentation for details. Parameters: | | | | --- | --- | | R1 `path` | path to transform | | R2 `base` | absolute path | | cs | whether filespec comparisons are sensitive or not; defaults to `CaseSensitive.osDefault` | Returns: a random access range of the transformed path See Also: [`relativePath`](#relativePath) Examples: ``` import std.array; version (Posix) { writeln(asRelativePath("foo", "/bar").array); // "foo" writeln(asRelativePath("/foo/bar", "/foo/bar").array); // "." writeln(asRelativePath("/foo/bar", "/foo/baz").array); // "../bar" writeln(asRelativePath("/foo/bar/baz", "/foo/woo/wee").array); // "../../bar/baz" writeln(asRelativePath("/foo/bar/baz", "/foo/bar").array); // "baz" } else version (Windows) { writeln(asRelativePath("foo", `c:\bar`).array); // "foo" writeln(asRelativePath(`c:\foo\bar`, `c:\foo\bar`).array); // "." writeln(asRelativePath(`c:\foo\bar`, `c:\foo\baz`).array); // `..\bar` writeln(asRelativePath(`c:\foo\bar\baz`, `c:\foo\woo\wee`).array); // `..\..\bar\baz` writeln(asRelativePath(`c:/foo/bar/baz`, `c:\foo\woo\wee`).array); // `..\..\bar\baz` writeln(asRelativePath(`c:\foo\bar\baz`, `c:\foo\bar`).array); // "baz" writeln(asRelativePath(`c:\foo\bar`, `d:\foo`).array); // `c:\foo\bar` writeln(asRelativePath(`\\foo\bar`, `c:\foo`).array); // `\\foo\bar` } else static assert(0); ``` pure nothrow @safe int **filenameCharCmp**(CaseSensitive cs = CaseSensitive.osDefault)(dchar a, dchar b); Compares filename characters. This function can perform a case-sensitive or a case-insensitive comparison. This is controlled through the `cs` template parameter which, if not specified, is given by [`CaseSensitive`](#CaseSensitive)`.osDefault`. On Windows, the backslash and slash characters (`\` and `/`) are considered equal. Parameters: | | | | --- | --- | | cs | Case-sensitivity of the comparison. | | dchar `a` | A filename character. | | dchar `b` | A filename character. | Returns: `< 0` if `a < b`, `0` if `a == b`, and `> 0` if `a > b`. Examples: ``` writeln(filenameCharCmp('a', 'a')); // 0 assert(filenameCharCmp('a', 'b') < 0); assert(filenameCharCmp('b', 'a') > 0); version (linux) { // Same as calling filenameCharCmp!(CaseSensitive.yes)(a, b) assert(filenameCharCmp('A', 'a') < 0); assert(filenameCharCmp('a', 'A') > 0); } version (Windows) { // Same as calling filenameCharCmp!(CaseSensitive.no)(a, b) writeln(filenameCharCmp('a', 'A')); // 0 assert(filenameCharCmp('a', 'B') < 0); assert(filenameCharCmp('A', 'b') < 0); } ``` int **filenameCmp**(CaseSensitive cs = CaseSensitive.osDefault, Range1, Range2)(Range1 filename1, Range2 filename2) Constraints: if (isInputRange!Range1 && !isInfinite!Range1 && isSomeChar!(ElementEncodingType!Range1) && !isConvertibleToString!Range1 && isInputRange!Range2 && !isInfinite!Range2 && isSomeChar!(ElementEncodingType!Range2) && !isConvertibleToString!Range2); Compares file names and returns Individual characters are compared using `filenameCharCmp!cs`, where `cs` is an optional template parameter determining whether the comparison is case sensitive or not. Treatment of invalid UTF encodings is implementation defined. Parameters: | | | | --- | --- | | cs | case sensitivity | | Range1 `filename1` | range for first file name | | Range2 `filename2` | range for second file name | Returns: `< 0` if `filename1 < filename2`, `0` if `filename1 == filename2` and `> 0` if `filename1 > filename2`. See Also: [`filenameCharCmp`](#filenameCharCmp) Examples: ``` writeln(filenameCmp("abc", "abc")); // 0 assert(filenameCmp("abc", "abd") < 0); assert(filenameCmp("abc", "abb") > 0); assert(filenameCmp("abc", "abcd") < 0); assert(filenameCmp("abcd", "abc") > 0); version (linux) { // Same as calling filenameCmp!(CaseSensitive.yes)(filename1, filename2) assert(filenameCmp("Abc", "abc") < 0); assert(filenameCmp("abc", "Abc") > 0); } version (Windows) { // Same as calling filenameCmp!(CaseSensitive.no)(filename1, filename2) writeln(filenameCmp("Abc", "abc")); // 0 writeln(filenameCmp("abc", "Abc")); // 0 assert(filenameCmp("Abc", "abD") < 0); assert(filenameCmp("abc", "AbB") > 0); } ``` pure nothrow @safe bool **globMatch**(CaseSensitive cs = CaseSensitive.osDefault, C, Range)(Range path, const(C)[] pattern) Constraints: if (isForwardRange!Range && !isInfinite!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range && isSomeChar!C && is(immutable(C) == immutable(ElementEncodingType!Range))); Matches a pattern against a path. Some characters of pattern have a special meaning (they are *meta-characters*) and can't be escaped. These are: | | | | --- | --- | | `*` | Matches 0 or more instances of any character. | | `?` | Matches exactly one instance of any character. | | `[`*chars*`]` | Matches one instance of any character that appears between the brackets. | | `[!`*chars*`]` | Matches one instance of any character that does not appear between the brackets after the exclamation mark. | | `{`*string1*`,`*string2*`,`…`}` | Matches either of the specified strings. | Individual characters are compared using `filenameCharCmp!cs`, where `cs` is an optional template parameter determining whether the comparison is case sensitive or not. See the [`filenameCharCmp`](#filenameCharCmp) documentation for details. Note that directory separators and dots don't stop a meta-character from matching further portions of the path. Parameters: | | | | --- | --- | | cs | Whether the matching should be case-sensitive | | Range `path` | The path to be matched against | | const(C)[] `pattern` | The glob pattern | Returns: `true` if pattern matches path, `false` otherwise. See Also: [Wikipedia: glob (programming)](http://en.wikipedia.org/wiki/Glob_%28programming%29) Examples: ``` assert(globMatch("foo.bar", "*")); assert(globMatch("foo.bar", "*.*")); assert(globMatch(`foo/foo\bar`, "f*b*r")); assert(globMatch("foo.bar", "f???bar")); assert(globMatch("foo.bar", "[fg]???bar")); assert(globMatch("foo.bar", "[!gh]*bar")); assert(globMatch("bar.fooz", "bar.{foo,bif}z")); assert(globMatch("bar.bifz", "bar.{foo,bif}z")); version (Windows) { // Same as calling globMatch!(CaseSensitive.no)(path, pattern) assert(globMatch("foo", "Foo")); assert(globMatch("Goo.bar", "[fg]???bar")); } version (linux) { // Same as calling globMatch!(CaseSensitive.yes)(path, pattern) assert(!globMatch("foo", "Foo")); assert(!globMatch("Goo.bar", "[fg]???bar")); } ``` bool **isValidFilename**(Range)(Range filename) Constraints: if ((isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && isSomeChar!(ElementEncodingType!Range) || isNarrowString!Range) && !isConvertibleToString!Range); Checks that the given file or directory name is valid. The maximum length of `filename` is given by the constant `core.stdc.stdio.FILENAME_MAX`. (On Windows, this number is defined as the maximum number of UTF-16 code points, and the test will therefore only yield strictly correct results when `filename` is a string of `wchar`s.) On Windows, the following criteria must be satisfied ([source](http://msdn.microsoft.com/en-us/library/aa365247(v=vs.85).aspx)): * `filename` must not contain any characters whose integer representation is in the range 0-31. * `filename` must not contain any of the following *reserved characters*: `<>:"/\|?*` * `filename` may not end with a space (`' '`) or a period (`'.'`). On POSIX, `filename` may not contain a forward slash (`'/'`) or the null character (`'\0'`). Parameters: | | | | --- | --- | | Range `filename` | string to check | Returns: `true` if and only if `filename` is not empty, not too long, and does not contain invalid characters. Examples: ``` import std.utf : byCodeUnit; assert(isValidFilename("hello.exe".byCodeUnit)); ``` bool **isValidPath**(Range)(Range path) Constraints: if ((isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && isSomeChar!(ElementEncodingType!Range) || isNarrowString!Range) && !isConvertibleToString!Range); Checks whether `path` is a valid path. Generally, this function checks that `path` is not empty, and that each component of the path either satisfies [`isValidFilename`](#isValidFilename) or is equal to `"."` or `".."`. **It does *not* check whether the path points to an existing file or directory; use [`std.file.exists`](std_file#exists) for this purpose.** On Windows, some special rules apply: * If the second character of `path` is a colon (`':'`), the first character is interpreted as a drive letter, and must be in the range A-Z (case insensitive). * If `path` is on the form `\\*server*\*share*\...` (UNC path), [`isValidFilename`](#isValidFilename) is applied to *server* and *share* as well. * If `path` starts with `\\?\` (long UNC path), the only requirement for the rest of the string is that it does not contain the null character. * If `path` starts with `\\.\` (Win32 device namespace) this function returns `false`; such paths are beyond the scope of this module. Parameters: | | | | --- | --- | | Range `path` | string or Range of characters to check | Returns: true if `path` is a valid path. Examples: ``` assert(isValidPath("/foo/bar")); assert(!isValidPath("/foo\0/bar")); assert(isValidPath("/")); assert(isValidPath("a")); version (Windows) { assert(isValidPath(`c:\`)); assert(isValidPath(`c:\foo`)); assert(isValidPath(`c:\foo\.\bar\\\..\`)); assert(!isValidPath(`!:\foo`)); assert(!isValidPath(`c::\foo`)); assert(!isValidPath(`c:\foo?`)); assert(!isValidPath(`c:\foo.`)); assert(isValidPath(`\\server\share`)); assert(isValidPath(`\\server\share\foo`)); assert(isValidPath(`\\server\share\\foo`)); assert(!isValidPath(`\\\server\share\foo`)); assert(!isValidPath(`\\server\\share\foo`)); assert(!isValidPath(`\\ser*er\share\foo`)); assert(!isValidPath(`\\server\sha?e\foo`)); assert(!isValidPath(`\\server\share\|oo`)); assert(isValidPath(`\\?\<>:"?*|/\..\.`)); assert(!isValidPath("\\\\?\\foo\0bar")); assert(!isValidPath(`\\.\PhysicalDisk1`)); assert(!isValidPath(`\\`)); } import std.utf : byCodeUnit; assert(isValidPath("/foo/bar".byCodeUnit)); ``` nothrow @safe string **expandTilde**(string inputPath); Performs tilde expansion in paths on POSIX systems. On Windows, this function does nothing. There are two ways of using tilde expansion in a path. One involves using the tilde alone or followed by a path separator. In this case, the tilde will be expanded with the value of the environment variable `HOME`. The second way is putting a username after the tilde (i.e. `~john/Mail`). Here, the username will be searched for in the user database (i.e. `/etc/passwd` on Unix systems) and will expand to whatever path is stored there. The username is considered the string after the tilde ending at the first instance of a path separator. Note that using the `~user` syntax may give different values from just `~` if the environment variable doesn't match the value stored in the user database. When the environment variable version is used, the path won't be modified if the environment variable doesn't exist or it is empty. When the database version is used, the path won't be modified if the user doesn't exist in the database or there is not enough memory to perform the query. This function performs several memory allocations. Parameters: | | | | --- | --- | | string `inputPath` | The path name to expand. | Returns: `inputPath` with the tilde expanded, or just `inputPath` if it could not be expanded. For Windows, `expandTilde` merely returns its argument `inputPath`. Example ``` void processFile(string path) { // Allow calling this function with paths such as ~/foo auto fullPath = expandTilde(path); ... } ``` Examples: ``` version (Posix) { import std.process : environment; auto oldHome = environment["HOME"]; scope(exit) environment["HOME"] = oldHome; environment["HOME"] = "dmd/test"; writeln(expandTilde("~/")); // "dmd/test/" writeln(expandTilde("~")); // "dmd/test" } ```
programming_docs
d Associative Arrays Associative Arrays ================== **Contents** 1. [Removing Keys](#removing_keys) 2. [Testing Membership](#testing_membership) 3. [Using Classes as the KeyType](#using_classes_as_key) 4. [Using Structs or Unions as the KeyType](#using_struct_as_key) 5. [Construction or Assignment on Setting AA Entries](#construction_assignment_entries) 6. [Inserting if not present](#inserting_if_not_present) 7. [Advanced updating](#advanced_updating) 8. [Static Initialization of AAs](#static_initialization) 9. [Runtime Initialization of Immutable AAs](#runtime_initialization) 10. [Construction and Reference Semantics](#construction_and_ref_semantic) 11. [Properties](#properties) 1. [Associative Array Example: word count](#aa_example) 2. [Associative Array Example: counting Tuples](#aa_example_iteration) Associative arrays have an index that is not necessarily an integer, and can be sparsely populated. The index for an associative array is called the *key*, and its type is called the *KeyType*. Associative arrays are declared by placing the *KeyType* within the `[ ]` of an array declaration: ``` int[string] aa; // Associative array of ints that are // indexed by string keys. // The KeyType is string. aa["hello"] = 3; // set value associated with key "hello" to 3 int value = aa["hello"]; // lookup value from a key assert(value == 3); ``` Neither the *KeyType*s nor the element types of an associative array can be function types or `void`. **Implementation Defined:** The built-in associative arrays do not preserve the order of the keys inserted into the array. In particular, in a `foreach` loop the order in which the elements are iterated is typically unspecified. Removing Keys ------------- Particular keys in an associative array can be removed with the `remove` function: ``` aa.remove("hello"); ``` `remove(key)` does nothing if the given *key* does not exist and returns `false`. If the given *key* does exist, it removes it from the AA and returns `true`. All keys can be removed by using the method `clear`. Testing Membership ------------------ The [*InExpression*](expression#InExpression) yields a pointer to the value if the key is in the associative array, or `null` if not: ``` int* p; p = ("hello" in aa); if (p !is null) { *p = 4; // update value associated with key assert(aa["hello"] == 4); } ``` **Undefined Behavior:** Adjusting the pointer to point before or after the element whose address is returned, and then dereferencing it. Using Classes as the KeyType ---------------------------- Classes can be used as the *KeyType*. For this to work, the class definition must override the following member functions of class `Object`: * `size_t toHash() @trusted nothrow` * `bool opEquals(Object)` Note that the parameter to `opEquals` is of type `Object`, not the type of the class in which it is defined. For example: ``` class Foo { int a, b; override size_t toHash() { return a + b; } override bool opEquals(Object o) { Foo foo = cast(Foo) o; return foo && a == foo.a && b == foo.b; } } ``` **Implementation Defined:** `opCmp` is not used to check for equality by the associative array. However, since the actual `opEquals` or `opCmp` called is not decided until runtime, the compiler cannot always detect mismatched functions. Because of legacy issues, the compiler may reject an associative array key type that overrides `opCmp` but not `opEquals`. This restriction may be removed in future versions. **Undefined Behavior:** 1. If `toHash` must consistently be the same value when `opEquals` returns true. In other words, two objects that are considered equal should always have the same hash value. Otherwise, undefined behavior will result. **Best Practices:** 1. Use the attributes `@safe`, `@nogc`, `pure`, `const`, and `scope` as much as possible on the `toHash` and `opEquals` overrides. Using Structs or Unions as the KeyType -------------------------------------- If the *KeyType* is a struct or union type, a default mechanism is used to compute the hash and comparisons of it based on the fields of the struct value. A custom mechanism can be used by providing the following functions as struct members: ``` size_t toHash() const @safe pure nothrow; bool opEquals(ref const typeof(this) s) const @safe pure nothrow; ``` For example: ``` import std.string; struct MyString { string str; size_t toHash() const @safe pure nothrow { size_t hash; foreach (char c; str) hash = (hash * 9) + c; return hash; } bool opEquals(ref const MyString s) const @safe pure nothrow { return std.string.cmp(this.str, s.str) == 0; } } ``` The functions can use `@trusted` instead of `@safe`. **Implementation Defined:** `opCmp` is not used to check for equality by the associative array. For this reason, and for legacy reasons, an associative array key is not allowed to define a specialized `opCmp`, but omit a specialized `opEquals`. This restriction may be removed in future versions of D. **Undefined Behavior:** 1. If `toHash` must consistently be the same value when `opEquals` returns true. In other words, two structs that are considered equal should always have the same hash value. Otherwise, undefined behavior will result. **Best Practices:** 1. Use the attributes `@nogc` as much as possible on the `toHash` and `opEquals` overrides. Construction or Assignment on Setting AA Entries ------------------------------------------------ When an AA indexing access appears on the left side of an assignment operator, it is specially handled for setting an AA entry associated with the key. ``` string[int] aa; string s; s = aa[1]; // throws RangeError in runtime aa[1] = "hello"; // handled for setting AA entry s = aa[1]; // succeeds to lookup assert(s == "hello"); ``` If the assigned value type is equivalent with the AA element type: 1. If the indexing key does not yet exist in AA, a new AA entry will be allocated, and it will be initialized with the assigned value. 2. If the indexing key already exists in the AA, the setting runs normal assignment. ``` struct S { int val; void opAssign(S rhs) { this.val = rhs.val * 2; } } S[int] aa; aa[1] = S(10); // first setting initializes the entry aa[1] assert(aa[1].val == 10); aa[1] = S(10); // second setting invokes normal assignment, and // operator-overloading rewrites it to member opAssign function. assert(aa[1].val == 20); ``` If the assigned value type is **not** equivalent with the AA element type, the expression could invoke operator overloading with normal indexing access: ``` struct S { int val; void opAssign(int v) { this.val = v * 2; } } S[int] aa; aa[1] = 10; // is rewritten to: aa[1].opAssign(10), and // throws RangeError before opAssign is called ``` However, if the AA element type is a struct which supports an implicit constructor call from the assigned value, implicit construction is used for setting the AA entry: ``` struct S { int val; this(int v) { this.val = v; } void opAssign(int v) { this.val = v * 2; } } S s = 1; // OK, rewritten to: S s = S(1); s = 1; // OK, rewritten to: s.opAssign(1); S[int] aa; aa[1] = 10; // first setting is rewritten to: aa[1] = S(10); assert(aa[1].val == 10); aa[1] = 10; // second setting is rewritten to: aa[1].opAssign(10); assert(aa[1].val == 20); ``` This is designed for efficient memory reuse with some value-semantics structs, eg. [`std.bigint.BigInt`](https://dlang.org/phobos/std_bigint.html#BigInt). ``` import std.bigint; BigInt[string] aa; aa["a"] = 10; // construct BigInt(10) and move it in AA aa["a"] = 20; // call aa["a"].opAssign(20) ``` Inserting if not present ------------------------ When AA access requires that there must be a value corresponding to the key, a value must be constructed and inserted if not present. The `require` function provides a means to construct a new value via a lazy argument. The lazy argument is evaluated when the key is not present. The `require` operation avoids the need to perform multiple key lookups. ``` class C{} C[string] aa; auto a = aa.require("a", new C); // lookup "a", construct if not present ``` Sometimes it is necessary to know whether the value was constructed or already exists. The `require` function doesn't provide a boolean parameter to indicate whether the value was constructed but instead allows the construction via a function or delegate. This allows the use of any mechanism as demonstrated below. ``` class C{} C[string] aa; bool constructed; auto a = aa.require("a", { constructed=true; return new C;}()); assert(constructed == true); C newc; auto b = aa.require("b", { newc = new C; return newc;}()); assert(b is newc); ``` Advanced updating ----------------- Typically updating a value in an associative array is simply done with an assign statement. ``` int[string] aa; aa["a"] = 3; // set value associated with key "a" to 3 ``` Sometimes it is necessary to perform different operations depending on whether a value already exists or needs to be constructed. The `update` function provides a means to construct a new value via the `create` delegate or update an existing value via the `update` delegate. The `update` operation avoids the need to perform multiple key lookups. ``` class C{} C[string] aa; C older; C newer; aa.update("a", { newer = new C; return newer; }, (ref C c) { older = c; newer = new C; return newer; }); ``` Static Initialization of AAs ---------------------------- NOTE: Not yet implemented. ``` immutable long[string] aa = [ "foo": 5, "bar": 10, "baz": 2000 ]; unittest { assert(aa["foo"] == 5); assert(aa["bar"] == 10); assert(aa["baz"] == 2000); } ``` Runtime Initialization of Immutable AAs --------------------------------------- Immutable associative arrays are often desirable, but sometimes initialization must be done at runtime. This can be achieved with a constructor (static constructor depending on scope), a buffer associative array and `assumeUnique`: ``` immutable long[string] aa; shared static this() { import std.exception : assumeUnique; import std.conv : to; long[string] temp; // mutable buffer foreach(i; 0 .. 10) { temp[to!string(i)] = i; } temp.rehash; // for faster lookups aa = assumeUnique(temp); } unittest { assert(aa["1"] == 1); assert(aa["5"] == 5); assert(aa["9"] == 9); } ``` Construction and Reference Semantics ------------------------------------ An Associative Array defaults to `null`, and is constructed upon assigning the first key/value pair. However, once constructed, an associative array has *reference semantics*, meaning that assigning one array to another does not copy the data. This is especially important when attempting to create multiple references to the same array. ``` int[int] aa; // defaults to null int[int] aa2 = aa; // copies the null reference aa[1] = 1; assert(aa2.length == 0); // aa2 still is null aa2 = aa; aa2[2] = 2; assert(aa[2] == 2); // now both refer to the same instance ``` Properties ---------- Properties for associative arrays are: Associative Array Properties| **Property** | **Description** | | `.sizeof` | Returns the size of the reference to the associative array; it is 4 in 32-bit builds and 8 on 64-bit builds. | | `.length` | Returns number of values in the associative array. Unlike for dynamic arrays, it is read-only. | | `.dup` | Create a new associative array of the same size and copy the contents of the associative array into it. | | `.keys` | Returns dynamic array, the elements of which are the keys in the associative array. | | `.values` | Returns dynamic array, the elements of which are the values in the associative array. | | `.rehash` | Reorganizes the associative array in place so that lookups are more efficient. `rehash` is effective when, for example, the program is done loading up a symbol table and now needs fast lookups in it. Returns a reference to the reorganized array. | | `.clear` | Removes all remaining keys and values from an associative array. The array is not rehashed after removal, to allow for the existing storage to be reused. This will affect all references to the same instance and is not equivalent to `destroy(aa)` which only sets the current reference to `null` | | `.byKey()` | Returns a forward range suitable for use as a *ForeachAggregate* to a [*ForeachStatement*](statement#ForeachStatement) which will iterate over the keys of the associative array. | | `.byValue()` | Returns a forward range suitable for use as a *ForeachAggregate* to a [*ForeachStatement*](statement#ForeachStatement) which will iterate over the values of the associative array. | | `.byKeyValue()` | Returns a forward range suitable for use as a *ForeachAggregate* to a [*ForeachStatement*](statement#%20%20%20%20%20%20%20%20ForeachStatement) which will iterate over key-value pairs of the associative array. The returned pairs are represented by an opaque type with `.key` and `.value` properties for accessing the key and value of the pair, respectively. Note that this is a low-level interface to iterating over the associative array and is not compatible with the [`Tuple`](https://dlang.org/phobos/std_typecons.html#Tuple) type in Phobos. For compatibility with `Tuple`, use [std.array.byPair](https://dlang.org/phobos/std_array.html#byPair) instead. | | `.get(Key key, lazy Value defVal)` | Looks up `key`; if it exists returns corresponding value else evaluates and returns `defVal`. | | `.require(Key key, lazy Value value)` | Looks up `key`; if it exists returns corresponding value else evaluates `value`, adds it to the associative array and returns it. | | `.update(Key key, Value delegate() create, Value delegate(Value) update)` | Looks up `key`; if it exists applies the `update` delegate else evaluates the `create` delegate and adds it to the associative array | --- ### Associative Array Example: word count Let's consider the file is ASCII encoded with LF EOL. In general case we should use *dchar c* for iteration over code points and functions from [std.uni](https://dlang.org/phobos/std_uni.html). ``` import std.file; // D file I/O import std.stdio; import std.ascii; void main (string[] args) { ulong totalWords, totalLines, totalChars; ulong[string] dictionary; writeln(" lines words bytes file"); foreach (arg; args[1 .. $]) // for each argument except the first one { ulong wordCount, lineCount, charCount; foreach(line; File(arg).byLine()) { bool inWord; size_t wordStart; void tryFinishWord(size_t wordEnd) { if (inWord) { auto word = line[wordStart .. wordEnd]; ++dictionary[word.idup]; // increment count for word inWord = false; } } foreach (i, char c; line) { if (std.ascii.isDigit(c)) { // c is a digit (0..9) } else if (std.ascii.isAlpha(c)) { // c is an ASCII letter (A..Z, a..z) if (!inWord) { wordStart = i; inWord = true; ++wordCount; } } else tryFinishWord(i); ++charCount; } tryFinishWord(line.length); ++lineCount; } writefln("%8s%8s%8s %s", lineCount, wordCount, charCount, arg); totalWords += wordCount; totalLines += lineCount; totalChars += charCount; } if (args.length > 2) { writefln("-------------------------------------\n%8s%8s%8s total", totalLines, totalWords, totalChars); } writeln("-------------------------------------"); foreach (word; dictionary.keys.sort) { writefln("%3s %s", dictionary[word], word); } } ``` ### Associative Array Example: counting Tuples An Associative Array can be iterated in key/value fashion using a [foreach statement](statement#ForeachStatement). As an example, the number of occurrences of all possible substrings of length 2 (aka 2-mers) in a string will be counted: ``` import std.range : dropOne, only, save, zip; import std.stdio : writefln; import std.typecons : Tuple; import std.utf : byCodeUnit; // avoids UTF-8 auto-decoding int[Tuple!(immutable char, immutable char)] aa; // The string `arr` has a limited alphabet: {A, C, G, T} // Thus, for better performance, iteration can be done _without_ decoding auto arr = "AGATAGA".byCodeUnit; // iterate over all pairs in the string and observe each pair // ('A', 'G'), ('G', 'A'), ('A', 'T'), ... foreach (window; arr.zip(arr.save.dropOne)) aa[window]++; // iterate over all key/value pairs of the Associative Array foreach (key, value; aa) { // the second parameter uses tuple-expansion writefln("key: %s [%s], value: %d", key, key.expand.only, value); } ``` ``` % rdmd count.d key: Tuple!(immutable(char), immutable(char))('A', 'G') [AG], value: 2 key: Tuple!(immutable(char), immutable(char))('G', 'A') [GA], value: 2 key: Tuple!(immutable(char), immutable(char))('A', 'T') [AT], value: 1 key: Tuple!(immutable(char), immutable(char))('T', 'A') [TA], value: 1 ``` d std.container std.container ============= This module defines generic containers. Construction To implement the different containers both struct and class based approaches have been used. [`std.container.util.make`](std_container_util#make) allows for uniform construction with either approach. ``` import std.container; // Construct a red-black tree and an array both containing the values 1, 2, 3. // RedBlackTree should typically be allocated using `new` RedBlackTree!int rbTree = new RedBlackTree!int(1, 2, 3); // But `new` should not be used with Array Array!int array = Array!int(1, 2, 3); // `make` hides the differences RedBlackTree!int rbTree2 = make!(RedBlackTree!int)(1, 2, 3); Array!int array2 = make!(Array!int)(1, 2, 3); ``` Note that `make` can infer the element type from the given arguments. ``` import std.container; auto rbTree = make!RedBlackTree(1, 2, 3); // RedBlackTree!int auto array = make!Array("1", "2", "3"); // Array!string ``` Reference semantics All containers have reference semantics, which means that after assignment both variables refer to the same underlying data. To make a copy of a container, use the `c.dup` container primitive. ``` import std.container, std.range; Array!int originalArray = make!(Array!int)(1, 2, 3); Array!int secondArray = originalArray; assert(equal(originalArray[], secondArray[])); // changing one instance changes the other one as well! originalArray[0] = 12; assert(secondArray[0] == 12); // secondArray now refers to an independent copy of originalArray secondArray = originalArray.dup; secondArray[0] = 1; // assert that originalArray has not been affected assert(originalArray[0] == 12); ``` **Attention:** If the container is implemented as a class, using an uninitialized instance can cause a null pointer dereference. ``` import std.container; RedBlackTree!int rbTree; rbTree.insert(5); // null pointer dereference ``` Using an uninitialized struct-based container will work, because the struct intializes itself upon use; however, up to this point the container will not have an identity and assignment does not create two references to the same data. ``` import std.container; // create an uninitialized array Array!int array1; // array2 does _not_ refer to array1 Array!int array2 = array1; array2.insertBack(42); // thus array1 will not be affected assert(array1.empty); // after initialization reference semantics work as expected array1 = array2; // now affects array2 as well array1.removeBack(); assert(array2.empty); ``` It is therefore recommended to always construct containers using [`std.container.util.make`](std_container_util#make). This is in fact necessary to put containers into another container. For example, to construct an `Array` of ten empty `Array`s, use the following that calls `make` ten times. ``` import std.container, std.range; auto arrOfArrs = make!Array(generate!(() => make!(Array!int)).take(10)); ``` Submodules This module consists of the following submodules: * The [`std.container.array`](std_container_array) module provides an array type with deterministic control of memory, not reliant on the GC unlike built-in arrays. * The [`std.container.binaryheap`](std_container_binaryheap) module provides a binary heap implementation that can be applied to any user-provided random-access range. * The [`std.container.dlist`](std_container_dlist) module provides a doubly-linked list implementation. * The [`std.container.rbtree`](std_container_rbtree) module implements red-black trees. * The [`std.container.slist`](std_container_slist) module implements singly-linked lists. * The [`std.container.util`](std_container_util) module contains some generic tools commonly used by container implementations. The primary range of a container While some containers offer direct access to their elements e.g. via `opIndex`, `c.front` or `c.back`, access and modification of a container's contents is generally done through its primary [range](std_range) type, which is aliased as `C.Range`. For example, the primary range type of `Array!int` is `Array!int.Range`. If the documentation of a member function of a container takes a parameter of type `Range`, then it refers to the primary range type of this container. Oftentimes `Take!Range` will be used, in which case the range refers to a span of the elements in the container. Arguments to these parameters **must** be obtained from the same container instance as the one being worked with. It is important to note that many generic range algorithms return the same range type as their input range. ``` import std.algorithm.comparison : equal; import std.algorithm.iteration : find; import std.container; import std.range : take; auto array = make!Array(1, 2, 3); // `find` returns an Array!int.Range advanced to the element "2" array.linearRemove(array[].find(2)); assert(array[].equal([1])); array = make!Array(1, 2, 3); // the range given to `linearRemove` is a Take!(Array!int.Range) // spanning just the element "2" array.linearRemove(array[].find(2).take(1)); assert(array[].equal([1, 3])); ``` When any [range](std_range) can be passed as an argument to a member function, the documention usually refers to the parameter's templated type as `Stuff`. ``` import std.algorithm.comparison : equal; import std.container; import std.range : iota; auto array = make!Array(1, 2); // the range type returned by `iota` is completely unrelated to Array, // which is fine for Array.insertBack: array.insertBack(iota(3, 10)); assert(array[].equal([1, 2, 3, 4, 5, 6, 7, 8, 9])); ``` Container primitives Containers do not form a class hierarchy, instead they implement a common set of primitives (see table below). These primitives each guarantee a specific worst case complexity and thus allow generic code to be written independently of the container implementation. For example the primitives `c.remove(r)` and `c.linearRemove(r)` both remove the sequence of elements in range `r` from the container `c`. The primitive `c.remove(r)` guarantees Ο(`nr log nc`) complexity in the worst case and `c.linearRemove(r)` relaxes this guarantee to Ο(`nc`). Since a sequence of elements can be removed from a [doubly linked list](std_container_dlist) in constant time, `DList` provides the primitive `c.remove(r)` as well as `c.linearRemove(r)`. On the other hand [Array](std_container_array) only offers `c.linearRemove(r)`. The following table describes the common set of primitives that containers implement. A container need not implement all primitives, but if a primitive is implemented, it must support the syntax described in the **syntax** column with the semantics described in the **description** column, and it must not have a worst-case complexity worse than denoted in big-O notation in the Ο(`·`) column. Below, `C` means a container type, `c` is a value of container type, `nx` represents the effective length of value `x`, which could be a single element (in which case `nx` is `1`), a container, or a range. Container primitives| Syntax | Ο(`·`) | Description | | `C(x)` | `nx` | Creates a container of type `C` from either another container or a range. The created container must not be a null reference even if x is empty. | | `c.dup` | `nc` | Returns a duplicate of the container. | | `c ~ x` | `nc + nx` | Returns the concatenation of `c` and `r`. `x` may be a single element or an input range. | | `x ~ c` | `nc + nx` | Returns the concatenation of `x` and `c`. `x` may be a single element or an input range type. | | *Iteration* | | `c.Range` | | The primary range type associated with the container. | | `c[]` | `log nc` | Returns a range iterating over the entire container, in a container-defined order. | | `c[a .. b]` | `log nc` | Fetches a portion of the container from key `a` to key `b`. | | *Capacity* | | `c.empty` | `1` | Returns `true` if the container has no elements, `false` otherwise. | | `c.length` | `log nc` | Returns the number of elements in the container. | | `c.length = n` | `nc + n` | Forces the number of elements in the container to `n`. If the container ends up growing, the added elements are initialized in a container-dependent manner (usually with `T.init`). | | `c.capacity` | `log nc` | Returns the maximum number of elements that can be stored in the container without triggering a reallocation. | | `c.reserve(x)` | `nc` | Forces `capacity` to at least `x` without reducing it. | | *Access* | | `c.front` | `log nc` | Returns the first element of the container, in a container-defined order. | | `c.moveFront` | `log nc` | Destructively reads and returns the first element of the container. The slot is not removed from the container; it is left initialized with `T.init`. This routine need not be defined if `front` returns a `ref`. | | `c.front = v` | `log nc` | Assigns `v` to the first element of the container. | | `c.back` | `log nc` | Returns the last element of the container, in a container-defined order. | | `c.moveBack` | `log nc` | Destructively reads and returns the last element of the container. The slot is not removed from the container; it is left initialized with `T.init`. This routine need not be defined if `front` returns a `ref`. | | `c.back = v` | `log nc` | Assigns `v` to the last element of the container. | | `c[x]` | `log nc` | Provides indexed access into the container. The index type is container-defined. A container may define several index types (and consequently overloaded indexing). | | `c.moveAt(x)` | `log nc` | Destructively reads and returns the value at position `x`. The slot is not removed from the container; it is left initialized with `T.init`. | | `c[x] = v` | `log nc` | Sets element at specified index into the container. | | `c[x] *op*= v` | `log nc` | Performs read-modify-write operation at specified index into the container. | | *Operations* | | `e in c` | `log nc` | Returns nonzero if e is found in `c`. | | `c.lowerBound(v)` | `log nc` | Returns a range of all elements strictly less than `v`. | | `c.upperBound(v)` | `log nc` | Returns a range of all elements strictly greater than `v`. | | `c.equalRange(v)` | `log nc` | Returns a range of all elements in `c` that are equal to `v`. | | *Modifiers* | | `c ~= x` | `nc + nx` | Appends `x` to `c`. `x` may be a single element or an input range type. | | `c.clear()` | `nc` | Removes all elements in `c`. | | `c.insert(x)` | `nx * log nc` | Inserts `x` in `c` at a position (or positions) chosen by `c`. | | `c.stableInsert(x)` | `nx * log nc` | Same as `c.insert(x)`, but is guaranteed to not invalidate any ranges. | | `c.linearInsert(v)` | `nc` | Same as `c.insert(v)` but relaxes complexity to linear. | | `c.stableLinearInsert(v)` | `nc` | Same as `c.stableInsert(v)` but relaxes complexity to linear. | | `c.removeAny()` | `log nc` | Removes some element from `c` and returns it. | | `c.stableRemoveAny()` | `log nc` | Same as `c.removeAny()`, but is guaranteed to not invalidate any iterators. | | `c.insertFront(v)` | `log nc` | Inserts `v` at the front of `c`. | | `c.stableInsertFront(v)` | `log nc` | Same as `c.insertFront(v)`, but guarantees no ranges will be invalidated. | | `c.insertBack(v)` | `log nc` | Inserts `v` at the back of `c`. | | `c.stableInsertBack(v)` | `log nc` | Same as `c.insertBack(v)`, but guarantees no ranges will be invalidated. | | `c.removeFront()` | `log nc` | Removes the element at the front of `c`. | | `c.stableRemoveFront()` | `log nc` | Same as `c.removeFront()`, but guarantees no ranges will be invalidated. | | `c.removeBack()` | `log nc` | Removes the value at the back of `c`. | | `c.stableRemoveBack()` | `log nc` | Same as `c.removeBack()`, but guarantees no ranges will be invalidated. | | `c.remove(r)` | `nr * log nc` | Removes range `r` from `c`. | | `c.stableRemove(r)` | `nr * log nc` | Same as `c.remove(r)`, but guarantees iterators are not invalidated. | | `c.linearRemove(r)` | `nc` | Removes range `r` from `c`. | | `c.stableLinearRemove(r)` | `nc` | Same as `c.linearRemove(r)`, but guarantees iterators are not invalidated. | | `c.removeKey(k)` | `log nc` | Removes an element from `c` by using its key `k`. The key's type is defined by the container. | Source [std/container/package.d](https://github.com/dlang/phobos/blob/master/std/container/package.d) License: Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE\_1\_0.txt or copy at [boost.org/LICENSE\_1\_0.txt](http://boost.org/LICENSE_1_0.txt)). Authors: Steven Schveighoffer, [Andrei Alexandrescu](http://erdani.com)
programming_docs
d std.complex std.complex =========== This module contains the [`Complex`](#Complex) type, which is used to represent complex numbers, along with related mathematical operations and functions. [`Complex`](#Complex) will eventually [replace](https://dlang.org/deprecate.html) the built-in types `cfloat`, `cdouble`, `creal`, `ifloat`, `idouble`, and `ireal`. Authors: Lars Tandle Kyllingstad, Don Clugston License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt) Source [std/complex.d](https://github.com/dlang/phobos/blob/master/std/complex.d) pure nothrow @nogc @safe auto **complex**(R)(const R re) Constraints: if (is(R : double)); pure nothrow @nogc @safe auto **complex**(R, I)(const R re, const I im) Constraints: if (is(R : double) && is(I : double)); Helper function that returns a complex number with the specified real and imaginary parts. Parameters: | | | | --- | --- | | R | (template parameter) type of real part of complex number | | I | (template parameter) type of imaginary part of complex number | | R `re` | real part of complex number to be constructed | | I `im` | (optional) imaginary part of complex number, 0 if omitted. | Returns: `Complex` instance with real and imaginary parts set to the values provided as input. If neither `re` nor `im` are floating-point numbers, the return type will be `Complex!double`. Otherwise, the return type is deduced using `std.traits.CommonType!(R, I)`. Examples: ``` auto a = complex(1.0); static assert(is(typeof(a) == Complex!double)); writeln(a.re); // 1.0 writeln(a.im); // 0.0 auto b = complex(2.0L); static assert(is(typeof(b) == Complex!real)); writeln(b.re); // 2.0L writeln(b.im); // 0.0L auto c = complex(1.0, 2.0); static assert(is(typeof(c) == Complex!double)); writeln(c.re); // 1.0 writeln(c.im); // 2.0 auto d = complex(3.0, 4.0L); static assert(is(typeof(d) == Complex!real)); writeln(d.re); // 3.0 writeln(d.im); // 4.0L auto e = complex(1); static assert(is(typeof(e) == Complex!double)); writeln(e.re); // 1 writeln(e.im); // 0 auto f = complex(1L, 2); static assert(is(typeof(f) == Complex!double)); writeln(f.re); // 1L writeln(f.im); // 2 auto g = complex(3, 4.0L); static assert(is(typeof(g) == Complex!real)); writeln(g.re); // 3 writeln(g.im); // 4.0L ``` struct **Complex**(T) if (isFloatingPoint!T); A complex number parametrised by a type `T`, which must be either `float`, `double` or `real`. T **re**; The real part of the number. T **im**; The imaginary part of the number. const @safe string **toString**(); const void **toString**(Writer, Char)(scope Writer w, ref scope const FormatSpec!Char formatSpec) Constraints: if (isOutputRange!(Writer, const(Char)[])); Converts the complex number to a string representation. The second form of this function is usually not called directly; instead, it is used via [`std.string.format`](std_string#format), as shown in the examples below. Supported format characters are 'e', 'f', 'g', 'a', and 's'. See the [`std.format`](std_format) and [`std.string.format`](std_string#format) documentation for more information. Examples: ``` auto c = complex(1.2, 3.4); // Vanilla toString formatting: writeln(c.toString()); // "1.2+3.4i" // Formatting with std.string.format specs: the precision and width // specifiers apply to both the real and imaginary parts of the // complex number. import std.format : format; writeln(format("%.2f", c)); // "1.20+3.40i" writeln(format("%4.1f", c)); // " 1.2+ 3.4i" ``` this(R : T)(Complex!R z); this(Rx : T, Ry : T)(const Rx x, const Ry y); this(R : T)(const R r); Construct a complex number with the specified real and imaginary parts. In the case where a single argument is passed that is not complex, the imaginary part of the result will be zero. pure nothrow @nogc @safe T **abs**(T)(Complex!T z); Parameters: | | | | --- | --- | | Complex!T `z` | A complex number. | Returns: The absolute value (or modulus) of `z`. Examples: ``` static import std.math; writeln(abs(complex(1.0))); // 1.0 writeln(abs(complex(0.0, 1.0))); // 1.0 writeln(abs(complex(1.0L, -2.0L))); // std.math.sqrt(5.0L) ``` pure nothrow @nogc @safe T **sqAbs**(T)(Complex!T z); pure nothrow @nogc @safe T **sqAbs**(T)(const T x) Constraints: if (isFloatingPoint!T); Parameters: | | | | --- | --- | | Complex!T `z` | A complex number. | | T `x` | A real number. | Returns: The squared modulus of `z`. For genericity, if called on a real number, returns its square. Examples: ``` import std.math; writeln(sqAbs(complex(0.0))); // 0.0 writeln(sqAbs(complex(1.0))); // 1.0 writeln(sqAbs(complex(0.0, 1.0))); // 1.0 assert(approxEqual(sqAbs(complex(1.0L, -2.0L)), 5.0L)); assert(approxEqual(sqAbs(complex(-3.0L, 1.0L)), 10.0L)); assert(approxEqual(sqAbs(complex(1.0f,-1.0f)), 2.0f)); ``` pure nothrow @nogc @safe T **arg**(T)(Complex!T z); Parameters: | | | | --- | --- | | Complex!T `z` | A complex number. | Returns: The argument (or phase) of `z`. Examples: ``` import std.math; writeln(arg(complex(1.0))); // 0.0 writeln(arg(complex(0.0L, 1.0L))); // PI_2 writeln(arg(complex(1.0L, 1.0L))); // PI_4 ``` pure nothrow @nogc @safe T **norm**(T)(Complex!T z); Extracts the norm of a complex number. Parameters: | | | | --- | --- | | Complex!T `z` | A complex number | Returns: The squared magnitude of `z`. Examples: ``` import std.math : isClose, PI; writeln(norm(complex(3.0, 4.0))); // 25.0 writeln(norm(fromPolar(5.0, 0.0))); // 25.0 assert(isClose(norm(fromPolar(5.0L, PI / 6)), 25.0L)); assert(isClose(norm(fromPolar(5.0L, 13 * PI / 6)), 25.0L)); ``` pure nothrow @nogc @safe Complex!T **conj**(T)(Complex!T z); Parameters: | | | | --- | --- | | Complex!T `z` | A complex number. | Returns: The complex conjugate of `z`. Examples: ``` writeln(conj(complex(1.0))); // complex(1.0) writeln(conj(complex(1.0, 2.0))); // complex(1.0, -2.0) ``` Complex!T **proj**(T)(Complex!T z); Returns the projection of `z` onto the Riemann sphere. Parameters: | | | | --- | --- | | Complex!T `z` | A complex number | Returns: The projection of `z` onto the Riemann sphere. Examples: ``` writeln(proj(complex(1.0))); // complex(1.0) writeln(proj(complex(double.infinity, 5.0))); // complex(double.infinity, 0.0) writeln(proj(complex(5.0, -double.infinity))); // complex(double.infinity, -0.0) ``` pure nothrow @nogc @safe Complex!(CommonType!(T, U)) **fromPolar**(T, U)(const T modulus, const U argument); Constructs a complex number given its absolute value and argument. Parameters: | | | | --- | --- | | T `modulus` | The modulus | | U `argument` | The argument | Returns: The complex number with the given modulus and argument. Examples: ``` import std.math; auto z = fromPolar(std.math.sqrt(2.0), PI_4); assert(approxEqual(z.re, 1.0L, real.epsilon)); assert(approxEqual(z.im, 1.0L, real.epsilon)); ``` pure nothrow @nogc @safe Complex!T **sin**(T)(Complex!T z); pure nothrow @nogc @safe Complex!T **cos**(T)(Complex!T z); pure nothrow @nogc @safe Complex!T **tan**(T)(Complex!T z); Trigonometric functions on complex numbers. Parameters: | | | | --- | --- | | Complex!T `z` | A complex number. | Returns: The sine, cosine and tangent of `z`, respectively. Examples: ``` static import std.math; writeln(sin(complex(0.0))); // 0.0 writeln(sin(complex(2.0, 0))); // std.math.sin(2.0) ``` Examples: ``` static import std.math; writeln(cos(complex(0.0))); // 1.0 writeln(cos(complex(1.3, 0.0))); // std.math.cos(1.3) writeln(cos(complex(0.0, 5.2))); // std.math.cosh(5.2) ``` Examples: ``` static import std.math; assert(ceqrel(tan(complex(1.0, 0.0)), complex(std.math.tan(1.0), 0.0)) >= double.mant_dig - 2); assert(ceqrel(tan(complex(0.0, 1.0)), complex(0.0, std.math.tanh(1.0))) >= double.mant_dig - 2); ``` pure nothrow @nogc @trusted Complex!real **expi**(real y); Parameters: | | | | --- | --- | | real `y` | A real number. | Returns: The value of cos(y) + i sin(y). Note `expi` is included here for convenience and for easy migration of code. Examples: ``` import std.math : cos, sin; writeln(expi(0.0L)); // 1.0L writeln(expi(1.3e5L)); // complex(cos(1.3e5L), sin(1.3e5L)) ``` pure nothrow @nogc @safe Complex!real **coshisinh**(real y); Parameters: | | | | --- | --- | | real `y` | A real number. | Returns: The value of cosh(y) + i sinh(y) Note `coshisinh` is included here for convenience and for easy migration of code. Examples: ``` import std.math : cosh, sinh; writeln(coshisinh(3.0L)); // complex(cosh(3.0L), sinh(3.0L)) ``` pure nothrow @nogc @safe Complex!T **sqrt**(T)(Complex!T z); Parameters: | | | | --- | --- | | Complex!T `z` | A complex number. | Returns: The square root of `z`. Examples: ``` static import std.math; writeln(sqrt(complex(0.0))); // 0.0 writeln(sqrt(complex(1.0L, 0))); // std.math.sqrt(1.0L) writeln(sqrt(complex(-1.0L, 0))); // complex(0, 1.0L) writeln(sqrt(complex(-8.0, -6.0))); // complex(1.0, -3.0) ``` pure nothrow @nogc @trusted Complex!T **exp**(T)(Complex!T x); Calculates ex. Parameters: | | | | --- | --- | | Complex!T `x` | A complex number | Returns: The complex base e exponential of `x` Special Values| x | exp(x) | | (±0, +0) | (1, +0) | | (any, +∞) | (NAN, NAN) | | (any, NAN) | (NAN, NAN) | | (+∞, +0) | (+∞, +0) | | (-∞, any) | (±0, cis(x.im)) | | (+∞, any) | (±∞, cis(x.im)) | | (-∞, +∞) | (±0, ±0) | | (+∞, +∞) | (±∞, NAN) | | (-∞, NAN) | (±0, ±0) | | (+∞, NAN) | (±∞, NAN) | | (NAN, +0) | (NAN, +0) | | (NAN, any) | (NAN, NAN) | | (NAN, NAN) | (NAN, NAN) | Examples: ``` import std.math : isClose, PI; writeln(exp(complex(0.0, 0.0))); // complex(1.0, 0.0) auto a = complex(2.0, 1.0); writeln(exp(conj(a))); // conj(exp(a)) auto b = exp(complex(0.0L, 1.0L) * PI); assert(isClose(b, -1.0L, 0.0, 1e-15)); ``` pure nothrow @nogc @safe Complex!T **log**(T)(Complex!T x); Calculate the natural logarithm of x. The branch cut is along the negative axis. Parameters: | | | | --- | --- | | Complex!T `x` | A complex number | Returns: The complex natural logarithm of `x` Special Values| x | log(x) | | (-0, +0) | (-∞, π) | | (+0, +0) | (-∞, +0) | | (any, +∞) | (+∞, π/2) | | (any, NAN) | (NAN, NAN) | | (-∞, any) | (+∞, π) | | (+∞, any) | (+∞, +0) | | (-∞, +∞) | (+∞, 3π/4) | | (+∞, +∞) | (+∞, π/4) | | (±∞, NAN) | (+∞, NAN) | | (NAN, any) | (NAN, NAN) | | (NAN, +∞) | (+∞, NAN) | | (NAN, NAN) | (NAN, NAN) | Examples: ``` import std.math : sqrt, PI, isClose; auto a = complex(2.0, 1.0); writeln(log(conj(a))); // conj(log(a)) auto b = 2.0 * log10(complex(0.0, 1.0)); auto c = 4.0 * log10(complex(sqrt(2.0) / 2, sqrt(2.0) / 2)); assert(isClose(b, c, 0.0, 1e-15)); writeln(log(complex(-1.0L, 0.0L))); // complex(0.0L, PI) writeln(log(complex(-1.0L, -0.0L))); // complex(0.0L, -PI) ``` pure nothrow @nogc @safe Complex!T **log10**(T)(Complex!T x); Calculate the base-10 logarithm of x. Parameters: | | | | --- | --- | | Complex!T `x` | A complex number | Returns: The complex base 10 logarithm of `x` Examples: ``` import std.math : LN10, PI, isClose, sqrt; auto a = complex(2.0, 1.0); writeln(log10(a)); // log(a) / log(complex(10.0)) auto b = log10(complex(0.0, 1.0)) * 2.0; auto c = log10(complex(sqrt(2.0) / 2, sqrt(2.0) / 2)) * 4.0; assert(isClose(b, c, 0.0, 1e-15)); assert(ceqrel(log10(complex(-100.0L, 0.0L)), complex(2.0L, PI / LN10)) >= real.mant_dig - 1); assert(ceqrel(log10(complex(-100.0L, -0.0L)), complex(2.0L, -PI / LN10)) >= real.mant_dig - 1); ``` pure nothrow @nogc @safe Complex!T **pow**(T, Int)(Complex!T x, const Int n) Constraints: if (isIntegral!Int); pure nothrow @nogc @trusted Complex!T **pow**(T)(Complex!T x, const T n); pure nothrow @nogc @trusted Complex!T **pow**(T)(Complex!T x, Complex!T y); pure nothrow @nogc @trusted Complex!T **pow**(T)(const T x, Complex!T n); Calculates xn. The branch cut is on the negative axis. Parameters: | | | | --- | --- | | Complex!T `x` | base | | Int `n` | exponent | Returns: `x` raised to the power of `n` Examples: ``` import std.math : isClose; auto a = complex(1.0, 2.0); writeln(pow(a, 2)); // a * a writeln(pow(a, 3)); // a * a * a writeln(pow(a, -2)); // 1.0 / (a * a) assert(isClose(pow(a, -3), 1.0 / (a * a * a))); auto b = complex(2.0); assert(ceqrel(pow(b, 3), exp(3 * log(b))) >= double.mant_dig - 1); ``` Examples: ``` import std.math : isClose; writeln(pow(complex(0.0), 2.0)); // complex(0.0) writeln(pow(complex(5.0), 2.0)); // complex(25.0) auto a = pow(complex(-1.0, 0.0), 0.5); assert(isClose(a, complex(0.0, +1.0), 0.0, 1e-16)); auto b = pow(complex(-1.0, -0.0), 0.5); assert(isClose(b, complex(0.0, -1.0), 0.0, 1e-16)); ``` Examples: ``` import std.math : isClose, exp, PI; auto a = complex(0.0); auto b = complex(2.0); writeln(pow(a, b)); // complex(0.0) auto c = complex(0.0L, 1.0L); assert(isClose(pow(c, c), exp((-PI) / 2))); ``` Examples: ``` import std.math : isClose; writeln(pow(2.0, complex(0.0))); // complex(1.0) writeln(pow(2.0, complex(5.0))); // complex(32.0) auto a = pow(-2.0, complex(-1.0)); assert(isClose(a, complex(-0.5), 0.0, 1e-16)); auto b = pow(-0.5, complex(-1.0)); assert(isClose(b, complex(-2.0), 0.0, 1e-15)); ``` d std.experimental.allocator.building_blocks.scoped_allocator std.experimental.allocator.building\_blocks.scoped\_allocator ============================================================= Source [std/experimental/allocator/building\_blocks/scoped\_allocator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/scoped_allocator.d) struct **ScopedAllocator**(ParentAllocator); `ScopedAllocator` delegates all allocation requests to `ParentAllocator`. When destroyed, the `ScopedAllocator` object automatically calls `deallocate` for all memory allocated through its lifetime. (The `deallocateAll` function is also implemented with the same semantics.) `deallocate` is also supported, which is where most implementation effort and overhead of `ScopedAllocator` go. If `deallocate` is not needed, a simpler design combining `AllocatorList` with `Region` is recommended. Examples: ``` import std.experimental.allocator.mallocator : Mallocator; import std.typecons : Ternary; ScopedAllocator!Mallocator alloc; writeln(alloc.empty); // Ternary.yes const b = alloc.allocate(10); writeln(b.length); // 10 writeln(alloc.empty); // Ternary.no ``` Allocator **parent**; If `ParentAllocator` is stateful, `parent` is a property giving access to an `AffixAllocator!ParentAllocator`. Otherwise, `parent` is an alias for `AffixAllocator!ParentAllocator.instance`. enum auto **alignment**; Alignment offered size\_t **goodAllocSize**(size\_t n); Forwards to `parent.goodAllocSize` (which accounts for the management overhead). void[] **allocate**(size\_t n); Allocates memory. For management it actually allocates extra memory from the parent. bool **expand**(ref void[] b, size\_t delta); Forwards to `parent.expand(b, delta)`. bool **reallocate**(ref void[] b, size\_t s); Reallocates `b` to new size `s`. Ternary **owns**(void[] b); Forwards to `parent.owns(b)`. bool **deallocate**(void[] b); Deallocates `b`. bool **deallocateAll**(); Deallocates all memory allocated. const pure nothrow @nogc @safe Ternary **empty**(); Returns `Ternary.yes` if this allocator is not responsible for any memory, `Ternary.no` otherwise. (Never returns `Ternary.unknown`.) d Floating Point Floating Point ============== **Contents** 1. [Floating Point Intermediate Values](#fp_intermediate_values) 2. [Floating Point Constant Folding](#fp_const_folding) 3. [Rounding Control](#rounding_control) 4. [Exception Flags](#esception_flags) 5. [Floating Point Transformations](#floating-point-transformations) Floating Point Intermediate Values ---------------------------------- On many computers, greater precision operations do not take any longer than lesser precision operations, so it makes numerical sense to use the greatest precision available for internal temporaries. The philosophy is not to dumb down the language to the lowest common hardware denominator, but to enable the exploitation of the best capabilities of target hardware. For floating point operations and expression intermediate values, a greater precision can be used than the type of the expression. Only the minimum precision is set by the types of the operands, not the maximum. **Implementation Note:** On Intel x86 machines, for example, it is expected (but not required) that the intermediate calculations be done to the full 80 bits of precision implemented by the hardware. It's possible that, due to greater use of temporaries and common subexpressions, optimized code may produce a more accurate answer than unoptimized code. Algorithms should be written to work based on the minimum precision of the calculation. They should not degrade or fail if the actual precision is greater. Float or double types, as opposed to the real (extended) type, should only be used for: * reducing memory consumption for large arrays * when speed is more important than accuracy * data and function argument compatibility with C Floating Point Constant Folding ------------------------------- Regardless of the type of the operands, floating point constant folding is done in `real` or greater precision. It is always done following IEEE 754 rules and round-to-nearest is used. Floating point constants are internally represented in the implementation in at least `real` precision, regardless of the constant's type. The extra precision is available for constant folding. Committing to the precision of the result is done as late as possible in the compilation process. For example: ``` const float f = 0.2f; writeln(f - 0.2); ``` will print 0. A non-const static variable's value cannot be propagated at compile time, so: ``` static float f = 0.2f; writeln(f - 0.2); ``` will print 2.98023e-09. Hex floating point constants can also be used when specific floating point bit patterns are needed that are unaffected by rounding. To find the hex value of 0.2f: ``` import std.stdio; void main() { writefln("%a", 0.2f); } ``` which is 0x1.99999ap-3. Using the hex constant: ``` const float f = 0x1.99999ap-3f; writeln(f - 0.2); ``` prints 2.98023e-09. Different compiler settings, optimization settings, and inlining settings can affect opportunities for constant folding, therefore the results of floating point calculations may differ depending on those settings. Rounding Control ---------------- IEEE 754 floating point arithmetic includes the ability to set 4 different rounding modes. These are accessible via the functions in `core.stdc.fenv`. If the floating-point rounding mode is changed within a function, it must be restored before the function exits. If this rule is violated (for example, by the use of inline asm), the rounding mode used for subsequent calculations is undefined. Exception Flags --------------- IEEE 754 floating point arithmetic can set several flags based on what happened with a computation: | | | --- | | `FE_INVALID` | | `FE_DENORMAL` | | `FE_DIVBYZERO` | | `FE_OVERFLOW` | | `FE_UNDERFLOW` | | `FE_INEXACT` | These flags can be set/reset via the functions in `core.stdc.fenv`. Floating Point Transformations ------------------------------ An implementation may perform transformations on floating point computations in order to reduce their strength, i.e. their runtime computation time. Because floating point math does not precisely follow mathematical rules, some transformations are not valid, even though some other programming languages still allow them. The following transformations of floating point expressions are not allowed because under IEEE rules they could produce different results. Disallowed Floating Point Transformations| **transformation** | **comments** | | *x* + 0 → *x* | not valid if *x* is -0 | | *x* - 0 → *x* | not valid if *x* is ±0 and rounding is towards -∞ | | -*x* ↔ 0 - *x* | not valid if *x* is +0 | | *x* - *x* → 0 | not valid if *x* is NaN or ±∞ | | *x* - *y* ↔ -(*y* - *x*) | not valid because (1-1=+0) whereas -(1-1)=-0 | | *x* \* 0 → 0 | not valid if *x* is NaN or ±∞ | | *x* / *c* ↔ *x* \* (1/*c*) | valid if (1/*c*) yields an e*x*act result | | *x* != *x* → false | not valid if *x* is a NaN | | *x* == *x* → true | not valid if *x* is a NaN | | *x* !*op* *y* ↔ !(*x* *op* *y*) | not valid if *x* or *y* is a NaN | Of course, transformations that would alter side effects are also invalid.
programming_docs
d Contract Programming Contract Programming ==================== **Contents** 1. [Assert Contract](#assert_contracts) 2. [Pre and Post Contracts](#pre_post_contracts) 3. [Invariants](#Invariants) 4. [References](#references) Contracts enable specifying conditions that must hold true when the flow of runtime execution reaches the contract. If a contract is not true, then the program is assumed to have entered an undefined state. **Rationale:** Building contract support into the language provides: 1. a consistent look and feel for the contracts 2. tool support 3. the implementation can generate better code using information gathered from the contracts 4. easier management and enforcement of contracts 5. handling of contract inheritance Assert Contract --------------- See [*AssertExpression*](expression#AssertExpression). Pre and Post Contracts ---------------------- See [contracts](function). Invariants ---------- See [Struct Invariants](https://dlang.org/struct.html#StructInvariant) and [Class Invariants](https://dlang.org/class.html#invariants). References ---------- * [Contracts Reading List](https://web.archive.org/web/20080919174640/http://people.cs.uchicago.edu/~robby/contract-reading-list/) * [Adding Contracts to Java](http://jan.newmarch.name/java/contracts/paper-long.html) d std.experimental.logger.filelogger std.experimental.logger.filelogger ================================== Source [std/experimental/logger/filelogger.d](https://github.com/dlang/phobos/blob/master/std/experimental/logger/filelogger.d) alias **CreateFolder** = std.typecons.Flag!"**CreateFolder**".Flag; An option to create [`FileLogger`](#FileLogger) directory if it is non-existent. class **FileLogger**: std.experimental.logger.core.Logger; This `Logger` implementation writes log messages to the associated file. The name of the file has to be passed on construction time. If the file is already present new log messages will be append at its end. @safe this(const string fn, const LogLevel lv = LogLevel.all); A constructor for the `FileLogger` Logger. Parameters: | | | | --- | --- | | string `fn` | The filename of the output file of the `FileLogger`. If that file can not be opened for writting an exception will be thrown. | | LogLevel `lv` | The `LogLevel` for the `FileLogger`. By default the | Example ``` auto l1 = new FileLogger("logFile"); auto l2 = new FileLogger("logFile", LogLevel.fatal); auto l3 = new FileLogger("logFile", LogLevel.fatal, CreateFolder.yes); ``` @safe this(const string fn, const LogLevel lv, CreateFolder createFileNameFolder); A constructor for the `FileLogger` Logger that takes a reference to a `File`. The `File` passed must be open for all the log call to the `FileLogger`. If the `File` gets closed, using the `FileLogger` for logging will result in undefined behaviour. Parameters: | | | | --- | --- | | string `fn` | The file used for logging. | | LogLevel `lv` | The `LogLevel` for the `FileLogger`. By default the `LogLevel` for `FileLogger` is `LogLevel.all`. | | CreateFolder `createFileNameFolder` | if yes and fn contains a folder name, this folder will be created. | Example ``` auto file = File("logFile.log", "w"); auto l1 = new FileLogger(file); auto l2 = new FileLogger(file, LogLevel.fatal); ``` @safe this(File file, const LogLevel lv = LogLevel.all); A constructor for the `FileLogger` Logger that takes a reference to a `File`. The `File` passed must be open for all the log call to the `FileLogger`. If the `File` gets closed, using the `FileLogger` for logging will result in undefined behaviour. Parameters: | | | | --- | --- | | File `file` | The file used for logging. | | LogLevel `lv` | The `LogLevel` for the `FileLogger`. By default the `LogLevel` for `FileLogger` is `LogLevel.all`. | Example ``` auto file = File("logFile.log", "w"); auto l1 = new FileLogger(file); auto l2 = new FileLogger(file, LogLevel.fatal); ``` @property @safe File **file**(); If the `FileLogger` is managing the `File` it logs to, this method will return a reference to this File. string **getFilename**(); If the `FileLogger` was constructed with a filename, this method returns this filename. Otherwise an empty `string` is returned. protected File **file\_**; The `File` log messages are written to. protected string **filename**; The filename of the `File` log messages are written to. d core.stdc.tgmath core.stdc.tgmath ================ D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<tgmath.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/tgmath.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly Source [core/stdc/tgmath.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/tgmath.d) Standards: ISO/IEC 9899:1999 (E) alias **acos** = **acos**; alias **acos** = **acos**; alias **acos** = **acos**; alias **acos** = **acos**; alias **acos** = **acos**; alias **acos** = core.stdc.complex.cacosl; alias **asin** = **asin**; alias **asin** = **asin**; alias **asin** = **asin**; alias **asin** = **asin**; alias **asin** = **asin**; alias **asin** = core.stdc.complex.casinl; alias **atan** = **atan**; alias **atan** = **atan**; alias **atan** = **atan**; alias **atan** = **atan**; alias **atan** = **atan**; alias **atan** = core.stdc.complex.catanl; alias **atan2** = **atan2**; alias **atan2** = **atan2**; alias **atan2** = core.stdc.math.atan2l; alias **cos** = **cos**; alias **cos** = **cos**; alias **cos** = **cos**; alias **cos** = **cos**; alias **cos** = **cos**; alias **cos** = core.stdc.complex.ccosl; alias **sin** = **sin**; alias **sin** = **sin**; alias **sin** = core.stdc.math.sinl; alias **csin** = **csin**; alias **csin** = **csin**; alias **csin** = core.stdc.complex.csinl; alias **tan** = **tan**; alias **tan** = **tan**; alias **tan** = **tan**; alias **tan** = **tan**; alias **tan** = **tan**; alias **tan** = core.stdc.complex.ctanl; alias **acosh** = **acosh**; alias **acosh** = **acosh**; alias **acosh** = **acosh**; alias **acosh** = **acosh**; alias **acosh** = **acosh**; alias **acosh** = core.stdc.complex.cacoshl; alias **asinh** = **asinh**; alias **asinh** = **asinh**; alias **asinh** = **asinh**; alias **asinh** = **asinh**; alias **asinh** = **asinh**; alias **asinh** = core.stdc.complex.casinhl; alias **atanh** = **atanh**; alias **atanh** = **atanh**; alias **atanh** = **atanh**; alias **atanh** = **atanh**; alias **atanh** = **atanh**; alias **atanh** = core.stdc.complex.catanhl; alias **cosh** = **cosh**; alias **cosh** = **cosh**; alias **cosh** = **cosh**; alias **cosh** = **cosh**; alias **cosh** = **cosh**; alias **cosh** = core.stdc.complex.ccoshl; alias **sinh** = **sinh**; alias **sinh** = **sinh**; alias **sinh** = **sinh**; alias **sinh** = **sinh**; alias **sinh** = **sinh**; alias **sinh** = core.stdc.complex.csinhl; alias **tanh** = **tanh**; alias **tanh** = **tanh**; alias **tanh** = **tanh**; alias **tanh** = **tanh**; alias **tanh** = **tanh**; alias **tanh** = core.stdc.complex.ctanhl; alias **exp** = **exp**; alias **exp** = **exp**; alias **exp** = **exp**; alias **exp** = **exp**; alias **exp** = **exp**; alias **exp** = core.stdc.complex.cexpl; alias **exp2** = **exp2**; alias **exp2** = **exp2**; alias **exp2** = core.stdc.math.exp2l; alias **expm1** = **expm1**; alias **expm1** = **expm1**; alias **expm1** = core.stdc.math.expm1l; alias **frexp** = **frexp**; alias **frexp** = **frexp**; alias **frexp** = core.stdc.math.frexpl; alias **ilogb** = **ilogb**; alias **ilogb** = **ilogb**; alias **ilogb** = core.stdc.math.ilogbl; alias **ldexp** = **ldexp**; alias **ldexp** = **ldexp**; alias **ldexp** = core.stdc.math.ldexpl; alias **log** = **log**; alias **log** = **log**; alias **log** = **log**; alias **log** = **log**; alias **log** = **log**; alias **log** = core.stdc.complex.clogl; alias **log10** = **log10**; alias **log10** = **log10**; alias **log10** = core.stdc.math.log10l; alias **log1p** = **log1p**; alias **log1p** = **log1p**; alias **log1p** = core.stdc.math.log1pl; alias **log2** = **log2**; alias **log2** = **log2**; alias **log2** = core.stdc.math.log2l; alias **logb** = **logb**; alias **logb** = **logb**; alias **logb** = core.stdc.math.logbl; alias **modf** = **modf**; alias **modf** = **modf**; alias **modf** = core.stdc.math.modfl; alias **scalbn** = **scalbn**; alias **scalbn** = **scalbn**; alias **scalbn** = core.stdc.math.scalbnl; alias **scalbln** = **scalbln**; alias **scalbln** = **scalbln**; alias **scalbln** = core.stdc.math.scalblnl; alias **cbrt** = **cbrt**; alias **cbrt** = **cbrt**; alias **cbrt** = core.stdc.math.cbrtl; alias **fabs** = **fabs**; alias **fabs** = **fabs**; alias **fabs** = **fabs**; alias **fabs** = **fabs**; alias **fabs** = **fabs**; alias **fabs** = core.stdc.complex.cabsl; alias **hypot** = **hypot**; alias **hypot** = **hypot**; alias **hypot** = core.stdc.math.hypotl; alias **pow** = **pow**; alias **pow** = **pow**; alias **pow** = **pow**; alias **pow** = **pow**; alias **pow** = **pow**; alias **pow** = core.stdc.complex.cpowl; alias **sqrt** = **sqrt**; alias **sqrt** = **sqrt**; alias **sqrt** = **sqrt**; alias **sqrt** = **sqrt**; alias **sqrt** = **sqrt**; alias **sqrt** = core.stdc.complex.csqrtl; alias **erf** = **erf**; alias **erf** = **erf**; alias **erf** = core.stdc.math.erfl; alias **erfc** = **erfc**; alias **erfc** = **erfc**; alias **erfc** = core.stdc.math.erfcl; alias **lgamma** = **lgamma**; alias **lgamma** = **lgamma**; alias **lgamma** = core.stdc.math.lgammal; alias **tgamma** = **tgamma**; alias **tgamma** = **tgamma**; alias **tgamma** = core.stdc.math.tgammal; alias **ceil** = **ceil**; alias **ceil** = **ceil**; alias **ceil** = core.stdc.math.ceill; alias **floor** = **floor**; alias **floor** = **floor**; alias **floor** = core.stdc.math.floorl; alias **nearbyint** = **nearbyint**; alias **nearbyint** = **nearbyint**; alias **nearbyint** = core.stdc.math.nearbyintl; alias **rint** = **rint**; alias **rint** = **rint**; alias **rint** = core.stdc.math.rintl; alias **lrint** = **lrint**; alias **lrint** = **lrint**; alias **lrint** = core.stdc.math.lrintl; alias **llrint** = **llrint**; alias **llrint** = **llrint**; alias **llrint** = core.stdc.math.llrintl; alias **round** = **round**; alias **round** = **round**; alias **round** = core.stdc.math.roundl; alias **lround** = **lround**; alias **lround** = **lround**; alias **lround** = core.stdc.math.lroundl; alias **llround** = **llround**; alias **llround** = **llround**; alias **llround** = core.stdc.math.llroundl; alias **trunc** = **trunc**; alias **trunc** = **trunc**; alias **trunc** = core.stdc.math.truncl; alias **fmod** = **fmod**; alias **fmod** = **fmod**; alias **fmod** = core.stdc.math.fmodl; alias **remainder** = **remainder**; alias **remainder** = **remainder**; alias **remainder** = core.stdc.math.remainderl; alias **remquo** = **remquo**; alias **remquo** = **remquo**; alias **remquo** = core.stdc.math.remquol; alias **copysign** = **copysign**; alias **copysign** = **copysign**; alias **copysign** = core.stdc.math.copysignl; alias **nan** = **nan**; alias **nan** = **nan**; alias **nan** = core.stdc.math.nanl; alias **nextafter** = **nextafter**; alias **nextafter** = **nextafter**; alias **nextafter** = core.stdc.math.nextafterl; alias **nexttoward** = **nexttoward**; alias **nexttoward** = **nexttoward**; alias **nexttoward** = core.stdc.math.nexttowardl; alias **fdim** = **fdim**; alias **fdim** = **fdim**; alias **fdim** = core.stdc.math.fdiml; alias **fmax** = **fmax**; alias **fmax** = **fmax**; alias **fmax** = core.stdc.math.fmaxl; alias **fmin** = **fmin**; alias **fmin** = **fmin**; alias **fmin** = core.stdc.math.fminl; alias **fma** = **fma**; alias **fma** = **fma**; alias **fma** = core.stdc.math.fmal; alias **carg** = **carg**; alias **carg** = **carg**; alias **carg** = core.stdc.complex.cargl; alias **cimag** = **cimag**; alias **cimag** = **cimag**; alias **cimag** = core.stdc.complex.cimagl; alias **conj** = **conj**; alias **conj** = **conj**; alias **conj** = core.stdc.complex.conjl; alias **cproj** = **cproj**; alias **cproj** = **cproj**; alias **cproj** = core.stdc.complex.cprojl; d rt.llmath rt.llmath ========= Support for 64-bit longs. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright, Sean Kelly Source [rt/llmath.d](https://github.com/dlang/druntime/blob/master/src/rt/llmath.d) void **\_\_ULDIV2\_\_**(); Unsigned long divide. Input [EDX,EAX],[ECX,EBX] Output [EDX,EAX] = [EDX,EAX] / [ECX,EBX] [ECX,EBX] = [EDX,EAX] % [ECX,EBX] void **\_\_LDIV2\_\_**(); Signed long divide. Input [EDX,EAX],[ECX,EBX] Output [EDX,EAX] = [EDX,EAX] / [ECX,EBX] [ECX,EBX] = [EDX,EAX] % [ECX,EBX] ESI,EDI destroyed d rt.minfo rt.minfo ======== Written in the D programming language. Module initialization routines. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright, Sean Kelly Source [rt/minfo.d](https://github.com/dlang/druntime/blob/master/src/rt/minfo.d) struct **ModuleGroup**; A ModuleGroup is an unordered collection of modules. There is exactly one for: 1. all statically linked in D modules, either directely or as shared libraries 2. each call to rt\_loadLibrary() void **sortCtors**(string cycleHandling); void **sortCtors**(); Allocate and fill in ctors[] and tlsctors[]. Modules are inserted into the arrays in the order in which the constructors need to be run. Parameters: Throws: Exception if it fails. bool **sortCtorsOld**(int[][] edges); This is the old ctor sorting algorithm that does not find all cycles. It is here to allow the deprecated behavior from the original algorithm until people have fixed their code. If no cycles are found, the ctors and tlsctors are replaced with the ones generated by this algorithm to preserve the old incorrect ordering behavior. Parameters: | | | | --- | --- | | int[][] `edges` | The module edges as found in the `importedModules` member of each ModuleInfo. Generated in sortCtors. | Returns: true if no cycle is found, false if one was. int **moduleinfos\_apply**(scope int delegate(immutable(ModuleInfo\*)) dg); Iterate over all module infos. void **rt\_moduleCtor**(); Module constructor and destructor routines. void **rt\_moduleTlsCtor**(); Module constructor and destructor routines. void **rt\_moduleTlsDtor**(); Module constructor and destructor routines. void **rt\_moduleDtor**(); Module constructor and destructor routines. void **runModuleFuncs**(alias getfp)(const(immutable(ModuleInfo)\*)[] modules); d std.mathspecial std.mathspecial =============== Mathematical Special Functions The technical term 'Special Functions' includes several families of transcendental functions, which have important applications in particular branches of mathematics and physics. The gamma and related functions, and the error function are crucial for mathematical statistics. The Bessel and related functions arise in problems involving wave propagation (especially in optics). Other major categories of special functions include the elliptic integrals (related to the arc length of an ellipse), and the hypergeometric functions. Status Many more functions will be added to this module. The naming convention for the distribution functions (gammaIncomplete, etc) is not yet finalized and will probably change. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Stephen L. Moshier (original C code). Conversion to D by Don Clugston Source [std/mathspecial.d](https://github.com/dlang/phobos/blob/master/std/mathspecial.d) pure nothrow @nogc @safe real **gamma**(real x); The Gamma function, Γ(x) Γ(x) is a generalisation of the factorial function to real and complex numbers. Like x!, Γ(x+1) = x \* Γ(x). Mathematically, if z.re > 0 then Γ(z) = *∫0∞* tz-1e-t dt Special Values| x | Γ(x) | | NAN | NAN | | ±0.0 | ±∞ | | integer > 0 | (x-1)! | | integer < 0 | NAN | | +∞ | +∞ | | -∞ | NAN | pure nothrow @nogc @safe real **logGamma**(real x); Natural logarithm of the gamma function, Γ(x) Returns the base e (2.718...) logarithm of the absolute value of the gamma function of the argument. For reals, logGamma is equivalent to log(fabs(gamma(x))). Special Values| x | logGamma(x) | | NAN | NAN | | integer <= 0 | +∞ | | ±∞ | +∞ | pure nothrow @nogc @safe real **sgnGamma**(real x); The sign of Γ(x). Returns -1 if Γ(x) < 0, +1 if Γ(x) > 0, NAN if sign is indeterminate. Note that this function can be used in conjunction with logGamma(x) to evaluate gamma for very large values of x. pure nothrow @nogc @safe real **beta**(real x, real y); Beta function The beta function is defined as beta(x, y) = (Γ(x) \* Γ(y)) / Γ(x + y) pure nothrow @nogc @safe real **digamma**(real x); Digamma function The digamma function is the logarithmic derivative of the gamma function. digamma(x) = d/dx logGamma(x) See Also: [`logmdigamma`](#logmdigamma), [`logmdigammaInverse`](#logmdigammaInverse). pure nothrow @nogc @safe real **logmdigamma**(real x); Log Minus Digamma function logmdigamma(x) = log(x) - digamma(x) See Also: [`digamma`](#digamma), [`logmdigammaInverse`](#logmdigammaInverse). pure nothrow @nogc @safe real **logmdigammaInverse**(real x); Inverse of the Log Minus Digamma function Given y, the function finds x such log(x) - digamma(x) = y. See Also: [`logmdigamma`](#logmdigamma), [`digamma`](#digamma). pure nothrow @nogc @safe real **betaIncomplete**(real a, real b, real x); Incomplete beta integral Returns incomplete beta integral of the arguments, evaluated from zero to x. The regularized incomplete beta function is defined as betaIncomplete(a, b, x) = Γ(a + b) / ( Γ(a) Γ(b) ) \* *∫0x* ta-1(1-t)b-1 dt and is the same as the the cumulative distribution function. The domain of definition is 0 <= x <= 1. In this implementation a and b are restricted to positive values. The integral from x to 1 may be obtained by the symmetry relation betaIncompleteCompl(a, b, x ) = betaIncomplete( b, a, 1-x ) The integral is evaluated by a continued fraction expansion or, when b \* x is small, by a power series. pure nothrow @nogc @safe real **betaIncompleteInverse**(real a, real b, real y); Inverse of incomplete beta integral Given y, the function finds x such that betaIncomplete(a, b, x) == y Newton iterations or interval halving is used. pure nothrow @nogc @safe real **gammaIncomplete**(real a, real x); pure nothrow @nogc @safe real **gammaIncompleteCompl**(real a, real x); Incomplete gamma integral and its complement These functions are defined by gammaIncomplete = ( *∫0x* e-t ta-1 dt )/ Γ(a) gammaIncompleteCompl(a,x) = 1 - gammaIncomplete(a,x) = (*∫x∞* e-t ta-1 dt )/ Γ(a) In this implementation both arguments must be positive. The integral is evaluated by either a power series or continued fraction expansion, depending on the relative values of a and x. pure nothrow @nogc @safe real **gammaIncompleteComplInverse**(real a, real p); Inverse of complemented incomplete gamma integral Given a and p, the function finds x such that gammaIncompleteCompl( a, x ) = p. pure nothrow @nogc @safe real **erf**(real x); Error function The integral is erf(x) = 2/ √(π) *∫0x* exp( - t2) dt The magnitude of x is limited to about 106.56 for IEEE 80-bit arithmetic; 1 or -1 is returned outside this range. pure nothrow @nogc @safe real **erfc**(real x); Complementary error function erfc(x) = 1 - erf(x) = 2/ √(π) *∫x∞* exp( - t2) dt This function has high relative accuracy for values of x far from zero. (For values near zero, use erf(x)). pure nothrow @nogc @safe real **normalDistribution**(real x); Standard normal distribution function. The normal (or Gaussian, or bell-shaped) distribution is defined as: normalDist(x) = 1/√(2π) *∫-∞x* exp( - t2/2) dt = 0.5 + 0.5 \* erf(x/sqrt(2)) = 0.5 \* erfc(- x/sqrt(2)) To maintain accuracy at values of x near 1.0, use normalDistribution(x) = 1.0 - normalDistribution(-x). References <http://www.netlib.org/cephes/ldoubdoc.html>, G. Marsaglia, "Evaluating the Normal Distribution", Journal of Statistical Software **11**, (July 2004). pure nothrow @nogc @safe real **normalDistributionInverse**(real p); Inverse of Standard normal distribution function Returns the argument, x, for which the area under the Normal probability density function (integrated from minus infinity to x) is equal to p. Note This function is only implemented to 80 bit precision.
programming_docs
d rt.sections_win64 rt.sections\_win64 ================== Written in the D programming language. This module provides Win32-specific support for sections. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright, Sean Kelly, Martin Nowak Source [rt/sections\_win64.d](https://github.com/dlang/druntime/blob/master/src/rt/sections_win64.d) d rt.deh_win64_posix rt.deh\_win64\_posix ==================== Implementation of exception handling support routines for Win64. Note that this code also support POSIX, however since v2.070.0, DWARF exception handling is used instead when possible, as it provides better compatibility with C++. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright, Sean Kelly Source [rt/deh\_win64\_posix.d](https://github.com/dlang/druntime/blob/master/src/rt/deh_win64_posix.d) See Also: <https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64?view=vs-2019> immutable(FuncTable)\* **\_\_eh\_finddata**(void\* address); Given address that is inside a function, figure out which function it is in. Return DHandlerTable if there is one, NULL if not. size\_t **\_\_eh\_find\_caller**(size\_t regbp, size\_t\* pretaddr); Given EBP, find return address to caller, and caller's EBP. Input regbp Value of EBP for current function \*pretaddr Return address Output \*pretaddr return address to caller Returns: caller's EBP void **\_d\_throwc**(Throwable h); Throw a D object. d std.mmfile std.mmfile ========== Read and write memory mapped files. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com), Matthew Wilson Source [std/mmfile.d](https://github.com/dlang/phobos/blob/master/std/mmfile.d) class **MmFile**; MmFile objects control the memory mapped file resource. enum **Mode**: int; The mode the memory mapped file is opened with. **read** Read existing file **readWriteNew** Delete existing file, write new file **readWrite** Read/Write existing file, create if not existing **readCopyOnWrite** Read/Write existing file, copy on write this(string filename); Open memory mapped file filename for reading. File is closed when the object instance is deleted. Throws: std.file.FileException this(string filename, Mode mode, ulong size, void\* address, size\_t window = 0); Open memory mapped file filename in mode. File is closed when the object instance is deleted. Parameters: | | | | --- | --- | | string `filename` | name of the file. If null, an anonymous file mapping is created. | | Mode `mode` | access mode defined above. | | ulong `size` | the size of the file. If 0, it is taken to be the size of the existing file. | | void\* `address` | the preferred address to map the file to, although the system is not required to honor it. If null, the system selects the most convenient address. | | size\_t `window` | preferred block size of the amount of data to map at one time with 0 meaning map the entire file. The window size must be a multiple of the memory allocation page size. | Throws: std.file.FileException const @property ulong **length**(); Gives size in bytes of the memory mapped file. alias **opDollar** = length; Forwards `length`. Mode **mode**(); Read-only property returning the file mode. void[] **opSlice**(); Returns entire file contents as an array. void[] **opSlice**(ulong i1, ulong i2); Returns slice of file contents as an array. ubyte **opIndex**(ulong i); Returns byte at index i in file. ubyte **opIndexAssign**(ubyte value, ulong i); Sets and returns byte at index i in file to value. d std.experimental.allocator.common std.experimental.allocator.common ================================= Utility and ancillary artifacts of `std.experimental.allocator`. This module shouldn't be used directly; its functionality will be migrated into more appropriate parts of `std`. Authors: [Andrei Alexandrescu](http://erdani.com), Timon Gehr (`Ternary`) Source [std/experimental/allocator/common.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/common.d) template **stateSize**(T) Returns the size in bytes of the state that needs to be allocated to hold an object of type `T`. `stateSize!T` is zero for `struct`s that are not nested and have no nonstatic member variables. enum auto **hasStaticallyKnownAlignment**(Allocator); Returns `true` if the `Allocator` has the alignment known at compile time; otherwise it returns `false`. enum ulong **chooseAtRuntime**; `chooseAtRuntime` is a compile-time constant of type `size_t` that several parameterized structures in this module recognize to mean deferral to runtime of the exact value. For example, `BitmappedBlock!(Allocator, 4096)` (described in detail below) defines a block allocator with block size of 4096 bytes, whereas `BitmappedBlock!(Allocator, chooseAtRuntime)` defines a block allocator that has a field storing the block size, initialized by the user. enum ulong **unbounded**; `unbounded` is a compile-time constant of type `size_t` that several parameterized structures in this module recognize to mean "infinite" bounds for the parameter. For example, `Freelist` (described in detail below) accepts a `maxNodes` parameter limiting the number of freelist items. If `unbounded` is passed for `maxNodes`, then there is no limit and no checking for the number of nodes. enum uint **platformAlignment**; The alignment that is guaranteed to accommodate any D object allocation on the current platform. size\_t **goodAllocSize**(A)(auto ref A a, size\_t n); The default good size allocation is deduced as `n` rounded up to the allocator's alignment. bool **reallocate**(Allocator)(ref Allocator a, ref void[] b, size\_t s); The default `reallocate` function first attempts to use `expand`. If `Allocator.expand` is not defined or returns `false`, `reallocate` allocates a new block of memory of appropriate size and copies data from the old block to the new block. Finally, if `Allocator` defines `deallocate`, `reallocate` uses it to free the old memory block. `reallocate` does not attempt to use `Allocator.reallocate` even if defined. This is deliberate so allocators may use it internally within their own implementation of `reallocate`. bool **alignedReallocate**(Allocator)(ref Allocator alloc, ref void[] b, size\_t s, uint a) Constraints: if (hasMember!(Allocator, "alignedAllocate")); The default `alignedReallocate` function first attempts to use `expand`. If `Allocator.expand` is not defined or returns `false`, `alignedReallocate` allocates a new block of memory of appropriate size and copies data from the old block to the new block. Finally, if `Allocator` defines `deallocate`, `alignedReallocate` uses it to free the old memory block. `alignedReallocate` does not attempt to use `Allocator.reallocate` even if defined. This is deliberate so allocators may use it internally within their own implementation of `reallocate`. string **forwardToMember**(string member, string[] funs...); Forwards each of the methods in `funs` (if defined) to `member`. d std.algorithm.setops std.algorithm.setops ==================== This is a submodule of [`std.algorithm`](std_algorithm). It contains generic algorithms that implement set operations. The functions [`multiwayMerge`](#multiwayMerge), [`multiwayUnion`](#multiwayUnion), [`setDifference`](#setDifference), [`setIntersection`](#setIntersection), [`setSymmetricDifference`](#setSymmetricDifference) expect a range of sorted ranges as input. All algorithms are generalized to accept as input not only sets but also [multisets](http://https//en.wikipedia.org/wiki/Multiset). Each algorithm documents behaviour in the presence of duplicated inputs. Cheat Sheet| Function Name | Description | | [`cartesianProduct`](#cartesianProduct) | Computes Cartesian product of two ranges. | | [`largestPartialIntersection`](#largestPartialIntersection) | Copies out the values that occur most frequently in a range of ranges. | | [`largestPartialIntersectionWeighted`](#largestPartialIntersectionWeighted) | Copies out the values that occur most frequently (multiplied by per-value weights) in a range of ranges. | | [`multiwayMerge`](#multiwayMerge) | Merges a range of sorted ranges. | | [`multiwayUnion`](#multiwayUnion) | Computes the union of a range of sorted ranges. | | [`setDifference`](#setDifference) | Lazily computes the set difference of two or more sorted ranges. | | [`setIntersection`](#setIntersection) | Lazily computes the intersection of two or more sorted ranges. | | [`setSymmetricDifference`](#setSymmetricDifference) | Lazily computes the symmetric set difference of two or more sorted ranges. | License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: [Andrei Alexandrescu](http://erdani.com) Source [std/algorithm/setops.d](https://github.com/dlang/phobos/blob/master/std/algorithm/setops.d) auto **cartesianProduct**(R1, R2)(R1 range1, R2 range2) Constraints: if (!allSatisfy!(isForwardRange, R1, R2) || anySatisfy!(isInfinite, R1, R2)); auto **cartesianProduct**(RR...)(RR ranges) Constraints: if (ranges.length >= 2 && allSatisfy!(isForwardRange, RR) && !anySatisfy!(isInfinite, RR)); auto **cartesianProduct**(R1, R2, RR...)(R1 range1, R2 range2, RR otherRanges) Constraints: if (!allSatisfy!(isForwardRange, R1, R2, RR) || anySatisfy!(isInfinite, R1, R2, RR)); 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](std_range_primitives#isForwardRange) and the other an [input range](std_range_primitives#isInputRange). 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. Parameters: | | | | --- | --- | | R1 `range1` | The first range | | R2 `range2` | The second range | | RR `ranges` | Two or more non-infinite forward ranges | | RR `otherRanges` | Zero or more non-infinite forward ranges | Returns: A forward range of [`std.typecons.Tuple`](std_typecons#Tuple) representing elements of the cartesian product of the given ranges. Examples: ``` 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))); ``` Examples: ``` 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]))); } ``` Examples: ``` 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") ])); ``` void **largestPartialIntersection**(alias less = "a < b", RangeOfRanges, Range)(RangeOfRanges ror, Range tgt, SortOutput sorted = No.sortOutput); Given a range of sorted [forward ranges](std_range_primitives#isForwardRange) `ror`, copies to `tgt` the elements that are common to most ranges, along with their number of occurrences. All ranges in `ror` are assumed to be sorted by `less`. Only the most frequent `tgt.length` elements are returned. Parameters: | | | | --- | --- | | less | The predicate the ranges are sorted by. | | RangeOfRanges `ror` | A range of forward ranges sorted by `less`. | | Range `tgt` | The target range to copy common elements to. | | SortOutput `sorted` | Whether the elements copied should be in sorted order. The function `largestPartialIntersection` is useful for e.g. searching an [inverted index](https://en.wikipedia.org/wiki/Inverted_index) for the documents most likely to contain some terms of interest. The complexity of the search is Ο(`n * log(tgt.length)`), where `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 (`largestPartialIntersection` builds its result directly in `tgt` and requires no extra memory). If at least one of the ranges is a multiset, then all occurences of a duplicate element are taken into account. The result is equivalent to merging all ranges and picking the most frequent `tgt.length` elements. | Warning Because `largestPartialIntersection` does not allocate extra memory, it will leave `ror` modified. Namely, `largestPartialIntersection` assumes ownership of `ror` and discretionarily swaps and advances elements of it. If you want `ror` to preserve its contents after the call, you may want to pass a duplicate to `largestPartialIntersection` (and perhaps cache the duplicate in between calls). Examples: ``` 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 writeln(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); writeln(c[0]); // tuple(1.0, 3u) // 1.0 occurs in 3 inputs // multiset double[][] x = [ [1, 1, 1, 1, 4, 7, 8], [1, 7], [1, 7, 8], [4, 7], [7] ]; auto y = new Tuple!(double, uint)[2]; largestPartialIntersection(x.dup, y); // 7.0 occurs 5 times writeln(y[0]); // tuple(7.0, 5u) // 1.0 occurs 6 times writeln(y[1]); // tuple(1.0, 6u) ``` void **largestPartialIntersectionWeighted**(alias less = "a < b", RangeOfRanges, Range, WeightsAA)(RangeOfRanges ror, Range tgt, WeightsAA weights, SortOutput sorted = No.sortOutput); Similar to `largestPartialIntersection`, but associates a weight with each distinct element in the intersection. If at least one of the ranges is a multiset, then all occurences of a duplicate element are taken into account. The result is equivalent to merging all input ranges and picking the highest `tgt.length`, weight-based ranking elements. Parameters: | | | | --- | --- | | less | The predicate the ranges are sorted by. | | RangeOfRanges `ror` | A range of [forward ranges](std_range_primitives#isForwardRange) sorted by `less`. | | Range `tgt` | The target range to copy common elements to. | | WeightsAA `weights` | An associative array mapping elements to weights. | | SortOutput `sorted` | Whether the elements copied should be in sorted order. | Examples: ``` 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 writeln(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) // multiset double[][] x = [ [ 1, 1, 1, 4, 7, 8 ], [ 1, 7 ], [ 1, 7, 8], [ 4 ], [ 7 ], ]; auto y = new Tuple!(double, uint)[1]; largestPartialIntersectionWeighted(x, y, weights); writeln(y[0]); // tuple(1.0, 5u) // 1.0 occurs 5 times -> 1.2 * 5 = 6 ``` struct **MultiwayMerge**(alias less, RangeOfRanges); MultiwayMerge!(less, RangeOfRanges) **multiwayMerge**(alias less = "a < b", RangeOfRanges)(RangeOfRanges ror); Merges multiple sets. The input sets are passed as a range of ranges and each is assumed to be sorted by `less`. Computation is done lazily, one union element at a time. The complexity of one `popFront` operation is Ο(`log(ror.length)`). However, the length of `ror` decreases as ranges in it are exhausted, so the complexity of a full pass through `MultiwayMerge` is dependent on the distribution of the lengths of ranges contained within `ror`. If all ranges have the same length `n` (worst case scenario), the complexity of a full pass through `MultiwayMerge` is Ο(`n * ror.length * log(ror.length)`), i.e., `log(ror.length)` times worse than just spanning all ranges in turn. The output comes sorted (unstably) by `less`. The length of the resulting range is the sum of all lengths of the ranges passed as input. This means that all elements (duplicates included) are transferred to the resulting range. For backward compatibility, `multiwayMerge` is available under the name `nWayUnion` and `MultiwayMerge` under the name of `NWayUnion` . Future code should use `multiwayMerge` and `MultiwayMerge` as `nWayUnion` and `NWayUnion` will be deprecated. Parameters: | | | | --- | --- | | less | Predicate the given ranges are sorted by. | | RangeOfRanges `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 `MultiwayMerge` does not allocate extra memory, it will leave `ror` modified. Namely, `MultiwayMerge` assumes ownership of `ror` and discretionarily swaps and advances elements of it. If you want `ror` to preserve its contents after the call, you may want to pass a duplicate to `MultiwayMerge` (and perhaps cache the duplicate in between calls). See Also: [`std.algorithm.sorting.merge`](std_algorithm_sorting#merge) for an analogous function that takes a static number of ranges of possibly disparate types. Examples: ``` 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(multiwayMerge(a), witness)); double[][] b = [ // range with duplicates [ 1, 1, 4, 7, 8 ], [ 7 ], [ 1, 7, 8], [ 4 ], [ 7 ], ]; // duplicates are propagated to the resulting range assert(equal(multiwayMerge(b), witness)); ``` static bool **compFront**(.ElementType!RangeOfRanges a, .ElementType!RangeOfRanges b); this(RangeOfRanges ror); @property bool **empty**(); @property ref auto **front**(); void **popFront**(); auto **multiwayUnion**(alias less = "a < b", RangeOfRanges)(RangeOfRanges ror); Computes the union of multiple ranges. The [input ranges](std_range_primitives#isInputRange) are passed as a range of ranges and each is assumed to be sorted by `less`. Computation is done lazily, one union element at a time. `multiwayUnion(ror)` is functionally equivalent to `multiwayMerge(ror).uniq`. "The output of multiwayUnion has no duplicates even when its inputs contain duplicates." Parameters: | | | | --- | --- | | less | Predicate the given ranges are sorted by. | | RangeOfRanges `ror` | A range of ranges sorted by `less` to compute the intersection for. | Returns: A range of the union of the ranges in `ror`. See also: [`multiwayMerge`](#multiwayMerge) Examples: ``` import std.algorithm.comparison : equal; // sets double[][] a = [ [ 1, 4, 7, 8 ], [ 1, 7 ], [ 1, 7, 8], [ 4 ], [ 7 ], ]; auto witness = [1, 4, 7, 8]; assert(equal(multiwayUnion(a), witness)); // multisets double[][] b = [ [ 1, 1, 1, 4, 7, 8 ], [ 1, 7 ], [ 1, 7, 7, 8], [ 4 ], [ 7 ], ]; assert(equal(multiwayUnion(b), witness)); double[][] c = [ [9, 8, 8, 8, 7, 6], [9, 8, 6], [9, 8, 5] ]; auto witness2 = [9, 8, 7, 6, 5]; assert(equal(multiwayUnion!"a > b"(c), witness2)); ``` struct **SetDifference**(alias less = "a < b", R1, R2) if (isInputRange!R1 && isInputRange!R2); SetDifference!(less, R1, R2) **setDifference**(alias less = "a < b", R1, R2)(R1 r1, R2 r2); Lazily computes the difference of `r1` and `r2`. The two ranges are assumed to be sorted by `less`. The element types of the two ranges must have a common type. In the case of multisets, considering that element `a` appears `x` times in `r1` and `y` times and `r2`, the number of occurences of `a` in the resulting range is going to be `x-y` if x > y or 0 otherwise. Parameters: | | | | --- | --- | | less | Predicate the given ranges are sorted by. | | R1 `r1` | The first range. | | R2 `r2` | The range to subtract from `r1`. | Returns: A range of the difference of `r1` and `r2`. See Also: [`setSymmetricDifference`](#setSymmetricDifference) Examples: ``` import std.algorithm.comparison : equal; import std.range.primitives : isForwardRange; //sets 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)))); // multisets int[] x = [1, 1, 1, 2, 3]; int[] y = [1, 1, 2, 4, 5]; auto r = setDifference(x, y); assert(equal(r, [1, 3])); assert(setDifference(r, x).empty); ``` this(R1 r1, R2 r2); void **popFront**(); @property ref auto **front**(); @property typeof(this) **save**(); @property bool **empty**(); struct **SetIntersection**(alias less = "a < b", Rs...) if (Rs.length >= 2 && allSatisfy!(isInputRange, Rs) && !is(CommonType!(staticMap!(ElementType, Rs)) == void)); SetIntersection!(less, Rs) **setIntersection**(alias less = "a < b", Rs...)(Rs ranges) Constraints: if (Rs.length >= 2 && allSatisfy!(isInputRange, Rs) && !is(CommonType!(staticMap!(ElementType, Rs)) == void)); Lazily computes the intersection of two or more [input ranges](std_range_primitives#isInputRange) `ranges`. The ranges are assumed to be sorted by `less`. The element types of the ranges must have a common type. In the case of multisets, the range with the minimum number of occurences of a given element, propagates the number of occurences of this element to the resulting range. Parameters: | | | | --- | --- | | less | Predicate the given ranges are sorted by. | | Rs `ranges` | The ranges to compute the intersection for. | Returns: A range containing the intersection of the given ranges. Examples: ``` import std.algorithm.comparison : equal; // sets 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])); // multisets int[] d = [ 1, 1, 2, 2, 7, 7 ]; int[] e = [ 1, 1, 1, 7]; assert(equal(setIntersection(a, d), [1, 2, 7])); assert(equal(setIntersection(d, e), [1, 1, 7])); ``` this(Rs input); @property bool **empty**(); void **popFront**(); @property ElementType **front**(); @property SetIntersection **save**(); struct **SetSymmetricDifference**(alias less = "a < b", R1, R2) if (isInputRange!R1 && isInputRange!R2); SetSymmetricDifference!(less, R1, R2) **setSymmetricDifference**(alias less = "a < b", R1, R2)(R1 r1, R2 r2); Lazily computes the symmetric difference of `r1` and `r2`, i.e. the elements that are present in exactly one of `r1` and `r2`. The two ranges are assumed to be sorted by `less`, and the output is also sorted by `less`. The element types of the two ranges must have a common type. If both ranges are sets (without duplicated elements), the resulting range is going to be a set. If at least one of the ranges is a multiset, the number of occurences of an element `x` in the resulting range is `abs(a-b)` where `a` is the number of occurences of `x` in `r1`, `b` is the number of occurences of `x` in `r2`, and `abs` is the absolute value. If both arguments are ranges of L-values of the same type then `SetSymmetricDifference` will also be a range of L-values of that type. Parameters: | | | | --- | --- | | less | Predicate the given ranges are sorted by. | | R1 `r1` | The first range. | | R2 `r2` | The second range. | Returns: A range of the symmetric difference between `r1` and `r2`. See Also: [`setDifference`](#setDifference) Examples: ``` import std.algorithm.comparison : equal; import std.range.primitives : isForwardRange; // sets 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)))); //mutisets int[] c = [1, 1, 1, 1, 2, 2, 2, 4, 5, 6]; int[] d = [1, 1, 2, 2, 2, 2, 4, 7, 9]; assert(equal(setSymmetricDifference(c, d), setSymmetricDifference(d, c))); assert(equal(setSymmetricDifference(c, d), [1, 1, 2, 5, 6, 7, 9])); ``` this(R1 r1, R2 r2); void **popFront**(); @property ref auto **front**(); @property typeof(this) **save**(); ref auto **opSlice**(); @property bool **empty**();
programming_docs
d rt.dmain2 rt.dmain2 ========= Contains druntime startup and shutdown routines. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright, Sean Kelly Source [rt/dmain2.d](https://github.com/dlang/druntime/blob/master/src/rt/dmain2.d) void\* **gc\_getProxy**(); These are a temporary means of providing a GC hook for DLL use. They may be replaced with some other similar functionality later. void **gc\_setProxy**(void\* p); These are a temporary means of providing a GC hook for DLL use. They may be replaced with some other similar functionality later. void **gc\_clrProxy**(); These are a temporary means of providing a GC hook for DLL use. They may be replaced with some other similar functionality later. alias **gcGetFn** = extern (C) void\* function(); These are a temporary means of providing a GC hook for DLL use. They may be replaced with some other similar functionality later. alias **gcSetFn** = extern (C) void function(void\*); These are a temporary means of providing a GC hook for DLL use. They may be replaced with some other similar functionality later. alias **gcClrFn** = extern (C) void function(); These are a temporary means of providing a GC hook for DLL use. They may be replaced with some other similar functionality later. shared size\_t **\_initCount**; Keep track of how often rt\_init/rt\_term were called. int **rt\_init**(); Initialize druntime. If a C program wishes to call D code, and there's no D main(), then it must call rt\_init() and rt\_term(). int **rt\_term**(); Terminate use of druntime. alias **TraceHandler** = TraceInfo function(void\* ptr); Trace handler void **rt\_setTraceHandler**(TraceHandler h); Overrides the default trace hander with a user-supplied version. Parameters: | | | | --- | --- | | TraceHandler `h` | The new trace handler. Set to null to use the default handler. | TraceHandler **rt\_getTraceHandler**(); Return the current trace handler Throwable.TraceInfo **\_d\_traceContext**(void\* ptr = null); This function will be called when an exception is constructed. The user-supplied trace handler will be called if one has been supplied, otherwise no trace will be generated. Parameters: | | | | --- | --- | | void\* `ptr` | A pointer to the location from which to generate the trace, or null if the trace should be generated from within the trace handler itself. | Returns: An object describing the current calling context or null if no handler is supplied. struct **CArgs**; Provide out-of-band access to the original C argc/argv passed to this program via main(argc,argv). int **\_d\_run\_main**(int argc, char\*\* argv, MainFunc mainFunc); Sets up the D char[][] command-line args, initializes druntime, runs embedded unittests and then runs the given D main() function, optionally catching and printing any unhandled exceptions. d std.experimental.allocator.building_blocks.free_tree std.experimental.allocator.building\_blocks.free\_tree ====================================================== Source [std/experimental/allocator/building\_blocks/free\_tree.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/free_tree.d) struct **FreeTree**(ParentAllocator); The Free Tree allocator, stackable on top of any other allocator, bears similarity with the free list allocator. Instead of a singly-linked list of previously freed blocks, it maintains a binary search tree. This allows the Free Tree allocator to manage blocks of arbitrary lengths and search them efficiently. Common uses of `FreeTree` include: * Adding `deallocate` capability to an allocator that lacks it (such as simple regions). * Getting the benefits of multiple adaptable freelists that do not need to be tuned for one specific size but insted automatically adapts itself to frequently used sizes. The free tree has special handling of duplicates (a singly-linked list per node) in anticipation of large number of duplicates. Allocation time from the free tree is expected to be Ο(`log n`) where `n` is the number of distinct sizes (not total nodes) kept in the free tree. Allocation requests first search the tree for a buffer of suitable size deallocated in the past. If a match is found, the node is removed from the tree and the memory is returned. Otherwise, the allocation is directed to `ParentAllocator`. If at this point `ParentAllocator` also fails to allocate, `FreeTree` frees everything and then tries the parent allocator again. Upon deallocation, the deallocated block is inserted in the internally maintained free tree (not returned to the parent). The free tree is not kept balanced. Instead, it has a last-in-first-out flavor because newly inserted blocks are rotated to the root of the tree. That way allocations are cache friendly and also frequently used sizes are more likely to be found quickly, whereas seldom used sizes migrate to the leaves of the tree. `FreeTree` rounds up small allocations to at least `4 * size_t.sizeof`, which on 64-bit system is one cache line size. If very small objects need to be efficiently allocated, the `FreeTree` should be fronted with an appropriate small object allocator. The following methods are defined if `ParentAllocator` defines them, and forward to it: `allocateAll`, `expand`, `owns`, `reallocate`. enum uint **alignment**; The `FreeTree` is word aligned. size\_t **goodAllocSize**(size\_t s); Returns `parent.goodAllocSize(max(Node.sizeof, s))`. void[] **allocate**(size\_t n); Allocates `n` bytes of memory. First consults the free tree, and returns from it if a suitably sized block is found. Otherwise, the parent allocator is tried. If allocation from the parent succeeds, the allocated block is returned. Otherwise, the free tree tries an alternate strategy: If `ParentAllocator` defines `deallocate`, `FreeTree` releases all of its contents and tries again. TODO Splitting and coalescing should be implemented if `ParentAllocator` does not defined `deallocate`. bool **deallocate**(void[] b); Places `b` into the free tree. void **clear**(); Defined if `ParentAllocator.deallocate` exists, and returns to it all memory held in the free tree. bool **deallocateAll**(); Defined if `ParentAllocator.deallocateAll` exists, and forwards to it. Also nullifies the free tree (it's assumed the parent frees all memory stil managed by the free tree). d std.experimental.allocator.building_blocks.kernighan_ritchie std.experimental.allocator.building\_blocks.kernighan\_ritchie ============================================================== Source [std/experimental/allocator/building\_blocks/kernighan\_ritchie.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/kernighan_ritchie.d) struct **KRRegion**(ParentAllocator = NullAllocator); `KRRegion` draws inspiration from the [region allocation strategy](std_experimental_allocator_building_blocks_region) and also the [famed allocator](http://stackoverflow.com/questions/13159564/explain-this-implementation-of-malloc-from-the-kr-book) described by Brian Kernighan and Dennis Ritchie in section 8.7 of the book ["The C Programming Language"](http://amazon.com/exec/obidos/ASIN/0131103628/classicempire), Second Edition, Prentice Hall, 1988. #### `KRRegion` = `Region` + Kernighan-Ritchie Allocator Initially, `KRRegion` starts in "region" mode: allocations are served from the memory chunk in a region fashion. Thus, as long as there is enough memory left, `KRRegion.allocate` has the performance profile of a region allocator. Deallocation inserts (in Ο(`1`) time) the deallocated blocks in an unstructured freelist, which is not read in region mode. Once the region cannot serve an `allocate` request, `KRRegion` switches to "free list" mode. It sorts the list of previously deallocated blocks by address and serves allocation requests off that free list. The allocation and deallocation follow the pattern described by Kernighan and Ritchie. The recommended use of `KRRegion` is as a *region with deallocation*. If the `KRRegion` is dimensioned appropriately, it could often not enter free list mode during its lifetime. Thus it is as fast as a simple region, whilst offering deallocation at a small cost. When the region memory is exhausted, the previously deallocated memory is still usable, at a performance cost. If the region is not excessively large and fragmented, the linear allocation and deallocation cost may still be compensated for by the good locality characteristics. If the chunk of memory managed is large, it may be desirable to switch management to free list from the beginning. That way, memory may be used in a more compact manner than region mode. To force free list mode, call `switchToFreeList` shortly after construction or when deemed appropriate. The smallest size that can be allocated is two words (16 bytes on 64-bit systems, 8 bytes on 32-bit systems). This is because the free list management needs two words (one for the length, the other for the next pointer in the singly-linked list). The `ParentAllocator` type parameter is the type of the allocator used to allocate the memory chunk underlying the `KRRegion` object. Choosing the default (`NullAllocator`) means the user is responsible for passing a buffer at construction (and for deallocating it if necessary). Otherwise, `KRRegion` automatically deallocates the buffer during destruction. For that reason, if `ParentAllocator` is not `NullAllocator`, then `KRRegion` is not copyable. #### Implementation Details In free list mode, `KRRegion` embeds a free blocks list onto the chunk of memory. The free list is circular, coalesced, and sorted by address at all times. Allocations and deallocations take time proportional to the number of previously deallocated blocks. (In practice the cost may be lower, e.g. if memory is deallocated in reverse order of allocation, all operations take constant time.) Memory utilization is good (small control structure and no per-allocation overhead). The disadvantages of freelist mode include proneness to fragmentation, a minimum allocation size of two words, and linear worst-case allocation and deallocation times. Similarities of `KRRegion` (in free list mode) with the Kernighan-Ritchie allocator: * Free blocks have variable size and are linked in a singly-linked list. * The freelist is maintained in increasing address order, which makes coalescing easy. * The strategy for finding the next available block is first fit. * The free list is circular, with the last node pointing back to the first. * Coalescing is carried during deallocation. Differences from the Kernighan-Ritchie allocator: * Once the chunk is exhausted, the Kernighan-Ritchie allocator allocates another chunk using operating system primitives. For better composability, `KRRegion` just gets full (returns `null` on new allocation requests). The decision to allocate more blocks is deferred to a higher-level entity. For an example, see the example below using `AllocatorList` in conjunction with `KRRegion`. * Allocated blocks do not hold a size prefix. This is because in D the size information is available in client code at deallocation time. Examples: `KRRegion` is preferable to `Region` as a front for a general-purpose allocator if `deallocate` is needed, yet the actual deallocation traffic is relatively low. The example below shows a `KRRegion` using stack storage fronting the GC allocator. ``` import std.experimental.allocator.building_blocks.fallback_allocator : fallbackAllocator; import std.experimental.allocator.gc_allocator : GCAllocator; import std.typecons : Ternary; // KRRegion fronting a general-purpose allocator ubyte[1024 * 128] buf; auto alloc = fallbackAllocator(KRRegion!()(buf), GCAllocator.instance); auto b = alloc.allocate(100); writeln(b.length); // 100 writeln((() pure nothrow @safe @nogc => alloc.primary.owns(b))()); // Ternary.yes ``` Examples: The code below defines a scalable allocator consisting of 1 MB (or larger) blocks fetched from the garbage-collected heap. Each block is organized as a KR-style heap. More blocks are allocated and freed on a need basis. This is the closest example to the allocator introduced in the K&R book. It should perform slightly better because instead of searching through one large free list, it searches through several shorter lists in LRU order. Also, it actually returns memory to the operating system when possible. ``` import std.algorithm.comparison : max; import std.experimental.allocator.building_blocks.allocator_list : AllocatorList; import std.experimental.allocator.mmap_allocator : MmapAllocator; AllocatorList!(n => KRRegion!MmapAllocator(max(n * 16, 1024 * 1024))) alloc; ``` ParentAllocator **parent**; If `ParentAllocator` holds state, `parent` is a public member of type `KRRegion`. Otherwise, `parent` is an `alias` for `ParentAllocator.instance`. this(ubyte[] b); this(size\_t n); this(ParentAllocator parent, size\_t n); Create a `KRRegion`. If `ParentAllocator` is not `NullAllocator`, `KRRegion`'s destructor will call `parent.deallocate`. Parameters: | | | | --- | --- | | ubyte[] `b` | Block of memory to serve as support for the allocator. Memory must be larger than two words and word-aligned. | | size\_t `n` | Capacity desired. This constructor is defined only if `ParentAllocator` is not `NullAllocator`. | void **switchToFreeList**(); Forces free list mode. If already in free list mode, does nothing. Otherwise, sorts the free list accumulated so far and switches strategy for future allocations to KR style. enum auto **alignment**; Word-level alignment. void[] **allocate**(size\_t n); Allocates `n` bytes. Allocation searches the list of available blocks until a free block with `n` or more bytes is found (first fit strategy). The block is split (if larger) and returned. Parameters: | | | | --- | --- | | size\_t `n` | number of bytes to allocate | Returns: A word-aligned buffer of `n` bytes, or `null`. nothrow @nogc bool **deallocate**(void[] b); Deallocates `b`, which is assumed to have been previously allocated with this allocator. Deallocation performs a linear search in the free list to preserve its sorting order. It follows that blocks with higher addresses in allocators with many free blocks are slower to deallocate. Parameters: | | | | --- | --- | | void[] `b` | block to be deallocated | void[] **allocateAll**(); Allocates all memory available to this allocator. If the allocator is empty, returns the entire available block of memory. Otherwise, it still performs a best-effort allocation: if there is no fragmentation (e.g. `allocate` has been used but not `deallocate`), allocates and returns the only available block of memory. The operation takes time proportional to the number of adjacent free blocks at the front of the free list. These blocks get coalesced, whether `allocateAll` succeeds or fails due to fragmentation. Examples: ``` import std.experimental.allocator.gc_allocator : GCAllocator; auto alloc = KRRegion!GCAllocator(1024 * 64); const b1 = alloc.allocate(2048); writeln(b1.length); // 2048 const b2 = alloc.allocateAll; writeln(b2.length); // 1024 * 62 ``` pure nothrow @nogc bool **deallocateAll**(); Deallocates all memory currently allocated, making the allocator ready for other allocations. This is a Ο(`1`) operation. pure nothrow @nogc @trusted Ternary **owns**(void[] b); Checks whether the allocator is responsible for the allocation of `b`. It does a simple Ο(`1`) range check. `b` should be a buffer either allocated with `this` or obtained through other means. static pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n); Adjusts `n` to a size suitable for allocation (two words or larger, word-aligned). pure nothrow @nogc @safe Ternary **empty**(); Returns: `Ternary.yes` if the allocator is empty, `Ternary.no` otherwise. Never returns `Ternary.unknown`. d std.net.curl std.net.curl ============ Networking client functionality as provided by [libcurl](http://curl.haxx.se/libcurl). The libcurl library must be installed on the system in order to use this module. | Category | Functions | | --- | --- | | High level | [*download*](#download) [*upload*](#upload) [*get*](#get) [*post*](#post) [*put*](#put) [*del*](#del) [*options*](#options) [*trace*](#trace) [*connect*](#connect) [*byLine*](#byLine) [*byChunk*](#byChunk) [*byLineAsync*](#byLineAsync) [*byChunkAsync*](#byChunkAsync) | | Low level | [*HTTP*](#HTTP) [*FTP*](#FTP) [*SMTP*](#SMTP) | Note You may need to link to the **curl** library, e.g. by adding `"libs": ["curl"]` to your **dub.json** file if you are using [DUB](http://code.dlang.org). Windows x86 note: A DMD compatible libcurl static library can be downloaded from the dlang.org [download archive page](http://downloads.dlang.org/other/index.html). This module is not available for iOS, tvOS or watchOS. 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 [range](std_range) 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 [`byLineAsync`](#byLineAsync) and [`byChunkAsync`](#byChunkAsync) provides asynchronous [range](std_range) 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. Cheat Sheet| Function Name | Description | | *High level* | | [`download`](#download) | `download("ftp.digitalmars.com/sieve.ds", "/tmp/downloaded-ftp-file")` downloads file from URL to file system. | | [`upload`](#upload) | `upload("/tmp/downloaded-ftp-file", "ftp.digitalmars.com/sieve.ds");` uploads file from file system to URL. | | [`get`](#get) | `get("dlang.org")` returns a char[] containing the dlang.org web page. | | [`put`](#put) | `put("dlang.org", "Hi")` returns a char[] containing the dlang.org web page. after a HTTP PUT of "hi" | | [`post`](#post) | `post("dlang.org", "Hi")` returns a char[] containing the dlang.org web page. after a HTTP POST of "hi" | | [`byLine`](#byLine) | `byLine("dlang.org")` returns a range of char[] containing the dlang.org web page. | | [`byChunk`](#byChunk) | `byChunk("dlang.org", 10)` returns a range of ubyte[10] containing the dlang.org web page. | | [`byLineAsync`](#byLineAsync) | `byLineAsync("dlang.org")` returns a range of char[] containing the dlang.org web page asynchronously. | | [`byChunkAsync`](#byChunkAsync) | `byChunkAsync("dlang.org", 10)` returns a range of ubyte[10] containing the dlang.org web page asynchronously. | | *Low level* | | [`HTTP`](#HTTP) | `HTTP` struct for advanced usage | | [`FTP`](#FTP) | `FTP` struct for advanced usage | | [`SMTP`](#SMTP) | `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 [`onReceiveHeader`](#onReceiveHeader)/[`onReceive`](#onReceive) for more information. Finally the HTTP request is effected by calling perform(), which is synchronous. Source [std/net/curl.d](https://github.com/dlang/phobos/blob/master/std/net/curl.d) License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Jonas Drewsen. Some of the SMTP code contributed by Jimmy Cao. Credits The functionally is based on [libcurl](http://curl.haxx.se/libcurl). LibCurl is licensed under an MIT/X derivative license. struct **AutoProtocol**; Example ``` import std.net.curl; // Two requests below will do the same. char[] 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 content = get("ftp://foo.com/file"); // and will end up detecting FTP from the url and be the same as content = get!FTP("ftp://foo.com/file"); ``` void **download**(Conn = AutoProtocol)(const(char)[] url, string saveToPath, Conn conn = Conn()) Constraints: if (isCurlConn!Conn); HTTP/FTP download to local file system. Parameters: | | | | --- | --- | | const(char)[] `url` | resource to download | | string `saveToPath` | path to store the downloaded content on local disk | | Conn `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("https://httpbin.org/get", "/tmp/downloaded-http-file"); ``` void **upload**(Conn = AutoProtocol)(string loadFromPath, const(char)[] url, Conn conn = Conn()) Constraints: if (isCurlConn!Conn); Upload file from local files system using the HTTP or FTP protocol. Parameters: | | | | --- | --- | | string `loadFromPath` | path load data from local disk. | | const(char)[] `url` | resource to upload to | | Conn `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", "https://httpbin.org/post"); ``` T[] **get**(Conn = AutoProtocol, T = char)(const(char)[] url, Conn conn = Conn()) Constraints: if (isCurlConn!Conn && (is(T == char) || is(T == ubyte))); HTTP/FTP get content. Parameters: | | | | --- | --- | | const(char)[] `url` | resource to get | | Conn `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 `T` specifies the type to return. Possible values are `char` and `ubyte` to return `char[]` or `ubyte[]`. If asking for `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("https://httpbin.org/get"); ``` Returns: A T[] range containing the content of the resource pointed to by the URL. Throws: `CurlException` on error. See Also: [`HTTP.Method`](#HTTP.Method) T[] **post**(T = char, PostUnit)(const(char)[] url, const(PostUnit)[] postData, HTTP conn = HTTP()) Constraints: if (is(T == char) || is(T == ubyte)); T[] **post**(T = char)(const(char)[] url, string[string] postDict, HTTP conn = HTTP()) Constraints: if (is(T == char) || is(T == ubyte)); HTTP post content. Parameters: | | | | --- | --- | | const(char)[] `url` | resource to post to | | string[string] `postDict` | data to send as the body of the request. An associative array of `string` is accepted and will be encoded using www-form-urlencoding | | const(PostUnit)[] `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. | | HTTP `conn` | HTTP connection to use | | T | The template parameter `T` specifies the type to return. Possible values are `char` and `ubyte` to return `char[]` or `ubyte[]`. If asking for `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("https://httpbin.org/post", ["name1" : "value1", "name2" : "value2"]); auto content2 = post("https://httpbin.org/post", [1,2,3,4]); ``` Returns: A T[] range containing the content of the resource pointed to by the URL. See Also: [`HTTP.Method`](#HTTP.Method) T[] **put**(Conn = AutoProtocol, T = char, PutUnit)(const(char)[] url, const(PutUnit)[] putData, Conn conn = Conn()) Constraints: if (isCurlConn!Conn && (is(T == char) || is(T == ubyte))); HTTP/FTP put content. Parameters: | | | | --- | --- | | const(char)[] `url` | resource to put | | const(PutUnit)[] `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 `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 `T` specifies the type to return. Possible values are `char` and `ubyte` to return `char[]` or `ubyte[]`. If asking for `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("https://httpbin.org/put", "Putting this data"); ``` Returns: A T[] range containing the content of the resource pointed to by the URL. See Also: [`HTTP.Method`](#HTTP.Method) void **del**(Conn = AutoProtocol)(const(char)[] url, Conn conn = Conn()) Constraints: if (isCurlConn!Conn); HTTP/FTP delete content. Parameters: | | | | --- | --- | | const(char)[] `url` | resource to delete | | Conn `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("https://httpbin.org/delete"); ``` See Also: [`HTTP.Method`](#HTTP.Method) T[] **options**(T = char)(const(char)[] url, HTTP conn = HTTP()) Constraints: if (is(T == char) || is(T == ubyte)); HTTP options request. Parameters: | | | | --- | --- | | const(char)[] `url` | resource make a option call to | | HTTP `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 `T` specifies the type to return. Possible values are `char` and `ubyte` to return `char[]` or `ubyte[]`. | Example ``` import std.net.curl; auto http = HTTP(); options("https://httpbin.org/headers", 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: [`HTTP.Method`](#HTTP.Method) T[] **trace**(T = char)(const(char)[] url, HTTP conn = HTTP()) Constraints: if (is(T == char) || is(T == ubyte)); HTTP trace request. Parameters: | | | | --- | --- | | const(char)[] `url` | resource make a trace call to | | HTTP `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 `T` specifies the type to return. Possible values are `char` and `ubyte` to return `char[]` or `ubyte[]`. | Example ``` import std.net.curl; trace("https://httpbin.org/headers"); ``` Returns: A T[] range containing the trace info of the resource pointed to by the URL. See Also: [`HTTP.Method`](#HTTP.Method) T[] **connect**(T = char)(const(char)[] url, HTTP conn = HTTP()) Constraints: if (is(T == char) || is(T == ubyte)); HTTP connect request. Parameters: | | | | --- | --- | | const(char)[] `url` | resource make a connect to | | HTTP `conn` | HTTP connection to use The template parameter `T` specifies the type to return. Possible values are `char` and `ubyte` to return `char[]` or `ubyte[]`. | Example ``` import std.net.curl; connect("https://httpbin.org/headers"); ``` Returns: A T[] range containing the connect info of the resource pointed to by the URL. See Also: [`HTTP.Method`](#HTTP.Method) T[] **patch**(T = char, PatchUnit)(const(char)[] url, const(PatchUnit)[] patchData, HTTP conn = HTTP()) Constraints: if (is(T == char) || is(T == ubyte)); HTTP patch content. Parameters: | | | | --- | --- | | const(char)[] `url` | resource to patch | | const(PatchUnit)[] `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. | | HTTP `conn` | HTTP connection to use The template parameter `T` specifies the type to return. Possible values are `char` and `ubyte` to return `char[]` or `ubyte[]`. | Example ``` auto http = HTTP(); http.addRequestHeader("Content-Type", "application/json"); auto content = patch("https://httpbin.org/patch", `{"title": "Patched Title"}`, http); ``` Returns: A T[] range containing the content of the resource pointed to by the URL. See Also: [`HTTP.Method`](#HTTP.Method) auto **byLine**(Conn = AutoProtocol, Terminator = char, Char = char)(const(char)[] url, KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\x0a', Conn conn = Conn()) Constraints: if (isCurlConn!Conn && isSomeChar!Char && isSomeChar!Terminator); 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 `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); ``` Parameters: | | | | --- | --- | | const(char)[] `url` | The url to receive content from | | KeepTerminator `keepTerminator` | `Yes.keepTerminator` signals that the line terminator should be returned as part of the lines in the range. | | Terminator `terminator` | The character that terminates a line | | Conn `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 **byChunk**(Conn = AutoProtocol)(const(char)[] url, size\_t chunkSize = 1024, Conn conn = Conn()) Constraints: if (isCurlConn!Conn); 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 `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] ``` Parameters: | | | | --- | --- | | const(char)[] `url` | The url to receive content from | | size\_t `chunkSize` | The size of each chunk | | Conn `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 **byLineAsync**(Conn = AutoProtocol, Terminator = char, Char = char, PostUnit)(const(char)[] url, const(PostUnit)[] postData, KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\x0a', size\_t transmitBuffers = 10, Conn conn = Conn()) Constraints: if (isCurlConn!Conn && isSomeChar!Char && isSomeChar!Terminator); auto **byLineAsync**(Conn = AutoProtocol, Terminator = char, Char = char)(const(char)[] url, KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\x0a', size\_t transmitBuffers = 10, Conn conn = Conn()); 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 `conn` parameter with a HTTP/FTP instance that has these properties set. If `postData` is non-null the method will be set to `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 `wait(Duration)` method on the [`LineInputRange`](#LineInputRange). 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 (range3.wait(dur!"seconds"(2))) writeln(range3.front); else writeln("No line received after 2 seconds!"); ``` Parameters: | | | | --- | --- | | const(char)[] `url` | The url to receive content from | | const(PostUnit)[] `postData` | Data to HTTP Post | | KeepTerminator `keepTerminator` | `Yes.keepTerminator` signals that the line terminator should be returned as part of the lines in the range. | | Terminator `terminator` | The character that terminates a line | | size\_t `transmitBuffers` | The number of lines buffered asynchronously | | Conn `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 **byChunkAsync**(Conn = AutoProtocol, PostUnit)(const(char)[] url, const(PostUnit)[] postData, size\_t chunkSize = 1024, size\_t transmitBuffers = 10, Conn conn = Conn()) Constraints: if (isCurlConn!Conn); auto **byChunkAsync**(Conn = AutoProtocol)(const(char)[] url, size\_t chunkSize = 1024, size\_t transmitBuffers = 10, Conn conn = Conn()) Constraints: if (isCurlConn!Conn); 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 `conn` parameter with a HTTP/FTP instance that has these properties set. If `postData` is non-null the method will be set to `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 `wait(Duration)` method on the [`ChunkInputRange`](#ChunkInputRange). 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 (range3.wait(dur!"seconds"(2))) writeln(range3.front); else writeln("No chunk received after 2 seconds!"); ``` Parameters: | | | | --- | --- | | const(char)[] `url` | The url to receive content from | | const(PostUnit)[] `postData` | Data to HTTP Post | | size\_t `chunkSize` | The size of the chunks | | size\_t `transmitBuffers` | The number of chunks buffered asynchronously | | Conn `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. struct **HTTP**; HTTP client functionality. Example Get with custom data receivers: ``` import std.net.curl, std.stdio; auto http = HTTP("https://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: ``` import std.net.curl, std.stdio; auto http = HTTP("https://dlang.org"); 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(); ``` Tracking progress: ``` import std.net.curl, std.stdio; auto http = HTTP(); 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: [RFC2616](http://www.ietf.org/rfc/rfc2616.txt) alias **AuthMethod** = etc.c.curl.CurlAuth; Authentication method equal to [`etc.c.curl.CurlAuth`](etc_c_curl#CurlAuth) alias **TimeCond** = etc.c.curl.CurlTimeCond; Time condition enumeration as an alias of [`etc.c.curl.CurlTimeCond`](etc_c_curl#CurlTimeCond) [RFC2616 Section 14.25](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25) static HTTP **opCall**(const(char)[] url); Constructor taking the url as parameter. static HTTP **opCall**(); HTTP **dup**(); CurlCode **perform**(ThrowOnError throwOnError = Yes.throwOnError); Perform a http request. After the HTTP client has been setup and possibly assigned callbacks the `perform()` method will start performing the request towards the specified server. Parameters: | | | | --- | --- | | ThrowOnError `throwOnError` | whether to throw an exception or return a CurlCode on error | @property void **url**(const(char)[] **url**); The URL to specify the location of the resource. @property void **caInfo**(const(char)[] caFile); Set the CA certificate bundle file to use for SSL peer verification alias **requestPause** = etc.c.curl.CurlReadFunc.pause; Value to return from `onSend`/`onReceive` delegates in order to pause a request alias **requestAbort** = etc.c.curl.CurlReadFunc.abort; Value to return from onSend delegate in order to abort a request @property bool **isStopped**(); True if the instance is stopped. A stopped instance is not usable. void **shutdown**(); Stop and invalidate this instance. @property void **verbose**(bool on); Set verbose. This will print request information to stderr. @property void **dataTimeout**(Duration d); Set timeout for activity on connection. @property void **operationTimeout**(Duration d); Set maximum time an operation is allowed to take. This includes dns resolution, connecting, data transfer, etc. @property void **connectTimeout**(Duration d); Set timeout for connecting. @property void **proxy**(const(char)[] host); Proxy See [proxy](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY) @property void **proxyPort**(ushort port); Proxy port See [proxy\_port](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXYPORT) alias **CurlProxy** = etc.c.curl.**CurlProxy**; Type of proxy @property void **proxyType**(CurlProxy type); Proxy type See [proxy\_type](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY) @property void **dnsTimeout**(Duration d); DNS lookup timeout. @property void **netInterface**(const(char)[] i); @property void **netInterface**(const(ubyte)[4] i); @property void **netInterface**(InternetAddress i); 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 [`std.socket.InternetAddress`](std_socket#InternetAddress) @property void **localPort**(ushort port); Set the local outgoing port to use. Parameters: | | | | --- | --- | | ushort `port` | the first outgoing port number to try and use | @property void **localPortRange**(ushort range); Set the local outgoing port range to use. This can be used together with the localPort property. Parameters: | | | | --- | --- | | ushort `range` | if the first port is occupied then try this many port number forwards | @property void **tcpNoDelay**(bool on); Set the tcp no-delay socket option on or off. See [nodelay](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTCPNODELAY) void **setAuthentication**(const(char)[] username, const(char)[] password, const(char)[] domain = ""); 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. Parameters: | | | | --- | --- | | const(char)[] `username` | the username | | const(char)[] `password` | the password | | const(char)[] `domain` | used for NTLM authentication only and is set to the NTLM domain name | void **setProxyAuthentication**(const(char)[] username, const(char)[] password); Set the user name and password for proxy authentication. Parameters: | | | | --- | --- | | const(char)[] `username` | the username | | const(char)[] `password` | the password | @property void **onSend**(size\_t delegate(void[]) callback); The event handler that gets called when data is needed for sending. The length of the `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 `.abortRequest` can be returned in order to abort the current request. The special value `.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 **onReceive**(size\_t delegate(ubyte[]) 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 **onProgress**(int delegate(size\_t dlTotal, size\_t dlNow, size\_t ulTotal, size\_t ulNow) callback); Register an event handler that gets called to inform of upload/download progress. Callback parameters | | | | --- | --- | | `dlTotal` | total bytes to download | | `dlNow` | currently downloaded bytes | | `ulTotal` | total bytes to upload | | `ulNow` | 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. 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 uln) { writeln("Progress: downloaded ", dln, " of ", dl); writeln("Progress: uploaded ", uln, " of ", ul); return 0; }; client.perform(); ``` void **clearRequestHeaders**(); Clear all outgoing headers. void **addRequestHeader**(const(char)[] name, const(char)[] value); Add a header e.g. "X-CustomField: Something is fishy". There is no remove header functionality. Do a [`clearRequestHeaders`](#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); ``` static @property string **defaultUserAgent**(); The default "User-Agent" value send with a request. It has the form "Phobos-std.net.curl/*PHOBOS\_VERSION* (libcurl/*CURL\_VERSION*)" void **setUserAgent**(const(char)[] userAgent); Set the value of the user agent request header field. By default a request has it's "User-Agent" field set to [`defaultUserAgent`](#%20defaultUserAgent) even if `setUserAgent` was never called. Pass an empty string to suppress the "User-Agent" field altogether. CurlCode **getTiming**(CurlInfo timing, ref double val); Get various timings defined in [`etc.c.curl.CurlInfo`](etc_c_curl#CurlInfo). The value is usable only if the return value is equal to `etc.c.curl.CurlError.ok`. Parameters: | | | | --- | --- | | CurlInfo `timing` | one of the timings defined in [`etc.c.curl.CurlInfo`](etc_c_curl#CurlInfo). The values are: `etc.c.curl.CurlInfo.namelookup_time`, `etc.c.curl.CurlInfo.connect_time`, `etc.c.curl.CurlInfo.pretransfer_time`, `etc.c.curl.CurlInfo.starttransfer_time`, `etc.c.curl.CurlInfo.redirect_time`, `etc.c.curl.CurlInfo.appconnect_time`, `etc.c.curl.CurlInfo.total_time`. | | double `val` | the actual value of the inquired timing. | Returns: The return code of the operation. The value stored in val should be used only if the return value is `etc.c.curl.CurlInfo.ok`. Example ``` import std.net.curl; import etc.c.curl : CurlError, CurlInfo; auto client = HTTP("dlang.org"); client.perform(); double val; CurlCode code; code = client.getTiming(CurlInfo.namelookup_time, val); assert(code == CurlError.ok); ``` @property string[string] **responseHeaders**(); The headers read from a successful response. @property void **method**(Method m); @property Method **method**(); HTTP method used. @property StatusLine **statusLine**(); HTTP status line of last response. One call to perform may result in several requests because of redirection. void **setCookie**(const(char)[] cookie); Set the active cookie string e.g. "name1=value1;name2=value2" void **setCookieJar**(const(char)[] path); Set a file path to where a cookie jar should be read/stored. void **flushCookieJar**(); Flush cookie jar to disk. void **clearSessionCookies**(); Clear session cookies. void **clearAllCookies**(); Clear all cookies. void **setTimeCondition**(HTTP.TimeCond cond, SysTime timestamp); Set time condition on the request. Parameters: | | | | --- | --- | | HTTP.TimeCond `cond` | `CurlTimeCond.{none,ifmodsince,ifunmodsince,lastmod}` | | SysTime `timestamp` | Timestamp for the condition [RFC2616 Section 14.25](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25) | @property void **postData**(const(void)[] data); 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(char)[] data); 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(); ``` void **setPostData**(const(void)[] data, string contentType); Specify data to post when not using the onSend callback, with user-specified Content-Type. Parameters: | | | | --- | --- | | const(void)[] `data` | Data to post. | | string `contentType` | MIME type of the data, for example, "text/plain" or "application/octet-stream". See also: [Internet media type](http://en.wikipedia.org/wiki/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(); ``` | @property void **onReceiveHeader**(void delegate(in char[] key, in char[] value) callback); Set the event handler that receives incoming headers. The callback will receive a header field key, value as parameter. The `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 **onReceiveStatusLine**(void delegate(StatusLine) callback); Callback for each received StatusLine. Notice that several callbacks can be done for each call to `perform()` due to redirections. See Also: [`StatusLine`](#StatusLine) @property void **contentLength**(ulong len); 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 **authenticationMethod**(AuthMethod authMethod); Authentication method as specified in [`AuthMethod`](#AuthMethod). @property void **maxRedirects**(uint maxRedirs); Set max allowed redirections using the location header. uint.max for infinite. enum **Method**: int; The standard HTTP methods : [RFC2616 Section 5.1.1](http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1) **head** **get** **post** **put** **del** **options** **trace** **connect** **patch** struct **StatusLine**; 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. 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. @safe void **reset**(); Reset this status line const string **toString**(); struct **FTP**; FTP client functionality. See Also: [RFC959](http://tools.ietf.org/html/rfc959) static FTP **opCall**(const(char)[] url); FTP access to the specified url. static FTP **opCall**(); FTP **dup**(); CurlCode **perform**(ThrowOnError throwOnError = Yes.throwOnError); Performs the ftp request as it has been configured. After a FTP client has been setup and possibly assigned callbacks the `perform()` method will start performing the actual communication with the server. Parameters: | | | | --- | --- | | ThrowOnError `throwOnError` | whether to throw an exception or return a CurlCode on error | @property void **url**(const(char)[] **url**); The URL to specify the location of the resource. alias **requestPause** = etc.c.curl.CurlReadFunc.pause; Value to return from `onSend`/`onReceive` delegates in order to pause a request alias **requestAbort** = etc.c.curl.CurlReadFunc.abort; Value to return from onSend delegate in order to abort a request @property bool **isStopped**(); True if the instance is stopped. A stopped instance is not usable. void **shutdown**(); Stop and invalidate this instance. @property void **verbose**(bool on); Set verbose. This will print request information to stderr. @property void **dataTimeout**(Duration d); Set timeout for activity on connection. @property void **operationTimeout**(Duration d); Set maximum time an operation is allowed to take. This includes dns resolution, connecting, data transfer, etc. @property void **connectTimeout**(Duration d); Set timeout for connecting. @property void **proxy**(const(char)[] host); Proxy See [proxy](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY) @property void **proxyPort**(ushort port); Proxy port See [proxy\_port](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXYPORT) alias **CurlProxy** = etc.c.curl.**CurlProxy**; Type of proxy @property void **proxyType**(CurlProxy type); Proxy type See [proxy\_type](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY) @property void **dnsTimeout**(Duration d); DNS lookup timeout. @property void **netInterface**(const(char)[] i); @property void **netInterface**(const(ubyte)[4] i); @property void **netInterface**(InternetAddress i); 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 [`std.socket.InternetAddress`](std_socket#InternetAddress) @property void **localPort**(ushort port); Set the local outgoing port to use. Parameters: | | | | --- | --- | | ushort `port` | the first outgoing port number to try and use | @property void **localPortRange**(ushort range); Set the local outgoing port range to use. This can be used together with the localPort property. Parameters: | | | | --- | --- | | ushort `range` | if the first port is occupied then try this many port number forwards | @property void **tcpNoDelay**(bool on); Set the tcp no-delay socket option on or off. See [nodelay](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTCPNODELAY) void **setAuthentication**(const(char)[] username, const(char)[] password, const(char)[] domain = ""); 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. Parameters: | | | | --- | --- | | const(char)[] `username` | the username | | const(char)[] `password` | the password | | const(char)[] `domain` | used for NTLM authentication only and is set to the NTLM domain name | void **setProxyAuthentication**(const(char)[] username, const(char)[] password); Set the user name and password for proxy authentication. Parameters: | | | | --- | --- | | const(char)[] `username` | the username | | const(char)[] `password` | the password | @property void **onSend**(size\_t delegate(void[]) callback); The event handler that gets called when data is needed for sending. The length of the `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 `.abortRequest` can be returned in order to abort the current request. 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 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 **onProgress**(int delegate(size\_t dlTotal, size\_t dlNow, size\_t ulTotal, size\_t ulNow) callback); The event handler that gets called to inform of upload/download progress. Callback parameters | | | | --- | --- | | `dlTotal` | total bytes to download | | `dlNow` | currently downloaded bytes | | `ulTotal` | total bytes to upload | | `ulNow` | 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. Callback returns Return 0 from the callback to signal success, return non-zero to abort transfer. void **clearCommands**(); Clear all commands send to ftp server. void **addCommand**(const(char)[] command); Add a command to send to ftp server. There is no remove command functionality. Do a [`clearCommands`](#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); ``` @property void **encoding**(string name); @property string **encoding**(); Connection encoding. Defaults to ISO-8859-1. @property void **contentLength**(ulong len); The content length in bytes of the ftp data. CurlCode **getTiming**(CurlInfo timing, ref double val); Get various timings defined in [`etc.c.curl.CurlInfo`](etc_c_curl#CurlInfo). The value is usable only if the return value is equal to `etc.c.curl.CurlError.ok`. Parameters: | | | | --- | --- | | CurlInfo `timing` | one of the timings defined in [`etc.c.curl.CurlInfo`](etc_c_curl#CurlInfo). The values are: `etc.c.curl.CurlInfo.namelookup_time`, `etc.c.curl.CurlInfo.connect_time`, `etc.c.curl.CurlInfo.pretransfer_time`, `etc.c.curl.CurlInfo.starttransfer_time`, `etc.c.curl.CurlInfo.redirect_time`, `etc.c.curl.CurlInfo.appconnect_time`, `etc.c.curl.CurlInfo.total_time`. | | double `val` | the actual value of the inquired timing. | Returns: The return code of the operation. The value stored in val should be used only if the return value is `etc.c.curl.CurlInfo.ok`. Example ``` import std.net.curl; import etc.c.curl : CurlError, CurlInfo; auto client = FTP(); client.addCommand("RNFR my_file.txt"); client.addCommand("RNTO my_renamed_file.txt"); upload("my_file.txt", "ftp.digitalmars.com", client); double val; CurlCode code; code = client.getTiming(CurlInfo.namelookup_time, val); assert(code == CurlError.ok); ``` struct **SMTP**; Basic SMTP protocol support. Example ``` import std.net.curl; // Send an email with SMTPS auto smtp = SMTP("smtps://smtp.gmail.com"); smtp.setAuthentication("[email protected]", "password"); smtp.mailTo = ["<[email protected]>"]; smtp.mailFrom = "<[email protected]>"; smtp.message = "Example Message"; smtp.perform(); ``` See Also: [RFC2821](http://www.ietf.org/rfc/rfc2821.txt) static SMTP **opCall**(const(char)[] url); Sets to the URL of the SMTP server. static SMTP **opCall**(); CurlCode **perform**(ThrowOnError throwOnError = Yes.throwOnError); Performs the request as configured. Parameters: | | | | --- | --- | | ThrowOnError `throwOnError` | whether to throw an exception or return a CurlCode on error | @property void **url**(const(char)[] **url**); The URL to specify the location of the resource. alias **requestPause** = etc.c.curl.CurlReadFunc.pause; Value to return from `onSend`/`onReceive` delegates in order to pause a request alias **requestAbort** = etc.c.curl.CurlReadFunc.abort; Value to return from onSend delegate in order to abort a request @property bool **isStopped**(); True if the instance is stopped. A stopped instance is not usable. void **shutdown**(); Stop and invalidate this instance. @property void **verbose**(bool on); Set verbose. This will print request information to stderr. @property void **dataTimeout**(Duration d); Set timeout for activity on connection. @property void **operationTimeout**(Duration d); Set maximum time an operation is allowed to take. This includes dns resolution, connecting, data transfer, etc. @property void **connectTimeout**(Duration d); Set timeout for connecting. @property void **proxy**(const(char)[] host); Proxy See [proxy](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY) @property void **proxyPort**(ushort port); Proxy port See [proxy\_port](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXYPORT) alias **CurlProxy** = etc.c.curl.**CurlProxy**; Type of proxy @property void **proxyType**(CurlProxy type); Proxy type See [proxy\_type](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY) @property void **dnsTimeout**(Duration d); DNS lookup timeout. @property void **netInterface**(const(char)[] i); @property void **netInterface**(const(ubyte)[4] i); @property void **netInterface**(InternetAddress i); 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 [`std.socket.InternetAddress`](std_socket#InternetAddress) @property void **localPort**(ushort port); Set the local outgoing port to use. Parameters: | | | | --- | --- | | ushort `port` | the first outgoing port number to try and use | @property void **localPortRange**(ushort range); Set the local outgoing port range to use. This can be used together with the localPort property. Parameters: | | | | --- | --- | | ushort `range` | if the first port is occupied then try this many port number forwards | @property void **tcpNoDelay**(bool on); Set the tcp no-delay socket option on or off. See [nodelay](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTCPNODELAY) void **setAuthentication**(const(char)[] username, const(char)[] password, const(char)[] domain = ""); 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. Parameters: | | | | --- | --- | | const(char)[] `username` | the username | | const(char)[] `password` | the password | | const(char)[] `domain` | used for NTLM authentication only and is set to the NTLM domain name | void **setProxyAuthentication**(const(char)[] username, const(char)[] password); Set the user name and password for proxy authentication. Parameters: | | | | --- | --- | | const(char)[] `username` | the username | | const(char)[] `password` | the password | @property void **onSend**(size\_t delegate(void[]) callback); The event handler that gets called when data is needed for sending. The length of the `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 `.abortRequest` can be returned in order to abort the current request. 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 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 **onProgress**(int delegate(size\_t dlTotal, size\_t dlNow, size\_t ulTotal, size\_t ulNow) callback); The event handler that gets called to inform of upload/download progress. Callback parameters | | | | --- | --- | | `dlTotal` | total bytes to download | | `dlNow` | currently downloaded bytes | | `ulTotal` | total bytes to upload | | `ulNow` | 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. Callback returns Return 0 from the callback to signal success, return non-zero to abort transfer. @property void **mailFrom**()(const(char)[] sender); Setter for the sender's email address. void **mailTo**()(const(char)[][] recipients...); Setter for the recipient email addresses. @property void **message**(string msg); Sets the message body text. class **CurlException**: object.Exception; Exception thrown on errors in std.net.curl functions. pure nothrow @safe this(string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null); Parameters: | | | | --- | --- | | string `msg` | The message for the exception. | | string `file` | The file where the exception occurred. | | size\_t `line` | The line number where the exception occurred. | | Throwable `next` | The previous exception in the chain of exceptions, if any. | class **CurlTimeoutException**: std.net.curl.CurlException; Exception thrown on timeout errors in std.net.curl functions. pure nothrow @safe this(string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null); Parameters: | | | | --- | --- | | string `msg` | The message for the exception. | | string `file` | The file where the exception occurred. | | size\_t `line` | The line number where the exception occurred. | | Throwable `next` | The previous exception in the chain of exceptions, if any. | class **HTTPStatusException**: std.net.curl.CurlException; Exception thrown on HTTP request failures, e.g. 404 Not Found. pure nothrow @safe this(int status, string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null); Parameters: | | | | --- | --- | | int `status` | The HTTP status code. | | string `msg` | The message for the exception. | | string `file` | The file where the exception occurred. | | size\_t `line` | The line number where the exception occurred. | | Throwable `next` | The previous exception in the chain of exceptions, if any. | immutable int **status**; The HTTP status code alias **CurlCode** = int; Equal to [`etc.c.curl.CURLcode`](etc_c_curl#CURLcode) alias **ThrowOnError** = std.typecons.Flag!"throwOnError".Flag; Flag to specify whether or not an exception is thrown on error. struct **Curl**; Wrapper to provide a better interface to libcurl than using the plain C API. It is recommended to use the `HTTP`/`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. void **initialize**(); Initialize the instance by creating a working curl handle. const @property bool **stopped**(); Curl **dup**(); 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. void **shutdown**(); Stop and invalidate this curl instance. Warning Do not call this from inside a callback handler e.g. `onReceive`. void **pause**(bool sendingPaused, bool receivingPaused); Pausing and continuing transfers. void **set**(CurlOption option, const(char)[] value); Set a string curl option. Parameters: | | | | --- | --- | | CurlOption `option` | A [`etc.c.curl.CurlOption`](etc_c_curl#CurlOption) as found in the curl documentation | | const(char)[] `value` | The string | void **set**(CurlOption option, long value); Set a long curl option. Parameters: | | | | --- | --- | | CurlOption `option` | A [`etc.c.curl.CurlOption`](etc_c_curl#CurlOption) as found in the curl documentation | | long `value` | The long | void **set**(CurlOption option, void\* value); Set a void\* curl option. Parameters: | | | | --- | --- | | CurlOption `option` | A [`etc.c.curl.CurlOption`](etc_c_curl#CurlOption) as found in the curl documentation | | void\* `value` | The pointer | void **clear**(CurlOption option); Clear a pointer option. Parameters: | | | | --- | --- | | CurlOption `option` | A [`etc.c.curl.CurlOption`](etc_c_curl#CurlOption) as found in the curl documentation | void **clearIfSupported**(CurlOption option); Clear a pointer option. Does not raise an exception if the underlying libcurl does not support the option. Use sparingly. Parameters: | | | | --- | --- | | CurlOption `option` | A [`etc.c.curl.CurlOption`](etc_c_curl#CurlOption) as found in the curl documentation | CurlCode **perform**(ThrowOnError throwOnError = Yes.throwOnError); perform the curl request by doing the HTTP,FTP etc. as it has been setup beforehand. Parameters: | | | | --- | --- | | ThrowOnError `throwOnError` | whether to throw an exception or return a CurlCode on error | CurlCode **getTiming**(CurlInfo timing, ref double val); Get the various timings like name lookup time, total time, connect time etc. The timed category is passed through the timing parameter while the timing value is stored at val. The value is usable only if res is equal to `etc.c.curl.CurlError.ok`. @property void **onReceive**(size\_t delegate(InData) callback); The event handler that receives incoming data. Parameters: | | | | --- | --- | | size\_t delegate(InData) `callback` | the callback that receives the `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 **onReceiveHeader**(void delegate(in char[]) callback); The event handler that receives incoming headers for protocols that uses headers. Parameters: | | | | --- | --- | | void delegate(in char[]) `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 **onSend**(size\_t delegate(OutData) callback); The event handler that gets called when data is needed for sending. Parameters: | | | | --- | --- | | size\_t delegate(OutData) `callback` | the callback that has a `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 `Curl.abortRequest` can be returned in order to abort the current request. The special value `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 **onSeek**(CurlSeek delegate(long, CurlSeekPos) callback); The event handler that gets called when the curl backend needs to seek the data to be sent. Parameters: | | | | --- | --- | | CurlSeek delegate(long, CurlSeekPos) `callback` | the callback that receives a seek offset and a seek position [`etc.c.curl.CurlSeekPos`](etc_c_curl#CurlSeekPos) | Returns: The callback returns the success state of the seeking [`etc.c.curl.CurlSeek`](etc_c_curl#CurlSeek) 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 **onSocketOption**(int delegate(curl\_socket\_t, CurlSockType) callback); The event handler that gets called when the net socket has been created but a `connect()` call has not yet been done. This makes it possible to set misc. socket options. Parameters: | | | | --- | --- | | int delegate(curl\_socket\_t, CurlSockType) `callback` | the callback that receives the socket and socket type [`etc.c.curl.CurlSockType`](etc_c_curl#CurlSockType) | 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 **onProgress**(int delegate(size\_t dlTotal, size\_t dlNow, size\_t ulTotal, size\_t ulNow) callback); The event handler that gets called to inform of upload/download progress. Parameters: | | | | --- | --- | | int delegate(size\_t dlTotal, size\_t dlNow, size\_t ulTotal, size\_t ulNow) `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, std.stdio; 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 ulnow) { writeln("Progress: downloaded bytes ", dlnow, " of ", dltotal); writeln("Progress: uploaded bytes ", ulnow, " of ", ultotal); return 0; }; curl.perform(); ```
programming_docs
d rt.tlsgc rt.tlsgc ======== License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Martin Nowak struct **Data**; Per thread record to store thread associated data for garbage collection. nothrow @nogc void\* **init**(); Initialization hook, called FROM each thread. No assumptions about module initialization state should be made. nothrow @nogc void **destroy**(void\* data); Finalization hook, called FOR each thread. No assumptions about module initialization state should be made. nothrow void **scan**(void\* data, scope ScanDg dg); GC scan hook, called FOR each thread. Can be used to scan additional thread local memory. nothrow void **processGCMarks**(void\* data, scope IsMarkedDg dg); GC sweep hook, called FOR each thread. Can be used to free additional thread local memory or associated data structures. Note that only memory allocated from the GC can have marks. d rt.adi rt.adi ====== Implementation of dynamic array property support routines. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright Source [rt/adi.d](https://github.com/dlang/druntime/blob/master/src/rt/adi.d) int **\_adEq2**(void[] a1, void[] a2, TypeInfo ti); Support for array equality test. Returns: 1 equal 0 not equal d object object ====== Forms the symbols available to all D programs. Includes Object, which is the root of the class object hierarchy. This module is implicitly imported. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Walter Bright, Sean Kelly class **Object**; All D class objects inherit from Object. string **toString**(); Convert Object to a human readable string. nothrow @trusted size\_t **toHash**(); Compute hash function for Object. int **opCmp**(Object o); Compare with another Object obj. Returns: | | | | --- | --- | | this < obj | < 0 | | this == obj | 0 | | this > obj | > 0 | bool **opEquals**(Object o); Test whether `this` is equal to `o`. The default implementation only compares by identity (using the `is` operator). Generally, overrides for `opEquals` should attempt to compare objects by their contents. static Object **factory**(string classname); Create instance of class specified by the fully qualified name classname. The class must either have no constructors or have a default constructor. Returns: null if failed Example ``` module foo.bar; class C { this() { x = 10; } int x; } void main() { auto c = cast(C)Object.factory("foo.bar.C"); assert(c !is null && c.x == 10); } ``` bool **opEquals**(const Object lhs, const Object rhs); Returns true if lhs and rhs are equal. Examples: If aliased to the same object or both null => equal ``` class F { int flag; this(int flag) { this.flag = flag; } } F f; assert(f == f); // both null f = new F(1); assert(f == f); // both aliased to the same object ``` Examples: If either is null => non-equal ``` class F { int flag; this(int flag) { this.flag = flag; } } F f; assert(!(new F(0) == f)); assert(!(f == new F(0))); ``` Examples: If same exact type => one call to method opEquals ``` class F { int flag; this(int flag) { this.flag = flag; } override bool opEquals(const Object o) { return flag == (cast(F) o).flag; } } F f; assert(new F(0) == new F(0)); assert(!(new F(0) == new F(1))); ``` Examples: General case => symmetric calls to method opEquals ``` int fEquals, gEquals; class Base { int flag; this(int flag) { this.flag = flag; } } class F : Base { this(int flag) { super(flag); } override bool opEquals(const Object o) { fEquals++; return flag == (cast(Base) o).flag; } } class G : Base { this(int flag) { super(flag); } override bool opEquals(const Object o) { gEquals++; return flag == (cast(Base) o).flag; } } assert(new F(1) == new G(1)); assert(fEquals == 1); assert(gEquals == 1); ``` struct **Interface**; Information about an interface. When an object is accessed via an interface, an Interface\* appears as the first entry in its vtbl. TypeInfo\_Class **classinfo**; .classinfo for this interface (not for containing class) size\_t **offset**; offset to Interface 'this' from Object 'this' struct **OffsetTypeInfo**; Array of pairs giving the offset and type information for each member in an aggregate. size\_t **offset**; Offset of member from start of object TypeInfo **ti**; TypeInfo for this member abstract class **TypeInfo**; Runtime type information about a type. Can be retrieved for any type using a [*TypeidExpression*](https://dlang.org/spec/expression.html#TypeidExpression). const nothrow @trusted size\_t **getHash**(scope const void\* p); Computes a hash of the instance of a type. Parameters: | | | | --- | --- | | void\* `p` | pointer to start of instance of the type | Returns: the hash Bugs: fix <https://issues.dlang.org/show_bug.cgi?id=12516> e.g. by changing this to a truly safe interface. const bool **equals**(in void\* p1, in void\* p2); Compares two instances for equality. const int **compare**(in void\* p1, in void\* p2); Compares two instances for <, ==, or >. const pure nothrow @nogc @property @safe size\_t **tsize**(); Returns size of the type. const void **swap**(void\* p1, void\* p2); Swaps two instances of the type. inout pure nothrow @nogc @property inout(TypeInfo) **next**(); Get TypeInfo for 'next' type, as defined by what kind of type this is, null if none. abstract const pure nothrow @nogc @safe const(void)[] **initializer**(); Return default initializer. If the type should be initialized to all zeros, an array with a null ptr and a length equal to the type size will be returned. For static arrays, this returns the default initializer for a single element of the array, use `tsize` to get the correct size. const pure nothrow @nogc @property @safe uint **flags**(); Get flags for type: 1 means GC should scan for pointers, 2 means arg of this type is passed in SIMD register(s) if available const const(OffsetTypeInfo)[] **offTi**(); Get type information on the contents of the type; null if not available const void **destroy**(void\* p); Run the destructor on the object and all its sub-objects const void **postblit**(void\* p); Run the postblit on the object and all its sub-objects const pure nothrow @nogc @property @safe size\_t **talign**(); Return alignment of type nothrow @safe int **argTypes**(out TypeInfo arg1, out TypeInfo arg2); Return internal info on arguments fitting into 8byte. See X86-64 ABI 3.2.3 const pure nothrow @nogc @property @safe immutable(void)\* **rtInfo**(); Return info used by the garbage collector to do precise collection. class **TypeInfo\_Class**: object.TypeInfo; Runtime type information about a class. Can be retrieved from an object instance by using the [.classinfo](https://dlang.org/spec/property.html#classinfo) property. byte[] **m\_init**; class static initializer (init.length gives size in bytes of class) string **name**; class name void\*[] **vtbl**; virtual function pointer table Interface[] **interfaces**; interfaces this class implements TypeInfo\_Class **base**; base class static const(TypeInfo\_Class) **find**(scope const char[] classname); Search all modules for TypeInfo\_Class corresponding to classname. Returns: null if not found const Object **create**(); Create instance of Object represented by 'this'. final const pure nothrow @nogc @trusted bool **isBaseOf**(scope const TypeInfo\_Class child); Returns true if the class described by `child` derives from or is the class described by this `TypeInfo_Class`. Always returns false if the argument is null. Parameters: | | | | --- | --- | | TypeInfo\_Class `child` | TypeInfo for some class | Returns: true if the class described by `child` derives from or is the class described by this `TypeInfo_Class`. struct **ModuleInfo**; An instance of ModuleInfo is generated into the object file for each compiled module. It provides access to various aspects of the module. It is not generated for betterC. const pure nothrow @nogc @property void function() **tlsctor**(); Returns: module constructor for thread locals, `null` if there isn't one const pure nothrow @nogc @property void function() **tlsdtor**(); Returns: module destructor for thread locals, `null` if there isn't one const pure nothrow @nogc @property void\* **xgetMembers**(); Returns: address of a module's `const(MemberInfo)[] getMembers(string)` function, `null` if there isn't one const pure nothrow @nogc @property void function() **ctor**(); Returns: module constructor, `null` if there isn't one const pure nothrow @nogc @property void function() **dtor**(); Returns: module destructor, `null` if there isn't one const pure nothrow @nogc @property void function() **ictor**(); Returns: module order independent constructor, `null` if there isn't one const pure nothrow @nogc @property void function() **unitTest**(); Returns: address of function that runs the module's unittests, `null` if there isn't one const pure nothrow @nogc @property immutable(ModuleInfo\*)[] **importedModules**(); Returns: array of pointers to the ModuleInfo's of modules imported by this one const pure nothrow @nogc @property TypeInfo\_Class[] **localClasses**(); Returns: array of TypeInfo\_Class references for classes defined in this module const pure nothrow @nogc @property string **name**(); Returns: name of module, `null` if no name class **Throwable**; The base class of all thrown objects. All thrown objects must inherit from Throwable. Class `Exception`, which derives from this class, represents the category of thrown objects that are safe to catch and handle. In principle, one should not catch Throwable objects that are not derived from `Exception`, as they represent unrecoverable runtime errors. Certain runtime guarantees may fail to hold when these errors are thrown, making it unsafe to continue execution after catching them. string **msg**; A message describing the error. string **file**; The file name of the D source code corresponding with where the error was thrown from. size\_t **line**; The line number of the D source code corresponding with where the error was thrown from. TraceInfo **info**; The stack trace of where the error happened. This is an opaque object that can either be converted to `string`, or iterated over with `foreach` to extract the items in the stack trace (as strings). inout pure nothrow @nogc @property scope @safe inout(Throwable) **next**() return; Returns: A reference to the next error in the list. This is used when a new `Throwable` is thrown from inside a `catch` block. The originally caught `Exception` will be chained to the new `Throwable` via this field. pure nothrow @nogc @property scope @safe void **next**(Throwable tail); Replace next in chain with `tail`. Use `chainTogether` instead if at all possible. final pure nothrow @nogc ref scope @system uint **refcount**() return; Returns: mutable reference to the reference count, which is 0 - allocated by the GC, 1 - allocated by d\_newThrowable(), and >=2 which is the reference count + 1 Note Marked as `@system` to discourage casual use of it. int **opApply**(scope int delegate(Throwable) dg); Loop over the chain of Throwables. static pure nothrow @nogc @system Throwable **chainTogether**(return scope Throwable e1, return scope Throwable e2); Append `e2` to chain of exceptions that starts with `e1`. Parameters: | | | | --- | --- | | Throwable `e1` | start of chain (can be null) | | Throwable `e2` | second part of chain (can be null) | Returns: Throwable that is at the start of the chain; null if both `e1` and `e2` are null string **toString**(); Overrides `Object.toString` and returns the error message. Internally this forwards to the `toString` overload that takes a sink delegate. const void **toString**(scope void delegate(in char[]) sink); The Throwable hierarchy uses a toString overload that takes a sink delegate to avoid GC allocations, which cannot be performed in certain error situations. Override this `toString` method to customize the error message. const const(char)[] **message**(); Get the message describing the error. Base behavior is to return the `Throwable.msg` field. Override to return some other error message. Returns: Error message class **Exception**: object.Throwable; The base class of all errors that are safe to catch and handle. In principle, only thrown objects derived from this class are safe to catch inside a `catch` block. Thrown objects not derived from Exception represent runtime errors that should not be caught, as certain runtime guarantees may not hold, making it unsafe to continue program execution. Examples: ``` bool gotCaught; try { throw new Exception("msg"); } catch (Exception e) { gotCaught = true; assert(e.msg == "msg"); } assert(gotCaught); ``` pure nothrow @nogc @safe this(string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable nextInChain = null); Creates a new instance of Exception. The nextInChain parameter is used internally and should always be `null` when passed by user code. This constructor does not automatically throw the newly-created Exception; the `throw` statement should be used for that purpose. class **Error**: object.Throwable; The base class of all unrecoverable runtime errors. This represents the category of `Throwable` objects that are **not** safe to catch and handle. In principle, one should not catch Error objects, as they represent unrecoverable runtime errors. Certain runtime guarantees may fail to hold when these errors are thrown, making it unsafe to continue execution after catching them. Examples: ``` bool gotCaught; try { throw new Error("msg"); } catch (Error e) { gotCaught = true; assert(e.msg == "msg"); } assert(gotCaught); ``` pure nothrow @nogc @safe this(string msg, Throwable nextInChain = null); Creates a new instance of Error. The nextInChain parameter is used internally and should always be `null` when passed by user code. This constructor does not automatically throw the newly-created Error; the `throw` statement should be used for that purpose. Throwable **bypassedException**; The first `Exception` which was bypassed when this Error was thrown, or `null` if no `Exception`s were pending. void **clear**(Value, Key)(Value[Key] aa); Removes all remaining keys and values from an associative array. Parameters: | | | | --- | --- | | Value[Key] `aa` | The associative array. | T **rehash**(T : Value[Key], Value, Key)(T aa); Reorganizes the associative array in place so that lookups are more efficient. Parameters: | | | | --- | --- | | T `aa` | The associative array. | Returns: The rehashed associative array. V[K] **dup**(T : V[K], K, V)(T aa); Create a new associative array of the same size and copy the contents of the associative array into it. Parameters: | | | | --- | --- | | T `aa` | The associative array. | pure nothrow @nogc @safe auto **byKey**(T : V[K], K, V)(T aa); Returns a forward range over the keys of the associative array. Parameters: | | | | --- | --- | | T `aa` | The associative array. | Returns: A forward range. pure nothrow @nogc @safe auto **byValue**(T : V[K], K, V)(T aa); Returns a forward range over the values of the associative array. Parameters: | | | | --- | --- | | T `aa` | The associative array. | Returns: A forward range. pure nothrow @nogc @safe auto **byKeyValue**(T : V[K], K, V)(T aa); Returns a forward range over the key value pairs of the associative array. Parameters: | | | | --- | --- | | T `aa` | The associative array. | Returns: A forward range. @property Key[] **keys**(T : Value[Key], Value, Key)(T aa); Returns a dynamic array, the elements of which are the keys in the associative array. Parameters: | | | | --- | --- | | T `aa` | The associative array. | Returns: A dynamic array. @property Value[] **values**(T : Value[Key], Value, Key)(T aa); Returns a dynamic array, the elements of which are the values in the associative array. Parameters: | | | | --- | --- | | T `aa` | The associative array. | Returns: A dynamic array. inout(V) **get**(K, V)(inout(V[K]) aa, K key, lazy inout(V) defaultValue); Looks up key; if it exists returns corresponding value else evaluates and returns defaultValue. Parameters: | | | | --- | --- | | inout(V[K]) `aa` | The associative array. | | K `key` | The key. | | inout(V) `defaultValue` | The default value. | Returns: The value. ref V **require**(K, V)(ref V[K] aa, K key, lazy V value = V.init); Looks up key; if it exists returns corresponding value else evaluates value, adds it to the associative array and returns it. Parameters: | | | | --- | --- | | V[K] `aa` | The associative array. | | K `key` | The key. | | V `value` | The required value. | Returns: The value. Examples: ``` auto aa = ["k1": 1]; assert(aa.require("k1", 0) == 1); assert(aa.require("k2", 0) == 0); assert(aa["k2"] == 0); ``` void **update**(K, V, C, U)(ref V[K] aa, K key, scope C create, scope U **update**) Constraints: if (is(typeof(create()) : V) && (is(typeof(update(aa[K.init])) : V) || is(typeof(update(aa[K.init])) == void))); Looks up key; if it exists applies the update callable else evaluates the create callable and adds it to the associative array Parameters: | | | | --- | --- | | V[K] `aa` | The associative array. | | K `key` | The key. | | C `create` | The callable to apply on create. | | U `update` | The callable to apply on update. | Examples: ``` auto aa = ["k1": 1]; aa.update("k1", { return -1; // create (won't be executed) }, (ref int v) { v += 1; // update }); assert(aa["k1"] == 2); aa.update("k2", { return 0; // create }, (ref int v) { v = -1; // update (won't be executed) }); assert(aa["k2"] == 0); ``` size\_t **hashOf**(T)(auto ref T arg, size\_t seed); size\_t **hashOf**(T)(auto ref T arg); Calculates the hash value of `arg` with an optional `seed` initial value. The result might not be equal to `typeid(T).getHash(&arg)`. Parameters: | | | | --- | --- | | T `arg` | argument to calculate the hash value of | | size\_t `seed` | optional `seed` value (may be used for hash chaining) | Return calculated hash value of `arg` Examples: ``` class MyObject { size_t myMegaHash() const @safe pure nothrow { return 42; } } struct Test { int a; string b; MyObject c; size_t toHash() const pure nothrow { size_t hash = a.hashOf(); hash = b.hashOf(hash); size_t h1 = c.myMegaHash(); hash = h1.hashOf(hash); //Mix two hash values return hash; } } ``` immutable size\_t[pointerBitmap.length] **RTInfoImpl**(size\_t[] pointerBitmap); Create RTInfo for type T enum immutable(void)\* **rtinfoNoPointers**; shortcuts for the precise GC, also generated by the compiler used instead of the actual pointer bitmap @property auto **dup**(T)(T[] a) Constraints: if (!is(const(T) : T)); @property T[] **dup**(T)(const(T)[] a) Constraints: if (is(const(T) : T)); Provide the .dup array property. Examples: ``` auto arr = [1, 2]; auto arr2 = arr.dup; arr[0] = 0; assert(arr == [0, 2]); assert(arr2 == [1, 2]); ``` @property immutable(T)[] **idup**(T)(T[] a); @property immutable(T)[] **idup**(T : void)(const(T)[] a); Provide the .idup array property. Examples: ``` char[] arr = ['a', 'b', 'c']; string s = arr.idup; arr[0] = '.'; assert(s == "abc"); ``` pure nothrow @property @trusted size\_t **capacity**(T)(T[] arr); (Property) Gets the current capacity of a slice. The capacity is the size that the slice can grow to before the underlying array must be reallocated or extended. If an append must reallocate a slice with no possibility of extension, then `0` is returned. This happens when the slice references a static array, or if another slice references elements past the end of the current slice. Note The capacity of a slice may be impacted by operations on other slices. Examples: ``` //Static array slice: no capacity int[4] sarray = [1, 2, 3, 4]; int[] slice = sarray[]; assert(sarray.capacity == 0); //Appending to slice will reallocate to a new array slice ~= 5; assert(slice.capacity >= 5); //Dynamic array slices int[] a = [1, 2, 3, 4]; int[] b = a[1 .. $]; int[] c = a[1 .. $ - 1]; debug(SENTINEL) {} else // non-zero capacity very much depends on the array and GC implementation { assert(a.capacity != 0); assert(a.capacity == b.capacity + 1); //both a and b share the same tail } assert(c.capacity == 0); //an append to c must relocate c. ``` pure nothrow @trusted size\_t **reserve**(T)(ref T[] arr, size\_t newcapacity); Reserves capacity for a slice. The capacity is the size that the slice can grow to before the underlying array must be reallocated or extended. Returns: The new capacity of the array (which may be larger than the requested capacity). Examples: ``` //Static array slice: no capacity. Reserve relocates. int[4] sarray = [1, 2, 3, 4]; int[] slice = sarray[]; auto u = slice.reserve(8); assert(u >= 8); assert(&sarray[0] !is &slice[0]); assert(slice.capacity == u); //Dynamic array slices int[] a = [1, 2, 3, 4]; a.reserve(8); //prepare a for appending 4 more items auto p = &a[0]; u = a.capacity; a ~= [5, 6, 7, 8]; assert(p == &a[0]); //a should not have been reallocated assert(u == a.capacity); //a should not have been extended ``` nothrow ref @system inout(T[]) **assumeSafeAppend**(T)(auto ref inout(T[]) arr); Assume that it is safe to append to this array. Appends made to this array after calling this function may append in place, even if the array was a slice of a larger array to begin with. Use this only when it is certain there are no elements in use beyond the array in the memory block. If there are, those elements will be overwritten by appending to this array. Warning Calling this function, and then using references to data located after the given array results in undefined behavior. Returns: The input is returned. Examples: ``` int[] a = [1, 2, 3, 4]; // Without assumeSafeAppend. Appending relocates. int[] b = a [0 .. 3]; b ~= 5; assert(a.ptr != b.ptr); debug(SENTINEL) {} else { // With assumeSafeAppend. Appending overwrites. int[] c = a [0 .. 3]; c.assumeSafeAppend() ~= 5; assert(a.ptr == c.ptr); } ``` void **destroy**(bool initialize = true, T)(ref T obj) Constraints: if (is(T == struct)); void **destroy**(bool initialize = true, T)(T obj) Constraints: if (is(T == class)); void **destroy**(bool initialize = true, T)(T obj) Constraints: if (is(T == interface)); void **destroy**(bool initialize = true, T : U[n], U, size\_t n)(ref T obj) Constraints: if (!is(T == struct) && !is(T == class) && !is(T == interface)); void **destroy**(bool initialize = true, T)(ref T obj) Constraints: if (!is(T == struct) && !is(T == interface) && !is(T == class) && !\_\_traits(isStaticArray, T)); Destroys the given object and optionally resets to initial state. It's used to destroy an object, calling its destructor or finalizer so it no longer references any other objects. It does *not* initiate a GC cycle or free any GC memory. If `initialize` is supplied `false`, the object is considered invalid after destruction, and should not be referenced. Examples: Reference type demonstration ``` class C { struct Agg { static int dtorCount; int x = 10; ~this() { dtorCount++; } } static int dtorCount; string s = "S"; Agg a; ~this() { dtorCount++; } } C c = new C(); assert(c.dtorCount == 0); // destructor not yet called assert(c.s == "S"); // initial state `c.s` is `"S"` assert(c.a.dtorCount == 0); // destructor not yet called assert(c.a.x == 10); // initial state `c.a.x` is `10` c.s = "T"; c.a.x = 30; assert(c.s == "T"); // `c.s` is `"T"` destroy(c); assert(c.dtorCount == 1); // `c`'s destructor was called assert(c.s == "S"); // `c.s` is back to its inital state, `"S"` assert(c.a.dtorCount == 1); // `c.a`'s destructor was called assert(c.a.x == 10); // `c.a.x` is back to its inital state, `10` // check C++ classes work too! extern (C++) class CPP { struct Agg { __gshared int dtorCount; int x = 10; ~this() { dtorCount++; } } __gshared int dtorCount; string s = "S"; Agg a; ~this() { dtorCount++; } } CPP cpp = new CPP(); assert(cpp.dtorCount == 0); // destructor not yet called assert(cpp.s == "S"); // initial state `cpp.s` is `"S"` assert(cpp.a.dtorCount == 0); // destructor not yet called assert(cpp.a.x == 10); // initial state `cpp.a.x` is `10` cpp.s = "T"; cpp.a.x = 30; assert(cpp.s == "T"); // `cpp.s` is `"T"` destroy!false(cpp); // destroy without initialization assert(cpp.dtorCount == 1); // `cpp`'s destructor was called assert(cpp.s == "T"); // `cpp.s` is not initialized assert(cpp.a.dtorCount == 1); // `cpp.a`'s destructor was called assert(cpp.a.x == 30); // `cpp.a.x` is not initialized destroy(cpp); assert(cpp.dtorCount == 2); // `cpp`'s destructor was called again assert(cpp.s == "S"); // `cpp.s` is back to its inital state, `"S"` assert(cpp.a.dtorCount == 2); // `cpp.a`'s destructor was called again assert(cpp.a.x == 10); // `cpp.a.x` is back to its inital state, `10` ``` Examples: Value type demonstration ``` int i; assert(i == 0); // `i`'s initial state is `0` i = 1; assert(i == 1); // `i` changed to `1` destroy!false(i); assert(i == 1); // `i` was not initialized destroy(i); assert(i == 0); // `i` is back to its initial state `0` ```
programming_docs
d core.sync.semaphore core.sync.semaphore =================== The semaphore module provides a general use semaphore for synchronization. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) Authors: Sean Kelly Source [core/sync/semaphore.d](https://github.com/dlang/druntime/blob/master/src/core/sync/semaphore.d) class **Semaphore**; This class represents a general counting semaphore as concieved by Edsger Dijkstra. As per Mesa type monitors however, "signal" has been replaced with "notify" to indicate that control is not transferred to the waiter when a notification is sent. Examples: ``` import core.thread, core.atomic; void testWait() { auto semaphore = new Semaphore; shared bool stopConsumption = false; immutable numToProduce = 20; immutable numConsumers = 10; shared size_t numConsumed; shared size_t numComplete; void consumer() { while (true) { semaphore.wait(); if (atomicLoad(stopConsumption)) break; atomicOp!"+="(numConsumed, 1); } atomicOp!"+="(numComplete, 1); } void producer() { assert(!semaphore.tryWait()); foreach (_; 0 .. numToProduce) semaphore.notify(); // wait until all items are consumed while (atomicLoad(numConsumed) != numToProduce) Thread.yield(); // mark consumption as finished atomicStore(stopConsumption, true); // wake all consumers foreach (_; 0 .. numConsumers) semaphore.notify(); // wait until all consumers completed while (atomicLoad(numComplete) != numConsumers) Thread.yield(); assert(!semaphore.tryWait()); semaphore.notify(); assert(semaphore.tryWait()); assert(!semaphore.tryWait()); } auto group = new ThreadGroup; for ( int i = 0; i < numConsumers; ++i ) group.create(&consumer); group.create(&producer); group.joinAll(); } void testWaitTimeout() { auto sem = new Semaphore; shared bool semReady; bool alertedOne, alertedTwo; void waiter() { while (!atomicLoad(semReady)) Thread.yield(); alertedOne = sem.wait(dur!"msecs"(1)); alertedTwo = sem.wait(dur!"msecs"(1)); assert(alertedOne && !alertedTwo); } auto thread = new Thread(&waiter); thread.start(); sem.notify(); atomicStore(semReady, true); thread.join(); assert(alertedOne && !alertedTwo); } testWait(); testWaitTimeout(); ``` this(uint count = 0); Initializes a semaphore object with the specified initial count. Parameters: | | | | --- | --- | | uint `count` | The initial count for the semaphore. | Throws: SyncError on error. void **wait**(); Wait until the current count is above zero, then atomically decrement the count by one and return. Throws: SyncError on error. bool **wait**(Duration period); Suspends the calling thread until the current count moves above zero or until the supplied time period has elapsed. If the count moves above zero in this interval, then atomically decrement the count by one and return true. Otherwise, return false. Parameters: | | | | --- | --- | | Duration `period` | The time to wait. | In period must be non-negative. Throws: SyncError on error. Returns: true if notified before the timeout and false if not. void **notify**(); Atomically increment the current count by one. This will notify one waiter, if there are any in the queue. Throws: SyncError on error. bool **tryWait**(); If the current count is equal to zero, return. Otherwise, atomically decrement the count by one and return true. Throws: SyncError on error. Returns: true if the count was above zero and false if not. protected alias **Handle** = core.sys.posix.semaphore.sem\_t; Aliases the operating-system-specific semaphore type. protected Handle **m\_hndl**; Handle to the system-specific semaphore. d std.experimental.allocator.building_blocks.quantizer std.experimental.allocator.building\_blocks.quantizer ===================================================== Source [std/experimental/allocator/building\_blocks/quantizer.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/quantizer.d) struct **Quantizer**(ParentAllocator, alias roundingFunction); This allocator sits on top of `ParentAllocator` and quantizes allocation sizes, usually from arbitrary positive numbers to a small set of round numbers (e.g. powers of two, page sizes etc). This technique is commonly used to: * Preallocate more memory than requested such that later on, when reallocation is needed (e.g. to grow an array), expansion can be done quickly in place. Reallocation to smaller sizes is also fast (in-place) when the new size requested is within the same quantum as the existing size. Code that's reallocation-heavy can therefore benefit from fronting a generic allocator with a `Quantizer`. These advantages are present even if `ParentAllocator` does not support reallocation at all. * Improve behavior of allocators sensitive to allocation sizes, such as `FreeList` and `FreeTree`. Rounding allocation requests up makes for smaller free lists/trees at the cost of slack memory (internal fragmentation). The following methods are forwarded to the parent allocator if present: `allocateAll`, `owns`, `deallocateAll`, `empty`. Preconditions `roundingFunction` must satisfy three constraints. These are not enforced (save for the use of `assert`) for the sake of efficiency. 1. `roundingFunction(n) >= n` for all `n` of type `size_t`; 2. `roundingFunction` must be monotonically increasing, i.e. `roundingFunction(n1) <= roundingFunction(n2)` for all `n1 < n2`; 3. `roundingFunction` must be `nothrow`, `@safe`, `@nogc` and `pure`, i.e. always return the same value for a given `n`. Examples: ``` import std.experimental.allocator.building_blocks.free_tree : FreeTree; import std.experimental.allocator.gc_allocator : GCAllocator; size_t roundUpToMultipleOf(size_t s, uint base) { auto rem = s % base; return rem ? s + base - rem : s; } // Quantize small allocations to a multiple of cache line, large ones to a // multiple of page size alias MyAlloc = Quantizer!( FreeTree!GCAllocator, n => roundUpToMultipleOf(n, n <= 16_384 ? 64 : 4096)); MyAlloc alloc; const buf = alloc.allocate(256); assert(buf.ptr); ``` ParentAllocator **parent**; The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`. size\_t **goodAllocSize**(size\_t n); Returns `roundingFunction(n)`. enum auto **alignment**; Alignment is identical to that of the parent. void[] **allocate**(size\_t n); Gets a larger buffer `buf` by calling `parent.allocate(goodAllocSize(n))`. If `buf` is `null`, returns `null`. Otherwise, returns `buf[0 .. n]`. void[] **alignedAllocate**(size\_t n, uint a); Defined only if `parent.alignedAllocate` exists and works similarly to `allocate` by forwarding to `parent.alignedAllocate(goodAllocSize(n), a)`. bool **expand**(ref void[] b, size\_t delta); First checks whether there's enough slack memory preallocated for `b` by evaluating `b.length + delta <= goodAllocSize(b.length)`. If that's the case, expands `b` in place. Otherwise, attempts to use `parent.expand` appropriately if present. bool **reallocate**(ref void[] b, size\_t s); Expands or shrinks allocated block to an allocated size of `goodAllocSize(s)`. Expansion occurs in place under the conditions required by `expand`. Shrinking occurs in place if `goodAllocSize(b.length) == goodAllocSize(s)`. bool **alignedReallocate**(ref void[] b, size\_t s, uint a); Defined only if `ParentAllocator.alignedAllocate` exists. Expansion occurs in place under the conditions required by `expand`. Shrinking occurs in place if `goodAllocSize(b.length) == goodAllocSize(s)`. bool **deallocate**(void[] b); Defined if `ParentAllocator.deallocate` exists and forwards to `parent.deallocate(b.ptr[0 .. goodAllocSize(b.length)])`. d Classes Classes ======= **Contents** 1. [Access Control](#access_control) 2. [Fields](#fields) 3. [Field Properties](#field_properties) 4. [Class Properties](#class_properties) 5. [Super Class](#super_class) 6. [Member Functions (a.k.a. Methods)](#member-functions) 1. [Objective-C linkage](#objc-member-functions) 7. [Synchronized Classes](#synchronized-classes) 8. [Constructors](#constructors) 1. [Delegating Constructors](#delegating-constructors) 2. [Implicit Base Class Construction](#implicit-base-construction) 3. [Class Instantiation](#class-instantiation) 4. [Constructor Attributes](#constructor-attributes) 5. [Field initialization inside a constructor](#field-init) 9. [Destructors](#destructors) 10. [Static Constructors](#static-constructor) 11. [Static Destructors](#static-destructor) 12. [Shared Static Constructors](#shared_static_constructors) 13. [Shared Static Destructors](#shared_static_destructors) 14. [Class Invariants](#invariants) 15. [Class Allocators](#allocators) 16. [Class Deallocators](#deallocators) 17. [Alias This](#alias-this) 18. [Scope Classes](#auto) 19. [Final Classes](#final) 20. [Nested Classes](#nested) 1. [Static Nested Classes](#static-nested) 2. [Context Pointer](#nested-context) 3. [Explicit Instantiation](#nested-explicit) 4. [`outer` Property](#outer-property) 5. [Anonymous Nested Classes](#anonymous) 21. [Const, Immutable and Shared Classes](#const-class) The object-oriented features of D all come from classes. The class hierarchy has as its root the class Object. Object defines a minimum level of functionality that each derived class has, and a default implementation for that functionality. Classes are programmer defined types. Support for classes are what make D an object oriented language, giving it encapsulation, inheritance, and polymorphism. D classes support the single inheritance paradigm, extended by adding support for interfaces. Class objects are instantiated by reference only. A class can be exported, which means its name and all its non-private members are exposed externally to the DLL or EXE. A class declaration is defined: ``` ClassDeclaration: class Identifier ; class Identifier BaseClassListopt AggregateBody ClassTemplateDeclaration BaseClassList: : SuperClass : SuperClass , Interfaces : Interfaces SuperClass: BasicType Interfaces: Interface Interface , Interfaces Interface: BasicType ``` Classes consist of: * a super class * interfaces * a nested anonymous metaclass for classes declared with `extern (Objective-C)` * dynamic fields * static fields * types * [an optional synchronized attribute](#synchronized-classes) * [member functions](#member-functions) + static member functions + [Virtual Functions](function#virtual-functions) + [Constructors](#constructors) + [Destructors](#destructors) + [Static Constructors](#static-constructor) + [Static Destructors](#static-destructor) + [*SharedStaticConstructor*](#SharedStaticConstructor)s + [*SharedStaticDestructor*](#SharedStaticDestructor)s + [Class Invariants](#invariants) + [Unit Tests](unittest#unittest) + [Class Allocators](#allocators) + [Class Deallocators](#deallocators) + [Alias This](#alias-this) A class is defined: ``` class Foo { ... members ... } ``` Note that there is no trailing `;` after the closing `}` of the class definition. It is also not possible to declare a variable var like: ``` class Foo { } var; ``` Instead: ``` class Foo { } Foo var; ``` Access Control -------------- Access to class members is controlled using [visibility attributes](attribute#visibility_attributes). The default visibility attribute is `public`. Fields ------ Class members are always accessed with the `.` operator. Members of a base class can be accessed by prepending the name of the base class followed by a dot: ``` class A { int a; int a2;} class B : A { int a; } void foo(B b) { b.a = 3; // accesses field B.a b.a2 = 4; // accesses field A.a2 b.A.a = 5; // accesses field A.a } ``` The D compiler is free to rearrange the order of fields in a class to optimally pack them in an implementation-defined manner. Consider the fields much like the local variables in a function - the compiler assigns some to registers and shuffles others around all to get the optimal stack frame layout. This frees the code designer to organize the fields in a manner that makes the code more readable rather than being forced to organize it according to machine optimization rules. Explicit control of field layout is provided by struct/union types, not classes. Fields of `extern(Objective-C)` classes have a dynamic offset. That means that the base class can change (add or remove instance variables) without the subclasses needing to recompile or relink. Field Properties ---------------- The `.offsetof` property gives the offset in bytes of the field from the beginning of the class instantiation. `.offsetof` is not available for fields of `extern(Objective-C)` classes due to their fields having a dynamic offset. `.offsetof` can only be applied to expressions which produce the type of the field itself, not the class type: ``` class Foo { int x; } ... void test(Foo foo) { size_t o; o = Foo.x.offsetof; // error, Foo.x needs a 'this' reference o = foo.x.offsetof; // ok } ``` Class Properties ---------------- The `.tupleof` property is an [expression sequence](template#variadic-templates) of all the fields in the class, excluding the hidden fields and the fields in the base class. `.tupleof` is not available for `extern(Objective-C)` classes due to their fields having a dynamic offset. ``` class Foo { int x; long y; } void test(Foo foo) { import std.stdio; static assert(typeof(foo.tupleof).stringof == `(int, long)`); foo.tupleof[0] = 1; // set foo.x to 1 foo.tupleof[1] = 2; // set foo.y to 2 foreach (x; foo.tupleof) write(x); // prints 12 } ``` The properties `.__vptr` and `.__monitor` give access to the class object's vtbl[] and monitor, respectively, but should not be used in user code. Super Class ----------- All classes inherit from a super class. If one is not specified, it inherits from [`Object`](https://dlang.org/phobos/object.html#Object). `Object` forms the root of the D class inheritance hierarchy. Member Functions (a.k.a. Methods) --------------------------------- Non-static member functions have an extra hidden parameter called *this* through which the class object's other members can be accessed. Non-static member functions can have, in addition to the usual [*FunctionAttribute*](function#FunctionAttribute)s, the attributes `const`, `immutable`, `shared`, or `inout`. These attributes apply to the hidden *this* parameter. ``` class C { int a; const void foo() { a = 3; // error, 'this' is const } void foo() immutable { a = 3; // error, 'this' is immutable } } ``` ### Objective-C linkage Static member functions with `Objective-C` linkage also have an extra hidden parameter called *this* through which the class object's other members can be accessed. Member functions with Objective-C linkage have an additional hidden, anonymous, parameter which is the selector the function was called with. Static member functions with Objective-C linkage are placed in the hidden nested metaclass as non-static member functions. Synchronized Classes -------------------- All member functions of synchronized classes are synchronized. A static member function is synchronized on the *classinfo* object for the class, which means that one monitor is used for all static member functions for that synchronized class. For non-static functions of a synchronized class, the monitor used is part of the class object. For example: ``` synchronized class Foo { void bar() { ...statements... } } ``` is equivalent to (as far as the monitors go): ``` synchronized class Foo { void bar() { synchronized (this) { ...statements... } } } ``` Member functions of non-synchronized classes can be individually marked as synchronized. ``` class Foo { synchronized void foo() { } // foo is synchronized } ``` Member fields of a synchronized class cannot be public: ``` synchronized class Foo { int foo; // disallowed: public field } synchronized class Bar { private int bar; // ok } ``` The `synchronized` attribute can only be applied to classes, structs cannot be marked to be synchronized. Constructors ------------ ``` Constructor: this Parameters MemberFunctionAttributesopt ; this Parameters MemberFunctionAttributesopt FunctionBody ConstructorTemplate ``` Fields are by default initialized to the default initializer for their type (usually 0 for integer types and NAN for floating point types). If the field declaration has an optional [*Initializer*](declaration#Initializer) that will be used instead of the default. ``` class Abc { int a; // default initializer for a is 0 long b = 7; // default initializer for b is 7 float f; // default initializer for f is NAN } ``` The *Initializer* is evaluated at compile time. This initialization is done before any constructors are called. Constructors are defined with a function name of `this` and have no return value: ``` class Foo { this(int x) // declare constructor for Foo { ... } this() { ... } } ``` Base class construction is done by calling the base class constructor by the name `super`: ``` class A { this(int y) { } } class B : A { int j; this() { ... super(3); // call base constructor A.this(3) ... } } ``` ### Delegating Constructors A constructor can call another constructor for the same class in order to share common initializations. This is called a *delegating constructor*: ``` class C { int j; this() { ... } this(int i) { this(); // delegating constructor call j = i; } } ``` The following restrictions apply: 1. It is illegal for constructors to mutually call each other. ``` this() { this(1); } this(int i) { this(); } // illegal, cyclic constructor calls ``` **Implementation Defined:** The compiler is not required to detect cyclic constructor calls. **Undefined Behavior:** If the program executes with cyclic constructor calls. 2. If a constructor's code contains a delegating constructor call, all possible execution paths through the constructor must make exactly one delegating constructor call: ``` this() { a || super(); } // illegal this() { (a) ? this(1) : super(); } // ok this() { for (...) { super(); // illegal, inside loop } } ``` 3. It is illegal to refer to `this` implicitly or explicitly prior to making a delegating constructor call. 4. Delegating constructor calls cannot appear after labels. ### Implicit Base Class Construction If there is no constructor for a class, but there is a constructor for the base class, a default constructor is implicitly generated with the form: ``` this() { } ``` If no calls to a delegating constructor or `super` appear in a constructor, and the base class has a nullary constructor, a call to `super()` is inserted at the beginning of the constructor. If that base class has a constructor that requires arguments and no nullary constructor, a matching call to `super` is required. ### Class Instantiation Instances of class objects are created with a [*NewExpression*](expression#NewExpression): ``` A a = new A(3); ``` The following steps happen: 1. Storage is allocated for the object. If this fails, rather than return `null`, an [OutOfMemoryError](https://dlang.org/library/core/exception/out_of_memory_error.html) is thrown. Thus, tedious checks for null references are unnecessary. 2. The raw data is statically initialized using the values provided in the class definition. The pointer to the vtbl[] (the array of pointers to virtual functions) is assigned. Constructors are passed fully formed objects for which virtual functions can be called. This operation is equivalent to doing a memory copy of a static version of the object onto the newly allocated one. 3. If there is a constructor defined for the class, the constructor matching the argument list is called. 4. If a delegating constructor is not called, a call to the base class's default constructor is issued. 5. The body of the constructor is executed. 6. If class invariant checking is turned on, the class invariant is called at the end of the constructor. ### Constructor Attributes Constructors can have one of these member function attributes: `const`, `immutable`, and `shared`. Construction of qualified objects will then be restricted to the implemented qualified constructors. ``` class C { this(); // non-shared mutable constructor } // create mutable object C m = new C(); // create const object using mutable constructor const C c2 = new const C(); // a mutable constructor cannot create an immutable object // immutable C i = new immutable C(); // a mutable constructor cannot create a shared object // shared C s = new shared C(); ``` Constructors can be overloaded with different attributes. ``` class C { this(); // non-shared mutable constructor this() shared; // shared mutable constructor this() immutable; // immutable constructor } C m = new C(); shared s = new shared C(); immutable i = new immutable C(); ``` #### Pure Constructors If the constructor can create a unique object (e.g. if it is `pure`), the object can be implicitly convertible to any qualifiers. ``` class C { this() pure; // Based on the definition, this creates a mutable object. But the // created object cannot contain any mutable global data. // Therefore the created object is unique. this(int[] arr) immutable pure; // Based on the definition, this creates an immutable object. But // the argument int[] never appears in the created object so it // isn't implicitly convertible to immutable. Also, it cannot store // any immutable global data. // Therefore the created object is unique. } immutable i = new immutable C(); // this() pure is called shared s = new shared C(); // this() pure is called C m = new C([1,2,3]); // this(int[]) immutable pure is called ``` ### Field initialization inside a constructor In a constructor body, the first instance of field assignment is its initialization. ``` class C { int num; this() { num = 1; // initialization num = 2; // assignment } } ``` If the field type has an [`opAssign`](operatoroverloading#assignment) method, it will not be used for initialization. ``` struct A { this(int n) {} void opAssign(A rhs) {} } class C { A val; this() { val = A(1); // val is initialized to the value of A(1) val = A(2); // rewritten to val.opAssign(A(2)) } } ``` If the field type is not mutable, multiple initialization will be rejected. ``` class C { immutable int num; this() { num = 1; // OK num = 2; // Error: multiple field initialization } } ``` If the field is initialized on one path, it must be initialized on all paths. ``` class C { immutable int num; immutable int ber; this(int i) { if (i) num = 3; // initialization else num = 4; // initialization } this(long j) { j ? (num = 3) : (num = 4); // ok j || (ber = 3); // error, intialized on only one path j && (ber = 3); // error, intialized on only one path } } ``` A field initialization may not appear in a loop or after a label. ``` class C { immutable int num; immutable string str; this() { foreach (i; 0..2) { num = 1; // Error: field initialization not allowed in loops } size_t i = 0; Label: str = "hello"; // Error: field initialization not allowed after labels if (i++ < 2) goto Label; } } ``` If a field's type has disabled default construction, then it must be initialized in the constructor. ``` struct S { int y; @disable this(); } class C { S s; this(S t) { s = t; } // ok this(int i) { this(); } // ok this() { } // error, s not initialized } ``` Destructors ----------- ``` Destructor: ~ this ( ) MemberFunctionAttributesopt ; ~ this ( ) MemberFunctionAttributesopt FunctionBody ``` The garbage collector calls the destructor function when the object is deleted. The syntax is: ``` class Foo { ~this() // destructor for Foo { } } ``` There can be only one destructor per class, the destructor does not have any parameters, and has no attributes. It is always virtual. The destructor is expected to release any resources held by the object. The program can explicitly inform the garbage collector that an object is no longer referred to with [`destroy`](https://dlang.org/phobos/object.html#destroy), and then the garbage collector calls the destructor immediately. The destructor is guaranteed to never be called twice. The destructor for the super class automatically gets called when the destructor ends. There is no way to call the super destructor explicitly. The garbage collector is not guaranteed to run the destructor for all unreferenced objects. Furthermore, the order in which the garbage collector calls destructors for unreferenced objects is not specified. This means that when the garbage collector calls a destructor for an object of a class that has members which are references to garbage collected objects, those references may no longer be valid. This means that destructors cannot reference sub objects. This rule does not apply to auto objects or objects destructed with [`destroy`](https://dlang.org/phobos/object.html#destroy), as the destructor is not being run by the garbage collector, meaning all references are valid. Objects referenced from the data segment never get collected by the gc. Static Constructors ------------------- ``` StaticConstructor: static this ( ) MemberFunctionAttributesopt ; static this ( ) MemberFunctionAttributesopt FunctionBody ``` A static constructor is a function that performs initializations of thread local data before the `main()` function gets control for the main thread, and upon thread startup. Static constructors are used to initialize static class members with values that cannot be computed at compile time. Static constructors in other languages are built implicitly by using member initializers that can't be computed at compile time. The trouble with this stems from not having good control over exactly when the code is executed, for example: ``` class Foo { static int a = b + 1; static int b = a * 2; } ``` What values do a and b end up with, what order are the initializations executed in, what are the values of a and b before the initializations are run, is this a compile error, or is this a runtime error? Additional confusion comes from it not being obvious if an initializer is static or dynamic. D makes this simple. All member initializations must be determinable by the compiler at compile time, hence there is no order-of-evaluation dependency for member initializations, and it is not possible to read a value that has not been initialized. Dynamic initialization is performed by a static constructor, defined with a special syntax `static this()`. ``` class Foo { static int a; // default initialized to 0 static int b = 1; static int c = b + a; // error, not a constant initializer static this() // static constructor { a = b + 1; // a is set to 2 b = a * 2; // b is set to 4 } } ``` If `main()` or the thread returns normally, (does not throw an exception), the static destructor is added to the list of functions to be called on thread termination. Static constructors have empty parameter lists. Static constructors within a module are executed in the lexical order in which they appear. All the static constructors for modules that are directly or indirectly imported are executed before the static constructors for the importer. The `static` in the static constructor declaration is not an attribute, it must appear immediately before the `this`: ``` class Foo { static this() { ... } // a static constructor static private this() { ... } // not a static constructor static { this() { ... } // not a static constructor } static: this() { ... } // not a static constructor } ``` Static Destructors ------------------ ``` StaticDestructor: static ~ this ( ) MemberFunctionAttributesopt ; static ~ this ( ) MemberFunctionAttributesopt FunctionBody ``` A static destructor is defined as a special static function with the syntax `static ~this()`. ``` class Foo { static ~this() // static destructor { } } ``` A static destructor gets called on thread termination, but only if the static constructor completed successfully. Static destructors have empty parameter lists. Static destructors get called in the reverse order that the static constructors were called in. The `static` in the static destructor declaration is not an attribute, it must appear immediately before the `~this`: ``` class Foo { static ~this() { ... } // a static destructor static private ~this() { ... } // not a static destructor static { ~this() { ... } // not a static destructor } static: ~this() { ... } // not a static destructor } ``` Shared Static Constructors -------------------------- ``` SharedStaticConstructor: shared static this ( ) MemberFunctionAttributesopt ; shared static this ( ) MemberFunctionAttributesopt FunctionBody ``` Shared static constructors are executed before any [*StaticConstructor*](#StaticConstructor)s, and are intended for initializing any shared global data. Shared Static Destructors ------------------------- ``` SharedStaticDestructor: shared static ~ this ( ) MemberFunctionAttributesopt ; shared static ~ this ( ) MemberFunctionAttributesopt FunctionBody ``` Shared static destructors are executed at program termination in the reverse order that [*SharedStaticConstructor*](#SharedStaticConstructor)s were executed. Class Invariants ---------------- ``` ClassInvariant: invariant ( ) BlockStatement invariant BlockStatement invariant ( AssertArguments ) ; ``` *ClassInvariant* specify the relationships among the members of a class instance. Those relationships must hold for any interactions with the instance from its public interface. The invariant is in the form of a `const` member function. The invariant is defined to *hold* if all the [*AssertExpression*](expression#AssertExpression)s within the invariant that are executed succeed. If the invariant does not hold, then the program enters an invalid state. Any class invariants for base classes are applied before the class invariant for the derived class. There may be multiple invariants in a class. They are applied in lexical order. *ClassInvariant*s must hold at the exit of the class constructor (if any), at the entry of the class destructor (if any). *ClassInvariant*s must hold at the entry and exit of all public or exported non-static member functions. The order of application of invariants is: 1. preconditions 2. invariant 3. function body 4. invariant 5. postconditions The invariant need not hold if the class instance is implicitly constructed using the default `.init` value. ``` class Date { this(int d, int h) { day = d; // days are 1..31 hour = h; // hours are 0..23 } invariant { assert(1 <= day && day <= 31); assert(0 <= hour && hour < 24); } private: int day; int hour; } ``` Public or exported non-static member functions cannot be called from within an invariant. ``` class Foo { public void f() { } private void g() { } invariant { f(); // error, cannot call public member function from invariant g(); // ok, g() is not public } } ``` **Undefined Behavior:** happens if the invariant does not hold and execution continues. **Implementation Defined:** 1. Whether the *Class Invariant* is executed at runtime or not. This is typically controlled with a compiler switch. 2. The behavior when the invariant does not hold is typically the same as for when [*AssertExpression*](expression#AssertExpression)s fail. **Best Practices:** 1. Do not indirectly call exported or public member functions within a class invariant, as this can result in infinite recursion. 2. Avoid reliance on side effects in the invariant. as the invariant may or may not be executed. 3. Avoid having mutable public fields of classes with invariants, as then the invariant cannot verify the public interface. Class Allocators ---------------- **Note**: Class allocators are deprecated in D2. ``` Allocator: new Parameters ; new Parameters FunctionBody ``` A class member function of the form: ``` new(size_t size) { ... } ``` is called a class allocator. The class allocator can have any number of parameters, provided the first one is of type `size_t`. Any number can be defined for a class, the correct one is determined by the usual function overloading rules. When a new expression: ``` new Foo; ``` is executed, and Foo is a class that has an allocator, the allocator is called with the first argument set to the size in bytes of the memory to be allocated for the instance. The allocator must allocate the memory and return it as a `void*`. If the allocator fails, it must not return a `null`, but must throw an exception. If there is more than one parameter to the allocator, the additional arguments are specified within parentheses after the `new` in the *NewExpression*: ``` class Foo { this(string a) { ... } new(size_t size, int x, int y) { ... } } ... new(1,2) Foo(a); // calls new(Foo.sizeof,1,2) ``` Derived classes inherit any allocator from their base class, if one is not specified. The class allocator is not called if the instance is created on the stack. See also [Explicit Class Instance Allocation](https://wiki.dlang.org/Memory_Management#Explicit_Class_Instance_Allocation). Class Deallocators ------------------ **Note**: Class deallocators and the delete operator are deprecated in D2. Use the `destroy` function to finalize an object by calling its destructor. The memory of the object is **not** immediately deallocated, instead the GC will collect the memory of the object at an undetermined point after finalization: ``` class Foo { int x; this() { x = 1; } } Foo foo = new Foo; destroy(foo); assert(foo.x == int.init); // object is still accessible ``` ``` Deallocator: delete Parameters ; delete Parameters FunctionBody ``` A class member function of the form: ``` delete(void *p) { ... } ``` is called a class deallocator. The deallocator must have exactly one parameter of type `void*`. Only one can be specified for a class. When a delete expression: ``` delete f; ``` is executed, and f is a reference to a class instance that has a deallocator, the deallocator is called with a pointer to the class instance after the destructor (if any) for the class is called. It is the responsibility of the deallocator to free the memory. Derived classes inherit any deallocator from their base class, if one is not specified. The class allocator is not called if the instance is created on the stack. See also [Explicit Class Instance Allocation](https://wiki.dlang.org/Memory_Management#Explicit_Class_Instance_Allocation). Alias This ---------- ``` AliasThis: alias Identifier this ; ``` An *AliasThis* declaration names a member to subtype. The *Identifier* names that member. A class or struct can be implicitly converted to the *AliasThis* member. ``` struct S { int x; alias x this; } int foo(int i) { return i * 2; } void test() { S s; s.x = 7; int i = -s; // i == -7 i = s + 8; // i == 15 i = s + s; // i == 14 i = 9 + s; // i == 16 i = foo(s); // implicit conversion to int } ``` If the member is a class or struct, undefined lookups will be forwarded to the *AliasThis* member. ``` struct Foo { int baz = 4; int get() { return 7; } } class Bar { Foo foo; alias foo this; } void test() { auto bar = new Bar; int i = bar.baz; // i == 4 i = bar.get(); // i == 7 } ``` If the *Identifier* refers to a property member function with no parameters, conversions and undefined lookups are forwarded to the return value of the function. ``` struct S { int x; @property int get() { return x * 2; } alias get this; } void test() { S s; s.x = 2; int i = s; // i == 4 } ``` If an aggregate declaration defines an `opCmp` or `opEquals` method, it will take precedence to that of the aliased this member. Note that, unlike an `opCmp` method, an `opEquals` method is implicitly defined for a `struct` declaration if a user defined one isn't provided; this means that if the aliased this member `opEquals` is preferred it should be explicitly defined: ``` struct S { int a; bool opEquals(S rhs) const { return this.a == rhs.a; } } struct T { int b; S s; alias s this; } struct U { int a; bool opCmp(U rhs) const { return this.a < rhs.a; } } struct V { int b; U u; alias u this; } void main() { S s1, s2; T t1, t2; U u1, u2; V v1, v2; assert(s1 == s2); // calls S.opEquals assert(t1 == t2); // calls compiler generated T.opEquals that implements member-wise equality assert(!(u1 < u2)); // calls U.opCmp assert(!(v1 < v2)); // calls U.opCmp because V does not define an opCmp method // so the alias this of v1 is employed; U.opCmp expects a // paramter of type U, so alias this of v2 is used assert(s1 == t1); // calls s1.opEquals(t1.s); assert(t1 == s1); // calls t1.s.opEquals(s1); assert(!(u1 < v1)); // calls u1.opCmp(v1.u); assert(!(v1 < u1)); // calls v1.u.opCmp(v1); } ``` [*Attribute*](attribute#Attribute)s are ignored for `AliasThis`. Multiple *AliasThis* are currently not allowed. Scope Classes ------------- **Note**: Scope classes have been [recommended for deprecation](https://dlang.org/deprecate.html#scope%20for%20allocating%20classes%20on%20the%20stack). A scope class is a class with the `scope` attribute, as in: ``` scope class Foo { ... } ``` The scope characteristic is inherited, so any classes derived from a scope class are also scope. A scope class reference can only appear as a function local variable. It must be declared as being `scope`: ``` scope class Foo { ... } void func() { Foo f; // error, reference to scope class must be scope scope Foo g = new Foo(); // correct } ``` When a scope class reference goes out of scope, the destructor (if any) for it is automatically called. This holds true even if the scope was exited via a thrown exception. Final Classes ------------- Final classes cannot be subclassed: ``` final class A { } class B : A { } // error, class A is final ``` Methods of a final class are `final` by default. Nested Classes -------------- A *nested class* is a class that is declared inside the scope of a function or another class. A nested class has access to the variables and other symbols of the classes and functions it is nested inside: ``` class Outer { int m; class Inner { int foo() { return m; // Ok to access member of Outer } } } void func() { int m; class Inner { int foo() { return m; // Ok to access local variable m of func() } } } ``` ### Static Nested Classes If a nested class has the `static` attribute, then it can not access variables of the enclosing scope that are local to the stack or need a `this` reference: ``` class Outer { int m; static int n; static class Inner { int foo() { return m; // Error, Inner is static and m needs a this return n; // Ok, n is static } } } void func() { int m; static int n; static class Inner { int foo() { return m; // Error, Inner is static and m is local to the stack return n; // Ok, n is static } } } ``` ### Context Pointer Non-static nested classes work by containing an extra hidden member (called the context pointer) that is the frame pointer of the enclosing function if it is nested inside a function, or the `this` reference of the enclosing class's instance if it is nested inside a class. When a non-static nested class is instantiated, the context pointer is assigned before the class's constructor is called, therefore the constructor has full access to the enclosing variables. A non-static nested class can only be instantiated when the necessary context pointer information is available: ``` class Outer { class Inner { } static class SInner { } } void func() { class Nested { } Outer o = new Outer; // Ok Outer.Inner oi = new Outer.Inner; // Error, no 'this' for Outer Outer.SInner os = new Outer.SInner; // Ok Nested n = new Nested; // Ok } ``` ### Explicit Instantiation A `this` reference can be supplied to the creation of an inner class instance by prefixing it to the *NewExpression*: ``` class Outer { int a; class Inner { int foo() { return a; } } } int bar() { Outer o = new Outer; o.a = 3; Outer.Inner oi = o.new Inner; return oi.foo(); // returns 3 } ``` Here `o` supplies the `this` reference to the inner class instance of `Outer`. ### `outer` Property For a nested class instance, the `.outer` property is the `this` reference for the enclosing class's instance. If there is no enclosing class context, `.outer` would be a `void*` to the enclosing function frame. ``` class Outer { class Inner1 { Outer getOuter() { return this.outer; } } void foo() { Inner1 i = new Inner1; assert(i.getOuter() is this); } void bar() { // x is referenced from nested scope, so // bar makes a closure environment. int x = 1; class Inner2 { Outer getOuter() { x = 2; // The Inner2 instance has access to the function frame // of bar as a static frame pointer, but .outer returns // the enclosing Outer class instance property. return this.outer; } } Inner2 i = new Inner2; assert(i.getOuter() is this); } // baz cannot access an instance of Outer static void baz() { // make a closure environment int x = 1; class Inner3 { void* getOuter() { x = 2; // There's no accessible enclosing class instance, so the // .outer property returns the function frame of baz. return this.outer; } } Inner3 i = new Inner3; assert(i.getOuter() !is null); } } ``` ### Anonymous Nested Classes An anonymous nested class is both defined and instantiated with a *NewAnonClassExpression*: ``` NewAnonClassExpression: new AllocatorArgumentsopt class ConstructorArgsopt SuperClassopt Interfacesopt AggregateBody ConstructorArgs: ( ArgumentListopt ) ``` which is equivalent to: ``` class Identifier : SuperClass Interfaces AggregateBody // ... new AllocatorArguments Identifier ConstructorArgs ``` where *Identifier* is the name generated for the anonymous nested class. ``` interface I { void foo(); } auto obj = new class I { void foo() { writeln("foo"); } }; obj.foo(); ``` Const, Immutable and Shared Classes ----------------------------------- If a *ClassDeclaration* has a `const`, `immutable` or `shared` storage class, then it is as if each member of the class was declared with that storage class. If a base class is const, immutable or shared, then all classes derived from it are also const, immutable or shared.
programming_docs
d Interfacing to C++ Interfacing to C++ ================== **Contents** 1. [The General Idea](#general_idea) 2. [Global Functions](#global-functions) 1. [Calling C++ Global Functions from D](#calling_cpp_global_from_d) 2. [Calling Global D Functions From C++](#calling_global_d_functions_from_cpp) 3. [C++ Namespaces](#cpp-namespaces) 4. [Classes](#classes) 1. [Using C++ Classes From D](#using_cpp_classes_from_d) 2. [Using D Classes From C++](#using_d_classes_from_cpp) 5. [Structs](#structs) 6. [C++ Templates](#cpp-templates) 7. [Function Overloading](#function-overloading) 8. [Memory Allocation](#memory-allocation) 9. [Data Type Compatibility](#data-type-compatibility) 10. [Packing and Alignment](#packing-and-alignment) 11. [Lifetime Management](#lifetime-management) 12. [Special Member Functions](#special-member-functions) 13. [Runtime Type Identification](#rtti) 14. [Exception Handling](#exception-handling) 15. [Comparing D Immutable and Const with C++ Const](#comparing-d-immutable-and-const-with-cpp-const) This document specifies how to interface with C++ directly. It is also possible to indirectly interface with C++ code, either through a [C interface](interfacetoc) or a COM interface. The General Idea ---------------- Being 100% compatible with C++ means more or less adding a fully functional C++ compiler front end to D. Anecdotal evidence suggests that writing such is a minimum of a 10 man-year project, essentially making a D compiler with such capability unimplementable. Other languages looking to hook up to C++ face the same problem, and the solutions have been: 1. Support the COM interface (but that only works for Windows). 2. Laboriously construct a C wrapper around the C++ code. 3. Use an automated tool such as SWIG to construct a C wrapper. 4. Reimplement the C++ code in the other language. 5. Give up. D takes a pragmatic approach that assumes a couple modest accommodations can solve a significant chunk of the problem: * matching C++ name mangling conventions * matching C++ function calling conventions * matching C++ virtual function table layout for single inheritance Global Functions ---------------- C++ global functions, including those in namespaces, can be declared and called in D, or defined in D and called in C++. ### Calling C++ Global Functions from D Given a C++ function in a C++ source file: ``` #include <iostream> using namespace std; int foo(int i, int j, int k) { cout << "i = " << i << endl; cout << "j = " << j << endl; cout << "k = " << k << endl; return 7; } ``` In the corresponding D code, `foo` is declared as having C++ linkage and function calling conventions: ``` extern (C++) int foo(int i, int j, int k); ``` and then it can be called within the D code: ``` extern (C++) int foo(int i, int j, int k); void main() { foo(1, 2, 3); } ``` Compiling the two files, the first with a C++ compiler, the second with a D compiler, linking them together, and then running it yields: ``` > g++ -c foo.cpp > dmd bar.d foo.o -L-lstdc++ && ./bar i = 1 j = 2 k = 3 ``` There are several things going on here: * D understands how C++ function names are "mangled" and the correct C++ function call/return sequence. * Because modules are not part of C++, each function with C++ linkage in the global namespace must be globally unique within the program. * There are no `__cdecl`, `__far`, `__stdcall`, `__declspec`, or other such nonstandard C++ extensions in D. * There are no volatile type modifiers in D. * Strings are not 0 terminated in D. See "Data Type Compatibility" for more information about this. However, string literals in D are 0 terminated. ### Calling Global D Functions From C++ To make a D function accessible from C++, give it C++ linkage: ``` import std.stdio; extern (C++) int foo(int i, int j, int k) { writefln("i = %s", i); writefln("j = %s", j); writefln("k = %s", k); return 1; } extern (C++) void bar(); void main() { bar(); } ``` The C++ end looks like: ``` int foo(int i, int j, int k); void bar() { foo(6, 7, 8); } ``` Compiling, linking, and running produces the output: ``` > dmd -c foo.d > g++ bar.cpp foo.o -lphobos2 -pthread -o bar && ./bar i = 6 j = 7 k = 8 ``` C++ Namespaces -------------- C++ symbols that reside in namespaces can be accessed from D. A [namespace](attribute#namespace) can be added to the `extern (C++)` [LinkageAttribute](attribute#linkage): ``` extern (C++, N) int foo(int i, int j, int k); void main() { N.foo(1, 2, 3); // foo is in C++ namespace 'N' } ``` C++ can open the same namespace in the same file and multiple files. In D, this can be done as follows: ``` module ns; extern (C++, `ns`) { int foo() { return 1; } } ``` Any expression that resolves to either a tuple of strings or an empty tuple is accepted. When the expression resolves to an empty tuple, it is equivalent to `extern (C++)` ``` extern(C++, (expression)) { int bar() { return 2; } } ``` or in multiple files, by organizing them in a package consisting of several modules: ``` ns/ |-- a.d |-- b.d |-- package.d ``` File `ns/a.d`: ``` module a; extern (C++, `ns`) { int foo() { return 1; } } ``` File `ns/b.d`: ``` module b; extern (C++, `ns`) { int bar() { return 2; } } ``` File `ns/package.d`: ``` module ns; public import a, b; ``` Then import the package containing the extern C++ declarations as follows: ``` import ns; static assert(foo() == 1 && bar() == 2); ``` Note that the `extern (C++,` ns`)` linkage attribute affects only the ABI (name mangling and calling convention) of these declarations. Importing them follows the usual [D module import semantics](spec/module). Alternatively, the non-string form can be used to introduce a scope. Note that the enclosing module already provides a scope for the symbols declared in the namespace. This form does not allow closing and reopening the same namespace with in the same module. That is: ``` module a; extern (C++, ns1) { int foo() { return 1; } } ``` ``` module b; extern (C++, ns1) { int bar() { return 2; } } ``` ``` import a, b; static assert(foo() == 1 && bar() == 2); ``` works, but: ``` extern (C++, ns1) { int foo() { return 1; } } extern (C++, ns1) { int bar() { return 2; } } ``` does not. Additionally, aliases can be used to avoid collision of symbols: ``` module a; extern (C++, ns) { int foo() { return 1; } } ``` ``` module b; extern (C++, ns) { int bar() { return 2; } } ``` ``` module ns; import a, b; alias foo = a.ns.foo; alias bar = b.ns.bar; ``` ``` import ns; static assert(foo() == 1 && bar() == 2); ``` Classes ------- C++ classes can be declared in D by using the `extern (C++)` attribute on `class`, `struct` and `interface` declarations. `extern (C++)` interfaces have the same restrictions as D interfaces, which means that Multiple Inheritance is supported to the extent that only one base class can have member fields. `extern (C++)` structs do not support virtual functions but can be used to map C++ value types. Unlike classes and interfaces with D linkage, `extern (C++)` classes and interfaces are not rooted in `Object` and cannot be used with `typeid`. D structs and classes have different semantics whereas C++ structs and classes are basically the same. The use of a D struct or class depends on the C++ implementation and not on the used C++ keyword. When mapping a D `class` onto a C++ `struct`, use `extern(C++, struct)` to avoid linking problems with C++ compilers (notably MSVC) that distinguish between C++'s `class` and `struct` when mangling. Conversely, use `extern(C++, class)` to map a D `struct` onto a C++ `class`. `extern(C++, class)` and `extern(C++, struct)` can be combined with C++ namespaces: ``` extern (C++, struct) extern (C++, foo) class Bar { } ``` ### Using C++ Classes From D The following example shows binding of a pure virtual function, its implementation in a derived class, a non-virtual member function, and a member field: ``` #include <iostream> using namespace std; class Base { public: virtual void print3i(int a, int b, int c) = 0; }; class Derived : public Base { public: int field; Derived(int field) : field(field) {} void print3i(int a, int b, int c) { cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; } int mul(int factor); }; int Derived::mul(int factor) { return field * factor; } Derived *createInstance(int i) { return new Derived(i); } void deleteInstance(Derived *&d) { delete d; d = 0; } ``` We can use it in D code like: ``` extern(C++) { abstract class Base { void print3i(int a, int b, int c); } class Derived : Base { int field; @disable this(); override void print3i(int a, int b, int c); final int mul(int factor); } Derived createInstance(int i); void deleteInstance(ref Derived d); } void main() { import std.stdio; auto d1 = createInstance(5); writeln(d1.field); writeln(d1.mul(4)); Base b1 = d1; b1.print3i(1, 2, 3); deleteInstance(d1); assert(d1 is null); auto d2 = createInstance(42); writeln(d2.field); deleteInstance(d2); assert(d2 is null); } ``` Compiling, linking, and running produces the output: ``` > g++ base.cpp > dmd main.d base.o -L-lstdc++ && ./main 5 20 a = 1 b = 2 c = 3 42 ``` Note how in the above example, the constructor is not bindable and is instead disabled on the D side; an alternative would be to reimplement the constructor in D. See the [section below on lifetime management](cpp_interface#lifetime-management) for more information. ### Using D Classes From C++ Given D code like: ``` extern (C++) int callE(E); extern (C++) interface E { int bar(int i, int j, int k); } class F : E { extern (C++) int bar(int i, int j, int k) { import std.stdio : writefln; writefln("i = %s", i); writefln("j = %s", j); writefln("k = %s", k); return 8; } } void main() { F f = new F(); callE(f); } ``` The C++ code to access it looks like: ``` class E { public: virtual int bar(int i, int j, int k); }; int callE(E *e) { return e->bar(11, 12, 13); } ``` ``` > dmd -c base.d > g++ klass.cpp base.o -lphobos2 -pthread -o klass && ./klass i = 11 j = 12 k = 13 ``` Structs ------- C++ allows a struct to inherit from a base struct. This is done in D using `alias this`: ``` struct Base { ... members ... }; struct Derived { Base base; // make it the first field alias base this; ... members ... } ``` In both C++ and D, if a struct has zero fields, the struct still has a size of 1 byte. But, in C++ if the struct with zero fields is used as a base struct, its size is zero (called the [Empty Base Optimization](https://en.cppreference.com/w/cpp/language/ebo)). There are two methods for emulating this behavior in D. The first forwards references to a function returning a faked reference to the base: ``` struct Base { ... members ... }; struct DerivedStruct { static if (Base.tupleof.length > 0) Base base; else ref inout(Base) base() inout { return *cast(inout(Base)*)&this; } alias base this; ... members ... } ``` The second makes use of template mixins: ``` mixin template BaseMembers() { void memberFunction() { ... } } struct Base { mixin BaseMembers!(); } struct Derived { mixin BaseMembers!(); ... members ... } ``` Note that the template mixin is evaluated in the context of its instantiation, not declaration. If this is a problem, the template mixin can use local imports, or have the member functions forward to the actual functions. C++ Templates ------------- C++ function and type templates can be bound by using the `extern (C++)` attribute on a function or type template declaration. Note that all instantiations used in D code must be provided by linking to C++ object code or shared libraries containing the instantiations. For example: ``` #include <iostream> template<class T> struct Foo { private: T field; public: Foo(T t) : field(t) {} T get(); void set(T t); }; template<class T> T Foo<T>::get() { return field; } template<class T> void Foo<T>::set(T t) { field = t; } Foo<int> makeIntFoo(int i) { return Foo<int>(i); } Foo<char> makeCharFoo(char c) { return Foo<char>(c); } template<class T> void increment(Foo<T> &foo) { foo.set(foo.get() + 1); } template<class T> void printThreeNext(Foo<T> foo) { for(size_t i = 0; i < 3; ++i) { std::cout << foo.get() << std::endl; increment(foo); } } // The following two functions ensure that the required instantiations of // printThreeNext are provided by this code module void printThreeNexti(Foo<int> foo) { printThreeNext(foo); } void printThreeNextc(Foo<char> foo) { printThreeNext(foo); } ``` ``` extern(C++): struct Foo(T) { private: T field; public: @disable this(); T get(); void set(T t); } Foo!int makeIntFoo(int i); Foo!char makeCharFoo(char c); void increment(T)(ref Foo!T foo); void printThreeNext(T)(Foo!T foo); extern(D) void main() { auto i = makeIntFoo(42); assert(i.get() == 42); i.set(1); increment(i); assert(i.get() == 2); auto c = makeCharFoo('a'); increment(c); assert(c.get() == 'b'); c.set('A'); printThreeNext(c); } ``` Compiling, linking, and running produces the output: ``` > g++ -c template.cpp > dmd main.d template.o -L-lstdc++ && ./main A B C ``` Function Overloading -------------------- C++ and D follow different rules for function overloading. D source code, even when calling `extern (C++)` functions, will still follow D overloading rules. Memory Allocation ----------------- C++ code explicitly manages memory with calls to `::operator new()` and `::operator delete()`. D's `new` operator allocates memory using the D garbage collector, so no explicit delete is necessary. D's `new` operator is not compatible with C++'s `::operator new` and `::operator delete`. Attempting to allocate memory with D's `new` and deallocate with C++ `::operator delete` will result in miserable failure. D can explicitly manage memory using a variety of library tools, such as with [`std.experimental.allocator`](https://dlang.org/phobos/std_experimental_allocator.html). Additionally, `core.stdc.stdlib.malloc` and `core.stdc.stdlib.free` can be used directly for connecting to C++ functions that expect `malloc`'d buffers. If pointers to memory allocated on the D garbage collector heap are passed to C++ functions, it's critical to ensure that the referenced memory will not be collected by the D garbage collector before the C++ function is done with it. This is accomplished by: * Making a copy of the data using [`std.experimental.allocator`](https://dlang.org/phobos/std_experimental_allocator.html) or `core.stdc.stdlib.malloc` and passing the copy instead. * Leaving a pointer to it on the stack (as a parameter or automatic variable), as the garbage collector will scan the stack. * Leaving a pointer to it in the static data segment, as the garbage collector will scan the static data segment. * Registering the pointer with the garbage collector using the `core.memory.GC.addRoot` or `core.memory.GC.addRange` functions. An interior pointer to the allocated memory block is sufficient to let the GC know the object is in use; i.e. it is not necessary to maintain a pointer to the *beginning* of the allocated memory. The garbage collector does not scan the stacks of threads not registered with the D runtime, nor does it scan the data segments of shared libraries that aren't registered with the D runtime. Data Type Compatibility ----------------------- D And C++ Type Equivalence| **D type** | **C++ type** | | void | void | | byte | signed char | | ubyte | unsigned char | | char | char (chars are unsigned in D) | | `core.stdc.stddef.wchar_t` | `wchar_t` | | short | short | | ushort | unsigned short | | int | int | | uint | unsigned | | long | long long | | ulong | unsigned long long | | `core.stdc.config.cpp_long` | long | | `core.stdc.config.cpp_ulong` | unsigned long | | float | float | | double | double | | real | long double | | `extern (C++)` struct | struct or class | | `extern (C++)` class | struct or class | | `extern (C++)` interface | struct or class with no member fields | | union | union | | enum | enum | | *type*\* | *type* \* | | ref *type* (in parameter lists only) | *type* `&` | | *type*[*dim*] | *type*[*dim*] | | *type*[*dim*]\* | *type*(\*)[*dim*] | | *type*[] | no equivalent | | *type*[*type*] | no equivalent | | *type* function(*parameters*) | *type*(\*)(*parameters*) | | *type* delegate(*parameters*) | no equivalent | These equivalents hold when the D and C++ compilers used are companions on the host platform. Packing and Alignment --------------------- D structs and unions are analogous to C's. C code often adjusts the alignment and packing of struct members with a command line switch or with various implementation specific #pragmas. D supports explicit alignment attributes that correspond to the C compiler's rules. Check what alignment the C code is using, and explicitly set it for the D struct declaration. D supports bitfields in the standard library: see [`std.bitmanip.bitfields`](https://dlang.org/phobos/std_bitmanip.html#bitfields). Lifetime Management ------------------- C++ constructors, copy constructors, move constructors and destructors cannot be called directly in D code, and D constructors, postblit operators and destructors cannot be directly exported to C++ code. Interoperation of types with these special operators is possible by either 1) disabling the operator in the client language and only using it in the host language, or 2) faithfully reimplementing the operator in the client language. With the latter approach, care needs to be taken to ensure observable semantics remain the same with both implementations, which can be difficult, or in some edge cases impossible, due to differences in how the operators work in the two languages. For example, in D all objects are movable and there is no move constructor. Special Member Functions ------------------------ D cannot directly call C++ special member functions, and vice versa. These include constructors, destructors, conversion operators, operator overloading, and allocators. Runtime Type Identification --------------------------- D runtime type identification uses completely different techniques than C++. The two are incompatible. Exception Handling ------------------ Exception interoperability is a work in progress. At present, C++ exceptions cannot be caught in or thrown from D, and D exceptions cannot be caught in or thrown from C++. Additionally, objects in C++ stack frames are not guaranteed to be destroyed when unwinding the stack due to a D exception, and vice versa. The plan is to support all of the above except throwing D exceptions directly in C++ code (but they will be throwable indirectly by calling into a D function with C++ linkage). Comparing D Immutable and Const with C++ Const ---------------------------------------------- Const, Immutable Comparison| **Feature** | **D** | **C++98** | | `const` keyword | Yes | Yes | | `immutable` keyword | Yes | No | | const notation | ``` // Functional: //ptr to const ptr to const int const(int*)* p; ``` | ``` // Postfix: //ptr to const ptr to const int const int *const *p; ``` | | transitive const | ``` // Yes: //const ptr to const ptr to const int const int** p; **p = 3; // error ``` | ``` // No: // const ptr to ptr to int int** const p; **p = 3; // ok ``` | | cast away const | ``` // Yes: // ptr to const int const(int)* p; int* q = cast(int*)p; // ok ``` | ``` // Yes: // ptr to const int const int* p; int* q = const_cast<int*>p; //ok ``` | | cast+mutate | ``` // No: // ptr to const int const(int)* p; int* q = cast(int*)p; *q = 3; // undefined behavior ``` | ``` // Yes: // ptr to const int const int* p; int* q = const_cast<int*>p; *q = 3; // ok ``` | | overloading | ``` // Yes: void foo(int x); void foo(const int x); //ok ``` | ``` // No: void foo(int x); void foo(const int x); //error ``` | | const/mutable aliasing | ``` // Yes: void foo(const int* x, int* y) { bar(*x); // bar(3) *y = 4; bar(*x); // bar(4) } ... int i = 3; foo(&i, &i); ``` | ``` // Yes: void foo(const int* x, int* y) { bar(*x); // bar(3) *y = 4; bar(*x); // bar(4) } ... int i = 3; foo(&i, &i); ``` | | immutable/mutable aliasing | ``` // No: void foo(immutable int* x, int* y) { bar(*x); // bar(3) *y = 4; // undefined behavior bar(*x); // bar(??) } ... int i = 3; foo(cast(immutable)&i, &i); ``` | No immutables | | type of string literal | `immutable(char)[]` | `const char*` | | string literal to non-const | not allowed | allowed, but deprecated |
programming_docs
d rt.arraycat rt.arraycat =========== Implementation of array copy support routines. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Walter Bright, Sean Kelly Source [rt/arraycat.d](https://github.com/dlang/druntime/blob/master/src/rt/arraycat.d) d etc.c.odbc.sql etc.c.odbc.sql ============== Declarations for interfacing with the ODBC library. Adapted with minimal changes from the work of David L. Davis (refer to the [original announcement](http://forum.dlang.org/post/cfk7ql&dollar;1p4n&dollar;[email protected])). `etc.c.odbc.sql` is the the main include for ODBC v3.0+ Core functions, corresponding to the `sql.h` C header file. It `import`s `public`ly `etc.c.odbc.sqltypes` for conformity with the C header. Note The ODBC library itself not a part of the `dmd` distribution (and typically not a part of the distribution packages of other compilers such as `gdc` and `ldc`). To use ODBC, install it per the vendor- and platform-specific instructions and then use the appropriate command-line flags (e.g. for dmd, `-L-lodbc` on Posix and `-Lodbc32.lib` on Windows) to link with the ODBC library. On Windows, using `pragma(lib, "odbc32")` in D code at top level is also appropriate. See Also: [ODBC API Reference on MSN Online](https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/odbc-api-reference) d std.experimental.allocator.building_blocks.region std.experimental.allocator.building\_blocks.region ================================================== Source [std/experimental/allocator/building\_blocks/region.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/region.d) struct **Region**(ParentAllocator = NullAllocator, uint minAlign = platformAlignment, Flag!"growDownwards" growDownwards = No.growDownwards); A `Region` allocator allocates memory straight from one contiguous chunk. There is no deallocation, and once the region is full, allocation requests return `null`. Therefore, `Region`s are often used (a) in conjunction with more sophisticated allocators; or (b) for batch-style very fast allocations that deallocate everything at once. The region only stores three pointers, corresponding to the current position in the store and the limits. One allocation entails rounding up the allocation size for alignment purposes, bumping the current pointer, and comparing it against the limit. If `ParentAllocator` is different from [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator), `Region` deallocates the chunk of memory during destruction. The `minAlign` parameter establishes alignment. If `minAlign > 1`, the sizes of all allocation requests are rounded up to a multiple of `minAlign`. Applications aiming at maximum speed may want to choose `minAlign = 1` and control alignment externally. Examples: ``` import std.algorithm.comparison : max; import std.experimental.allocator.building_blocks.allocator_list : AllocatorList; import std.experimental.allocator.mallocator : Mallocator; import std.typecons : Ternary; // Create a scalable list of regions. Each gets at least 1MB at a time by // using malloc. auto batchAllocator = AllocatorList!( (size_t n) => Region!Mallocator(max(n, 1024 * 1024)) )(); writeln(batchAllocator.empty); // Ternary.yes auto b = batchAllocator.allocate(101); writeln(b.length); // 101 writeln(batchAllocator.empty); // Ternary.no // This will cause a second allocation b = batchAllocator.allocate(2 * 1024 * 1024); writeln(b.length); // 2 * 1024 * 1024 // Destructor will free the memory ``` ParentAllocator **parent**; The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`. pure nothrow @nogc this(ubyte[] store); this(size\_t n); this(ParentAllocator parent, size\_t n); Constructs a region backed by a user-provided store. Assumes the memory was allocated with `ParentAllocator` (if different from [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator)). Parameters: | | | | --- | --- | | ubyte[] `store` | User-provided store backing up the region. If `ParentAllocator` is different from [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator), memory is assumed to have been allocated with `ParentAllocator`. | | size\_t `n` | Bytes to allocate using `ParentAllocator`. This constructor is only defined If `ParentAllocator` is different from [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator). If `parent.allocate(n)` returns `null`, the region will be initialized as empty (correctly initialized but unable to allocate). | const pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n); Rounds the given size to a multiple of the `alignment` alias **alignment** = minAlign; Alignment offered. pure nothrow @nogc @trusted void[] **allocate**(size\_t n); Allocates `n` bytes of memory. The shortest path involves an alignment adjustment (if `alignment > 1`), an increment, and a comparison. Parameters: | | | | --- | --- | | size\_t `n` | number of bytes to allocate | Returns: A properly-aligned buffer of size `n` or `null` if request could not be satisfied. pure nothrow @nogc @trusted void[] **alignedAllocate**(size\_t n, uint a); Allocates `n` bytes of memory aligned at alignment `a`. Parameters: | | | | --- | --- | | size\_t `n` | number of bytes to allocate | | uint `a` | alignment for the allocated block | Returns: Either a suitable block of `n` bytes aligned at `a`, or `null`. pure nothrow @nogc @trusted void[] **allocateAll**(); Allocates and returns all memory available to this region. pure nothrow @nogc @safe bool **expand**(ref void[] b, size\_t delta); Expands an allocated block in place. Expansion will succeed only if the block is the last allocated. Defined only if `growDownwards` is `No.growDownwards`. pure nothrow @nogc bool **deallocate**(void[] b); Deallocates `b`. This works only if `b` was obtained as the last call to `allocate`; otherwise (i.e. another allocation has occurred since) it does nothing. Parameters: | | | | --- | --- | | void[] `b` | Block previously obtained by a call to `allocate` against this allocator (`null` is allowed). | pure nothrow @nogc bool **deallocateAll**(); Deallocates all memory allocated by this region, which can be subsequently reused for new allocations. const pure nothrow @nogc @trusted Ternary **owns**(const void[] b); Queries whether `b` has been allocated with this region. Parameters: | | | | --- | --- | | void[] `b` | Arbitrary block of memory (`null` is allowed; `owns(null)` returns `false`). | Returns: `true` if `b` has been allocated with this region, `false` otherwise. const pure nothrow @nogc @safe Ternary **empty**(); Returns `Ternary.yes` if no memory has been allocated in this region, `Ternary.no` otherwise. (Never returns `Ternary.unknown`.) const pure nothrow @nogc @safe size\_t **available**(); Nonstandard property that returns bytes available for allocation. struct **InSituRegion**(size\_t size, size\_t minAlign = platformAlignment); `InSituRegion` is a convenient region that carries its storage within itself (in the form of a statically-sized array). The first template argument is the size of the region and the second is the needed alignment. Depending on the alignment requested and platform details, the actual available storage may be smaller than the compile-time parameter. To make sure that at least `n` bytes are available in the region, use `InSituRegion!(n + a - 1, a)`. Given that the most frequent use of `InSituRegion` is as a stack allocator, it allocates starting at the end on systems where stack grows downwards, such that hot memory is used first. Examples: ``` // 128KB region, allocated to x86's cache line InSituRegion!(128 * 1024, 16) r1; auto a1 = r1.allocate(101); writeln(a1.length); // 101 // 128KB region, with fallback to the garbage collector. import std.experimental.allocator.building_blocks.fallback_allocator : FallbackAllocator; import std.experimental.allocator.building_blocks.free_list : FreeList; import std.experimental.allocator.building_blocks.bitmapped_block : BitmappedBlock; import std.experimental.allocator.gc_allocator : GCAllocator; FallbackAllocator!(InSituRegion!(128 * 1024), GCAllocator) r2; const a2 = r2.allocate(102); writeln(a2.length); // 102 // Reap with GC fallback. InSituRegion!(128 * 1024, 8) tmp3; FallbackAllocator!(BitmappedBlock!(64, 8), GCAllocator) r3; r3.primary = BitmappedBlock!(64, 8)(cast(ubyte[]) (tmp3.allocateAll())); const a3 = r3.allocate(103); writeln(a3.length); // 103 // Reap/GC with a freelist for small objects up to 16 bytes. InSituRegion!(128 * 1024, 64) tmp4; FreeList!(FallbackAllocator!(BitmappedBlock!(64, 64), GCAllocator), 0, 16) r4; r4.parent.primary = BitmappedBlock!(64, 64)(cast(ubyte[]) (tmp4.allocateAll())); const a4 = r4.allocate(104); writeln(a4.length); // 104 ``` alias **alignment** = minAlign; An alias for `minAlign`, which must be a valid alignment (nonzero power of 2). The start of the region and all allocation requests will be rounded up to a multiple of the alignment. ``` InSituRegion!(4096) a1; assert(a1.alignment == platformAlignment); InSituRegion!(4096, 64) a2; assert(a2.alignment == 64); ``` void[] **allocate**(size\_t n); Allocates `bytes` and returns them, or `null` if the region cannot accommodate the request. For efficiency reasons, if `bytes == 0` the function returns an empty non-null slice. void[] **alignedAllocate**(size\_t n, uint a); As above, but the memory allocated is aligned at `a` bytes. bool **deallocate**(void[] b); Deallocates `b`. This works only if `b` was obtained as the last call to `allocate`; otherwise (i.e. another allocation has occurred since) it does nothing. This semantics is tricky and therefore `deallocate` is defined only if `Region` is instantiated with `Yes.defineDeallocate` as the third template argument. Parameters: | | | | --- | --- | | void[] `b` | Block previously obtained by a call to `allocate` against this allocator (`null` is allowed). | pure nothrow @nogc @safe Ternary **owns**(const void[] b); Returns `Ternary.yes` if `b` is the result of a previous allocation, `Ternary.no` otherwise. bool **expand**(ref void[] b, size\_t delta); Expands an allocated block in place. Expansion will succeed only if the block is the last allocated. bool **deallocateAll**(); Deallocates all memory allocated with this allocator. void[] **allocateAll**(); Allocates all memory available with this allocator. size\_t **available**(); Nonstandard function that returns the bytes available for allocation. struct **SbrkRegion**(uint minAlign = platformAlignment); Allocator backed by `[sbrk](https://en.wikipedia.org/wiki/Sbrk)` for Posix systems. Due to the fact that `sbrk` is not thread-safe [by design](http://lifecs.likai.org/2010/02/sbrk-is-not-thread-safe.html), `SbrkRegion` uses a mutex internally. This implies that uncontrolled calls to `brk` and `sbrk` may affect the workings of `SbrkRegion` adversely. static shared SbrkRegion **instance**; Instance shared by all callers. enum uint **alignment**; Standard allocator primitives. shared const pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n); shared nothrow @nogc @trusted void[] **allocate**(size\_t bytes); shared nothrow @nogc @trusted void[] **alignedAllocate**(size\_t bytes, uint a); Rounds the given size to a multiple of thew `alignment` shared nothrow @nogc @trusted bool **expand**(ref void[] b, size\_t delta); shared pure nothrow @nogc @trusted Ternary **owns**(const void[] b); The `expand` method may only succeed if the argument is the last block allocated. In that case, `expand` attempts to push the break pointer to the right. shared nothrow @nogc bool **deallocate**(void[] b); The `deallocate` method only works (and returns `true`) on systems that support reducing the break address (i.e. accept calls to `sbrk` with negative offsets). OSX does not accept such. In addition the argument must be the last block allocated. shared nothrow @nogc bool **deallocateAll**(); The `deallocateAll` method only works (and returns `true`) on systems that support reducing the break address (i.e. accept calls to `sbrk` with negative offsets). OSX does not accept such. shared pure nothrow @nogc @safe Ternary **empty**(); Standard allocator API. struct **SharedRegion**(ParentAllocator = NullAllocator, uint minAlign = platformAlignment, Flag!"growDownwards" growDownwards = No.growDownwards); The threadsafe version of the `Region` allocator. Allocations and deallocations are lock-free based using [`core.atomic.cas`](core_atomic#cas). ParentAllocator **parent**; The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`. pure nothrow @nogc this(ubyte[] store); this(size\_t n); Constructs a region backed by a user-provided store. Assumes the memory was allocated with `ParentAllocator` (if different from [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator)). Parameters: | | | | --- | --- | | ubyte[] `store` | User-provided store backing up the region. If `ParentAllocator` is different from [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator), memory is assumed to have been allocated with `ParentAllocator`. | | size\_t `n` | Bytes to allocate using `ParentAllocator`. This constructor is only defined If `ParentAllocator` is different from [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator). If `parent.allocate(n)` returns `null`, the region will be initialized as empty (correctly initialized but unable to allocate). | const pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n); Rounds the given size to a multiple of the `alignment` alias **alignment** = minAlign; Alignment offered. pure nothrow @nogc @trusted void[] **allocate**(size\_t n); Allocates `n` bytes of memory. The allocation is served by atomically incrementing a pointer which keeps track of the current used space. Parameters: | | | | --- | --- | | size\_t `n` | number of bytes to allocate | Returns: A properly-aligned buffer of size `n`, or `null` if request could not be satisfied. pure nothrow @nogc bool **deallocate**(void[] b); Deallocates `b`. This works only if `b` was obtained as the last call to `allocate`; otherwise (i.e. another allocation has occurred since) it does nothing. Parameters: | | | | --- | --- | | void[] `b` | Block previously obtained by a call to `allocate` against this allocator (`null` is allowed). | pure nothrow @nogc bool **deallocateAll**(); Deallocates all memory allocated by this region, which can be subsequently reused for new allocations. pure nothrow @nogc @trusted void[] **alignedAllocate**(size\_t n, uint a); Allocates `n` bytes of memory aligned at alignment `a`. Parameters: | | | | --- | --- | | size\_t `n` | number of bytes to allocate | | uint `a` | alignment for the allocated block | Returns: Either a suitable block of `n` bytes aligned at `a`, or `null`. const pure nothrow @nogc @trusted Ternary **owns**(const void[] b); Queries whether `b` has been allocated with this region. Parameters: | | | | --- | --- | | void[] `b` | Arbitrary block of memory (`null` is allowed; `owns(null)` returns `false`). | Returns: `true` if `b` has been allocated with this region, `false` otherwise. const pure nothrow @nogc @safe Ternary **empty**(); Returns `Ternary.yes` if no memory has been allocated in this region, `Ternary.no` otherwise. (Never returns `Ternary.unknown`.) d core.stdcpp.exception core.stdcpp.exception ===================== Interface to C++ License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com) Manu Evans Source [core/stdcpp/exception.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/exception.d) alias **terminate\_handler** = extern (C++) void function() nothrow @nogc; nothrow @nogc terminate\_handler **set\_terminate**(terminate\_handler f); nothrow @nogc terminate\_handler **get\_terminate**(); nothrow @nogc void **terminate**(); alias **unexpected\_handler** = extern (C++) void function() @nogc; deprecated nothrow @nogc unexpected\_handler **set\_unexpected**(unexpected\_handler f); deprecated nothrow @nogc unexpected\_handler **get\_unexpected**(); deprecated @nogc void **unexpected**(); nothrow @nogc bool **uncaught\_exception**(); class **exception**; nothrow @nogc this(); const nothrow @nogc const(char)\* **what**(); class **bad\_exception**: core.stdcpp.exception.exception; @nogc this(const(char)\* message = "bad exception"); d Better C Better C ======== **Contents** 1. [Retained Features](#retained) 1. [Running unittests in `-betterC`](#unittests) 2. [Unavailable Features](#consequences) It is straightforward to link C functions and libraries into D programs. But linking D functions and libraries into C programs is not straightforward. D programs generally require: 1. The D runtime library to be linked in, because many features of the core language require runtime library support. 2. The `main()` function to be written in D, to ensure that the required runtime library support is properly initialized. To link D functions and libraries into C programs, it's necessary to only require the C runtime library to be linked in. This is accomplished by defining a subset of D that fits this requirement, called **BetterC**. **Implementation Defined:** **BetterC** is typically enabled by setting the *-betterC* command line flag for the implementation. When **BetterC** is enabled, the predefined <version> `D_BetterC` can be used for conditional compilation. An entire program can be written in **BetterC** by supplying a C `main()` function: ``` extern(C) void main() { import core.stdc.stdio : printf; printf("Hello betterC\n"); } ``` ``` > dmd -betterC hello.d && ./hello Hello betterC ``` Limiting a program to this subset of runtime features is useful when targeting constrained environments where the use of such features is not practical or possible. **BetterC** makes embedding D libraries in existing larger projects easier by: 1. Simplifying the process of integration at the build-system level 2. Removing the need to ensure that Druntime is properly initialized on calls to the library, for situations when an initialization step is not performed or would be difficult to insert before the library is used. 3. Mixing memory management strategies (GC + manual memory management) can be tricky, hence removing D's GC from the equation may be worthwhile sometimes. Retained Features ----------------- Nearly the full language remains available. Highlights include: 1. Unrestricted use of compile-time features 2. Full metaprogramming facilities 3. Nested functions, nested structs, delegates and [lambdas](expression#function_literals) 4. Member functions, constructors, destructors, operating overloading, etc. 5. The full module system 6. Array slicing, and array bounds checking 7. RAII (yes, it can work without exceptions) 8. `scope(exit)` 9. Memory safety protections 10. Interfacing with C++ 11. COM classes and C++ classes 12. `assert` failures are directed to the C runtime library 13. `switch` with strings 14. `final switch` 15. `unittest` 16. [`printf` format validation](interfacetoc#calling_printf) ### Running unittests in `-betterC` While, testing can be done without the *-betterC* flag, it is sometimes desirable to run the testsuite in `-betterC` too. `unittest` blocks can be listed with the [`getUnitTests`](traits#getUnitTests) trait: ``` unittest { assert(0); } extern(C) void main() { static foreach(u; __traits(getUnitTests, __traits(parent, main))) u(); } ``` ``` > dmd -betterC -unittest -run test.d dmd_runpezoXK: foo.d:3: Assertion `0' failed. ``` However, in `-betterC` `assert` expressions don't use Druntime's assert and are directed to `assert` of the C runtime library instead. Unavailable Features -------------------- D features not available with **BetterC**: 1. Garbage Collection 2. TypeInfo and ModuleInfo 3. Classes 4. Built-in threading (e.g. [`core.thread`](https://dlang.org/phobos/core_thread.html)) 5. Dynamic arrays (though slices of static arrays work) and associative arrays 6. Exceptions 7. `synchronized` and [`core.sync`](https://dlang.org/phobos/core_sync.html) 8. Static module constructors or destructors
programming_docs
d Expressions Expressions =========== **Contents** 1. [Definitions and Terms](#definitions-and-terms) 2. [Order Of Evaluation](#order-of-evaluation) 3. [Lifetime of Temporaries](#temporary-lifetime) 4. [Expressions](#expression) 5. [Assign Expressions](#assign_expressions) 1. [Simple Assignment Expression](#simple_assignment_expressions) 2. [Assignment Operator Expressions](#assignment_operator_expressions) 6. [Conditional Expressions](#conditional_expressions) 7. [OrOr Expressions](#oror_expressions) 8. [AndAnd Expressions](#andand_expressions) 9. [Bitwise Expressions](#bitwise_expressions) 1. [Or Expressions](#or_expressions) 2. [Xor Expressions](#xor_expressions) 3. [And Expressions](#and_expressions) 10. [Compare Expressions](#compare_expressions) 11. [Equality Expressions](#equality_expressions) 1. [Identity Expressions](#identity_expressions) 12. [Relational Expressions](#relation_expressions) 1. [Integer comparisons](#integer_comparisons) 2. [Floating point comparisons](#floating-point-comparisons) 3. [Class comparisons](#class-comparisons) 13. [In Expressions](#in_expressions) 14. [Shift Expressions](#shift_expressions) 15. [Add Expressions](#add_expressions) 16. [Cat Expressions](#cat_expressions) 17. [Mul Expressions](#mul_expressions) 18. [Unary Expressions](#unary-expression) 1. [Complement Expressions](#complement_expressions) 2. [New Expressions](#new_expressions) 3. [Delete Expressions](#delete_expressions) 4. [Cast Expressions](#cast_expressions) 19. [Pow Expressions](#pow_expressions) 20. [Postfix Expressions](#postfix_expressions) 21. [Index Expressions](#index_expressions) 22. [Slice Expressions](#slice_expressions) 23. [Primary Expressions](#primary_expressions) 1. [.Identifier](#identifier) 2. [this](#this) 3. [super](#super) 4. [null](#null) 5. [true, false](#true_false) 6. [Character Literals](#character-literal) 7. [String Literals](#string_literals) 8. [Array Literals](#array_literals) 9. [Associative Array Literals](#associative_array_literals) 10. [Function Literals](#function_literals) 11. [Uniform construction syntax for built-in scalar types](#uniform_construction_syntax) 12. [Assert Expressions](#assert_expressions) 13. [Mixin Expressions](#mixin_expressions) 14. [Import Expressions](#import_expressions) 15. [Typeid Expressions](#typeid_expressions) 16. [IsExpression](#is_expression) 24. [Special Keywords](#specialkeywords) 25. [Associativity and Commutativity](#associativity) An expression is a sequence of operators and operands that specifies an evaluation. The syntax, order of evaluation, and semantics of expressions are as follows. Expressions are used to compute values with a resulting type. These values can then be assigned, tested, or ignored. Expressions can also have side effects. Definitions and Terms --------------------- **Definition** (“Full expression”): For any expression *expr*, the full expression of *expr* is defined as follows. If *expr* parses as a subexpression of another expression *expr1*, then the full expression of *expr* is the full expression of *expr1*. Otherwise, *expr* is its own full expression. Each expression has a unique full expression. Example: in the statement `return f() + g() * 2;`, the full expression of `g() * 2` is `f() + g() * 2`, but not the full expression of `f() + g()` because the latter is not parsed as a subexpression. Note: Although the definition is straightforward, a few subtleties exist related to function literals. In the statement `return (() => x + f())() * g();`, the full expression of `f()` is `x + f()`, not the expression passed to `return`. This is because the parent of `x + f()` has function literal type, not expression type. **Definition** (“Lvalue”): The following expressions, and no others, are called lvalue expressions or lvalues: 1. `this` inside `struct` and `union` member functions; 2. a variable or the result of the *DotIdentifier* grammatical construct `.` (left side may be missing) when the rightmost side of the dot is a variable, field (direct or `static`), function name, or invocation of a function that returns by reference; 3. the result of the following expressions: * built-in unary operators `+` (when applied to an lvalue), `*`, `++` (prefix only), `--` (prefix only); * built-in indexing operator `[]` (but not the slicing operator); * built-in assignment binary operators, i.e. `=`, `+=`, `*=`, `/=`, `%=`, `&=`, `|=`, `^=`, `~=`, `<<=`, `>>=`, `>>>=`, and `^^=`; * the ternary operator *e* `?` *e1* `:` *e2* under the following circumstances: 1. *e1* and *e2* are lvalues of the same type; OR 2. One of *e1* and *e2* is an lvalue of type `T` and the other has and `alias this` converting it to `ref T`; 4. user-defined operators if and only if the function called as a result of lowering returns by reference; 5. `mixin` expressions if and only if the compilation of the expression resulting from compiling the argument(s) to `mixin` is an lvalue; 6. `cast(U)` expressions applied to lvalues of type `T` when `T*` is implicitly convertible to `U*`; 7. `cast()` and `cast(`*qualifier list*`)` when applied to an lvalue. **Definition** (“Rvalue”): Expressions that are not lvalues are rvalues. Note: Rvalues include all literals, special value keywords such as `__FILE__` and `__LINE__`, `enum` values, and the result of expressions not defined as lvalues above. The built-in address-of operator (unary `&`) may only be applied to lvalues. **Definition** (“Smallest short-circuit expression”): Given an expression *expr* that is a subexpression of a full expression *fullexpr*, the smallest short-circuit expression, if any, is the shortest subexpression *scexpr* of *fullexpr* that is an [*AndAndExpression*](#AndAndExpression) (`&&`) or an [*OrOrExpression*](#OrOrExpression) (`||`), such that *expr* is a subexpression of *scexpr*. Example: in the expression `((f() * 2 && g()) + 1) || h()`, the smallest short-circuit expression of the subexpression `f() * 2` is `f() * 2 && g()`. In the expression `(f() && g()) + h()`, the subexpression `h()` has no smallest short-circuit expression. Order Of Evaluation ------------------- Built-in prefix unary expressions `++` and `--` are evaluated as if lowered (rewritten) to assignments as follows: `++expr` becomes `((expr) += 1)`, and `--expr` becomes `((expr) -= 1)`. Therefore, the result of prefix `++` and `--` is the lvalue after the side effect has been effected. Built-in postfix unary expressions `++` and `--` are evaluated as if lowered (rewritten) to [lambda](expression#function_literals) invocations as follows: `expr++` becomes `(ref T x){auto t = x; ++x; return t;}(expr)`, and `expr--` becomes `(ref T x){auto t = x; --x; return t;}(expr)`. Therefore, the result of postfix `++` and `--` is an rvalue just before the side effect has been effected. Binary expressions except for [*AssignExpression*](#AssignExpression), [*OrOrExpression*](#OrOrExpression), and [*AndAndExpression*](#AndAndExpression) are evaluated in lexical order (left-to-right). Example: ``` int i = 2; i = ++i * i++ + i; assert(i == 3 * 3 + 4); ``` [*OrOrExpression*](#OrOrExpression) and [*AndAndExpression*](#AndAndExpression) evaluate their left-hand side argument first. Then, [*OrOrExpression*](#OrOrExpression) evaluates its right-hand side if and only if its left-hand side does not evaluate to nonzero. [*AndAndExpression*](#AndAndExpression) evaluates its right-hand side if and only if its left-hand side evaluates to nonzero. [*ConditionalExpression*](#ConditionalExpression) evaluates its left-hand side argument first. Then, if the result is nonzero, the second operand is evaluated. Otherwise, the third operand is evaluated. Calls to functions with `extern(D)` [linkage](attribute#linkage) (which is the default linkage) are evaluated in the following order: first, if necessary, the address of the function to call is evaluated (e.g. in the case of a computed function pointer or delegate). Then, arguments are evaluated left to right. Finally, transfer is passed to the function. Example: ``` import std.stdio; void function(int a, int b, int c) fun() { writeln("fun() called"); static void r(int a, int b, int c) { writeln("callee called"); } return &r; } int f1() { writeln("f1() called"); return 1; } int f2() { writeln("f2() called"); return 2; } int f3(int x) { writeln("f3() called"); return x + 3; } int f4() { writeln("f4() called"); return 4; } // evaluates fun() then f1() then f2() then f3() then f4() // after which control is transferred to the callee fun()(f1(), f3(f2()), f4()); ``` **Implementation Defined:** 1. The order of evaluation of the operands of [*AssignExpression*](#AssignExpression). 2. The order of evaluation of function arguments for functions with linkage other than `extern (D)`. **Best Practices:** Even though the order of evaluation is well-defined, writing code that depends on it is rarely recommended. Lifetime of Temporaries ----------------------- Expressions and statements may create and/or consume rvalues. Such values are called *temporaries* and do not have a name or a visible scope. Their lifetime is managed automatically as defined in this section. For each evaluation that yields a temporary value, the lifetime of that temporary begins at the evaluation point, similarly to creation of a usual named value initialized with an expression. Termination of lifetime of temporaries does not obey the customary scoping rules and is defined as follows: * If: 1. the full expression has a smallest short-circuit expression *expr*; and 2. the temporary is created on the right-hand side of the `&&` or `||` operator; and 3. the right-hand side is evaluated, then temporary destructors are evaluated right after the right-hand side expression has been evaluated and converted to `bool`. Evaluation of destructors proceeds in reverse order of construction. * For all other cases, the temporaries generated for the purpose of invoking functions are deferred to the end of the full expression. The order of destruction is inverse to the order of construction. If a subexpression of an expression throws an exception, all temporaries created up to the evaluation of that subexpression will be destroyed per the rules above. No destructor calls will be issued for temporaries not yet constructed. Note: An intuition behind these rules is that destructors of temporaries are deferred to the end of full expression and in reverse order of construction, with the exception that the right-hand side of `&&` and `||` are considered their own full expressions even when part of larger expressions. Note: The ternary expression *e1 ? e2 : e3* is not a special case although it evaluates expressions conditionally: *e1* and one of *e2* and *e3* may create temporaries. Their destructors are inserted to the end of the full expression in the reverse order of creation. Example: ``` import std.stdio; struct S { int x; this(int n) { x = n; writefln("S(%s)", x); } ~this() { writefln("~S(%s)", x); } } bool b = (S(1) == S(2) || S(3) != S(4)) && S(5) == S(6); ``` The output of the code above is: ``` S(1) S(2) S(3) S(4) ~S(4) ~S(3) S(5) S(6) ~S(6) ~S(5) ~S(2) ~S(1) ``` First, `S(1)` and `S(2)` are evaluated in lexical order. Per the rules, they will be destroyed at the end of the full expression and in reverse order. The comparison `S(1) == S(2)` yields `false`, so the right-hand side of the `||` is evaluated causing `S(3)` and `S(4)` to be evaluated, also in lexical order. However, their destruction is not deferred to the end of the full expression. Instead, `S(4)` and then `S(3)` are destroyed at the end of the `||` expression. Following their destruction, `S(5)` and `S(6)` are constructed in lexical order. Again they are not destroyed at the end of the full expression, but right at the end of the `&&` expression. Consequently, the destruction of `S(6)` and `S(5)` is carried before that of `S(2)` and `S(1)`. Expressions ----------- ``` Expression: CommaExpression CommaExpression: AssignExpression AssignExpression , CommaExpression ``` The left operand of the `,` is evaluated, then the right operand is evaluated. The type of the expression is the type of the right operand, and the result is the result of the right operand. Using the result of comma expressions isn't allowed. Assign Expressions ------------------ ``` AssignExpression: ConditionalExpression ConditionalExpression = AssignExpression ConditionalExpression += AssignExpression ConditionalExpression -= AssignExpression ConditionalExpression *= AssignExpression ConditionalExpression /= AssignExpression ConditionalExpression %= AssignExpression ConditionalExpression &= AssignExpression ConditionalExpression |= AssignExpression ConditionalExpression ^= AssignExpression ConditionalExpression ~= AssignExpression ConditionalExpression <<= AssignExpression ConditionalExpression >>= AssignExpression ConditionalExpression >>>= AssignExpression ConditionalExpression ^^= AssignExpression ``` For all assign expressions, the left operand must be a modifiable lvalue. The type of the assign expression is the type of the left operand, and the value is the value of the left operand after assignment occurs. The resulting expression is a modifiable lvalue. **Undefined Behavior:** If either operand is a reference type and one of the following: 1. the operands have partially overlapping storage 2. the operands' storage overlaps exactly but the types are different **Implementation Defined:** If neither operand is a reference type and one of the following: 1. the operands have partially overlapping storage 2. the operands' storage overlaps exactly but the types are different ### Simple Assignment Expression If the operator is `=` then it is simple assignment. The right operand is implicitly converted to the type of the left operand, and assigned to it. If the left and right operands are of the same struct type, and the struct type has a [*Postblit*](struct#Postblit), then the copy operation is as described in [Struct Postblit](struct#struct-postblit). If the lvalue is the `.length` property of a dynamic array, the behavior is as described in [Setting Dynamic Array Length](array#resize). If the lvalue is a static array or a slice, the behavior is as described in [Array Copying](array#array-copying) and [Array Setting](array#array-setting). If the lvalue is a user-defined property, the behavior is as described in [Property Functions](function#property-functions). ### Assignment Operator Expressions For arguments of built-in types, assignment operator expressions such as ``` a op= b ``` are semantically equivalent to: ``` a = cast(typeof(a))(a op b) ``` except that * operand `a` is only evaluated once, * overloading *op* uses a different function than overloading *op*= does, and * the left operand of `>>>=` does not undergo [Integer Promotions](type#integer-promotions) before shifting. For user-defined types, assignment operator expressions are overloaded separately from the binary operator. Still the left operand must be an lvalue. Conditional Expressions ----------------------- ``` ConditionalExpression: OrOrExpression OrOrExpression ? Expression : ConditionalExpression ``` The first expression is converted to `bool`, and is evaluated. If it is `true`, then the second expression is evaluated, and its result is the result of the conditional expression. If it is `false`, then the third expression is evaluated, and its result is the result of the conditional expression. If either the second or third expressions are of type `void`, then the resulting type is `void`. Otherwise, the second and third expressions are implicitly converted to a common type which becomes the result type of the conditional expression. **Note:** When a conditional expression is the left operand of an [assign expression](#assign_expressions), parentheses are required for disambiguation: ``` bool test; int a, b, c; ... test ? a = b : c = 2; // Deprecated (test ? a = b : c) = 2; // Equivalent ``` This makes the intent clearer, because the first statement can easily be misread as the following code: ``` test ? a = b : (c = 2); ``` OrOr Expressions ---------------- ``` OrOrExpression: AndAndExpression OrOrExpression || AndAndExpression ``` The result type of an *OrOrExpression* is `bool`, unless the right operand has type `void`, when the result is type `void`. The *OrOrExpression* evaluates its left operand. If the left operand, converted to type `bool`, evaluates to `true`, then the right operand is not evaluated. If the result type of the *OrOrExpression* is `bool` then the result of the expression is `true`. If the left operand is `false`, then the right operand is evaluated. If the result type of the *OrOrExpression* is `bool` then the result of the expression is the right operand converted to type `bool`. AndAnd Expressions ------------------ ``` AndAndExpression: OrExpression AndAndExpression && OrExpression ``` The result type of an *AndAndExpression* is `bool`, unless the right operand has type `void`, when the result is type `void`. The *AndAndExpression* evaluates its left operand. If the left operand, converted to type `bool`, evaluates to `false`, then the right operand is not evaluated. If the result type of the *AndAndExpression* is `bool` then the result of the expression is `false`. If the left operand is `true`, then the right operand is evaluated. If the result type of the *AndAndExpression* is `bool` then the result of the expression is the right operand converted to type `bool`. Bitwise Expressions ------------------- Bit wise expressions perform a bitwise operation on their operands. Their operands must be integral types. First, the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions) are done. Then, the bitwise operation is done. ### Or Expressions ``` OrExpression: XorExpression OrExpression | XorExpression ``` The operands are OR'd together. ### Xor Expressions ``` XorExpression: AndExpression XorExpression ^ AndExpression ``` The operands are XOR'd together. ### And Expressions ``` AndExpression: CmpExpression AndExpression & CmpExpression ``` The operands are AND'd together. Compare Expressions ------------------- ``` CmpExpression: ShiftExpression EqualExpression IdentityExpression RelExpression InExpression ``` Equality Expressions -------------------- ``` EqualExpression: ShiftExpression == ShiftExpression ShiftExpression != ShiftExpression ``` Equality expressions compare the two operands for equality (`==`) or inequality (`!=`). The type of the result is `bool`. Inequality is defined as the logical negation of equality. If the operands are integral values, the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions) are applied to bring them to a common type before comparison. Equality is defined as the bit patterns of the common type match exactly. If the operands are pointers, equality is defined as the bit patterns of the operands match exactly. For float, double, and real values, the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions) are applied to bring them to a common type before comparison. The values `-0` and `+0` are considered equal. If either or both operands are NAN, then `==` returns false and `!=` returns `true`. Otherwise, the bit patterns of the common type are compared for equality. For complex numbers, equality is defined as equivalent to: ``` x.re == y.re && x.im == y.im ``` For struct objects, equality means the result of the [`opEquals()` member function](operatoroverloading#equals). If an `opEquals()` is not provided, equality is defined as the logical product of all equality results of the corresponding object fields. **Implementation Defined:** The contents of any alignment gaps in the struct object. **Best Practices:** If there are overlapping fields, which happens with unions, the default equality will compare each of the overlapping fields. An `opEquals()` can account for which of the overlapping fields contains valid data. An `opEquals()` can override the default behavior of floating point NaN values always comparing as unequal. Be careful using `memcmp()` to implement `opEquals()` if: * there are any alignment gaps * if any fields have an `opEquals()` * there are any floating point fields that may contain NaN or `-0` values For class and struct objects, the expression `(a == b)` is rewritten as `a.opEquals(b)`, and `(a != b)` is rewritten as `!a.opEquals(b)`. For class objects, the `==` and `!=` operators are intended to compare the contents of the objects, however an appropriate `opEquals` override must be defined for this to work. The default `opEquals` provided by the root `Object` class is equivalent to the `is` operator. Comparing against `null` is invalid, as `null` has no contents. Use the `is` and `!is` operators instead. ``` class C; C c; if (c == null) // error ... if (c is null) // ok ... ``` For static and dynamic arrays, equality is defined as the lengths of the arrays matching, and all the elements are equal. ### Identity Expressions ``` IdentityExpression: ShiftExpression is ShiftExpression ShiftExpression !is ShiftExpression ``` The `is` compares for identity. To compare for nonidentity, use `e1 !is e2`. The type of the result is `bool`. The operands undergo the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions) to bring them to a common type before comparison. For class objects, identity is defined as the object references are for the same object. Null class objects can be compared with `is`. For struct objects and floating point values, identity is defined as the bits in the operands being identical. For static and dynamic arrays, identity is defined as referring to the same array elements and the same number of elements. For other operand types, identity is defined as being the same as equality. The identity operator `is` cannot be overloaded. Relational Expressions ---------------------- ``` RelExpression: ShiftExpression < ShiftExpression ShiftExpression <= ShiftExpression ShiftExpression > ShiftExpression ShiftExpression >= ShiftExpression ``` First, the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions) are done on the operands. The result type of a relational expression is `bool`. For class objects, the result of Object.opCmp() forms the left operand, and 0 forms the right operand. The result of the relational expression (o1 op o2) is: ``` (o1.opCmp(o2) op 0) ``` It is an error to compare objects if one is `null`. For static and dynamic arrays, the result of the relational op is the result of the operator applied to the first non-equal element of the array. If two arrays compare equal, but are of different lengths, the shorter array compares as "less" than the longer array. ### Integer comparisons Integer comparisons happen when both operands are integral types. Integer comparison operators| **Operator** | **Relation** | | `<` | less | | `>` | greater | | `<``=` | less or equal | | `>=` | greater or equal | | `==` | equal | | `!=` | not equal | It is an error to have one operand be signed and the other unsigned for a `<`, `<``=`, `>` or `>``=` expression. Use casts to make both operands signed or both operands unsigned. ### Floating point comparisons If one or both operands are floating point, then a floating point comparison is performed. A relational operator can have `NaN` operands. If either or both operands is `NaN`, the floating point comparison operation returns as follows: Floating point comparison operators| **Operator** | **Relation** | **Returns** | | `<` | less | `false` | | `>` | greater | `false` | | `<``=` | less or equal | `false` | | `>=` | greater or equal | `false` | | `==` | equal | `false` | | `!=` | unordered, less, or greater | `true` | ### Class comparisons For class objects, the relational operators compare the contents of the objects. Therefore, comparing against `null` is invalid, as `null` has no contents. ``` class C; C c; if (c < null) // error ... ``` In Expressions -------------- ``` InExpression: ShiftExpression in ShiftExpression ShiftExpression !in ShiftExpression ``` An associative array can be tested to see if an element is in the array: ``` int foo[string]; ... if ("hello" in foo) ... ``` The `in` expression has the same precedence as the relational expressions `<`, `<``=`, etc. The return value of the *InExpression* is `null` if the element is not in the array; if it is in the array it is a pointer to the element. The `!in` expression is the logical negation of the `in` operation. Shift Expressions ----------------- ``` ShiftExpression: AddExpression ShiftExpression << AddExpression ShiftExpression >> AddExpression ShiftExpression >>> AddExpression ``` The operands must be integral types, and undergo the [Integer Promotions](type#integer-promotions). The result type is the type of the left operand after the promotions. The result value is the result of shifting the bits by the right operand's value. `<``<` is a left shift. `>``>` is a signed right shift. `>``>``>` is an unsigned right shift. It's illegal to shift by the same or more bits than the size of the quantity being shifted: ``` int c; auto x = c << 33; // error ``` Add Expressions --------------- ``` AddExpression: MulExpression AddExpression + MulExpression AddExpression - MulExpression CatExpression ``` If the operands are of integral types, they undergo the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions), and then are brought to a common type using the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions). If either operand is a floating point type, the other is implicitly converted to floating point and they are brought to a common type via the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions). If the operator is `+` or `-`, and the first operand is a pointer, and the second is an integral type, the resulting type is the type of the first operand, and the resulting value is the pointer plus (or minus) the second operand multiplied by the size of the type pointed to by the first operand. If the second operand is a pointer, and the first is an integral type, and the operator is `+`, the operands are reversed and the pointer arithmetic just described is applied. If both operands are pointers, and the operator is `+`, then it is illegal. If both operands are pointers, and the operator is `-`, the pointers are subtracted and the result is divided by the size of the type pointed to by the operands. In this calculation the assumed size of `void` is one byte. It is an error if the pointers point to different types. The type of the result is `ptrdiff_t`. If both operands are of integral types and an overflow or underflow occurs in the computation, wrapping will happen. For example, `uint.max + 1 == uint.min`, `uint.min - 1 == uint.max`, `int.max + 1 == int.min`, and `int.min - 1 == int.max`. Add expressions for floating point operands are not associative. Cat Expressions --------------- ``` CatExpression: AddExpression ~ MulExpression ``` A *CatExpression* concatenates arrays, producing a dynamic array with the result. The arrays must be arrays of the same element type. If one operand is an array and the other is of that array's element type, that element is converted to an array of length 1 of that element, and then the concatenation is performed. Mul Expressions --------------- ``` MulExpression: UnaryExpression MulExpression * UnaryExpression MulExpression / UnaryExpression MulExpression % UnaryExpression ``` The operands must be arithmetic types. They undergo the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions). For integral operands, the `*`, `/`, and `%` correspond to multiply, divide, and modulus operations. For multiply, overflows are ignored and simply chopped to fit into the integral type. For integral operands of the `/` and `%` operators, the quotient rounds towards zero and the remainder has the same sign as the dividend. The following divide or modulus integral operands: * denominator is 0 * signed `int.min` is the numerator and `-1` is the denominator * signed `long.min` is the numerator and `-1L` is the denominator are illegal if encountered during Compile Time Execution. **Undefined Behavior:** is exhibited if they are encountered during run time. [`core.checkedint`](https://dlang.org/phobos/core_checkedint.html) can be used to check for them and select a defined behavior. For floating point operands, the \* and / operations correspond to the IEEE 754 floating point equivalents. % is not the same as the IEEE 754 remainder. For example, 15.0 % 10.0 == 5.0, whereas for IEEE 754, remainder(15.0,10.0) == -5.0. Mul expressions for floating point operands are not associative. Unary Expressions ----------------- ``` UnaryExpression: & UnaryExpression ++ UnaryExpression -- UnaryExpression * UnaryExpression - UnaryExpression + UnaryExpression ! UnaryExpression ComplementExpression ( Type ) . Identifier ( Type ) . TemplateInstance DeleteExpression CastExpression PowExpression ``` ### Complement Expressions ``` ComplementExpression: ~ UnaryExpression ``` *ComplementExpression*s work on integral types (except `bool`). All the bits in the value are complemented. **Note:** the usual [Integer Promotions](type#integer-promotions) are not performed prior to the complement operation. ### New Expressions ``` NewExpression: new AllocatorArgumentsopt Type NewExpressionWithArgs NewExpressionWithArgs: new AllocatorArgumentsopt Type [ AssignExpression ] new AllocatorArgumentsopt Type ( ArgumentListopt ) NewAnonClassExpression AllocatorArguments: ( ArgumentListopt ) ArgumentList: AssignExpression AssignExpression , AssignExpression , ArgumentList ``` *NewExpression*s are used to allocate memory on the garbage collected heap (default) or using a class or struct specific allocator. To allocate multidimensional arrays, the declaration reads in the same order as the prefix array declaration order. ``` char[][] foo; // dynamic array of strings ... foo = new char[][30]; // allocate array of 30 strings ``` The above allocation can also be written as: ``` foo = new char[][](30); // allocate array of 30 strings ``` To allocate the nested arrays, multiple arguments can be used: ``` int[][][] bar; ... bar = new int[][][](5, 20, 30); ``` The code above is equivalent to: ``` bar = new int[][][5]; foreach (ref a; bar) { a = new int[][20]; foreach (ref b; a) { b = new int[30]; } } ``` If there is a `new (` [*ArgumentList*](#ArgumentList) `)`, then those arguments are passed to the class or struct specific [allocator function](class#allocators) after the size argument. If a *NewExpression* is used as an initializer for a function local variable with `scope` storage class, and the [*ArgumentList*](#ArgumentList) to `new` is empty, then the instance is allocated on the stack rather than the heap or using the class specific allocator. ### Delete Expressions ``` DeleteExpression: delete UnaryExpression ``` NOTE: `delete` has been deprecated. Instead, please use [`destroy`](https://dlang.org/phobos/object.html#destroy) if feasible, or [`core.memory.__delete`](https://dlang.org/phobos/core_memory.html#__delete) as a last resort. If the *UnaryExpression* is a class object reference, and there is a destructor for that class, the destructor is called for that object instance. Next, if the *UnaryExpression* is a class object reference, or a pointer to a struct instance, and the class or struct has overloaded operator delete, then that operator delete is called for that class object instance or struct instance. Otherwise, the garbage collector is called to immediately free the memory allocated for the class instance or struct instance. If the *UnaryExpression* is a pointer or a dynamic array, the garbage collector is called to immediately release the memory. The pointer, dynamic array, or reference is set to `null` after the delete is performed. Any attempt to reference the data after the deletion via another reference to it will result in undefined behavior. If *UnaryExpression* is a variable allocated on the stack, the class destructor (if any) is called for that instance. Neither the garbage collector nor any class deallocator is called. **Undefined Behavior:** 1. Using `delete` to free memory not allocated by the garbage collector. 2. Referring to data that has been the operand of `delete`. ### Cast Expressions ``` CastExpression: cast ( Type ) UnaryExpression cast ( TypeCtorsopt ) UnaryExpression ``` A *CastExpression* converts the *UnaryExpression* to [*Type*](type#Type). ``` cast(foo) -p; // cast (-p) to type foo (foo) - p; // subtract p from foo ``` Any casting of a class reference to a derived class reference is done with a runtime check to make sure it really is a downcast. `null` is the result if it isn't. ``` class A { ... } class B : A { ... } void test(A a, B b) { B bx = a; // error, need cast B bx = cast(B) a; // bx is null if a is not a B A ax = b; // no cast needed A ax = cast(A) b; // no runtime check needed for upcast } ``` In order to determine if an object `o` is an instance of a class `B` use a cast: ``` if (cast(B) o) { // o is an instance of B } else { // o is not an instance of B } ``` Casting a pointer type to and from a class type is done as a type paint (i.e. a reinterpret cast). Casting a dynamic array to another dynamic array is done only if the array lengths multiplied by the element sizes match. The cast is done as a type paint, with the array length adjusted to match any change in element size. If there's not a match, a runtime error is generated. ``` import std.stdio; int main() { byte[] a = [1,2,3]; auto b = cast(int[])a; // runtime array cast misalignment int[] c = [1, 2, 3]; auto d = cast(byte[])c; // ok // prints: // [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0] writeln(d); return 0; } ``` Casting a static array to another static array is done only if the array lengths multiplied by the element sizes match; a mismatch is illegal. The cast is done as a type paint (aka a reinterpret cast). The contents of the array are not changed. ``` import core.stdc.stdio; void main() { byte[16] b = 3; int[4] ia = cast(int[4]) b; foreach (i; ia) printf("%x\n", i); /* prints: 3030303 3030303 3030303 3030303 */ } ``` Casting a floating point literal from one type to another changes its type, but internally it is retained at full precision for the purposes of constant folding. ``` void test() { real a = 3.40483L; real b; b = 3.40483; // literal is not truncated to double precision assert(a == b); assert(a == 3.40483); assert(a == 3.40483L); assert(a == 3.40483F); double d = 3.40483; // truncate literal when assigned to variable assert(d != a); // so it is no longer the same const double x = 3.40483; // assignment to const is not assert(x == a); // truncated if the initializer is visible } ``` Casting a floating point value to an integral type is the equivalent of converting to an integer using truncation. ``` void main() { int a = cast(int) 0.8f; assert(a == 0); long b = cast(long) 1.5; assert(b == 1L); long c = cast(long) -1.5; assert(c == -1); } ``` Casting a value *v* to a struct *S*, when value is not a struct of the same type, is equivalent to: ``` S(v) ``` Casting to a [*CastQual*](#CastQual) replaces the qualifiers to the type of the [*UnaryExpression*](#UnaryExpression). ``` shared int x; assert(is(typeof(cast(const)x) == const int)); ``` Casting with no [*Type*](#Type) or [*CastQual*](#CastQual) removes any top level `const`, `immutable`, `shared` or `inout` type modifiers from the type of the [*UnaryExpression*](#UnaryExpression). ``` shared int x; assert(is(typeof(cast()x) == int)); ``` Casting an expression to `void` type is allowed to mark that the result is unused. On [*ExpressionStatement*](statement#ExpressionStatement), it could be used properly to avoid "has no effect" error. ``` void foo(lazy void exp) {} void main() { foo(10); // NG - has no effect in expression '10' foo(cast(void)10); // OK } ``` Pow Expressions --------------- ``` PowExpression: PostfixExpression PostfixExpression ^^ UnaryExpression ``` *PowExpression* raises its left operand to the power of its right operand. Postfix Expressions ------------------- ``` PostfixExpression: PrimaryExpression PostfixExpression . Identifier PostfixExpression . TemplateInstance PostfixExpression . NewExpression PostfixExpression ++ PostfixExpression -- PostfixExpression ( ArgumentListopt ) TypeCtorsopt BasicType ( ArgumentListopt ) IndexExpression SliceExpression ``` Index Expressions ----------------- ``` IndexExpression: PostfixExpression [ ArgumentList ] ``` *PostfixExpression* is evaluated. If *PostfixExpression* is an expression of type static array or dynamic array, the symbol &dollar; is set to be the number of elements in the array. If *PostfixExpression* is a *ValueSeq*, the symbol &dollar; is set to be the number of elements in the sequence. A new declaration scope is created for the evaluation of the [*ArgumentList*](#ArgumentList) and &dollar; appears in that scope only. If *PostfixExpression* is a *ValueSeq*, then the [*ArgumentList*](#ArgumentList) must consist of only one argument, and that must be statically evaluatable to an integral constant. That integral constant *n* then selects the *n*th expression in the *ValueSeq*, which is the result of the *IndexExpression*. It is an error if *n* is out of bounds of the *ValueSeq*. Slice Expressions ----------------- ``` SliceExpression: PostfixExpression [ ] PostfixExpression [ Slice ,opt ] Slice: AssignExpression AssignExpression , Slice AssignExpression .. AssignExpression AssignExpression .. AssignExpression , Slice ``` *PostfixExpression* is evaluated. if *PostfixExpression* is an expression of type static array or dynamic array, the special variable &dollar; is declared and set to be the length of the array. A new declaration scope is created for the evaluation of the [*AssignExpression*](#AssignExpression)..[*AssignExpression*](#AssignExpression) and &dollar; appears in that scope only. The first *AssignExpression* is taken to be the inclusive lower bound of the slice, and the second *AssignExpression* is the exclusive upper bound. The result of the expression is a slice of the *PostfixExpression* array. If the `[ ]` form is used, the slice is of the entire array. The type of the slice is a dynamic array of the element type of the *PostfixExpression*. A *SliceExpression* is not a modifiable lvalue. If the slice bounds can be known at compile time, the slice expression is implicitly convertible to an lvalue of static array. For example: ``` arr[a .. b] // typed T[] ``` If both `a` and `b` are integers (may be constant-folded), the slice expression can be converted to a static array type `T[b - a]`. ``` void foo(int[2] a) { assert(a == [2, 3]); } void bar(ref int[2] a) { assert(a == [2, 3]); a[0] = 4; a[1] = 5; assert(a == [4, 5]); } void baz(int[3] a) {} void main() { int[] arr = [1, 2, 3]; foo(arr[1 .. 3]); assert(arr == [1, 2, 3]); bar(arr[1 .. 3]); assert(arr == [1, 4, 5]); //baz(arr[1 .. 3]); // cannot match length } ``` The following forms of slice expression can be convertible to a static array type: `e` An expression that contains no side effects. `a`, `b` Integers (that may be constant-folded). Computing array lengths during compilation| **Form** | **The length calculated at compile time** | | `arr[]` | The compile time length of `arr` if it's known. | | `arr[a .. b]` | `b - a` | | `arr[e-a .. e]` | `a` | | `arr[e .. e+b]` | `b` | | `arr[e-a .. e+b]` | `a + b` | | `arr[e+a .. e+b]` | `b - a` *if* `a <= b` | | `arr[e-a .. e-b]` | `a - b` *if* `a >= b` | If *PostfixExpression* is a *ValueSeq*, then the result of the slice is a new *ValueSeq* formed from the upper and lower bounds, which must statically evaluate to integral constants. It is an error if those bounds are out of range. Primary Expressions ------------------- ``` PrimaryExpression: Identifier . Identifier TemplateInstance . TemplateInstance this super null true false $ IntegerLiteral FloatLiteral CharacterLiteral StringLiterals ArrayLiteral AssocArrayLiteral FunctionLiteral AssertExpression MixinExpression ImportExpression NewExpressionWithArgs FundamentalType . Identifier FundamentalType ( ArgumentListopt ) TypeCtor ( Type ) . Identifier TypeCtor ( Type ) ( ArgumentListopt ) Typeof TypeidExpression IsExpression ( Expression ) SpecialKeyword TraitsExpression ``` ### .Identifier [*Identifier*](lex#Identifier) is looked up at module scope, rather than the current lexically nested scope. ### this Within a non-static member function, `this` resolves to a reference to the object for which the function was called. If the object is an instance of a struct, `this` will be a pointer to that instance. If a member function is called with an explicit reference to `typeof(this)`, a non-virtual call is made: ``` class A { char get() { return 'A'; } char foo() { return typeof(this).get(); } char bar() { return this.get(); } } class B : A { override char get() { return 'B'; } } void main() { B b = new B(); assert(b.foo() == 'A'); assert(b.bar() == 'B'); } ``` Assignment to `this` is not allowed. ### super `super` is identical to `this`, except that it is cast to `this`'s base class. It is an error if there is no base class. It is an error to use `super` within a struct member function. (Only class `Object` has no base class.) If a member function is called with an explicit reference to `super`, a non-virtual call is made. Assignment to `super` is not allowed. ### null `null` represents the null value for pointers, pointers to functions, delegates, dynamic arrays, associative arrays, and class objects. If it has not already been cast to a type, it is given the singular type `typeof(null)` and it is an exact conversion to convert it to the null value for pointers, pointers to functions, delegates, etc. After it is cast to a type, such conversions are implicit, but no longer exact. ### true, false These are of type `bool` and when cast to another integral type become the values 1 and 0, respectively. ### Character Literals Character literals are single characters and resolve to one of type `char`, `wchar`, or `dchar`. If the literal is a `\u` escape sequence, it resolves to type `wchar`. If the literal is a `\U` escape sequence, it resolves to type `dchar`. Otherwise, it resolves to the type with the smallest size it will fit into. ### String Literals ``` StringLiterals: StringLiteral StringLiterals StringLiteral ``` String literals can implicitly convert to any of the following types, they have equal weight: | | | --- | | `immutable(char)*` | | `immutable(wchar)*` | | `immutable(dchar)*` | | `immutable(char)[]` | | `immutable(wchar)[]` | | `immutable(dchar)[]` | By default, a string literal is typed as a dynamic array, but the element count is known at compile time. So all string literals can be implicitly converted to static array types. ``` void foo(char[2] a) { assert(a == "bc"); } void bar(ref const char[2] a) { assert(a == "bc"); } void baz(const char[3] a) {} void main() { string str = "abc"; foo(str[1 .. 3]); bar(str[1 .. 3]); //baz(str[1 .. 3]); // cannot match length } ``` String literals have a 0 appended to them, which makes them easy to pass to C or C++ functions expecting a `const char*` string. The 0 is not included in the `.length` property of the string literal. ### Array Literals ``` ArrayLiteral: [ ArgumentListopt ] ``` Array literals are a comma-separated list of [*AssignExpression*](#AssignExpression)s between square brackets `[` and `]`. The *AssignExpression*s form the elements of a dynamic array, the length of the array is the number of elements. The common type of the all elements is taken to be the type of the array element, and all elements are implicitly converted to that type. ``` auto a1 = [1,2,3]; // type is int[], with elements 1, 2 and 3 auto a2 = [1u,2,3]; // type is uint[], with elements 1u, 2u, and 3u ``` By default, an array literal is typed as a dynamic array, but the element count is known at compile time. So all array literals can be implicitly converted to static array types. ``` void foo(long[2] a) { assert(a == [2, 3]); } void bar(ref long[2] a) { assert(a == [2, 3]); a[0] = 4; a[1] = 5; assert(a == [4, 5]); } void baz(const char[3] a) {} void main() { long[] arr = [1, 2, 3]; foo(arr[1 .. 3]); assert(arr == [1, 2, 3]); bar(arr[1 .. 3]); assert(arr == [1, 4, 5]); //baz(arr[1 .. 3]); // cannot match length } ``` If any of the arguments in the [*ArgumentList*](#ArgumentList) are a *ValueSeq*, then the elements of the *ValueSeq* are inserted as arguments in place of the sequence. Array literals are allocated on the memory managed heap. Thus, they can be returned safely from functions: ``` int[] foo() { return [1, 2, 3]; } ``` When array literals are cast to another array type, each element of the array is cast to the new element type. When arrays that are not literals are cast, the array is reinterpreted as the new type, and the length is recomputed: ``` import std.stdio; void main() { // cast array literal const short[] ct = cast(short[]) [cast(byte)1, 1]; // this is equivalent with: // const short[] ct = [cast(short)1, cast(short)1]; writeln(ct); // writes [1, 1] // cast other array expression // --> normal behavior of CastExpression byte[] arr = [cast(byte)1, cast(byte)1]; short[] rt = cast(short[]) arr; writeln(rt); // writes [257] } ``` In other words, casting literal expression will change the literal type. ### Associative Array Literals ``` AssocArrayLiteral: [ KeyValuePairs ] KeyValuePairs: KeyValuePair KeyValuePair , KeyValuePairs KeyValuePair: KeyExpression : ValueExpression KeyExpression: AssignExpression ValueExpression: AssignExpression ``` Associative array literals are a comma-separated list of *key*`:`*value* pairs between square brackets `[` and `]`. The list cannot be empty. The common type of the all keys is taken to be the key type of the associative array, and all keys are implicitly converted to that type. The common type of the all values is taken to be the value type of the associative array, and all values are implicitly converted to that type. An *AssocArrayLiteral* cannot be used to statically initialize anything. ``` [21u:"he", 38:"ho", 2:"hi"]; // type is string[uint], // with keys 21u, 38u and 2u // and values "he", "ho", and "hi" ``` If any of the keys or values in the *KeyValuePairs* are a *ValueSeq*, then the elements of the *ValueSeq* are inserted as arguments in place of the sequence. ### Function Literals ``` FunctionLiteral: function refopt Typeopt ParameterWithAttributes opt FunctionLiteralBody2 delegate refopt Typeopt ParameterWithMemberAttributes opt FunctionLiteralBody2 refopt ParameterWithMemberAttributes FunctionLiteralBody2 FunctionLiteralBody Identifier => AssignExpression ParameterWithAttributes: Parameters FunctionAttributesopt ParameterWithMemberAttributes: Parameters MemberFunctionAttributesopt FunctionLiteralBody2: => AssignExpression FunctionLiteralBody FunctionLiteralBody: BlockStatement FunctionContractsopt BodyStatement ``` *FunctionLiteral*s (also known as *Lambdas*) enable embedding anonymous functions and anonymous delegates directly into expressions. *Type* is the return type of the function or delegate, if omitted it is inferred from any *ReturnStatement*s in the *FunctionLiteralBody*. [*ParameterWithAttributes*](#ParameterWithAttributes) or [*ParameterWithMemberAttributes*](#ParameterWithMemberAttributes) can be used to specify the parameters for the function. If these are omitted, the function defaults to the empty parameter list `( )`. The type of a function literal is pointer to function or pointer to delegate. If the keywords `function` or `delegate` are omitted, it is inferred from whether *FunctionLiteralBody* is actually accessing to the outer context. For example: ``` int function(char c) fp; // declare pointer to a function void test() { static int foo(char c) { return 6; } fp = &foo; } ``` is exactly equivalent to: ``` int function(char c) fp; void test() { fp = function int(char c) { return 6;} ; } ``` Also: ``` int abc(int delegate(int i)); void test() { int b = 3; int foo(int c) { return 6 + b; } abc(&foo); } ``` is exactly equivalent to: ``` int abc(int delegate(int i)); void test() { int b = 3; abc( delegate int(int c) { return 6 + b; } ); } ``` and the following where the return type `int` and `function`/`delegate` are inferred: ``` int abc(int delegate(int i)); int def(int function(int s)); void test() { int b = 3; abc( (int c) { return 6 + b; } ); // inferred to delegate def( (int c) { return c * 2; } ); // inferred to function //def( (int c) { return c * b; } ); // error! // Because the FunctionLiteralBody accesses b, then the function literal type // is inferred to delegate. But def cannot receive delegate. } ``` If the type of a function literal can be uniquely determined from its context, the parameter type inference is possible. ``` void foo(int function(int) fp); void test() { int function(int) fp = (n) { return n * 2; }; // The type of parameter n is inferred to int. foo((n) { return n * 2; }); // The type of parameter n is inferred to int. } ``` Anonymous delegates can behave like arbitrary statement literals. For example, here an arbitrary statement is executed by a loop: ``` double test() { double d = 7.6; float f = 2.3; void loop(int k, int j, void delegate() statement) { for (int i = k; i < j; i++) { statement(); } } loop(5, 100, { d += 1; }); loop(3, 10, { f += 3; }); return d + f; } ``` The syntax `=> AssignExpression` is equivalent to `{ return AssignExpression; }`. The syntax `Identifier => AssignExpression` is equivalent to `(Identifier) { return AssignExpression; }`. Example usage: ``` import std.stdio; void main() { auto i = 3; auto twice = function (int x) => x * 2; auto square = delegate (int x) => x * x; auto n = 5; auto mul_n = (int x) => x * n; writeln(twice(i)); // prints 6 writeln(square(i)); // prints 9 writeln(mul_n(i)); // prints 15 } ``` When comparing with [nested functions](function#nested), the `function` form is analogous to static or non-nested functions, and the `delegate` form is analogous to non-static nested functions. In other words, a delegate literal can access stack variables in its enclosing function, a function literal cannot. ### Uniform construction syntax for built-in scalar types The implicit conversions of built-in scalar types can be explicitly represented by using function call syntax. For example: ``` auto a = short(1); // implicitly convert an integer literal '1' to short auto b = double(a); // implicitly convert a short variable 'a' to double auto c = byte(128); // error, 128 cannot be represented in a byte ``` If the argument is omitted, it means default construction of the scalar type: ``` auto a = ushort(); // same as: ushort.init auto b = wchar(); // same as: wchar.init auto c = creal(); // same as: creal.init ``` ### Assert Expressions ``` AssertExpression: assert ( AssertArguments ) AssertArguments: AssignExpression ,opt AssignExpression , AssignExpression ,opt ``` The first *AssignExpression* must evaluate to true. If it does not, an *Assert Failure* has occurred and the program enters an *Invalid State*. If the first *AssignExpression* consists entirely of compile time constants, and evaluates to false, it is a special case; it signifies that it is unreachable code. Compile Time Function Execution (CTFE) is not attempted. *AssertExpression* has different semantics if it is in a [`unittest`](unittest) or [`in` contract](contracts). The second *AssignExpression*, if present, must be implicitly convertible to type `const(char)[]`. If the first *AssignExpression* is a reference to a class instance for which a [Class Invariant](class#invariants) exists, the *Class Invariant* must hold. If the first *AssignExpression* is a pointer to a struct instance for which a *Struct Invariant* exists, the *Struct Invariant* must hold. The type of an *AssertExpression* is `void`. **Undefined Behavior:** Once in an *Invalid State* the behavior of the continuing execution of the program is undefined. **Implementation Defined:** Whether the first *AssertExpression* is evaluated or not at runtime is typically set with a compiler switch. If it is not evaluated, any side effects specified by the *AssertExpression* may not occur. The behavior if the first *AssertExpression* is evaluated and is false is also typically set with a compiler switch and may include these options: 1. continuing execution 2. immediately halting via execution of a special CPU instruction 3. aborting the program 4. calling the assert failure function in the corresponding C runtime library 5. throwing the `AssertError` exception in the D runtime library If the optional second *AssignExpression* is provided, the implementation may evaluate it and print the resulting message upon assert failure: ``` void main() { assert(0, "an" ~ " error message"); } ``` When compiled and run, it will produce the message: ``` [email protected](3) an error message ``` The implementation may handle the case of the first *AssignExpression* evaluating at compile time to false differently in that in release mode it may simply generate a `HLT` instruction or equivalent. **Best Practices:** 1. Do not have side effects in either *AssignExpression* that subsequent code depends on. 2. *AssertExpressions* are intended to detect bugs in the program, do not use for detecting input or environmental errors. 3. Do not attempt to resume normal execution after an *Assert Failure*. ### Mixin Expressions ``` MixinExpression: mixin ( ArgumentList ) ``` Each [*AssignExpression*](#AssignExpression) in the *ArgumentList* is evaluated at compile time, and the result must be representable as a string. The resulting strings are concatenated to form a string. The text contents of the string must be compilable as a valid [*Expression*](#Expression), and is compiled as such. ``` int foo(int x) { return mixin("x +", 1) * 7; // same as ((x + 1) * 7) } ``` ### Import Expressions ``` ImportExpression: import ( AssignExpression ) ``` The *AssignExpression* must evaluate at compile time to a constant string. The text contents of the string are interpreted as a file name. The file is read, and the exact contents of the file become a string literal. Implementations may restrict the file name in order to avoid directory traversal security vulnerabilities. A possible restriction might be to disallow any path components in the file name. Note that by default an import expression will not compile unless one or more paths are passed via the **-J** switch. This tells the compiler where it should look for the files to import. This is a security feature. ``` void foo() { // Prints contents of file foo.txt writeln(import("foo.txt")); } ``` ### Typeid Expressions ``` TypeidExpression: typeid ( Type ) typeid ( Expression ) ``` If *Type*, returns an instance of class [`TypeInfo`](https://dlang.org/phobos/object.html) corresponding to *Type*. If *Expression*, returns an instance of class [`TypeInfo`](https://dlang.org/phobos/object.html) corresponding to the type of the *Expression*. If the type is a class, it returns the `TypeInfo` of the dynamic type (i.e. the most derived type). The *Expression* is always executed. ``` class A { } class B : A { } void main() { writeln(typeid(int)); // int uint i; writeln(typeid(i++)); // uint writeln(i); // 1 A a = new B(); writeln(typeid(a)); // B writeln(typeid(typeof(a))); // A } ``` ### IsExpression ``` IsExpression: is ( Type ) is ( Type : TypeSpecialization ) is ( Type == TypeSpecialization ) is ( Type : TypeSpecialization , TemplateParameterList ) is ( Type == TypeSpecialization , TemplateParameterList ) is ( Type Identifier ) is ( Type Identifier : TypeSpecialization ) is ( Type Identifier == TypeSpecialization ) is ( Type Identifier : TypeSpecialization , TemplateParameterList ) is ( Type Identifier == TypeSpecialization , TemplateParameterList ) TypeSpecialization: Type struct union class interface enum __vector function delegate super const immutable inout shared return __parameters module package ``` *IsExpression*s are evaluated at compile time and are used for checking for valid types, comparing types for equivalence, determining if one type can be implicitly converted to another, and deducing the subtypes of a type. The result of an *IsExpression* is a boolean of value `true` if the condition is satisfied. If the condition is not satisfied, the result is a boolean of value `false`. *Type* is the type being tested. It must be syntactically correct, but it need not be semantically correct. If it is not semantically correct, the condition is not satisfied. [*Identifier*](lex#Identifier) is declared to be an alias of the resulting type if the condition is satisfied. The [*Identifier*](lex#Identifier) forms can only be used if the *IsExpression* appears in a [*StaticIfCondition*](version#StaticIfCondition). *TypeSpecialization* is the type that *Type* is being compared against. The forms of the *IsExpression* are: 1. `is (` *Type* `)` The condition is satisfied if `Type` is semantically correct (it must be syntactically correct regardless). ``` alias int func(int); // func is a alias to a function type void foo() { if (is(func[])) // not satisfied because arrays of // functions are not allowed writeln("satisfied"); else writeln("not satisfied"); if (is([][])) // error, [][] is not a syntactically valid type ... } ``` 2. `is (` *Type* `:` *TypeSpecialization* `)` The condition is satisfied if *Type* is semantically correct and it is the same as or can be implicitly converted to *TypeSpecialization*. *TypeSpecialization* is only allowed to be a *Type*. ``` alias Bar = short; void foo() { if (is(Bar : int)) // satisfied because short can be // implicitly converted to int writeln("satisfied"); else writeln("not satisfied"); } ``` 3. `is (` *Type* `==` *TypeSpecialization* `)` The condition is satisfied if *Type* is semantically correct and is the same type as *TypeSpecialization*. If *TypeSpecialization* is one of `struct` `union` `class` `interface` `enum` `function` `delegate` `const` `immutable` `shared` `module` `package` then the condition is satisfied if *Type* is one of those. [Package modules](https://dlang.org/%20%20%20%20%20%20%20%20spec/module.html#package-module) are considered to be both packages and modules. ``` alias Bar = short; void foo() { if (is(Bar == int)) // not satisfied because short is not // the same type as int writeln("satisfied"); else writeln("not satisfied"); } ``` 4. `is (` *Type* *Identifier* `)` The condition is satisfied if *Type* is semantically correct. If so, *Identifier* is declared to be an alias of *Type*. ``` alias Bar = short; void foo() { static if (is(Bar T)) alias S = T; else alias S = long; writeln(typeid(S)); // prints "short" if (is(Bar T)) // error, Identifier T form can // only be in StaticIfConditions ... } ``` 5. `is (` *Type* *Identifier* `:` *TypeSpecialization* `)` The condition is satisfied if *Type* is the same as *TypeSpecialization*, or if *Type* is a class and *TypeSpecialization* is a base class or base interface of it. The *Identifier* is declared to be either an alias of the *TypeSpecialization* or, if *TypeSpecialization* is dependent on *Identifier*, the deduced type. ``` alias Bar = int; alias Abc = long*; void foo() { static if (is(Bar T : int)) alias S = T; else alias S = long; writeln(typeid(S)); // prints "int" static if (is(Abc U : U*)) { U u; writeln(typeid(typeof(u))); // prints "long" } } ``` The way the type of *Identifier* is determined is analogous to the way template parameter types are determined by [*TemplateTypeParameterSpecialization*](template#TemplateTypeParameterSpecialization). 6. `is (` *Type* *Identifier* `==` *TypeSpecialization* `)` The condition is satisfied if *Type* is semantically correct and is the same as *TypeSpecialization*. The *Identifier* is declared to be either an alias of the *TypeSpecialization* or, if *TypeSpecialization* is dependent on *Identifier*, the deduced type. If *TypeSpecialization* is one of `struct` `union` `class` `interface` `enum` `function` `delegate` `const` `immutable` `shared` then the condition is satisfied if *Type* is one of those. Furthermore, *Identifier* is set to be an alias of the type: | **keyword** | **alias type for *Identifier*** | | --- | --- | | `struct` | *Type* | | `union` | *Type* | | `class` | *Type* | | `interface` | *Type* | | `super` | *TypeSeq* of base classes and interfaces | | `enum` | the base type of the enum | | `function` | *TypeSeq* of the function parameter types. For C- and D-style variadic functions, only the non-variadic parameters are included. For typesafe variadic functions, the `...` is ignored. | | `delegate` | the function type of the delegate | | `return` | the return type of the function, delegate, or function pointer | | `__parameters` | the parameter sequence of a function, delegate, or function pointer. This includes the parameter types, names, and default values. | | `const` | *Type* | | `immutable` | *Type* | | `shared` | *Type* | ``` alias Bar = short; enum E : byte { Emember } void foo() { static if (is(Bar T == int)) // not satisfied, short is not int alias S = T; alias U = T; // error, T is not defined static if (is(E V == enum)) // satisfied, E is an enum V v; // v is declared to be a byte } ``` 7. `is (` *Type* `:` *TypeSpecialization* `,` [*TemplateParameterList*](template#TemplateParameterList) `)` `is (` *Type* `==` *TypeSpecialization* `,` [*TemplateParameterList*](template#TemplateParameterList) `)` `is (` *Type* *Identifier* `:` *TypeSpecialization* `,` [*TemplateParameterList*](template#TemplateParameterList) `)` `is (` *Type* *Identifier* `==` *TypeSpecialization* `,` [*TemplateParameterList*](template#TemplateParameterList) `)` More complex types can be pattern matched; the [*TemplateParameterList*](template#TemplateParameterList) declares symbols based on the parts of the pattern that are matched, analogously to the way implied template parameters are matched. ``` import std.stdio, std.typecons; void main() { alias Tup = Tuple!(int, string); alias AA = long[string]; static if (is(Tup : Template!Args, alias Template, Args...)) { writeln(__traits(isSame, Template, Tuple)); // true writeln(is(Template!(int, string) == Tup)); // true writeln(typeid(Args[0])); // int writeln(typeid(Args[1])); // immutable(char)[] } static if (is(AA T : T[U], U : string)) { writeln(typeid(T)); // long writeln(typeid(U)); // string } static if (is(AA A : A[B], B : int)) { assert(0); // should not match, as B is not an int } static if (is(int[10] W : W[len], int len)) { writeln(typeid(W)); // int writeln(len); // 10 } static if (is(int[10] X : X[len], int len : 5)) { assert(0); // should not match, len should be 10 } } ``` Special Keywords ---------------- ``` SpecialKeyword: __FILE__ __FILE_FULL_PATH__ __MODULE__ __LINE__ __FUNCTION__ __PRETTY_FUNCTION__ ``` `__FILE__` and `__LINE__` expand to the source file name and line number at the point of instantiation. The path of the source file is left up to the compiler. `__FILE_FULL_PATH__` expands to the absolute source file name at the point of instantiation. `__MODULE__` expands to the module name at the point of instantiation. `__FUNCTION__` expands to the fully qualified name of the function at the point of instantiation. `__PRETTY_FUNCTION__` is similar to `__FUNCTION__`, but also expands the function return type, its parameter types, and its attributes. Example: ``` module test; import std.stdio; void test(string file = __FILE__, size_t line = __LINE__, string mod = __MODULE__, string func = __FUNCTION__, string pretty = __PRETTY_FUNCTION__, string fileFullPath = __FILE_FULL_PATH__) { writefln("file: '%s', line: '%s', module: '%s',\nfunction: '%s', " ~ "pretty function: '%s',\nfile full path: '%s'", file, line, mod, func, pretty, fileFullPath); } int main(string[] args) { test(); return 0; } ``` Assuming the file was at /example/test.d, this will output: ``` file: 'test.d', line: '13', module: 'test', function: 'test.main', pretty function: 'int test.main(string[] args)', file full path: '/example/test.d' ``` Associativity and Commutativity ------------------------------- An implementation may rearrange the evaluation of expressions according to arithmetic associativity and commutativity rules as long as, within that thread of execution, no observable difference is possible. This rule precludes any associative or commutative reordering of floating point expressions.
programming_docs
d Introduction Introduction ============ D is a general-purpose systems programming language with a C-like syntax that compiles to native code. It is statically typed and supports both automatic (garbage collected) and manual memory management. D programs are structured as modules that can be compiled separately and linked with external libraries to create native libraries or executables. This document is the reference manual for the D Programming Language. For more information and other documents, see [The D Language Website](https://dlang.org/). Phases of Compilation --------------------- The process of compiling is divided into multiple phases. Each phase is independent of subsequent phases. For example, the scanner is not affected by the semantic analyzer. This separation of passes makes language tools like syntax-directed editors relatively easy to create. It is also possible to compress D source by storing it in ‘tokenized’ form. 1. **source character set** The source file is checked to determine its encoding and the appropriate scanner is loaded. 7-bit ASCII and UTF encodings are accepted. 2. **script line** If the first line starts with "#!", then that line is ignored. 3. **lexical analysis** The source file is divided into a sequence of tokens. [Special tokens](lex#specialtokens) are replaced with other tokens. [*SpecialTokenSequence*](lex#SpecialTokenSequence)s are processed and removed. 4. **syntax analysis** The sequence of tokens is parsed to form syntax trees. 5. **semantic analysis** The syntax trees are traversed to declare variables, load symbol tables, assign types, and determine the meaning of the program. 6. **optimization** Optimization is an optional pass that attempts to rewrite the program in a semantically equivalent, more performant, version. 7. **code generation** Instructions are selected from the target architecture to implement the semantics of the program. The typical result will be an object file suitable for input to a linker. Memory Model ------------ The *byte* is the fundamental unit of storage. Each byte has 8 bits and is stored at a unique address. A *memory location* is a sequence of one or more bytes of the exact size required to hold a scalar type. Multiple threads can access separate memory locations without interference. Memory locations come in three groups: 1. *Thread-local memory locations* are accessible from only one thread at a time. 2. *Immutable memory locations* cannot be written to during their lifetime. Immutable memory locations can be read from by multiple threads without synchronization. 3. *Shared memory locations* are accessible from multiple threads. **Undefined Behavior:** Allowing multiple threads to access a thread-local memory location results in undefined behavior. **Undefined Behavior:** Writing to an immutable memory location during its lifetime results in undefined behavior. **Undefined Behavior:** Writing to a shared memory location in one thread while one or more additional threads read from or write to the same location is undefined behavior unless all of the reads and writes are synchronized. Execution of a single thread on thread-local and immutable memory locations is *sequentially consistent*. This means the collective result of the operations is the same as if they were executed in the same order that the operations appear in the program. A memory location can be transferred from thread-local to immutable or shared if there is only one reference to the location. A memory location can be transferred from shared to immutable or thread-local if there is only one reference to the location. A memory location can be temporarily transferred from shared to local if synchronization is used to prevent any other threads from accessing the memory location during the operation. Object Model ------------ An *object* is created in the following circumstances: * a definition * a [*NewExpression*](expression#NewExpression) * a temporary is created * changing which field of a union is active An object spans a sequence of memory locations which may or may not be contiguous. Its lifetime encompasses construction, destruction, and the period in between. Each object has a type which is determined either statically or by runtime type information. The object's memory locations may include any combination of thread-local, immutable, or shared. Objects can be composed into a *composed object*. Objects that make up a composed object are *subobjects*. An object that is not the subobject of another object is a *complete object*. The lifetime of a subobject is always within the lifetime of the complete object to which it belongs. An object's address is the address of the first byte of the first memory location for that object. Object addresses are distinct unless one object is nested within the other. d std.experimental.allocator.building_blocks.fallback_allocator std.experimental.allocator.building\_blocks.fallback\_allocator =============================================================== Source [std/experimental/allocator/building\_blocks/fallback\_allocator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/fallback_allocator.d) struct **FallbackAllocator**(Primary, Fallback); `FallbackAllocator` is the allocator equivalent of an "or" operator in algebra. An allocation request is first attempted with the `Primary` allocator. If that returns `null`, the request is forwarded to the `Fallback` allocator. All other requests are dispatched appropriately to one of the two allocators. In order to work, `FallbackAllocator` requires that `Primary` defines the `owns` method. This is needed in order to decide which allocator was responsible for a given allocation. `FallbackAllocator` is useful for fast, special-purpose allocators backed up by general-purpose allocators. The example below features a stack region backed up by the `GCAllocator`. Primary **primary**; The primary allocator. Fallback **fallback**; The fallback allocator. static FallbackAllocator **instance**; If both `Primary` and `Fallback` are stateless, `FallbackAllocator` defines a static instance called `instance`. enum uint **alignment**; The alignment offered is the minimum of the two allocators' alignment. void[] **allocate**(size\_t s); Allocates memory trying the primary allocator first. If it returns `null`, the fallback allocator is tried. void[] **alignedAllocate**(size\_t s, uint a); `FallbackAllocator` offers `alignedAllocate` iff at least one of the allocators also offers it. It attempts to allocate using either or both. bool **expand**(ref void[] b, size\_t delta); `expand` is defined if and only if at least one of the allocators defines `expand`. It works as follows. If `primary.owns(b)`, then the request is forwarded to `primary.expand` if it is defined, or fails (returning `false`) otherwise. If `primary` does not own `b`, then the request is forwarded to `fallback.expand` if it is defined, or fails (returning `false`) otherwise. bool **reallocate**(ref void[] b, size\_t newSize); `reallocate` works as follows. If `primary.owns(b)`, then `primary.reallocate(b, newSize)` is attempted. If it fails, an attempt is made to move the allocation from `primary` to `fallback`. If `primary` does not own `b`, then `fallback.reallocate(b, newSize)` is attempted. If that fails, an attempt is made to move the allocation from `fallback` to `primary`. Ternary **owns**(void[] b); `owns` is defined if and only if both allocators define `owns`. Returns `primary.owns(b) | fallback.owns(b)`. Ternary **resolveInternalPointer**(const void\* p, ref void[] result); `resolveInternalPointer` is defined if and only if both allocators define it. bool **deallocate**(void[] b); `deallocate` is defined if and only if at least one of the allocators define `deallocate`. It works as follows. If `primary.owns(b)`, then the request is forwarded to `primary.deallocate` if it is defined, or is a no-op otherwise. If `primary` does not own `b`, then the request is forwarded to `fallback.deallocate` if it is defined, or is a no-op otherwise. Ternary **empty**(); `empty` is defined if both allocators also define it. Returns: `primary.empty & fallback.empty` FallbackAllocator!(Primary, Fallback) **fallbackAllocator**(Primary, Fallback)(auto ref Primary p, auto ref Fallback f); Convenience function that uses type deduction to return the appropriate `FallbackAllocator` instance. To initialize with allocators that don't have state, use their `it` static member. Examples: ``` import std.experimental.allocator.building_blocks.region : Region; import std.experimental.allocator.gc_allocator : GCAllocator; import std.typecons : Ternary; auto a = fallbackAllocator(Region!GCAllocator(1024), GCAllocator.instance); auto b1 = a.allocate(1020); writeln(b1.length); // 1020 writeln(a.primary.owns(b1)); // Ternary.yes auto b2 = a.allocate(10); writeln(b2.length); // 10 writeln(a.primary.owns(b2)); // Ternary.no ``` d core.stdc.wchar_ core.stdc.wchar\_ ================= D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<wchar.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/wchar.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly Source [core/stdc/wchar\_.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/wchar_.d) Standards: ISO/IEC 9899:1999 (E) struct **mbstate\_t**; alias **wint\_t** = dchar; enum wchar\_t **WEOF**; nothrow @nogc @system int **fwprintf**(FILE\* stream, scope const wchar\_t\* format, ...); nothrow @nogc @system int **fwscanf**(FILE\* stream, scope const wchar\_t\* format, ...); nothrow @nogc @system int **swprintf**(wchar\_t\* s, size\_t n, scope const wchar\_t\* format, ...); nothrow @nogc @system int **swscanf**(scope const wchar\_t\* s, scope const wchar\_t\* format, ...); nothrow @nogc @system int **vfwprintf**(FILE\* stream, scope const wchar\_t\* format, va\_list arg); nothrow @nogc @system int **vfwscanf**(FILE\* stream, scope const wchar\_t\* format, va\_list arg); nothrow @nogc @system int **vswprintf**(wchar\_t\* s, size\_t n, scope const wchar\_t\* format, va\_list arg); nothrow @nogc @system int **vswscanf**(scope const wchar\_t\* s, scope const wchar\_t\* format, va\_list arg); nothrow @nogc @system int **vwprintf**(scope const wchar\_t\* format, va\_list arg); nothrow @nogc @system int **vwscanf**(scope const wchar\_t\* format, va\_list arg); nothrow @nogc @system int **wprintf**(scope const wchar\_t\* format, ...); nothrow @nogc @system int **wscanf**(scope const wchar\_t\* format, ...); nothrow @nogc @trusted wint\_t **fgetwc**(FILE\* stream); nothrow @nogc @trusted wint\_t **fputwc**(wchar\_t c, FILE\* stream); nothrow @nogc @system wchar\_t\* **fgetws**(wchar\_t\* s, int n, FILE\* stream); nothrow @nogc @system int **fputws**(scope const wchar\_t\* s, FILE\* stream); nothrow @nogc @trusted wint\_t **getwchar**(); nothrow @nogc @trusted wint\_t **putwchar**(wchar\_t c); nothrow @nogc @trusted wint\_t **getwc**(FILE\* stream); nothrow @nogc @trusted wint\_t **putwc**(wchar\_t c, FILE\* stream); nothrow @nogc @trusted wint\_t **ungetwc**(wint\_t c, FILE\* stream); nothrow @nogc @trusted int **fwide**(FILE\* stream, int mode); nothrow @nogc @system double **wcstod**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr); nothrow @nogc @system float **wcstof**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr); nothrow @nogc @system real **wcstold**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr); nothrow @nogc @system c\_long **wcstol**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr, int base); nothrow @nogc @system long **wcstoll**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr, int base); nothrow @nogc @system c\_ulong **wcstoul**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr, int base); nothrow @nogc @system ulong **wcstoull**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr, int base); pure nothrow @nogc @system wchar\_t\* **wcscpy**(return wchar\_t\* s1, scope const wchar\_t\* s2); pure nothrow @nogc @system wchar\_t\* **wcsncpy**(return wchar\_t\* s1, scope const wchar\_t\* s2, size\_t n); pure nothrow @nogc @system wchar\_t\* **wcscat**(return wchar\_t\* s1, scope const wchar\_t\* s2); pure nothrow @nogc @system wchar\_t\* **wcsncat**(return wchar\_t\* s1, scope const wchar\_t\* s2, size\_t n); pure nothrow @nogc @system int **wcscmp**(scope const wchar\_t\* s1, scope const wchar\_t\* s2); nothrow @nogc @system int **wcscoll**(scope const wchar\_t\* s1, scope const wchar\_t\* s2); pure nothrow @nogc @system int **wcsncmp**(scope const wchar\_t\* s1, scope const wchar\_t\* s2, size\_t n); nothrow @nogc @system size\_t **wcsxfrm**(scope wchar\_t\* s1, scope const wchar\_t\* s2, size\_t n); pure nothrow @nogc @system inout(wchar\_t)\* **wcschr**(return inout(wchar\_t)\* s, wchar\_t c); pure nothrow @nogc @system size\_t **wcscspn**(scope const wchar\_t\* s1, scope const wchar\_t\* s2); pure nothrow @nogc @system inout(wchar\_t)\* **wcspbrk**(return inout(wchar\_t)\* s1, scope const wchar\_t\* s2); pure nothrow @nogc @system inout(wchar\_t)\* **wcsrchr**(return inout(wchar\_t)\* s, wchar\_t c); pure nothrow @nogc @system size\_t **wcsspn**(scope const wchar\_t\* s1, scope const wchar\_t\* s2); pure nothrow @nogc @system inout(wchar\_t)\* **wcsstr**(return inout(wchar\_t)\* s1, scope const wchar\_t\* s2); nothrow @nogc @system wchar\_t\* **wcstok**(return wchar\_t\* s1, scope const wchar\_t\* s2, wchar\_t\*\* ptr); pure nothrow @nogc @system size\_t **wcslen**(scope const wchar\_t\* s); pure nothrow @nogc @system inout(wchar\_t)\* **wmemchr**(return inout wchar\_t\* s, wchar\_t c, size\_t n); pure nothrow @nogc @system int **wmemcmp**(scope const wchar\_t\* s1, scope const wchar\_t\* s2, size\_t n); pure nothrow @nogc @system wchar\_t\* **wmemcpy**(return wchar\_t\* s1, scope const wchar\_t\* s2, size\_t n); pure nothrow @nogc @system wchar\_t\* **wmemmove**(return wchar\_t\* s1, scope const wchar\_t\* s2, size\_t n); pure nothrow @nogc @system wchar\_t\* **wmemset**(return wchar\_t\* s, wchar\_t c, size\_t n); nothrow @nogc @system size\_t **wcsftime**(wchar\_t\* s, size\_t maxsize, scope const wchar\_t\* format, scope const tm\* timeptr); nothrow @nogc @trusted wint\_t **btowc**(int c); nothrow @nogc @trusted int **wctob**(wint\_t c); nothrow @nogc @system int **mbsinit**(scope const mbstate\_t\* ps); nothrow @nogc @system size\_t **mbrlen**(scope const char\* s, size\_t n, mbstate\_t\* ps); nothrow @nogc @system size\_t **mbrtowc**(wchar\_t\* pwc, scope const char\* s, size\_t n, mbstate\_t\* ps); nothrow @nogc @system size\_t **wcrtomb**(char\* s, wchar\_t wc, mbstate\_t\* ps); nothrow @nogc @system size\_t **mbsrtowcs**(wchar\_t\* dst, scope const char\*\* src, size\_t len, mbstate\_t\* ps); nothrow @nogc @system size\_t **wcsrtombs**(char\* dst, scope const wchar\_t\*\* src, size\_t len, mbstate\_t\* ps); d core.stdcpp.new_ core.stdcpp.new\_ ================= D binding to C++ License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Manu Evans Source [core/stdcpp/new\_.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/new_.d) struct **nothrow\_t**; enum **align\_val\_t**: ulong; class **bad\_alloc**: core.stdcpp.exception.exception; @nogc this(); T\* **cpp\_new**(T, Args...)(auto ref Args args) Constraints: if (!is(T == class)); T **cpp\_new**(T, Args...)(auto ref Args args) Constraints: if (is(T == class)); void **cpp\_delete**(T)(T\* ptr) Constraints: if (!is(T == class)); void **cpp\_delete**(T)(T instance) Constraints: if (is(T == class)); @nogc void\* **\_\_cpp\_new**(size\_t count); Binding for ::operator new(std::size\_t count) nothrow @nogc void\* **\_\_cpp\_new\_nothrow**(size\_t count, ref const(nothrow\_t) = std\_nothrow); Binding for ::operator new(std::size\_t count, const std::nothrow\_t&) @nogc void **\_\_cpp\_delete**(void\* ptr); Binding for ::operator delete(void\* ptr) nothrow @nogc void **\_\_cpp\_delete\_nothrow**(void\* ptr, ref const(nothrow\_t) = std\_nothrow); Binding for ::operator delete(void\* ptr, const std::nothrow\_t& tag) d std.experimental.allocator.building_blocks.stats_collector std.experimental.allocator.building\_blocks.stats\_collector ============================================================ Allocator that collects useful statistics about allocations, both global and per calling point. The statistics collected can be configured statically by choosing combinations of `Options` appropriately. Source [std/experimental/allocator/building\_blocks/stats\_collector.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/stats_collector.d) Examples: ``` import std.experimental.allocator.gc_allocator : GCAllocator; import std.experimental.allocator.building_blocks.free_list : FreeList; alias Allocator = StatsCollector!(GCAllocator, Options.bytesUsed); ``` enum **Options**: ulong; Options for `StatsCollector` defined below. Each enables during compilation one specific counter, statistic, or other piece of information. **numOwns** Counts the number of calls to `owns`. **numAllocate** Counts the number of calls to `allocate`. All calls are counted, including requests for zero bytes or failed requests. **numAllocateOK** Counts the number of calls to `allocate` that succeeded, i.e. they returned a block as large as requested. (N.B. requests for zero bytes count as successful.) **numExpand** Counts the number of calls to `expand`, regardless of arguments or result. **numExpandOK** Counts the number of calls to `expand` that resulted in a successful expansion. **numReallocate** Counts the number of calls to `reallocate`, regardless of arguments or result. **numReallocateOK** Counts the number of calls to `reallocate` that succeeded. (Reallocations to zero bytes count as successful.) **numReallocateInPlace** Counts the number of calls to `reallocate` that resulted in an in-place reallocation (no memory moved). If this number is close to the total number of reallocations, that indicates the allocator finds room at the current block's end in a large fraction of the cases, but also that internal fragmentation may be high (the size of the unit of allocation is large compared to the typical allocation size of the application). **numDeallocate** Counts the number of calls to `deallocate`. **numDeallocateAll** Counts the number of calls to `deallocateAll`. **numAlignedAllocate** Counts the number of calls to `alignedAllocate`. All calls are counted, including requests for zero bytes or failed requests. **numAlignedAllocateOk** Counts the number of calls to `alignedAllocate` that succeeded, i.e. they returned a block as large as requested. (N.B. requests for zero bytes count as successful.) **numAll** Chooses all `numXxx` flags. **bytesUsed** Tracks bytes currently allocated by this allocator. This number goes up and down as memory is allocated and deallocated, and is zero if the allocator currently has no active allocation. **bytesAllocated** Tracks total cumulative bytes allocated by means of `allocate`, `expand`, and `reallocate` (when resulting in an expansion). This number always grows and indicates allocation traffic. To compute bytes deallocated cumulatively, subtract `bytesUsed` from `bytesAllocated`. **bytesExpanded** Tracks the sum of all `delta` values in calls of the form `expand(b, delta)` that succeed (return `true`). **bytesContracted** Tracks the sum of all `b.length - s` with `b.length > s` in calls of the form `realloc(b, s)` that succeed (return `true`). In per-call statistics, also unambiguously counts the bytes deallocated with `deallocate`. **bytesMoved** Tracks the sum of all bytes moved as a result of calls to `realloc` that were unable to reallocate in place. A large number (relative to `bytesAllocated`) indicates that the application should use larger preallocations. **bytesNotMoved** Tracks the sum of all bytes NOT moved as result of calls to `realloc` that managed to reallocate in place. A large number (relative to `bytesAllocated`) indicates that the application is expansion-intensive and is saving a good amount of moves. However, if this number is relatively small and `bytesSlack` is high, it means the application is overallocating for little benefit. **bytesSlack** Measures the sum of extra bytes allocated beyond the bytes requested, i.e. the [internal fragmentation](http://goo.gl/YoKffF). This is the current effective number of slack bytes, and it goes up and down with time. **bytesHighTide** Measures the maximum bytes allocated over the time. This is useful for dimensioning allocators. **bytesAll** Chooses all `byteXxx` flags. **all** Combines all flags above. struct **StatsCollector**(Allocator, ulong flags = Options.all, ulong perCallFlags = 0); Allocator that collects extra data about allocations. Since each piece of information adds size and time overhead, statistics can be individually enabled or disabled through compile-time `flags`. All stats of the form `numXxx` record counts of events occurring, such as calls to functions and specific results. The stats of the form `bytesXxx` collect cumulative sizes. In addition, the data `callerSize`, `callerModule`, `callerFile`, `callerLine`, and `callerTime` is associated with each specific allocation. This data prefixes each allocation. Examples: ``` import std.experimental.allocator.building_blocks.free_list : FreeList; import std.experimental.allocator.gc_allocator : GCAllocator; alias Allocator = StatsCollector!(GCAllocator, Options.all, Options.all); Allocator alloc; auto b = alloc.allocate(10); alloc.reallocate(b, 20); alloc.deallocate(b); import std.file : deleteme, remove; import std.range : walkLength; import std.stdio : File; auto f = deleteme ~ "-dlang.std.experimental.allocator.stats_collector.txt"; scope(exit) remove(f); Allocator.reportPerCallStatistics(File(f, "w")); alloc.reportStatistics(File(f, "a")); writeln(File(f).byLine.walkLength); // 24 ``` Allocator **parent**; The parent allocator is publicly accessible either as a direct member if it holds state, or as an alias to `Allocator.instance` otherwise. One may use it for making calls that won't count toward statistics collection. alias **alignment** = Allocator.**alignment**; Alignment offered is equal to `Allocator.alignment`. Ternary **owns**(void[] b); Increments `numOwns` (per instance and and per call) and forwards to `parent.owns(b)`. void[] **allocate**(size\_t n); Forwards to `parent.allocate`. Affects per instance: `numAllocate`, `bytesUsed`, `bytesAllocated`, `bytesSlack`, `numAllocateOK`, and `bytesHighTide`. Affects per call: `numAllocate`, `numAllocateOK`, and `bytesAllocated`. void[] **alignedAllocate**(size\_t n, uint a); Forwards to `parent.alignedAllocate`. Affects per instance: `numAlignedAllocate`, `bytesUsed`, `bytesAllocated`, `bytesSlack`, `numAlignedAllocateOk`, and `bytesHighTide`. Affects per call: `numAlignedAllocate`, `numAlignedAllocateOk`, and `bytesAllocated`. bool **expand**(ref void[] b, size\_t delta); Defined whether or not `Allocator.expand` is defined. Affects per instance: `numExpand`, `numExpandOK`, `bytesExpanded`, `bytesSlack`, `bytesAllocated`, and `bytesUsed`. Affects per call: `numExpand`, `numExpandOK`, `bytesExpanded`, and `bytesAllocated`. bool **reallocate**(ref void[] b, size\_t s); Defined whether or not `Allocator.reallocate` is defined. Affects per instance: `numReallocate`, `numReallocateOK`, `numReallocateInPlace`, `bytesNotMoved`, `bytesAllocated`, `bytesSlack`, `bytesExpanded`, and `bytesContracted`. Affects per call: `numReallocate`, `numReallocateOK`, `numReallocateInPlace`, `bytesNotMoved`, `bytesExpanded`, `bytesContracted`, and `bytesMoved`. bool **deallocate**(void[] b); Defined whether or not `Allocator.deallocate` is defined. Affects per instance: `numDeallocate`, `bytesUsed`, and `bytesSlack`. Affects per call: `numDeallocate` and `bytesContracted`. bool **deallocateAll**(); Defined only if `Allocator.deallocateAll` is defined. Affects per instance and per call `numDeallocateAll`. pure nothrow @nogc @safe Ternary **empty**(); Defined only if `Options.bytesUsed` is defined. Returns `bytesUsed == 0`. void **reportStatistics**(R)(auto ref R output); Reports per instance statistics to `output` (e.g. `stdout`). The format is simple: one kind and value per line, separated by a colon, e.g. `bytesAllocated:7395404` struct **PerCallStatistics**; Defined if `perCallFlags` is nonzero. string **file**; uint **line**; The file and line of the call. Options[] **opts**; The options corresponding to the statistics collected. ulong[] **values**; The values of the statistics. Has the same length as `opts`. const string **toString**(); Format to a string such as: `mymodule.d(655): [numAllocate:21, numAllocateOK:21, bytesAllocated:324202]`. static auto **byFileLine**(); Defined if `perCallFlags` is nonzero. Iterates all monitored file/line instances. The order of iteration is not meaningful (items are inserted at the front of a list upon the first call), so preprocessing the statistics after collection might be appropriate. void **reportPerCallStatistics**(R)(auto ref R output); Defined if `perCallFlags` is nonzero. Outputs (e.g. to a `File`) a simple report of the collected per-call statistics.
programming_docs
d etc.c.odbc.sqltypes etc.c.odbc.sqltypes =================== Declarations for interfacing with the ODBC library. Adapted with minimal changes from the work of David L. Davis (refer to the [original announcement](http://forum.dlang.org/post/cfk7ql&dollar;1p4n&dollar;[email protected])). `etc.c.odbc.sqlext.d` corresponds to the `sqlext.h` C header file. See Also: [ODBC API Reference on MSN Online](https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/odbc-api-reference) d Interfacing to Objective-C Interfacing to Objective-C ========================== **Contents** 1. [Classes](#classes) 1. [Declaring an External Class](#external-class) 2. [Defining a Class](#defining-class) 2. [Protocols](#protocols) 1. [Declaring a Protocol](#declaring-protocol) 2. [Optional Methods](#optional-methods) 3. [Instance Variables](#instance-variables) 4. [Calling an Instance Method](#instance-method) 5. [The `@selector` Attribute](#selector-attribute) 1. [Compiler Checks](#compiler-checks) 6. [The `@optional` Attribute](#optional-attribute) 1. [Compiler Checks](#compiler-checks) 7. [Objective-C Linkage](#objc-linkage) 8. [Memory Management](#memory-management) 9. [Frameworks](#frameworks) 1. [Framework Paths](#framework-paths) 10. [Full Usage Example](#usage-example) D supports interfacing with Objective-C. It supports protocols, classes, subclasses, instance variables, instance methods and class methods. Platform support might vary between different compilers. Fully working example is available at [the bottom](#usage-example). Classes ------- ### Declaring an External Class ``` import core.attribute : selector; extern (Objective-C) extern class NSString { const(char)* UTF8String() @selector("UTF8String"); } ``` All Objective-C classes that should be accessible from within D need to be declared with the [Objective-C linkage](#objc-linkage). If the class is declared as `extern` (in addition to `extern (Objective-C)`) it is expected to be defined externally. The [`@selector`](#selector-attribute) attribute indicates which Objective-C selector should be used when calling this method. This attribute needs to be attached to all methods with the `Objective-C` linkage. ### Defining a Class ``` import core.attribute : selector; // externally defined extern (Objective-C) extern class NSObject { static NSObject alloc() @selector("alloc"); NSObject init() @selector("init"); } extern (Objective-C) class Foo : NSObject { override static Foo alloc() @selector("alloc"); override Foo init() @selector("init"); final int bar(int a) @selector("bar:") { return a; } } void main() { assert(Foo.alloc.init.bar(3) == 3); } ``` Defining an Objective-C class is exactly the same as declaring an external class but it should not be declared as `extern`. To match the Objective-C semantics, `static` and `final` methods are virtual. `static` methods are overridable as well. Protocols --------- ### Declaring a Protocol ``` import core.attribute : selector; import core.stdc.stdio : printf; extern (Objective-C) interface Foo { static void foo() @selector("foo"); void bar() @selector("bar"); } extern (Objective-C) class Bar : Foo { static void foo() @selector("foo") { printf("foo\n"); } void bar() @selector("bar") { printf("bar\n"); } } ``` Objective-C protocols are represented as interfaces in D and are declared using the `interface` keyword. All Objective-C protocols that should be accessible from within D need to be declared with the [Objective-C linkage](#objc-linkage). Objective-C protocols support virtual class (static) methods. These methods must be implemented by the class that implements the protocol (unless they are [optional](#optional-methods)). To match these semantics, `static` methods are virtual. That also means that static methods with Objective-C linkage, inside an interface cannot have a body. ### Optional Methods ``` import core.attribute : optional, selector; import core.stdc.stdio : printf; struct objc_selector; alias SEL = objc_selector*; extern (C) SEL sel_registerName(in char* str); extern (Objective-C) extern class NSObject { static NSObject alloc() @selector("alloc"); NSObject init() @selector("init"); } extern (Objective-C) interface Foo { bool respondsToSelector(SEL sel) @selector("respondsToSelector:"); void foo() @selector("foo"); // this is an optional method @optional void bar() @selector("bar"); } extern (Objective-C) class Bar : NSObject, Foo { override static Bar alloc() @selector("alloc"); override Bar init() @selector("init"); bool respondsToSelector(SEL sel) @selector("respondsToSelector:"); void foo() @selector("foo") { printf("foo\n"); } } void main() { Foo f = Bar.alloc.init; // check, at runtime, if the instance `f` implements the method `bar` if (f.respondsToSelector(sel_registerName("bar"))) f.bar(); else f.foo(); } ``` Objective-C protocols support optional methods. Optional methods are **not** required to be implemented by the class that implements the protocol. To safely call an optional method, a runtime check should be performed to make sure the receiver implements the method. In D, optional methods are represented using the [`@optional`](#optional-attribute) attribute. Instance Variables ------------------ ``` import core.attribute : selector; // externally defined extern (Objective-C) extern class NSObject { static NSObject alloc() @selector("alloc"); NSObject init() @selector("init"); } extern (Objective-C) class Foo : NSObject { int bar_; override static Foo alloc() @selector("alloc"); override Foo init() @selector("init"); int bar() @selector("bar") { return bar_; } } void main() { auto foo = Foo.alloc.init; foo.bar_ = 3; assert(foo.bar == 3); } ``` Declaring an instance variable looks exactly the same as for a regular D class. To solve the fragile base class problem, instance variables in Objective-C has a dynamic offset. That means that the base class can change (add or remove instance variables) without the subclasses needing to recompile or relink. Thanks to this feature it's not necessary to declare instance variables when creating bindings to Objective-C classes. Calling an Instance Method -------------------------- Calling an Objective-C instance method uses the same syntax as calling regular D methods: ``` const(char)* result = object.UTF8String(); ``` When the compiler sees a call to a method with Objective-C linkage it will generate a call similar to how an Objective-C compiler would call the method. The `@selector` Attribute ------------------------- The `@selector` attribute is a compiler recognized [UDA](attribute#uda). It is used to tell the compiler which selector to use when calling an Objective-C method. Selectors in Objective-C can contain the colon character, which is not valid in D identifiers. D supports method overloading while Objective-C achieves something similar by using different selectors. For these two reasons it is better to be able to specify the selectors manually in D, instead of trying to infer it. This allows to have a more natural names for the methods in D. Example: ``` import core.attribute : selector; extern (Objective-C) extern class NSString { NSString initWith(in char*) @selector("initWithUTF8String:"); NSString initWith(NSString) @selector("initWithString:"); } ``` Here the method `initWith` is overloaded with two versions, one accepting `in char*`, the other one `NSString`. These two methods are mapped to two different Objective-C selectors, `initWithUTF8String:` and `initWithString:`. The attribute is defined in druntime in [`core.attribute`](https://dlang.org/phobos/core_attribute.html). The attribute is only defined when the version identifier [`D_ObjectiveC`](#objc-version-identifier) is enabled. ### Compiler Checks The compiler performs the following checks to enforce the correct usage of the `@selector` attribute: * The attribute can only be attached to methods with Objective-C linkage * The attribute can only be attached once to a method * The attribute cannot be attached to a template method * The number of colons in the selector needs to match the number of parameters the method is declared with If any of the checks fail, a compile error will occur. The `@optional` Attribute ------------------------- The `@optional` attribute is a compiler recognized [UDA](attribute#uda). It is used to tell the compiler that a method, with Objective-C linkage, declared inside an interface is optional. That means that the class that implements the interface does **not** have to implement the method. To safely call an optional method, a runtime check should be performed to make sure the receiver implements the method. The attribute is defined in druntime in [`core.attribute`](https://dlang.org/phobos/core_attribute.html). The attribute is only defined when the version identifier [`D_ObjectiveC`](#objc-version-identifier) is enabled. ### Compiler Checks The compiler performs the following checks to enforce the correct usage of the `@optional` attribute: * The attribute can only be attached to methods with Objective-C linkage * The attribute can only be attached to a method inside an interface * The attribute can only be attached once to a method * The attribute cannot be attached to a template method If any of the checks fail, a compile error will occur. The `D_ObjectiveC` Version Identifier -------------------------------------- The `D_ObjectiveC` version identifier is a predefined version identifier. It is enabled if Objective-C support is available for the target. Objective-C Linkage ------------------- Objective-C linkage is achieved by attaching the `extern (Objective-C)` attribute to a class. Example: ``` import core.attribute : selector; extern (Objective-C) extern class NSObject { NSObject init() @selector("init"); } ``` All methods inside a class declared as `extern (Objective-C)` will get implicit Objective-C linkage. The linkage is recognized on all platforms but will issue a compile error if it is used on a platform where Objective-C support is not available. This allows to easily hide Objective-C declarations from platforms where it is not available using the [`version`](version#version) statement, without resorting to string mixins or other workarounds. Memory Management ----------------- The preferred way to do memory management in Objective-C is to use Automatic Reference Counting, [ARC](https://developer.apple.com/library/mac/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html). This is not supported in D, therefore manual memory management is required to be used instead. This is achieved by calling [`release`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/index.html#//apple_ref/occ/intfm/NSObject/release) on an Objective-C instance, like in the old days of Objective-C. Frameworks ---------- Most Objective-C code is bundled in something called a "Framework". This is basically a regular directory, with the `.framework` extension and a specific directory layout. A framework contains a dynamic library, all public header files and any resources (images, sounds and so on) required by the framework. These directories are recognized by some tools, like the Objective-C compiler and linker, to be frameworks. To link with a framework from DMD, use the following flags: ``` -L-framework -L<Framework> ``` where `<Framework>` is the name of the framework to link with, without the `.framework` extension. The two `-L` flags are required because the linker expects a space between the `-framework` flag and the name of the framework. DMD cannot handle this and will instead interpret the name of the framework as a separate flag. ### Framework Paths Using the above flag, the linker will search in the standard framework paths. The standard search paths for frameworks are: * `/System/Library/Frameworks` * `/Library/Frameworks` The following flag from DMD can be used to add a new path in which to search for frameworks: ``` -L-F<framework_path> ``` For more information see the [reference documentation](https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPFrameworks/Tasks/IncludingFrameworks.html) and the `ld` man page. Full Usage Example ------------------ This example will create an Objective-C string, `NSString`, and log the message using `NSLog` to stderr. ``` import core.attribute : selector; extern (Objective-C) extern class NSString { static NSString alloc() @selector("alloc"); NSString initWithUTF8String(in char* str) @selector("initWithUTF8String:"); void release() @selector("release"); } ``` This is a simplified declaration of the [`NSString`](https://developer.apple.com/documentation/foundation/nsstring?language=objc) class. The [`alloc`](https://developer.apple.com/documentation/objectivec/nsobject/1571958-alloc?language=objc) method allocates an instance of the class. The [`initWithUTF8String:`](https://developer.apple.com/documentation/foundation/nsstring/1412128-initwithutf8string?language=objc) method will be used to convert a C string in UTF-8 to an Objective-C string, `NSString`. The [`release`](https://developer.apple.com/documentation/objectivec/1418956-nsobject/1571957-release?language=objc) method is used to release an deallocate the string. Since D doesn't support [ARC](https://developer.apple.com/library/mac/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html) it's needed to manually release Objective-C instances. ``` extern (C) void NSLog(NSString, ...); ``` This [`NSLog`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/index.html#//apple_ref/c/func/NSLog) function prints a message to the System Log facility, i.e. to stderr and Console. ``` auto str = NSString.alloc(); ``` Allocate an instance of the class, `NSString`. ``` str = str.initWithUTF8String("Hello World!") ``` Initialize the Objective-C string using a C string. ``` NSLog(str); ``` Log the string to stderr, this will print something like this in the terminal: ``` 2015-07-18 13:14:27.978 main[11045:2934950] Hello World! ``` ``` str.release(); ``` Release and deallocate the string. All steps combined look like this: ``` module main; import core.attribute : selector; extern (Objective-C) extern class NSString { static NSString alloc() @selector("alloc"); NSString initWithUTF8String(in char* str) @selector("initWithUTF8String:"); void release() @selector("release"); } extern (C) void NSLog(NSString, ...); void main() { auto str = NSString.alloc().initWithUTF8String("Hello World!"); NSLog(str); str.release(); } ``` When compiling the application remember to link with the required libraries, in this case the Foundation framework. Example: ``` dmd -L-framework -LFoundation main.d ``` d core.stdcpp.string_view core.stdcpp.string\_view ======================== D header file for interaction with C++ std::string\_view. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Manu Evans Source [core/stdcpp/string\_view.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/string_view.d) alias **string\_view** = basic\_string\_view!(char, char\_traits!char).basic\_string\_view; alias **u16string\_view** = basic\_string\_view!(wchar, char\_traits!wchar).basic\_string\_view; alias **u32string\_view** = basic\_string\_view!(dchar, char\_traits!dchar).basic\_string\_view; alias **wstring\_view** = basic\_string\_view!(dchar, char\_traits!dchar).basic\_string\_view; struct **char\_traits**(CharT); Character traits classes specify character properties and provide specific semantics for certain operations on characters and sequences of characters. struct **basic\_string\_view**(T, Traits = char\_traits!T); D language counterpart to C++ std::basic\_string\_view. C++ reference: enum size\_type **npos**; alias **size\_type** = size\_t; alias **difference\_type** = ptrdiff\_t; alias **value\_type** = T; alias **pointer** = T\*; alias **const\_pointer** = const(T)\*; alias **toString** = as\_array; @trusted this(const(T)[] str); alias **length** = size; alias **opDollar** = length; const @safe size\_type **size**(); const @safe bool **empty**(); const @safe const(T)\* **data**(); const @trusted const(T)[] **as\_array**(); const ref @trusted const(T) **at**(size\_type i); const ref @safe const(T) **front**(); const ref @safe const(T) **back**(); d core.stdc.wctype core.stdc.wctype ================ D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<wctype.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/wctype.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly Source [core/stdc/wctype.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/wctype.d) Standards: ISO/IEC 9899:1999 (E) alias **wctrans\_t** = dchar; alias **wctype\_t** = dchar; pure nothrow @nogc @trusted int **iswalnum**(wint\_t wc); pure nothrow @nogc @trusted int **iswalpha**(wint\_t wc); pure nothrow @nogc @trusted int **iswblank**(wint\_t wc); pure nothrow @nogc @trusted int **iswcntrl**(wint\_t wc); pure nothrow @nogc @trusted int **iswdigit**(wint\_t wc); pure nothrow @nogc @trusted int **iswgraph**(wint\_t wc); pure nothrow @nogc @trusted int **iswlower**(wint\_t wc); pure nothrow @nogc @trusted int **iswprint**(wint\_t wc); pure nothrow @nogc @trusted int **iswpunct**(wint\_t wc); pure nothrow @nogc @trusted int **iswspace**(wint\_t wc); pure nothrow @nogc @trusted int **iswupper**(wint\_t wc); pure nothrow @nogc @trusted int **iswxdigit**(wint\_t wc); nothrow @nogc @trusted int **iswctype**(wint\_t wc, wctype\_t desc); nothrow @nogc @system wctype\_t **wctype**(scope const char\* property); pure nothrow @nogc @trusted wint\_t **towlower**(wint\_t wc); pure nothrow @nogc @trusted wint\_t **towupper**(wint\_t wc); nothrow @nogc @trusted wint\_t **towctrans**(wint\_t wc, wctrans\_t desc); nothrow @nogc @system wctrans\_t **wctrans**(scope const char\* property); d core.gc.gcinterface core.gc.gcinterface =================== Contains the internal GC interface. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Walter Bright, Sean Kelly, Jeremy DeHaan d std.format std.format ========== This module implements the formatting functionality for strings and I/O. It's comparable to C99's `vsprintf()` and uses a similar format encoding scheme. For an introductory look at **std.format**'s capabilities and how to use this module see the dedicated [DWiki article](http://wiki.dlang.org/Defining_custom_print_format_specifiers). This module centers around two functions: | Function Name | Description | | --- | --- | | [`formattedRead`](#formattedRead) | Reads values according to the format string from an InputRange. | | [`formattedWrite`](#formattedWrite) | Formats its arguments according to the format string and puts them to an OutputRange. | Please see the documentation of function [`formattedWrite`](#formattedWrite) for a description of the format string. Two functions have been added for convenience: | Function Name | Description | | --- | --- | | [`format`](#format) | Returns a GC-allocated string with the formatting result. | | [`sformat`](#sformat) | Puts the formatting result into a preallocated array. | These two functions are publicly imported by [`std.string`](std_string) to be easily available. The functions [`formatValue`](#formatValue) and [`unformatValue`](#unformatValue) are used for the plumbing. License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://walterbright.com), [Andrei Alexandrescu](http://erdani.com), and Kenji Hara Source [std/format.d](https://github.com/dlang/phobos/blob/master/std/format.d) class **FormatException**: object.Exception; Signals a mismatch between a format and its corresponding argument. Examples: ``` import std.exception : assertThrown; assertThrown!FormatException(format("%d", "foo")); ``` uint **formattedWrite**(alias fmt, Writer, A...)(auto ref Writer w, A args) Constraints: if (isSomeString!(typeof(fmt))); uint **formattedWrite**(Writer, Char, A...)(auto ref Writer w, scope const Char[] fmt, A args); Interprets variadic argument list `args`, formats them according to `fmt`, and sends the resulting characters to `w`. The encoding of the output is the same as `Char`. The type `Writer` must satisfy `[std.range.primitives.isOutputRange](std_range_primitives#isOutputRange)!(Writer, Char)`. The variadic arguments are normally consumed in order. POSIX-style [positional parameter syntax](http://opengroup.org/onlinepubs/009695399/functions/printf.html) is also supported. Each argument is formatted into a sequence of chars according to the format specification, and the characters are passed to `w`. As many arguments as specified in the format string are consumed and formatted. If there are fewer arguments than format specifiers, a `FormatException` is thrown. If there are more remaining arguments than needed by the format specification, they are ignored but only if at least one argument was formatted. The format string supports the formatting of array and nested array elements via the grouping format specifiers **%(** and **%)**. Each matching pair of **%(** and **%)** corresponds with a single array argument. The enclosed sub-format string is applied to individual array elements. The trailing portion of the sub-format string following the conversion specifier for the array element is interpreted as the array delimiter, and is therefore omitted following the last array element. The **%|** specifier may be used to explicitly indicate the start of the delimiter, so that the preceding portion of the string will be included following the last array element. (See below for explicit examples.) Parameters: | | | | --- | --- | | Writer `w` | Output is sent to this writer. Typical output writers include [`std.array.Appender!string`](std_array#Appender!string) and [`std.stdio.LockingTextWriter`](std_stdio#LockingTextWriter). | | Char[] `fmt` | Format string. | | A `args` | Variadic argument list. | Returns: Formatted number of arguments. Throws: Mismatched arguments and formats result in a `FormatException` being thrown. Format String *Format strings* consist of characters interspersed with *format specifications*. Characters are simply copied to the output (such as putc) after any necessary conversion to the corresponding UTF-8 sequence. The format string has the following grammar: ``` FormatString: FormatStringItem* FormatStringItem: '%%' '%' Position Flags Width Separator Precision FormatChar '%(' FormatString '%)' '%-(' FormatString '%)' OtherCharacterExceptPercent Position: empty Integer '$' Flags: empty '-' Flags '+' Flags '#' Flags '0' Flags ' ' Flags Width: empty Integer '*' Separator: empty ',' ',' '?' ',' '*' '?' ',' Integer '?' ',' '*' ',' Integer Precision: empty '.' '.' Integer '.*' Integer: Digit Digit Integer Digit: '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9' FormatChar: 's'|'c'|'b'|'d'|'o'|'x'|'X'|'e'|'E'|'f'|'F'|'g'|'G'|'a'|'A'|'|' ``` Flags affect formatting depending on the specifier as follows.| Flag | Types affected | Semantics | | '-' | numeric, bool, null, char, string, enum, pointer | Left justify the result in the field. It overrides any 0 flag. | | '+' | numeric | Prefix positive numbers in a signed conversion with a +. It overrides any *space* flag. | | '#' | integral ('o') | Add to precision as necessary so that the first digit of the octal formatting is a '0', even if both the argument and the *Precision* are zero. | | '#' | integral ('x', 'X') | If non-zero, prefix result with 0x (0X). | | '#' | floating | Always insert the decimal point and print trailing zeros. | | '0' | numeric | Use leading zeros to pad rather than spaces (except for the floating point values `nan` and `infinity`). Ignore if there's a *Precision*. | | ' ' | numeric | Prefix positive numbers in a signed conversion with a space. | *Width* Only used for numeric, bool, null, char, string, enum and pointer types. Specifies the minimum field width. If the width is a **\***, an additional argument of type **int**, preceding the actual argument, is taken as the width. If the width is negative, it is as if the **-** was given as a *Flags* character. *Precision* Gives the precision for numeric conversions. If the precision is a **\***, an additional argument of type **int**, preceding the actual argument, is taken as the precision. If it is negative, it is as if there was no *Precision* specifier. *Separator* Inserts the separator symbols ',' every *X* digits, from right to left, into numeric values to increase readability. The fractional part of floating point values inserts the separator from left to right. Entering an integer after the ',' allows to specify *X*. If a '\*' is placed after the ',' then *X* is specified by an additional parameter to the format function. Adding a '?' after the ',' or *X* specifier allows to specify the separator character as an additional parameter. *FormatChar* **'s'** The corresponding argument is formatted in a manner consistent with its type: **bool** The result is `"true"` or `"false"`. integral types The **%d** format is used. floating point types The **%g** format is used. string types The result is the string converted to UTF-8. A *Precision* specifies the maximum number of characters to use in the result. structs If the struct defines a **toString()** method the result is the string returned from this function. Otherwise the result is StructName(field0, field1, ...) where fieldn is the nth element formatted with the default format. classes derived from **Object** The result is the string returned from the class instance's **.toString()** method. A *Precision* specifies the maximum number of characters to use in the result. unions If the union defines a **toString()** method the result is the string returned from this function. Otherwise the result is the name of the union, without its contents. non-string static and dynamic arrays The result is [s0, s1, ...] where sn is the nth element formatted with the default format. associative arrays The result is the equivalent of what the initializer would look like for the contents of the associative array, e.g.: ["red" : 10, "blue" : 20]. **'c'** The corresponding argument must be a character type. **'b','d','o','x','X'** The corresponding argument must be an integral type and is formatted as an integer. If the argument is a signed type and the *FormatChar* is **d** it is converted to a signed string of characters, otherwise it is treated as unsigned. An argument of type **bool** is formatted as '1' or '0'. The base used is binary for **b**, octal for **o**, decimal for **d**, and hexadecimal for **x** or **X**. **x** formats using lower case letters, **X** uppercase. If there are fewer resulting digits than the *Precision*, leading zeros are used as necessary. If the *Precision* is 0 and the number is 0, no digits result. **'e','E'** A floating point number is formatted as one digit before the decimal point, *Precision* digits after, the *FormatChar*, ±, followed by at least a two digit exponent: *d.dddddd*e*±dd*. If there is no *Precision*, six digits are generated after the decimal point. If the *Precision* is 0, no decimal point is generated. **'f','F'** A floating point number is formatted in decimal notation. The *Precision* specifies the number of digits generated after the decimal point. It defaults to six. At least one digit is generated before the decimal point. If the *Precision* is zero, no decimal point is generated. **'g','G'** A floating point number is formatted in either **e** or **f** format for **g**; **E** or **F** format for **G**. The **f** format is used if the exponent for an **e** format is greater than -5 and less than the *Precision*. The *Precision* specifies the number of significant digits, and defaults to six. Trailing zeros are elided after the decimal point, if the fractional part is zero then no decimal point is generated. **'a','A'** A floating point number is formatted in hexadecimal exponential notation 0x*h.hhhhhh*p*±d*. There is one hexadecimal digit before the decimal point, and as many after as specified by the *Precision*. If the *Precision* is zero, no decimal point is generated. If there is no *Precision*, as many hexadecimal digits as necessary to exactly represent the mantissa are generated. The exponent is written in as few digits as possible, but at least one, is in decimal, and represents a power of 2 as in *h.hhhhhh*\*2*±d*. The exponent for zero is zero. The hexadecimal digits, x and p are in upper case if the *FormatChar* is upper case. Floating point NaN's are formatted as **nan** if the *FormatChar* is lower case, or **NAN** if upper. Floating point infinities are formatted as **inf** or **infinity** if the *FormatChar* is lower case, or **INF** or **INFINITY** if upper. The positional and non-positional styles can be mixed in the same format string. (POSIX leaves this behavior undefined.) The internal counter for non-positional parameters tracks the next parameter after the largest positional parameter already used. Example using array and nested array formatting: ``` import std.stdio; void main() { writefln("My items are %(%s %).", [1,2,3]); writefln("My items are %(%s, %).", [1,2,3]); } ``` The output is: ``` My items are 1 2 3. My items are 1, 2, 3. ``` The trailing end of the sub-format string following the specifier for each item is interpreted as the array delimiter, and is therefore omitted following the last array item. The **%|** delimiter specifier may be used to indicate where the delimiter begins, so that the portion of the format string prior to it will be retained in the last array element: ``` import std.stdio; void main() { writefln("My items are %(-%s-%|, %).", [1,2,3]); } ``` which gives the output: ``` My items are -1-, -2-, -3-. ``` These compound format specifiers may be nested in the case of a nested array argument: ``` import std.stdio; void main() { auto mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; writefln("%(%(%d %)\n%)", mat); writeln(); writefln("[%(%(%d %)\n %)]", mat); writeln(); writefln("[%([%(%d %)]%|\n %)]", mat); writeln(); } ``` The output is: ``` 1 2 3 4 5 6 7 8 9 [1 2 3 4 5 6 7 8 9] [[1 2 3] [4 5 6] [7 8 9]] ``` Inside a compound format specifier, strings and characters are escaped automatically. To avoid this behavior, add **'-'** flag to `"%("`. ``` import std.stdio; void main() { writefln("My friends are %s.", ["John", "Nancy"]); writefln("My friends are %(%s, %).", ["John", "Nancy"]); writefln("My friends are %-(%s, %).", ["John", "Nancy"]); } ``` which gives the output: ``` My friends are ["John", "Nancy"]. My friends are "John", "Nancy". My friends are John, Nancy. ``` Examples: The format string can be checked at compile-time (see [`format`](#format) for details): ``` import std.array : appender; auto writer = appender!string(); writer.formattedWrite!"%s is the ultimate %s."(42, "answer"); writeln(writer.data); // "42 is the ultimate answer." // Clear the writer writer = appender!string(); formattedWrite(writer, "Date: %2&dollar;s %1&dollar;s", "October", 5); writeln(writer.data); // "Date: 5 October" ``` Examples: ``` writeln(format("%,d", 1000)); // "1,000" writeln(format("%,f", 1234567.891011)); // "1,234,567.891011" writeln(format("%,?d", '?', 1000)); // "1?000" writeln(format("%,1d", 1000)); // "1,0,0,0" writeln(format("%,*d", 4, -12345)); // "-1,2345" writeln(format("%,*?d", 4, '_', -12345)); // "-1_2345" writeln(format("%,6?d", '_', -12345678)); // "-12_345678" assert(format("%12,3.3f", 1234.5678) == " 1,234.568", "'" ~ format("%12,3.3f", 1234.5678) ~ "'"); ``` uint **formattedRead**(alias fmt, R, S...)(auto ref R r, auto ref S args) Constraints: if (isSomeString!(typeof(fmt))); uint **formattedRead**(R, Char, S...)(auto ref R r, const(Char)[] fmt, auto ref S args); Reads characters from [input range](std_range_primitives#isInputRange) `r`, converts them according to `fmt`, and writes them to `args`. Parameters: | | | | --- | --- | | R `r` | The range to read from. | | const(Char)[] `fmt` | The format of the data to read. | | S `args` | The drain of the data read. | Returns: On success, the function returns the number of variables filled. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. Throws: A `FormatException` if `S.length == 0` and `fmt` has format specifiers. Examples: The format string can be checked at compile-time (see [`format`](#format) for details): ``` string s = "hello!124:34.5"; string a; int b; double c; s.formattedRead!"%s!%s:%s"(a, b, c); assert(a == "hello" && b == 124 && c == 34.5); ``` struct **FormatSpec**(Char) if (is(Unqual!Char == Char)); A General handler for `printf` style format specifiers. Used for building more specific formatting functions. Examples: ``` import std.array; auto a = appender!(string)(); auto fmt = "Number: %6.4e\nString: %s"; auto f = FormatSpec!char(fmt); writeln(f.writeUpToNextSpec(a)); // true writeln(a.data); // "Number: " writeln(f.trailing); // "\nString: %s" writeln(f.spec); // 'e' writeln(f.width); // 6 writeln(f.precision); // 4 writeln(f.writeUpToNextSpec(a)); // true writeln(a.data); // "Number: \nString: " writeln(f.trailing); // "" writeln(f.spec); // 's' writeln(f.writeUpToNextSpec(a)); // false writeln(a.data); // "Number: \nString: " ``` int **width**; Minimum width, default `0`. int **precision**; Precision. Its semantics depends on the argument type. For floating point numbers, precision dictates the number of decimals printed. int **separators**; Number of digits printed between separators. int **separatorCharPos**; Set to `DYNAMIC` when the separator character is supplied at runtime. dchar **separatorChar**; Character to insert between digits. enum int **DYNAMIC**; Special value for width and precision. `DYNAMIC` width or precision means that they were specified with `'*'` in the format string and are passed at runtime through the varargs. enum int **UNSPECIFIED**; Special value for precision, meaning the format specifier contained no explicit precision. char **spec**; The actual format specifier, `'s'` by default. ubyte **indexStart**; Index of the argument for positional parameters, from `1` to `ubyte.max`. (`0` means not used). ubyte **indexEnd**; Index of the last argument for positional parameter range, from `1` to `ubyte.max`. (`0` means not used). bool **flDash**; The format specifier contained a `'-'` (`printf` compatibility). bool **flZero**; The format specifier contained a `'0'` (`printf` compatibility). bool **flSpace**; The format specifier contained a `' '` (`printf` compatibility). bool **flPlus**; The format specifier contained a `'+'` (`printf` compatibility). bool **flHash**; The format specifier contained a `'#'` (`printf` compatibility). bool **flSeparator**; The format specifier contained a `','` const(Char)[] **nested**; In case of a compound format specifier starting with `"%("` and ending with `"%)"`, `_nested` contains the string contained within the two separators. const(Char)[] **sep**; In case of a compound format specifier, `_sep` contains the string positioning after `"%|"`. `sep is null` means no separator else `sep.empty` means 0 length separator. const(Char)[] **trailing**; `_trailing` contains the rest of the format string. pure @safe this(in Char[] fmt); Construct a new `FormatSpec` using the format string `fmt`, no processing is done until needed. scope bool **writeUpToNextSpec**(OutputRange)(ref OutputRange writer); Write the format string to an output range until the next format specifier is found and parse that format specifier. See [`FormatSpec`](#FormatSpec) for an example, how to use `writeUpToNextSpec`. Parameters: | | | | --- | --- | | OutputRange `writer` | the [output range](std_range_primitives#isOutputRange) | Returns: True, when a format specifier is found. Throws: A [`FormatException`](#FormatException) when the found format specifier could not be parsed. const pure @safe string **toString**(); const void **toString**(OutputRange)(ref OutputRange writer) Constraints: if (isOutputRange!(OutputRange, char)); Gives a string containing all of the member variables on their own line. Parameters: | | | | --- | --- | | OutputRange `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) | Returns: A `string` when not using an output range; `void` otherwise. FormatSpec!Char **singleSpec**(Char)(Char[] fmt); Helper function that returns a `FormatSpec` for a single specifier given in `fmt`. Parameters: | | | | --- | --- | | Char[] `fmt` | A format specifier. | Returns: A `FormatSpec` with the specifier parsed. Throws: A `FormatException` when more than one specifier is given or the specifier is malformed. Examples: ``` import std.exception : assertThrown; auto spec = singleSpec("%2.3e"); writeln(spec.trailing); // "" writeln(spec.spec); // 'e' writeln(spec.width); // 2 writeln(spec.precision); // 3 assertThrown!FormatException(singleSpec("")); assertThrown!FormatException(singleSpec("2.3e")); assertThrown!FormatException(singleSpec("%2.3eTest")); ``` void **formatValue**(Writer, T, Char)(auto ref Writer w, auto ref T val, ref scope const FormatSpec!Char f); Formats any value into `Char` accepting `OutputRange`, using the given `FormatSpec`. Aggregates `struct`, `union`, `class`, and `interface` are formatted by calling `toString`. `toString` should have one of the following signatures: ``` void toString(W)(ref W w, scope const ref FormatSpec fmt) void toString(W)(ref W w) string toString(); ``` Where `W` is an [output range](std_range_primitives#isOutputRange) which accepts characters. The template type does not have to be called `W`. The following overloads are also accepted for legacy reasons or for use in virtual functions. It's recommended that any new code forgo these overloads if possible for speed and attribute acceptance reasons. ``` void toString(scope void delegate(const(char)[]) sink, const ref FormatSpec fmt); void toString(scope void delegate(const(char)[]) sink, string fmt); void toString(scope void delegate(const(char)[]) sink); ``` For the class objects which have input range interface, * If the instance `toString` has overridden `Object.toString`, it is used. * Otherwise, the objects are formatted as input range. For the `struct` and `union` objects which does not have `toString`, * If they have range interface, formatted as input range. * Otherwise, they are formatted like `Type(field1, filed2, ...)`. Otherwise, are formatted just as their type name. Parameters: | | | | --- | --- | | Writer `w` | The [output range](std_range_primitives#isOutputRange) to write to. | | T `val` | The value to write. | | FormatSpec!Char `f` | The [`std.format.FormatSpec`](std_format#FormatSpec) defining how to write the value. | Examples: The following code compares the use of `formatValue` and `formattedWrite`. ``` import std.array : appender; auto writer1 = appender!string(); writer1.formattedWrite("%08b", 42); auto writer2 = appender!string(); auto f = singleSpec("%08b"); writer2.formatValue(42, f); assert(writer1.data == writer2.data && writer1.data == "00101010"); ``` Examples: `bool`s are formatted as `"true"` or `"false"` with `%s` and as `1` or `0` with integral-specific format specs. ``` import std.array : appender; auto w = appender!string(); auto spec = singleSpec("%s"); formatValue(w, true, spec); writeln(w.data); // "true" ``` Examples: `null` literal is formatted as `"null"`. ``` import std.array : appender; auto w = appender!string(); auto spec = singleSpec("%s"); formatValue(w, null, spec); writeln(w.data); // "null" ``` Examples: Integrals are formatted like [`core.stdc.stdio.printf`](core_stdc_stdio#printf). ``` import std.array : appender; auto w = appender!string(); auto spec = singleSpec("%d"); formatValue(w, 1337, spec); writeln(w.data); // "1337" ``` Examples: Floating-point values are formatted like [`core.stdc.stdio.printf`](core_stdc_stdio#printf) ``` import std.array : appender; auto w = appender!string(); auto spec = singleSpec("%.1f"); formatValue(w, 1337.7, spec); writeln(w.data); // "1337.7" ``` Examples: Individual characters (`char,` wchar`, or` dchar`) are formatted as Unicode characters with `%s` and as integers with integral-specific format specs. ``` import std.array : appender; auto w = appender!string(); auto spec = singleSpec("%c"); formatValue(w, 'a', spec); writeln(w.data); // "a" ``` Examples: Strings are formatted like [`core.stdc.stdio.printf`](core_stdc_stdio#printf) ``` import std.array : appender; auto w = appender!string(); auto spec = singleSpec("%s"); formatValue(w, "hello", spec); writeln(w.data); // "hello" ``` Examples: Static-size arrays are formatted as dynamic arrays. ``` import std.array : appender; auto w = appender!string(); auto spec = singleSpec("%s"); char[2] two = ['a', 'b']; formatValue(w, two, spec); writeln(w.data); // "ab" ``` Examples: Dynamic arrays are formatted as input ranges. Specializations: * `void[]` is formatted like `ubyte[]`. * Const array is converted to input range by removing its qualifier. ``` import std.array : appender; auto w = appender!string(); auto spec = singleSpec("%s"); auto two = [1, 2]; formatValue(w, two, spec); writeln(w.data); // "[1, 2]" ``` Examples: Associative arrays are formatted by using `':'` and `", "` as separators, and enclosed by `'['` and `']'`. ``` import std.array : appender; auto w = appender!string(); auto spec = singleSpec("%s"); auto aa = ["H":"W"]; formatValue(w, aa, spec); writeln(w.data); // "[\"H\":\"W\"]" ``` Examples: `enum`s are formatted like their base value ``` import std.array : appender; auto w = appender!string(); auto spec = singleSpec("%s"); enum A { first, second, third } formatValue(w, A.second, spec); writeln(w.data); // "second" ``` Examples: Formatting a struct by defining a method `toString`, which takes an output range. It's recommended that any `toString` using [output ranges](std_range_primitives#isOutputRange) use [`std.range.primitives.put`](std_range_primitives#put) rather than use the `put` method of the range directly. ``` import std.array : appender; import std.range.primitives; static struct Point { int x, y; void toString(W)(ref W writer, scope const ref FormatSpec!char f) if (isOutputRange!(W, char)) { // std.range.primitives.put put(writer, "("); formatValue(writer, x, f); put(writer, ","); formatValue(writer, y, f); put(writer, ")"); } } auto w = appender!string(); auto spec = singleSpec("%s"); auto p = Point(16, 11); formatValue(w, p, spec); writeln(w.data); // "(16,11)" ``` Examples: Another example of formatting a `struct` with a defined `toString`, this time using the `scope delegate` method. This method is now discouraged for non-virtual functions. If possible, please use the output range method instead. ``` static struct Point { int x, y; void toString(scope void delegate(scope const(char)[]) @safe sink, scope const FormatSpec!char fmt) const { sink("("); sink.formatValue(x, fmt); sink(","); sink.formatValue(y, fmt); sink(")"); } } auto p = Point(16,11); writeln(format("%03d", p)); // "(016,011)" writeln(format("%02x", p)); // "(10,0b)" ``` Examples: Pointers are formatted as hex integers. ``` import std.array : appender; auto w = appender!string(); auto spec = singleSpec("%s"); auto q = cast(void*) 0xFFEECCAA; formatValue(w, q, spec); writeln(w.data); // "FFEECCAA" ``` Examples: SIMD vectors are formatted as arrays. ``` import core.simd; import std.array : appender; auto w = appender!string(); auto spec = singleSpec("%s"); static if (is(float4)) { version (X86) {} else { float4 f4; f4.array[0] = 1; f4.array[1] = 2; f4.array[2] = 3; f4.array[3] = 4; formatValue(w, f4, spec); writeln(w.data); // "[1, 2, 3, 4]" } } ``` Examples: Delegates are formatted by `ReturnType delegate(Parameters) FunctionAttributes` ``` import std.conv : to; int i; int foo(short k) @nogc { return i + k; } @system int delegate(short) @nogc bar() nothrow pure { int* p = new int(1); i = *p; return &foo; } writeln(to!string(&bar)); // "int delegate(short) @nogc delegate() pure nothrow @system" writeln(() @trusted { return bar()(3); }()); // 4 ``` T **unformatValue**(T, Range, Char)(ref Range input, ref scope const FormatSpec!Char spec); Reads a value from the given input range according to spec and returns it as type `T`. Parameters: | | | | --- | --- | | T | the type to return | | Range `input` | the input range to read from | | FormatSpec!Char `spec` | the `FormatSpec` to use when reading from `input` | Returns: A value from `input` of type `T` Throws: A `FormatException` if `spec` cannot read a type `T` See Also: [`std.conv.parse`](std_conv#parse) and [`std.conv.to`](std_conv#to) Examples: Booleans ``` auto str = "false"; auto spec = singleSpec("%s"); writeln(unformatValue!bool(str, spec)); // false str = "1"; spec = singleSpec("%d"); assert(unformatValue!bool(str, spec)); ``` Examples: Null values ``` auto str = "null"; auto spec = singleSpec("%s"); writeln(str.unformatValue!(typeof(null))(spec)); // null ``` Examples: Integrals ``` auto str = "123"; auto spec = singleSpec("%s"); writeln(str.unformatValue!int(spec)); // 123 str = "ABC"; spec = singleSpec("%X"); writeln(str.unformatValue!int(spec)); // 2748 str = "11610"; spec = singleSpec("%o"); writeln(str.unformatValue!int(spec)); // 5000 ``` Examples: Floating point numbers ``` import std.math : approxEqual; auto str = "123.456"; auto spec = singleSpec("%s"); assert(str.unformatValue!double(spec).approxEqual(123.456)); ``` Examples: Character input ranges ``` auto str = "aaa"; auto spec = singleSpec("%s"); writeln(str.unformatValue!char(spec)); // 'a' // Using a numerical format spec reads a Unicode value from a string str = "65"; spec = singleSpec("%d"); writeln(str.unformatValue!char(spec)); // 'A' str = "41"; spec = singleSpec("%x"); writeln(str.unformatValue!char(spec)); // 'A' str = "10003"; spec = singleSpec("%d"); writeln(str.unformatValue!dchar(spec)); // '✓' ``` Examples: Arrays and static arrays ``` string str = "aaa"; auto spec = singleSpec("%s"); writeln(str.unformatValue!(dchar[])(spec)); // "aaa"d str = "aaa"; spec = singleSpec("%s"); dchar[3] ret = ['a', 'a', 'a']; writeln(str.unformatValue!(dchar[3])(spec)); // ret str = "[1, 2, 3, 4]"; spec = singleSpec("%s"); writeln(str.unformatValue!(int[])(spec)); // [1, 2, 3, 4] str = "[1, 2, 3, 4]"; spec = singleSpec("%s"); int[4] ret2 = [1, 2, 3, 4]; writeln(str.unformatValue!(int[4])(spec)); // ret2 ``` Examples: Associative arrays ``` auto str = `["one": 1, "two": 2]`; auto spec = singleSpec("%s"); writeln(str.unformatValue!(int[string])(spec)); // ["one":1, "two":2] ``` typeof(fmt) **format**(alias fmt, Args...)(Args args) Constraints: if (isSomeString!(typeof(fmt))); immutable(Char)[] **format**(Char, Args...)(in Char[] fmt, Args args) Constraints: if (isSomeChar!Char); Format arguments into a string. If the format string is fixed, passing it as a template parameter checks the type correctness of the parameters at compile-time. This also can result in better performance. Parameters: | | | | --- | --- | | Char[] `fmt` | Format string. For detailed specification, see [`formattedWrite`](#formattedWrite). | | Args `args` | Variadic list of arguments to format into returned string. | Throws: if the number of arguments doesn't match the number of format parameters and vice-versa. Examples: Type checking can be done when fmt is known at compile-time: ``` auto s = format!"%s is %s"("Pi", 3.14); writeln(s); // "Pi is 3.14" static assert(!__traits(compiles, {s = format!"%l"();})); // missing arg static assert(!__traits(compiles, {s = format!""(404);})); // surplus arg static assert(!__traits(compiles, {s = format!"%d"(4.03);})); // incompatible arg ``` char[] **sformat**(alias fmt, Args...)(char[] buf, Args args) Constraints: if (isSomeString!(typeof(fmt))); char[] **sformat**(Char, Args...)(return scope char[] buf, scope const(Char)[] fmt, Args args); Format arguments into buffer *buf* which must be large enough to hold the result. Returns: The slice of `buf` containing the formatted string. Throws: A `RangeError` if `buf` isn't large enough to hold the formatted string. A [`FormatException`](#FormatException) if the length of `args` is different than the number of format specifiers in `fmt`. Examples: The format string can be checked at compile-time (see [`format`](#format) for details): ``` char[10] buf; writeln(buf[].sformat!"foo%s"('C')); // "fooC" writeln(sformat(buf[], "%s foo", "bar")); // "bar foo" ```
programming_docs
d core.thread.fiber core.thread.fiber ================= The fiber module provides OS-indepedent lightweight threads aka fibers. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak Source [core/thread/fiber.d](https://github.com/dlang/druntime/blob/master/src/core/thread/fiber.d) class **Fiber**; This class provides a cooperative concurrency mechanism integrated with the threading and garbage collection functionality. Calling a fiber may be considered a blocking operation that returns when the fiber yields (via Fiber.yield()). Execution occurs within the context of the calling thread so synchronization is not necessary to guarantee memory visibility so long as the same thread calls the fiber each time. Please note that there is no requirement that a fiber be bound to one specific thread. Rather, fibers may be freely passed between threads so long as they are not currently executing. Like threads, a new fiber thread may be created using either derivation or composition, as in the following example. Warning Status registers are not saved by the current implementations. This means floating point exception status bits (overflow, divide by 0), rounding mode and similar stuff is set per-thread, not per Fiber! Warning On ARM FPU registers are not saved if druntime was compiled as ARM\_SoftFloat. If such a build is used on a ARM\_SoftFP system which actually has got a FPU and other libraries are using the FPU registers (other code is compiled as ARM\_SoftFP) this can cause problems. Druntime must be compiled as ARM\_SoftFP in this case. Authors: Based on a design by Mikola Lysenko. Examples: ``` int counter; class DerivedFiber : Fiber { this() { super( &run ); } private : void run() { counter += 2; } } void fiberFunc() { counter += 4; Fiber.yield(); counter += 8; } // create instances of each type Fiber derived = new DerivedFiber(); Fiber composed = new Fiber( &fiberFunc ); assert( counter == 0 ); derived.call(); assert( counter == 2, "Derived fiber increment." ); composed.call(); assert( counter == 6, "First composed fiber increment." ); counter += 16; assert( counter == 22, "Calling context increment." ); composed.call(); assert( counter == 30, "Second composed fiber increment." ); // since each fiber has run to completion, each should have state TERM assert( derived.state == Fiber.State.TERM ); assert( composed.state == Fiber.State.TERM ); ``` enum int **defaultStackPages**; nothrow this(void function() fn, size\_t sz = PAGESIZE \* defaultStackPages, size\_t guardPageSize = PAGESIZE); Initializes a fiber object which is associated with a static D function. Parameters: | | | | --- | --- | | void function() `fn` | The fiber function. | | size\_t `sz` | The stack size for this fiber. | | size\_t `guardPageSize` | size of the guard page to trap fiber's stack overflows. Beware that using this will increase the number of mmaped regions on platforms using mmap so an OS-imposed limit may be hit. | In fn must not be null. nothrow this(void delegate() dg, size\_t sz = PAGESIZE \* defaultStackPages, size\_t guardPageSize = PAGESIZE); Initializes a fiber object which is associated with a dynamic D function. Parameters: | | | | --- | --- | | void delegate() `dg` | The fiber function. | | size\_t `sz` | The stack size for this fiber. | | size\_t `guardPageSize` | size of the guard page to trap fiber's stack overflows. Beware that using this will increase the number of mmaped regions on platforms using mmap so an OS-imposed limit may be hit. | In dg must not be null. final Throwable **call**(Rethrow rethrow = Rethrow.yes); final Throwable **call**(Rethrow rethrow)(); Transfers execution to this fiber object. The calling context will be suspended until the fiber calls Fiber.yield() or until it terminates via an unhandled exception. Parameters: | | | | --- | --- | | Rethrow `rethrow` | Rethrow any unhandled exception which may have caused this fiber to terminate. | In This fiber must be in state HOLD. Throws: Any exception not handled by the joined thread. Returns: Any exception not handled by this fiber if rethrow = false, null otherwise. enum **Rethrow**: bool; Flag to control rethrow behavior of `[call](#call)` final nothrow @nogc void **reset**(); final nothrow @nogc void **reset**(void function() fn); final nothrow @nogc void **reset**(void delegate() dg); Resets this fiber so that it may be re-used, optionally with a new function/delegate. This routine should only be called for fibers that have terminated, as doing otherwise could result in scope-dependent functionality that is not executed. Stack-based classes, for example, may not be cleaned up properly if a fiber is reset before it has terminated. In This fiber must be in state TERM or HOLD. enum **State**: int; A fiber may occupy one of three states: HOLD, EXEC, and TERM. **HOLD** The HOLD state applies to any fiber that is suspended and ready to be called. **EXEC** The EXEC state will be set for any fiber that is currently executing. **TERM** The TERM state is set when a fiber terminates. Once a fiber terminates, it must be reset before it may be called again. final const pure nothrow @nogc @property @safe State **state**(); Gets the current state of this fiber. Returns: The state of this fiber as an enumerated value. static nothrow @nogc void **yield**(); Forces a context switch to occur away from the calling fiber. static nothrow @nogc void **yieldAndThrow**(Throwable t); Forces a context switch to occur away from the calling fiber and then throws obj in the calling fiber. Parameters: | | | | --- | --- | | Throwable `t` | The object to throw. | In t must not be null. static nothrow @nogc @safe Fiber **getThis**(); Provides a reference to the calling fiber or null if no fiber is currently active. Returns: The fiber object representing the calling fiber or null if no fiber is currently active within this thread. The result of deleting this object is undefined. d std.digest.murmurhash std.digest.murmurhash ===================== Computes [MurmurHash](https://en.wikipedia.org/wiki/MurmurHash) hashes of arbitrary data. MurmurHash is a non-cryptographic hash function suitable for general hash-based lookup. It is optimized for x86 but can be used on all architectures. The current version is MurmurHash3, which yields a 32-bit or 128-bit hash value. The older MurmurHash 1 and 2 are currently not supported. MurmurHash3 comes in three flavors, listed in increasing order of throughput: * `MurmurHash3!32` produces a 32-bit value and is optimized for 32-bit architectures * `MurmurHash3!(128, 32)` produces a 128-bit value and is optimized for 32-bit architectures * `MurmurHash3!(128, 64)` produces a 128-bit value and is optimized for 64-bit architectures Note * `MurmurHash3!(128, 32)` and `MurmurHash3!(128, 64)` produce different values. * The current implementation is optimized for little endian architectures. It will exhibit different results on big endian architectures and a slightly less uniform distribution. This module conforms to the APIs defined in [`std.digest`](std_digest). This module publicly imports [`std.digest`](std_digest) and can be used as a stand-alone module. Source [std/digest/murmurhash.d](https://github.com/dlang/phobos/blob/master/std/digest/murmurhash.d) License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Guillaume Chatelet References [Reference implementation](https://github.com/aappleby/smhasher) [Wikipedia](https://en.wikipedia.org/wiki/MurmurHash) struct **MurmurHash3**(uint size, uint opt = size\_t.sizeof == 8 ? 64 : 32); Implements the MurmurHash3 functions. You can specify the `size` of the hash in bit. For 128 bit hashes you can specify whether to optimize for 32 or 64 bit architectures. If you don't specify the `opt` value it will select the fastest version of the host platform. This hasher is compatible with the `Digest` API: * `void start()` * `void put(scope const(ubyte)[] data...)` * `ubyte[Element.sizeof] finish()` It also provides a faster, low level API working with data of size `Element.sizeof`: * `void putElements(scope const(Element[]) elements...)` * `void putRemainder(scope const(ubyte[]) data...)` * `void finalize()` * `Element get()` * `ubyte[Element.sizeof] getBytes()` Examples: The convenient digest template allows for quick hashing of any data. ``` ubyte[4] hashed = digest!(MurmurHash3!32)([1, 2, 3, 4]); writeln(hashed); // [0, 173, 69, 68] ``` Examples: One can also hash ubyte data piecewise by instanciating a hasher and call the 'put' method. ``` const(ubyte)[] data1 = [1, 2, 3]; const(ubyte)[] data2 = [4, 5, 6, 7]; // The incoming data will be buffered and hashed element by element. MurmurHash3!32 hasher; hasher.put(data1); hasher.put(data2); // The call to 'finish' ensures: // - the remaining bits are processed // - the hash gets finalized auto hashed = hasher.finish(); writeln(hashed); // [181, 151, 88, 252] ``` alias **Element** = uint; The element type for 32-bit implementation. pure nothrow @nogc void **putElement**(uint block); Adds a single Element of data without increasing `element_count`. Make sure to increase `element_count` by `Element.sizeof` for each call to `putElement`. pure nothrow @nogc void **putRemainder**(scope const(ubyte[]) data...); Put remainder bytes. This must be called only once after `putElement` and before `finalize`. pure nothrow @nogc void **finalize**(); Incorporate `element_count` and finalizes the hash. pure nothrow @nogc Element **get**(); Returns the hash as an uint value. pure nothrow @nogc ubyte[4] **getBytes**(); Returns the current hashed value as an ubyte array. pure nothrow @nogc void **putElements**(scope const(Element[]) elements...); Pushes an array of elements at once. It is more efficient to push as much data as possible in a single call. On platforms that do not support unaligned reads (MIPS or old ARM chips), the compiler may produce slower code to ensure correctness. pure nothrow void **put**(scope const(ubyte)[] data...); Adds data to the digester. This function can be called many times in a row after start but before finish. pure nothrow ubyte[Element.sizeof] **finish**(); Finalizes the computation of the hash and returns the computed value. Note that `finish` can be called only once and that no subsequent calls to `put` is allowed. d etc.c.zlib etc.c.zlib ========== immutable void\* **Z\_NULL**; for initializing zalloc, zfree, opaque (extern(D) for mangling) d core.cpuid core.cpuid ========== Identify the characteristics of the host CPU, providing information about cache sizes and assembly optimisation hints. This module is provided primarily for assembly language programmers. References Some of this information was extremely difficult to track down. Some of the documents below were found only in cached versions stored by search engines! This code relies on information found in: * "Intel(R) 64 and IA-32 Architectures Software Developers Manual, Volume 2A: Instruction Set Reference, A-M" (2007). * "AMD CPUID Specification", Advanced Micro Devices, Rev 2.28 (2008). * "AMD Processor Recognition Application Note For Processors Prior to AMD Family 0Fh Processors", Advanced Micro Devices, Rev 3.13 (2005). * "AMD Geode(TM) GX Processors Data Book", Advanced Micro Devices, Publication ID 31505E, (2005). * "AMD K6 Processor Code Optimisation", Advanced Micro Devices, Rev D (2000). * "Application note 106: Software Customization for the 6x86 Family", Cyrix Corporation, Rev 1.5 (1998) * <http://www.datasheetcatalog.org/datasheet/nationalsemiconductor/GX1.pdf> * "Geode(TM) GX1 Processor Series Low Power Integrated X86 Solution", National Semiconductor, (2002) * "The VIA Isaiah Architecture", G. Glenn Henry, Centaur Technology, Inc (2008). * <http://www.sandpile.org/ia32/cpuid.htm> * <http://www.akkadia.org/drepper/cpumemory.pdf> * "What every programmer should know about memory", Ulrich Depper, Red Hat, Inc., (2007). * "CPU Identification by the Windows Kernel", G. Chappell (2009). <http://www.geoffchappell.com/viewer.htm?doc=studies/windows/km/cpu/cx8.htm> * "Intel(R) Processor Identification and the CPUID Instruction, Application Note 485" (2009). Bugs: Currently only works on x86 and Itanium CPUs. Many processors have bugs in their microcode for the CPUID instruction, so sometimes the cache information may be incorrect. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) Authors: Don Clugston, Tomas Lindquist Olsen <[email protected]> Source [core/cpuid.d](https://github.com/dlang/druntime/blob/master/src/core/cpuid.d) struct **CacheInfo**; Cache size and behaviour size\_t **size**; Size of the cache, in kilobytes, per CPU. For L1 unified (data + code) caches, this size is half the physical size. (we don't halve it for larger sizes, since normally data size is much greater than code size for critical loops). ubyte **associativity**; Number of ways of associativity, eg: * 1 = direct mapped * 2 = 2-way set associative * 3 = 3-way set associative * ubyte.max = fully associative uint **lineSize**; Number of bytes read into the cache when a cache miss occurs. CacheInfo[5] **datacache**; Scheduled for deprecation. Please use `dataCaches` instead. pure nothrow @nogc @property @trusted const(CacheInfo)[5] **dataCaches**(); The data caches. If there are fewer than 5 physical caches levels, the remaining levels are set to size\_t.max (== entire memory space) pure nothrow @nogc @property @trusted string **vendor**(); Returns vendor string, for display purposes only. Do NOT use this to determine features! Note that some CPUs have programmable vendorIDs. pure nothrow @nogc @property @trusted string **processor**(); Returns processor string, for display purposes only pure nothrow @nogc @property @trusted bool **x87onChip**(); Does it have an x87 FPU on-chip? pure nothrow @nogc @property @trusted bool **mmx**(); Is MMX supported? pure nothrow @nogc @property @trusted bool **sse**(); Is SSE supported? pure nothrow @nogc @property @trusted bool **sse2**(); Is SSE2 supported? pure nothrow @nogc @property @trusted bool **sse3**(); Is SSE3 supported? pure nothrow @nogc @property @trusted bool **ssse3**(); Is SSSE3 supported? pure nothrow @nogc @property @trusted bool **sse41**(); Is SSE4.1 supported? pure nothrow @nogc @property @trusted bool **sse42**(); Is SSE4.2 supported? pure nothrow @nogc @property @trusted bool **sse4a**(); Is SSE4a supported? pure nothrow @nogc @property @trusted bool **aes**(); Is AES supported pure nothrow @nogc @property @trusted bool **hasPclmulqdq**(); Is pclmulqdq supported pure nothrow @nogc @property @trusted bool **hasRdrand**(); Is rdrand supported pure nothrow @nogc @property @trusted bool **avx**(); Is AVX supported pure nothrow @nogc @property @trusted bool **vaes**(); Is VEX-Encoded AES supported pure nothrow @nogc @property @trusted bool **hasVpclmulqdq**(); Is vpclmulqdq supported pure nothrow @nogc @property @trusted bool **fma**(); Is FMA supported pure nothrow @nogc @property @trusted bool **fp16c**(); Is FP16C supported pure nothrow @nogc @property @trusted bool **avx2**(); Is AVX2 supported pure nothrow @nogc @property @trusted bool **hle**(); Is HLE (hardware lock elision) supported pure nothrow @nogc @property @trusted bool **rtm**(); Is RTM (restricted transactional memory) supported pure nothrow @nogc @property @trusted bool **hasRdseed**(); Is rdseed supported pure nothrow @nogc @property @trusted bool **hasSha**(); Is SHA supported pure nothrow @nogc @property @trusted bool **amd3dnow**(); Is AMD 3DNOW supported? pure nothrow @nogc @property @trusted bool **amd3dnowExt**(); Is AMD 3DNOW Ext supported? pure nothrow @nogc @property @trusted bool **amdMmx**(); Are AMD extensions to MMX supported? pure nothrow @nogc @property @trusted bool **hasFxsr**(); Is fxsave/fxrstor supported? pure nothrow @nogc @property @trusted bool **hasCmov**(); Is cmov supported? pure nothrow @nogc @property @trusted bool **hasRdtsc**(); Is rdtsc supported? pure nothrow @nogc @property @trusted bool **hasCmpxchg8b**(); Is cmpxchg8b supported? pure nothrow @nogc @property @trusted bool **hasCmpxchg16b**(); Is cmpxchg8b supported? pure nothrow @nogc @property @trusted bool **hasSysEnterSysExit**(); Is SYSENTER/SYSEXIT supported? pure nothrow @nogc @property @trusted bool **has3dnowPrefetch**(); Is 3DNow prefetch supported? pure nothrow @nogc @property @trusted bool **hasLahfSahf**(); Are LAHF and SAHF supported in 64-bit mode? pure nothrow @nogc @property @trusted bool **hasPopcnt**(); Is POPCNT supported? pure nothrow @nogc @property @trusted bool **hasLzcnt**(); Is LZCNT supported? pure nothrow @nogc @property @trusted bool **isX86\_64**(); Is this an Intel64 or AMD 64? pure nothrow @nogc @property @trusted bool **isItanium**(); Is this an IA64 (Itanium) processor? pure nothrow @nogc @property @trusted bool **hyperThreading**(); Is hyperthreading supported? pure nothrow @nogc @property @trusted uint **threadsPerCPU**(); Returns number of threads per CPU pure nothrow @nogc @property @trusted uint **coresPerCPU**(); Returns number of cores in CPU pure nothrow @nogc @property @trusted bool **preferAthlon**(); Optimisation hints for assembly code. For forward compatibility, the CPU is compared against different microarchitectures. For 32-bit x86, comparisons are made against the Intel PPro/PII/PIII/PM family. The major 32-bit x86 microarchitecture 'dynasties' have been: * Intel P6 (PentiumPro, PII, PIII, PM, Core, Core2). * AMD Athlon (K7, K8, K10). * Intel NetBurst (Pentium 4, Pentium D). * In-order Pentium (Pentium1, PMMX, Atom) Other early CPUs (Nx586, AMD K5, K6, Centaur C3, Transmeta, Cyrix, Rise) were mostly in-order. Some new processors do not fit into the existing categories: * Intel Atom 230/330 (family 6, model 0x1C) is an in-order core. * Centaur Isiah = VIA Nano (family 6, model F) is an out-of-order core. Within each dynasty, the optimisation techniques are largely identical (eg, use instruction pairing for group 4). Major instruction set improvements occur within each dynasty. Does this CPU perform better on AMD K7 code than PentiumPro..Core2 code? pure nothrow @nogc @property @trusted bool **preferPentium4**(); Does this CPU perform better on Pentium4 code than PentiumPro..Core2 code? pure nothrow @nogc @property @trusted bool **preferPentium1**(); Does this CPU perform better on Pentium I code than Pentium Pro code? uint **stepping**; Warning: This field will be turned into a property in a future release. Processor type (vendor-dependent). This should be visible ONLY for display purposes. uint **model**; Warning: This field will be turned into a property in a future release. Processor type (vendor-dependent). This should be visible ONLY for display purposes. uint **family**; Warning: This field will be turned into a property in a future release. Processor type (vendor-dependent). This should be visible ONLY for display purposes. uint **numCacheLevels**; This field has been deprecated. Please use `cacheLevels` instead. nothrow @nogc @property @trusted uint **cacheLevels**(); The number of cache levels in the CPU. d core.thread core.thread =========== The thread module provides support for thread creation and management. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak Source [core/thread/package.d](https://github.com/dlang/druntime/blob/master/src/core/thread/package.d)
programming_docs
d rt.aaA rt.aaA ====== Implementation of associative arrays. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Martin Nowak immutable int **\_aaVersion**; AA version for debuggers, bump whenever changing the layout struct **AA**; Opaque AA wrapper pure nothrow @nogc size\_t **\_aaLen**(scope const AA aa); Determine number of entries in associative array. void\* **\_aaGetY**(AA\* paa, const TypeInfo\_AssociativeArray ti, const size\_t valsz, scope const void\* pkey); Lookup \*pkey in aa. Called only from implementation of (aa[key]) expressions when value is mutable. Parameters: | | | | --- | --- | | AA\* `paa` | associative array opaque pointer | | TypeInfo\_AssociativeArray `ti` | TypeInfo for the associative array | | size\_t `valsz` | ignored | | void\* `pkey` | pointer to the key value | Returns: if key was in the aa, a mutable pointer to the existing value. If key was not in the aa, a mutable pointer to newly inserted value which is set to all zeros void\* **\_aaGetX**(AA\* paa, const TypeInfo\_AssociativeArray ti, const size\_t valsz, scope const void\* pkey, out bool found); Lookup \*pkey in aa. Called only from implementation of require Parameters: | | | | --- | --- | | AA\* `paa` | associative array opaque pointer | | TypeInfo\_AssociativeArray `ti` | TypeInfo for the associative array | | size\_t `valsz` | ignored | | void\* `pkey` | pointer to the key value | | bool `found` | true if the value was found | Returns: if key was in the aa, a mutable pointer to the existing value. If key was not in the aa, a mutable pointer to newly inserted value which is set to all zeros inout(void)\* **\_aaGetRvalueX**(inout AA aa, scope const TypeInfo keyti, const size\_t valsz, scope const void\* pkey); Lookup \*pkey in aa. Called only from implementation of (aa[key]) expressions when value is not mutable. Parameters: | | | | --- | --- | | AA `aa` | associative array opaque pointer | | TypeInfo `keyti` | TypeInfo for the key | | size\_t `valsz` | ignored | | void\* `pkey` | pointer to the key value | Returns: pointer to value if present, null otherwise inout(void)\* **\_aaInX**(inout AA aa, scope const TypeInfo keyti, scope const void\* pkey); Lookup \*pkey in aa. Called only from implementation of (key in aa) expressions. Parameters: | | | | --- | --- | | AA `aa` | associative array opaque pointer | | TypeInfo `keyti` | TypeInfo for the key | | void\* `pkey` | pointer to the key value | Returns: pointer to value if present, null otherwise bool **\_aaDelX**(AA aa, scope const TypeInfo keyti, scope const void\* pkey); Delete entry scope const AA, return true if it was present pure nothrow void **\_aaClear**(AA aa); Remove all elements from AA. pure nothrow void\* **\_aaRehash**(AA\* paa, scope const TypeInfo keyti); Rehash AA pure nothrow inout(void[]) **\_aaValues**(inout AA aa, const size\_t keysz, const size\_t valsz, const TypeInfo tiValueArray); Return a GC allocated array of all values pure nothrow inout(void[]) **\_aaKeys**(inout AA aa, const size\_t keysz, const TypeInfo tiKeyArray); Return a GC allocated array of all keys int **\_aaApply**(AA aa, const size\_t keysz, dg\_t dg); foreach opApply over all values int **\_aaApply2**(AA aa, const size\_t keysz, dg2\_t dg); foreach opApply over all key/value pairs Impl\* **\_d\_assocarrayliteralTX**(const TypeInfo\_AssociativeArray ti, void[] keys, void[] vals); Construct an associative array of type ti from keys and value int **\_aaEqual**(scope const TypeInfo tiRaw, scope const AA aa1, scope const AA aa2); compares 2 AAs for equality nothrow hash\_t **\_aaGetHash**(scope const AA\* paa, scope const TypeInfo tiRaw); compute a hash struct **Range**; aaRange implements a ForwardRange d core.sync.event core.sync.event =============== The event module provides a primitive for lightweight signaling of other threads (emulating Windows events on Posix) License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Rainer Schuetze Source [core/sync/event.d](https://github.com/dlang/druntime/blob/master/src/core/sync/event.d) struct **Event**; represents an event. Clients of an event are suspended while waiting for the event to be "signaled". Implemented using `pthread_mutex` and `pthread_condition` on Posix and `CreateEvent` and `SetEvent` on Windows. ``` import core.sync.event, core.thread, std.file; struct ProcessFile { ThreadGroup group; Event event; void[] buffer; void doProcess() { event.wait(); // process buffer } void process(string filename) { event.initialize(true, false); group = new ThreadGroup; for (int i = 0; i < 10; ++i) group.create(&doProcess); buffer = std.file.read(filename); event.set(); group.joinAll(); event.terminate(); } } ``` nothrow @nogc this(bool manualReset, bool initialState); Creates an event object. Parameters: | | | | --- | --- | | bool `manualReset` | the state of the event is not reset automatically after resuming waiting clients | | bool `initialState` | initial state of the signal | nothrow @nogc void **initialize**(bool manualReset, bool initialState); Initializes an event object. Does nothing if the event is already initialized. Parameters: | | | | --- | --- | | bool `manualReset` | the state of the event is not reset automatically after resuming waiting clients | | bool `initialState` | initial state of the signal | nothrow @nogc void **terminate**(); deinitialize event. Does nothing if the event is not initialized. There must not be threads currently waiting for the event to be signaled. nothrow @nogc void **set**(); Set the event to "signaled", so that waiting clients are resumed nothrow @nogc void **reset**(); Reset the event manually nothrow @nogc bool **wait**(); Wait for the event to be signaled without timeout. Returns: `true` if the event is in signaled state, `false` if the event is uninitialized or another error occured nothrow @nogc bool **wait**(Duration tmout); Wait for the event to be signaled with timeout. Parameters: | | | | --- | --- | | Duration `tmout` | the maximum time to wait | Returns: `true` if the event is in signaled state, `false` if the event was nonsignaled for the given time or the event is uninitialized or another error occured d rt.sections_osx_x86 rt.sections\_osx\_x86 ===================== Written in the D programming language. This module provides OS X x86 specific support for sections. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright, Sean Kelly, Martin Nowak, Jacob Carlborg Source [rt/sections\_osx\_x86.d](https://github.com/dlang/druntime/blob/master/src/rt/sections_osx_x86.d) d std.digest std.digest ========== This module describes the digest APIs used in Phobos. All digests follow these APIs. Additionally, this module contains useful helper methods which can be used with every digest type. | Category | Functions | | --- | --- | | Template API | [*isDigest*](#isDigest) [*DigestType*](#DigestType) [*hasPeek*](#hasPeek) [*hasBlockSize*](#hasBlockSize) [*ExampleDigest*](#ExampleDigest) [*digest*](#digest) [*hexDigest*](#hexDigest) [*makeDigest*](#makeDigest) | | OOP API | [*Digest*](#Digest) | | Helper functions | [*toHexString*](#toHexString) [*secureEqual*](#secureEqual) | | Implementation helpers | [*digestLength*](#digestLength) [*WrapperDigest*](#WrapperDigest) | APIs There are two APIs for digests: The template API and the OOP API. The template API uses structs and template helpers like [`isDigest`](#isDigest). The OOP API implements digests as classes inheriting the [`Digest`](#Digest) interface. All digests are named so that the template API struct is called "**x**" and the OOP API class is called "**x**Digest". For example we have `MD5` <--> `MD5Digest`, `CRC32` <--> `CRC32Digest`, etc. The template API is slightly more efficient. It does not have to allocate memory dynamically, all memory is allocated on the stack. The OOP API has to allocate in the finish method if no buffer was provided. If you provide a buffer to the OOP APIs finish function, it doesn't allocate, but the [`Digest`](#Digest) classes still have to be created using `new` which allocates them using the GC. The OOP API is useful to change the digest function and/or digest backend at 'runtime'. The benefit here is that switching e.g. Phobos MD5Digest and an OpenSSLMD5Digest implementation is ABI compatible. If just one specific digest type and backend is needed, the template API is usually a good fit. In this simplest case, the template API can even be used without templates: Just use the "**x**" structs directly. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Johannes Pfau Source [std/digest/package.d](https://github.com/dlang/phobos/blob/master/std/digest/package.d) CTFE Digests do not work in CTFE TODO Digesting single bits (as opposed to bytes) is not implemented. This will be done as another template constraint helper (hasBitDigesting!T) and an additional interface (BitDigest) Examples: ``` import std.digest.crc; //Simple example char[8] hexHash = hexDigest!CRC32("The quick brown fox jumps over the lazy dog"); writeln(hexHash); // "39A34F41" //Simple example, using the API manually CRC32 context = makeDigest!CRC32(); context.put(cast(ubyte[])"The quick brown fox jumps over the lazy dog"); ubyte[4] hash = context.finish(); writeln(toHexString(hash)); // "39A34F41" ``` Examples: ``` //Generating the hashes of a file, idiomatic D way import std.digest.crc, std.digest.md, std.digest.sha; import std.stdio; // Digests a file and prints the result. void digestFile(Hash)(string filename) if (isDigest!Hash) { auto file = File(filename); auto result = digest!Hash(file.byChunk(4096 * 1024)); writefln("%s (%s) = %s", Hash.stringof, filename, toHexString(result)); } void main(string[] args) { foreach (name; args[1 .. $]) { digestFile!MD5(name); digestFile!SHA1(name); digestFile!CRC32(name); } } ``` Examples: ``` //Generating the hashes of a file using the template API import std.digest.crc, std.digest.md, std.digest.sha; import std.stdio; // Digests a file and prints the result. void digestFile(Hash)(ref Hash hash, string filename) if (isDigest!Hash) { File file = File(filename); //As digests imlement OutputRange, we could use std.algorithm.copy //Let's do it manually for now foreach (buffer; file.byChunk(4096 * 1024)) hash.put(buffer); auto result = hash.finish(); writefln("%s (%s) = %s", Hash.stringof, filename, toHexString(result)); } void uMain(string[] args) { MD5 md5; SHA1 sha1; CRC32 crc32; md5.start(); sha1.start(); crc32.start(); foreach (arg; args[1 .. $]) { digestFile(md5, arg); digestFile(sha1, arg); digestFile(crc32, arg); } } ``` Examples: ``` import std.digest.crc, std.digest.md, std.digest.sha; import std.stdio; // Digests a file and prints the result. void digestFile(Digest hash, string filename) { File file = File(filename); //As digests implement OutputRange, we could use std.algorithm.copy //Let's do it manually for now foreach (buffer; file.byChunk(4096 * 1024)) hash.put(buffer); ubyte[] result = hash.finish(); writefln("%s (%s) = %s", typeid(hash).toString(), filename, toHexString(result)); } void umain(string[] args) { auto md5 = new MD5Digest(); auto sha1 = new SHA1Digest(); auto crc32 = new CRC32Digest(); foreach (arg; args[1 .. $]) { digestFile(md5, arg); digestFile(sha1, arg); digestFile(crc32, arg); } } ``` struct **ExampleDigest**; This documents the general structure of a Digest in the template API. All digest implementations should implement the following members and therefore pass the [`isDigest`](#isDigest) test. Note * A digest must be a struct (value type) to pass the [`isDigest`](#isDigest) test. * A digest passing the [`isDigest`](#isDigest) test is always an `OutputRange` Examples: ``` //Using the OutputRange feature import std.algorithm.mutation : copy; import std.digest.md; import std.range : repeat; auto oneMillionRange = repeat!ubyte(cast(ubyte)'a', 1000000); auto ctx = makeDigest!MD5(); copy(oneMillionRange, &ctx); //Note: You must pass a pointer to copy! writeln(ctx.finish().toHexString()); // "7707D6AE4E027C70EEA2A935C2296F21" ``` @trusted void **put**(scope const(ubyte)[] data...); Use this to feed the digest with data. Also implements the [`std.range.primitives.isOutputRange`](std_range_primitives#isOutputRange) interface for `ubyte` and `const(ubyte)[]`. The following usages of `put` must work for any type which passes [`isDigest`](#isDigest): Example ``` ExampleDigest dig; dig.put(cast(ubyte) 0); //single ubyte dig.put(cast(ubyte) 0, cast(ubyte) 0); //variadic ubyte[10] buf; dig.put(buf); //buffer ``` @trusted void **start**(); This function is used to (re)initialize the digest. It must be called before using the digest and it also works as a 'reset' function if the digest has already processed data. @trusted ubyte[16] **finish**(); The finish function returns the final hash sum and resets the Digest. Note The actual type returned by finish depends on the digest implementation. `ubyte[16]` is just used as an example. It is guaranteed that the type is a static array of ubytes. * Use [`DigestType`](#DigestType) to obtain the actual return type. * Use [`digestLength`](#digestLength) to obtain the length of the ubyte array. enum bool **isDigest**(T); Use this to check if a type is a digest. See [`ExampleDigest`](#ExampleDigest) to see what a type must provide to pass this check. Note This is very useful as a template constraint (see examples) Bugs: * Does not yet verify that put takes scope parameters. * Should check that finish() returns a ubyte[num] array Examples: ``` import std.digest.crc; static assert(isDigest!CRC32); ``` Examples: ``` import std.digest.crc; void myFunction(T)() if (isDigest!T) { T dig; dig.start(); auto result = dig.finish(); } myFunction!CRC32(); ``` template **DigestType**(T) Use this template to get the type which is returned by a digest's [`finish`](#finish) method. Examples: ``` import std.digest.crc; assert(is(DigestType!(CRC32) == ubyte[4])); ``` Examples: ``` import std.digest.crc; CRC32 dig; dig.start(); DigestType!CRC32 result = dig.finish(); ``` enum bool **hasPeek**(T); Used to check if a digest supports the `peek` method. Peek has exactly the same function signatures as finish, but it doesn't reset the digest's internal state. Note * This is very useful as a template constraint (see examples) * This also checks if T passes [`isDigest`](#isDigest) Examples: ``` import std.digest.crc, std.digest.md; assert(!hasPeek!(MD5)); assert(hasPeek!CRC32); ``` Examples: ``` import std.digest.crc; void myFunction(T)() if (hasPeek!T) { T dig; dig.start(); auto result = dig.peek(); } myFunction!CRC32(); ``` template **hasBlockSize**(T) if (isDigest!T) Checks whether the digest has a `blockSize` member, which contains the digest's internal block size in bits. It is primarily used by [`std.digest.hmac.HMAC`](std_digest_hmac#HMAC). Examples: ``` import std.digest.hmac, std.digest.md; static assert(hasBlockSize!MD5 && MD5.blockSize == 512); static assert(hasBlockSize!(HMAC!MD5) && HMAC!MD5.blockSize == 512); ``` DigestType!Hash **digest**(Hash, Range)(auto ref Range range) Constraints: if (!isArray!Range && isDigestibleRange!Range); This is a convenience function to calculate a hash using the template API. Every digest passing the [`isDigest`](#isDigest) test can be used with this function. Parameters: | | | | --- | --- | | Range `range` | an `InputRange` with `ElementType` `ubyte`, `ubyte[]` or `ubyte[num]` | Examples: ``` import std.digest.md; import std.range : repeat; auto testRange = repeat!ubyte(cast(ubyte)'a', 100); auto md5 = digest!MD5(testRange); ``` DigestType!Hash **digest**(Hash, T...)(scope const T data) Constraints: if (allSatisfy!(isArray, typeof(data))); This overload of the digest function handles arrays. Parameters: | | | | --- | --- | | T `data` | one or more arrays of any type | Examples: ``` import std.digest.crc, std.digest.md, std.digest.sha; auto md5 = digest!MD5( "The quick brown fox jumps over the lazy dog"); auto sha1 = digest!SHA1( "The quick brown fox jumps over the lazy dog"); auto crc32 = digest!CRC32("The quick brown fox jumps over the lazy dog"); writeln(toHexString(crc32)); // "39A34F41" ``` Examples: ``` import std.digest.crc; auto crc32 = digest!CRC32("The quick ", "brown ", "fox jumps over the lazy dog"); writeln(toHexString(crc32)); // "39A34F41" ``` char[digestLength!Hash \* 2] **hexDigest**(Hash, Order order = Order.increasing, Range)(ref Range range) Constraints: if (!isArray!Range && isDigestibleRange!Range); This is a convenience function similar to [`digest`](#digest), but it returns the string representation of the hash. Every digest passing the [`isDigest`](#isDigest) test can be used with this function. Parameters: | | | | --- | --- | | order | the order in which the bytes are processed (see [`toHexString`](#toHexString)) | | Range `range` | an `InputRange` with `ElementType` `ubyte`, `ubyte[]` or `ubyte[num]` | Examples: ``` import std.digest.md; import std.range : repeat; auto testRange = repeat!ubyte(cast(ubyte)'a', 100); writeln(hexDigest!MD5(testRange)); // "36A92CC94A9E0FA21F625F8BFB007ADF" ``` char[digestLength!Hash \* 2] **hexDigest**(Hash, Order order = Order.increasing, T...)(scope const T data) Constraints: if (allSatisfy!(isArray, typeof(data))); This overload of the hexDigest function handles arrays. Parameters: | | | | --- | --- | | order | the order in which the bytes are processed (see [`toHexString`](#toHexString)) | | T `data` | one or more arrays of any type | Examples: ``` import std.digest.crc; // "414FA339" writeln(hexDigest!(CRC32, Order.decreasing)("The quick brown fox jumps over the lazy dog")); ``` Examples: ``` import std.digest.crc; // "414FA339" writeln(hexDigest!(CRC32, Order.decreasing)("The quick ", "brown ", "fox jumps over the lazy dog")); ``` Hash **makeDigest**(Hash)(); This is a convenience function which returns an initialized digest, so it's not necessary to call start manually. Examples: ``` import std.digest.md; auto md5 = makeDigest!MD5(); md5.put(0); writeln(toHexString(md5.finish())); // "93B885ADFE0DA089CDF634904FD59F71" ``` interface **Digest**; This describes the OOP API. To understand when to use the template API and when to use the OOP API, see the module documentation at the top of this page. The Digest interface is the base interface which is implemented by all digests. Note A Digest implementation is always an `OutputRange` Examples: ``` //Using the OutputRange feature import std.algorithm.mutation : copy; import std.digest.md; import std.range : repeat; auto oneMillionRange = repeat!ubyte(cast(ubyte)'a', 1000000); auto ctx = new MD5Digest(); copy(oneMillionRange, ctx); writeln(ctx.finish().toHexString()); // "7707D6AE4E027C70EEA2A935C2296F21" ``` Examples: ``` import std.digest.crc, std.digest.md, std.digest.sha; ubyte[] md5 = (new MD5Digest()).digest("The quick brown fox jumps over the lazy dog"); ubyte[] sha1 = (new SHA1Digest()).digest("The quick brown fox jumps over the lazy dog"); ubyte[] crc32 = (new CRC32Digest()).digest("The quick brown fox jumps over the lazy dog"); writeln(crcHexString(crc32)); // "414FA339" ``` Examples: ``` import std.digest.crc; ubyte[] crc32 = (new CRC32Digest()).digest("The quick ", "brown ", "fox jumps over the lazy dog"); writeln(crcHexString(crc32)); // "414FA339" ``` Examples: ``` void test(Digest dig) { dig.put(cast(ubyte) 0); //single ubyte dig.put(cast(ubyte) 0, cast(ubyte) 0); //variadic ubyte[10] buf; dig.put(buf); //buffer } ``` abstract nothrow @trusted void **put**(scope const(ubyte)[] data...); Use this to feed the digest with data. Also implements the [`std.range.primitives.isOutputRange`](std_range_primitives#isOutputRange) interface for `ubyte` and `const(ubyte)[]`. Example ``` void test(Digest dig) { dig.put(cast(ubyte) 0); //single ubyte dig.put(cast(ubyte) 0, cast(ubyte) 0); //variadic ubyte[10] buf; dig.put(buf); //buffer } ``` abstract nothrow @trusted void **reset**(); Resets the internal state of the digest. Note [`finish`](#finish) calls this internally, so it's not necessary to call `reset` manually after a call to [`finish`](#finish). abstract const nothrow @property @trusted size\_t **length**(); This is the length in bytes of the hash value which is returned by [`finish`](#finish). It's also the required size of a buffer passed to [`finish`](#finish). abstract nothrow @trusted ubyte[] **finish**(); abstract nothrow ubyte[] **finish**(ubyte[] buf); The finish function returns the hash value. It takes an optional buffer to copy the data into. If a buffer is passed, it must be at least [`length`](#length) bytes big. final nothrow @trusted ubyte[] **digest**(scope const(void[])[] data...); This is a convenience function to calculate the hash of a value using the OOP API. enum **Order**: bool; See [`toHexString`](#toHexString) Examples: ``` import std.digest.crc : CRC32; auto crc32 = digest!CRC32("The quick ", "brown ", "fox jumps over the lazy dog"); writeln(crc32.toHexString!(Order.decreasing)); // "414FA339" writeln(crc32.toHexString!(LetterCase.lower, Order.decreasing)); // "414fa339" ``` **increasing** **decreasing** char[num \* 2] **toHexString**(Order order = Order.increasing, size\_t num, LetterCase letterCase = LetterCase.upper)(const ubyte[num] digest); char[num \* 2] **toHexString**(LetterCase letterCase, Order order = Order.increasing, size\_t num)(in ubyte[num] digest); string **toHexString**(Order order = Order.increasing, LetterCase letterCase = LetterCase.upper)(in ubyte[] digest); string **toHexString**(LetterCase letterCase, Order order = Order.increasing)(in ubyte[] digest); Used to convert a hash value (a static or dynamic array of ubytes) to a string. Can be used with the OOP and with the template API. The additional order parameter can be used to specify the order of the input data. By default the data is processed in increasing order, starting at index 0. To process it in the opposite order, pass Order.decreasing as a parameter. The additional letterCase parameter can be used to specify the case of the output data. By default the output is in upper case. To change it to the lower case pass LetterCase.lower as a parameter. Note The function overloads returning a string allocate their return values using the GC. The versions returning static arrays use pass-by-value for the return value, effectively avoiding dynamic allocation. Examples: ``` import std.digest.crc; //Test with template API: auto crc32 = digest!CRC32("The quick ", "brown ", "fox jumps over the lazy dog"); //Lower case variant: writeln(toHexString!(LetterCase.lower)(crc32)); // "39a34f41" //Usually CRCs are printed in this order, though: writeln(toHexString!(Order.decreasing)(crc32)); // "414FA339" writeln(toHexString!(LetterCase.lower, Order.decreasing)(crc32)); // "414fa339" ``` Examples: ``` import std.digest.crc; // With OOP API auto crc32 = (new CRC32Digest()).digest("The quick ", "brown ", "fox jumps over the lazy dog"); //Usually CRCs are printed in this order, though: writeln(toHexString!(Order.decreasing)(crc32)); // "414FA339" ``` class **WrapperDigest**(T) if (isDigest!T): Digest; Wraps a template API hash struct into a Digest interface. Modules providing digest implementations will usually provide an alias for this template (e.g. MD5Digest, SHA1Digest, ...). Examples: ``` import std.digest.md; //Simple example auto hash = new WrapperDigest!MD5(); hash.put(cast(ubyte) 0); auto result = hash.finish(); ``` Examples: ``` //using a supplied buffer import std.digest.md; ubyte[16] buf; auto hash = new WrapperDigest!MD5(); hash.put(cast(ubyte) 0); auto result = hash.finish(buf[]); //The result is now in result (and in buf). If you pass a buffer which is bigger than //necessary, result will have the correct length, but buf will still have it's original //length ``` this(); Initializes the digest. nothrow @trusted void **put**(scope const(ubyte)[] data...); Use this to feed the digest with data. Also implements the [`std.range.primitives.isOutputRange`](std_range_primitives#isOutputRange) interface for `ubyte` and `const(ubyte)[]`. nothrow @trusted void **reset**(); Resets the internal state of the digest. Note [`finish`](#finish) calls this internally, so it's not necessary to call `reset` manually after a call to [`finish`](#finish). const pure nothrow @property @trusted size\_t **length**(); This is the length in bytes of the hash value which is returned by [`finish`](#finish). It's also the required size of a buffer passed to [`finish`](#finish). nothrow ubyte[] **finish**(ubyte[] buf); nothrow @trusted ubyte[] **finish**(); The finish function returns the hash value. It takes an optional buffer to copy the data into. If a buffer is passed, it must have a length at least [`length`](#length) bytes. Example ``` import std.digest.md; ubyte[16] buf; auto hash = new WrapperDigest!MD5(); hash.put(cast(ubyte) 0); auto result = hash.finish(buf[]); //The result is now in result (and in buf). If you pass a buffer which is bigger than //necessary, result will have the correct length, but buf will still have it's original //length ``` const @trusted ubyte[] **peek**(ubyte[] buf); const @trusted ubyte[] **peek**(); Works like `finish` but does not reset the internal state, so it's possible to continue putting data into this WrapperDigest after a call to peek. These functions are only available if `hasPeek!T` is true. bool **secureEqual**(R1, R2)(R1 r1, R2 r2) Constraints: if (isInputRange!R1 && isInputRange!R2 && !isInfinite!R1 && !isInfinite!R2 && (isIntegral!(ElementEncodingType!R1) || isSomeChar!(ElementEncodingType!R1)) && !is(CommonType!(ElementEncodingType!R1, ElementEncodingType!R2) == void)); Securely compares two digest representations while protecting against timing attacks. Do not use `==` to compare digest representations. The attack happens as follows: 1. An attacker wants to send harmful data to your server, which requires a integrity HMAC SHA1 token signed with a secret. 2. The length of the token is known to be 40 characters long due to its format, so the attacker first sends `"0000000000000000000000000000000000000000"`, then `"1000000000000000000000000000000000000000"`, and so on. 3. The given HMAC token is compared with the expected token using the `==` string comparison, which returns `false` as soon as the first wrong element is found. If a wrong element is found, then a rejection is sent back to the sender. 4. Eventually, the attacker is able to determine the first character in the correct token because the sever takes slightly longer to return a rejection. This is due to the comparison moving on to second item in the two arrays, seeing they are different, and then sending the rejection. 5. It may seem like too small of a difference in time for the attacker to notice, but security researchers have shown that differences as small as [20µs can be reliably distinguished](http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf) even with network inconsistencies. 6. Repeat the process for each character until the attacker has the whole correct token and the server accepts the harmful data. This can be done in a week with the attacker pacing the attack to 10 requests per second with only one client. This function defends against this attack by always comparing every single item in the array if the two arrays are the same length. Therefore, this function is always Ο(`n`) for ranges of the same length. This attack can also be mitigated via rate limiting and banning IPs which have too many rejected requests. However, this does not completely solve the problem, as the attacker could be in control of a bot net. To fully defend against the timing attack, rate limiting, banning IPs, and using this function should be used together. Parameters: | | | | --- | --- | | R1 `r1` | A digest representation | | R2 `r2` | A digest representation | Returns: `true` if both representations are equal, `false` otherwise See Also: [The Wikipedia article on timing attacks](https://en.wikipedia.org/wiki/Timing_attack). Examples: ``` import std.digest.hmac : hmac; import std.digest.sha : SHA1; import std.string : representation; // a typical HMAC data integrity verification auto secret = "A7GZIP6TAQA6OHM7KZ42KB9303CEY0MOV5DD6NTV".representation; auto data = "data".representation; auto hex1 = data.hmac!SHA1(secret).toHexString; auto hex2 = data.hmac!SHA1(secret).toHexString; auto hex3 = "data1".representation.hmac!SHA1(secret).toHexString; assert( secureEqual(hex1[], hex2[])); assert(!secureEqual(hex1[], hex3[])); ```
programming_docs
d std.system std.system ========== Information about the target operating system, environment, and CPU. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com) and [Jonathan M Davis](http://jmdavisprog.com) Source [std/system.d](https://github.com/dlang/phobos/blob/master/std/system.d) enum **OS**: int; Operating system. Note This is for cases where you need a value representing the OS at runtime. If you're doing something which should compile differently on different OSes, then please use `version (Windows)`, `version (linux)`, etc. See Also: [Predefined Versions](https://dlang.org/spec/version.html#PredefinedVersions) **win32** Microsoft 32 bit Windows systems **win64** Microsoft 64 bit Windows systems **linux** All Linux Systems, except for Android **osx** Mac OS X **iOS** iOS **tvOS** tvOS **watchOS** watchOS **freeBSD** FreeBSD **netBSD** NetBSD **dragonFlyBSD** DragonFlyBSD **solaris** Solaris **android** Android **otherPosix** Other Posix Systems immutable OS **os**; The OS that the program was compiled for. enum **Endian**: int; Byte order endianness. Note This is intended for cases where you need to deal with endianness at runtime. If you're doing something which should compile differently depending on whether you're compiling on a big endian or little endian machine, then please use `version (BigEndian)` and `version (LittleEndian)`. See Also: [Predefined Versions](https://dlang.org/spec/version.html#PredefinedVersions) **bigEndian** Big endian byte order **littleEndian** Little endian byte order immutable Endian **endian**; The endianness that the program was compiled for. d core.stdc.complex core.stdc.complex ================= D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<complex.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/complex.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly Source [core/stdc/complex.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/complex.d) Standards: ISO/IEC 9899:1999 (E) alias **complex** = creal; alias **imaginary** = ireal; nothrow @nogc @trusted cdouble **cacos**(cdouble z); nothrow @nogc @trusted cfloat **cacosf**(cfloat z); nothrow @nogc @trusted creal **cacosl**(creal z); nothrow @nogc @trusted cdouble **casin**(cdouble z); nothrow @nogc @trusted cfloat **casinf**(cfloat z); nothrow @nogc @trusted creal **casinl**(creal z); nothrow @nogc @trusted cdouble **catan**(cdouble z); nothrow @nogc @trusted cfloat **catanf**(cfloat z); nothrow @nogc @trusted creal **catanl**(creal z); nothrow @nogc @trusted cdouble **ccos**(cdouble z); nothrow @nogc @trusted cfloat **ccosf**(cfloat z); nothrow @nogc @trusted creal **ccosl**(creal z); nothrow @nogc @trusted cdouble **csin**(cdouble z); nothrow @nogc @trusted cfloat **csinf**(cfloat z); nothrow @nogc @trusted creal **csinl**(creal z); nothrow @nogc @trusted cdouble **ctan**(cdouble z); nothrow @nogc @trusted cfloat **ctanf**(cfloat z); nothrow @nogc @trusted creal **ctanl**(creal z); nothrow @nogc @trusted cdouble **cacosh**(cdouble z); nothrow @nogc @trusted cfloat **cacoshf**(cfloat z); nothrow @nogc @trusted creal **cacoshl**(creal z); nothrow @nogc @trusted cdouble **casinh**(cdouble z); nothrow @nogc @trusted cfloat **casinhf**(cfloat z); nothrow @nogc @trusted creal **casinhl**(creal z); nothrow @nogc @trusted cdouble **catanh**(cdouble z); nothrow @nogc @trusted cfloat **catanhf**(cfloat z); nothrow @nogc @trusted creal **catanhl**(creal z); nothrow @nogc @trusted cdouble **ccosh**(cdouble z); nothrow @nogc @trusted cfloat **ccoshf**(cfloat z); nothrow @nogc @trusted creal **ccoshl**(creal z); nothrow @nogc @trusted cdouble **csinh**(cdouble z); nothrow @nogc @trusted cfloat **csinhf**(cfloat z); nothrow @nogc @trusted creal **csinhl**(creal z); nothrow @nogc @trusted cdouble **ctanh**(cdouble z); nothrow @nogc @trusted cfloat **ctanhf**(cfloat z); nothrow @nogc @trusted creal **ctanhl**(creal z); nothrow @nogc @trusted cdouble **cexp**(cdouble z); nothrow @nogc @trusted cfloat **cexpf**(cfloat z); nothrow @nogc @trusted creal **cexpl**(creal z); nothrow @nogc @trusted cdouble **clog**(cdouble z); nothrow @nogc @trusted cfloat **clogf**(cfloat z); nothrow @nogc @trusted creal **clogl**(creal z); nothrow @nogc @trusted double **cabs**(cdouble z); nothrow @nogc @trusted float **cabsf**(cfloat z); nothrow @nogc @trusted real **cabsl**(creal z); nothrow @nogc @trusted cdouble **cpow**(cdouble x, cdouble y); nothrow @nogc @trusted cfloat **cpowf**(cfloat x, cfloat y); nothrow @nogc @trusted creal **cpowl**(creal x, creal y); nothrow @nogc @trusted cdouble **csqrt**(cdouble z); nothrow @nogc @trusted cfloat **csqrtf**(cfloat z); nothrow @nogc @trusted creal **csqrtl**(creal z); nothrow @nogc @trusted double **carg**(cdouble z); nothrow @nogc @trusted float **cargf**(cfloat z); nothrow @nogc @trusted real **cargl**(creal z); nothrow @nogc @trusted double **cimag**(cdouble z); nothrow @nogc @trusted float **cimagf**(cfloat z); nothrow @nogc @trusted real **cimagl**(creal z); nothrow @nogc @trusted cdouble **conj**(cdouble z); nothrow @nogc @trusted cfloat **conjf**(cfloat z); nothrow @nogc @trusted creal **conjl**(creal z); nothrow @nogc @trusted cdouble **cproj**(cdouble z); nothrow @nogc @trusted cfloat **cprojf**(cfloat z); nothrow @nogc @trusted creal **cprojl**(creal z); nothrow @nogc @trusted double **creald**(cdouble z); nothrow @nogc @trusted float **crealf**(cfloat z); nothrow @nogc @trusted real **creall**(creal z); d Unit Tests Unit Tests ========== **Contents** 1. [Attributed Unittests](#attributes_unittest) 2. [Documented Unittests](#documented-unittests) ``` UnitTest: unittest BlockStatement ``` Unit tests are a builtin framework of test cases applied to a module to determine if it is working properly. A D program can be run with unit tests enabled or disabled. Unit tests are a special function defined like: ``` unittest { ...test code... } ``` Individual tests are specified in the unit test using [AssertExpressions](expression#AssertExpression). Unlike *AssertExpression*s used elsewhere, the assert is not assumed to hold, and upon assert failure the program is still in a defined state. There can be any number of unit test functions in a module, including within struct, union and class declarations. They are executed in lexical order. Unit tests, when enabled, are run after all static initialization is complete and before the `main()` function is called. For example, given a class `Sum` that is used to add two values, a unit test can be given: ``` class Sum { int add(int x, int y) { return x + y; } unittest { Sum sum = new Sum; assert(sum.add(3,4) == 7); assert(sum.add(-2,0) == -2); } } ``` When unit tests are enabled, the [version identifier](version#PredefinedVersions) `unittest` is predefined. Attributed Unittests -------------------- A unittest may be attributed with any of the global function attributes. Such unittests are useful in verifying the given attribute(s) on a template function: ``` void myFunc(T)(T[] data) { if (data.length > 2) data[0] = data[1]; } @safe nothrow unittest { auto arr = [1,2,3]; myFunc(arr); assert(arr == [2,2,3]); } ``` This unittest verifies that `myFunc` contains only `@safe`, `nothrow` code. Although this can also be accomplished by attaching these attributes to `myFunc` itself, that would prevent `myFunc` from being instantiated with types `T` that have `@system` or throwing code in their `opAssign` method, or other methods that `myFunc` may call. The above idiom allows `myFunc` to be instantiated with such types, yet at the same time verify that the `@system` and throwing behavior is not introduced by the code within `myFunc` itself. **Implementation Defined:** 1. If unit tests are not enabled, the implementation is not required to check the [*UnitTest*](#UnitTest) for syntactic or semantic correctness. This is to reduce the compile time impact of larger unit test sections. The tokens must still be valid, and the implementation can merely count `{` and `}` tokens to find the end of the [*UnitTest*](#UnitTest)'s [*BlockStatement*](statement#BlockStatement). 2. The presentation of unit test results to the user. 3. The method used to enable or disable the unit tests. Use of a compiler switch such as [**-unittest**](https://dlang.org/dmd.html#switch-unittest) to enable them is suggested. 4. The order in which modules are called to run their unit tests. 5. Whether the program stops on the first unit test failure, or continues running the unit tests. **Best Practices:** 1. Using unit tests in conjunction with coverage testing (such as [**-cov**](https://dlang.org/dmd.html#switch-cov)) is effective. 2. A unit test for a function should appear immediately following it. Documented Unittests -------------------- Documented unittests allow the developer to deliver code examples to the user, while at the same time automatically verifying that the examples are valid. This avoids the frequent problem of having outdated documentation for some piece of code. If a declaration is followed by a documented unittest, the code in the unittest will be inserted in the **example** section of the declaration: ``` /// Math class class Math { /// add function static int add(int x, int y) { return x + y; } /// unittest { assert(add(2, 2) == 4); } } /// unittest { auto math = new Math(); auto result = math.add(2, 2); } ``` The above will generate the following documentation: class Math; Math class **Example:** ``` auto math = new Math; auto result = math.add(2, 2); ``` int add(int *x*, int *y*); add function **Example:** ``` assert(add(2, 2) == 4); ``` A unittest which is not documented, or is marked as private will not be used to generate code samples. There can be multiple documented unittests and they can appear in any order. They will be attached to the last non-unittest declaration: ``` /// add function int add(int x, int y) { return x + y; } /// code sample generated unittest { assert(add(1, 1) == 2); } /// code sample not generated because the unittest is private private unittest { assert(add(2, 2) == 4); } unittest { /// code sample not generated because the unittest isn't documented assert(add(3, 3) == 6); } /// code sample generated, even if it only includes comments (or is empty) unittest { /** assert(add(4, 4) == 8); */ } ``` The above will generate the following documentation: int add(int *x*, int *y*); add function **Examples:** code sample generated ``` assert(add(1, 1) == 2); ``` **Examples:** code sample generated, even if it is empty or only includes comments ``` /** assert(add(4, 4) == 8); */ ``` d std.experimental.logger.nulllogger std.experimental.logger.nulllogger ================================== Source [std/experimental/logger/nulllogger.d](https://github.com/dlang/phobos/blob/master/std/experimental/logger/nulllogger.d) class **NullLogger**: std.experimental.logger.core.Logger; The `NullLogger` will not process any log messages. In case of a log message with `LogLevel.fatal` nothing will happen. Examples: ``` import std.experimental.logger.core : LogLevel; auto nl1 = new NullLogger(LogLevel.all); nl1.info("You will never read this."); nl1.fatal("You will never read this, either and it will not throw"); ``` @safe this(const LogLevel lv = LogLevel.all); The default constructor for the `NullLogger`. Independent of the parameter this Logger will never log a message. Parameters: | | | | --- | --- | | LogLevel `lv` | The `LogLevel` for the `NullLogger`. By default the `LogLevel` for `NullLogger` is `LogLevel.all`. | d std.getopt std.getopt ========== Processing of command line options. The getopt module implements a `getopt` function, which adheres to the POSIX syntax for command line options. GNU extensions are supported in the form of long options introduced by a double dash ("--"). Support for bundling of command line options, as was the case with the more traditional single-letter approach, is provided but not enabled by default. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Andrei Alexandrescu](http://erdani.org) Credits This module and its documentation are inspired by Perl's [Getopt::Long](https://perldoc.perl.org/Getopt/Long.html) module. The syntax of D's `getopt` is simpler than its Perl counterpart because `getopt` infers the expected parameter types from the static types of the passed-in pointers. Source [std/getopt.d](https://github.com/dlang/phobos/blob/master/std/getopt.d) class **GetOptException**: object.Exception; Thrown on one of the following conditions: * An unrecognized command-line argument is passed, and `std.getopt.config.passThrough` was not present. * A command-line option was not found, and `std.getopt.config.required` was present. GetoptResult **getopt**(T...)(ref string[] args, T opts); Parse and remove command line options from a string array. Synopsis ``` import std.getopt; string data = "file.dat"; int length = 24; bool verbose; enum Color { no, yes }; Color color; void main(string[] args) { auto helpInformation = getopt( args, "length", &length, // numeric "file", &data, // string "verbose", &verbose, // flag "color", "Information about this color", &color); // enum ... if (helpInformation.helpWanted) { defaultGetoptPrinter("Some information about the program.", helpInformation.options); } } ``` The `getopt` function takes a reference to the command line (as received by `main`) as its first argument, and an unbounded number of pairs of strings and pointers. Each string is an option meant to "fill" the value referenced by the pointer to its right (the "bound" pointer). The option string in the call to `getopt` should not start with a dash. In all cases, the command-line options that were parsed and used by `getopt` are removed from `args`. Whatever in the arguments did not look like an option is left in `args` for further processing by the program. Values that were unaffected by the options are not touched, so a common idiom is to initialize options to their defaults and then invoke `getopt`. If a command-line argument is recognized as an option with a parameter and the parameter cannot be parsed properly (e.g., a number is expected but not present), a `ConvException` exception is thrown. If `std.getopt.config.passThrough` was not passed to `getopt` and an unrecognized command-line argument is found, a `GetOptException` is thrown. Depending on the type of the pointer being bound, `getopt` recognizes the following kinds of options: 1. *Boolean options*. A lone argument sets the option to `true`. Additionally **true** or **false** can be set within the option separated with an "=" sign: ``` bool verbose = false, debugging = true; getopt(args, "verbose", &verbose, "debug", &debugging); ``` To set `verbose` to `true`, invoke the program with either `--verbose` or `--verbose=true`. To set `debugging` to `false`, invoke the program with `--debugging=false`. 2. *Numeric options.* If an option is bound to a numeric type, a number is expected as the next option, or right within the option separated with an "=" sign: ``` uint timeout; getopt(args, "timeout", &timeout); ``` To set `timeout` to `5`, invoke the program with either `--timeout=5` or `--timeout 5`. 3. *Incremental options.* If an option name has a "+" suffix and is bound to a numeric type, then the option's value tracks the number of times the option occurred on the command line: ``` uint paranoid; getopt(args, "paranoid+", &paranoid); ``` Invoking the program with "--paranoid --paranoid --paranoid" will set `paranoid` to 3. Note that an incremental option never expects a parameter, e.g., in the command line "--paranoid 42 --paranoid", the "42" does not set `paranoid` to 42; instead, `paranoid` is set to 2 and "42" is not considered as part of the normal program arguments. 4. *Enum options.* If an option is bound to an enum, an enum symbol as a string is expected as the next option, or right within the option separated with an "=" sign: ``` enum Color { no, yes }; Color color; // default initialized to Color.no getopt(args, "color", &color); ``` To set `color` to `Color.yes`, invoke the program with either `--color=yes` or `--color yes`. 5. *String options.* If an option is bound to a string, a string is expected as the next option, or right within the option separated with an "=" sign: ``` string outputFile; getopt(args, "output", &outputFile); ``` Invoking the program with "--output=myfile.txt" or "--output myfile.txt" will set `outputFile` to "myfile.txt". If you want to pass a string containing spaces, you need to use the quoting that is appropriate to your shell, e.g. --output='my file.txt'. 6. *Array options.* If an option is bound to an array, a new element is appended to the array each time the option occurs: ``` string[] outputFiles; getopt(args, "output", &outputFiles); ``` Invoking the program with "--output=myfile.txt --output=yourfile.txt" or "--output myfile.txt --output yourfile.txt" will set `outputFiles` to `[ "myfile.txt", "yourfile.txt" ]`. Alternatively you can set [`arraySep`](#arraySep) to allow multiple elements in one parameter. ``` string[] outputFiles; arraySep = ","; // defaults to "", meaning one element per parameter getopt(args, "output", &outputFiles); ``` With the above code you can invoke the program with "--output=myfile.txt,yourfile.txt", or "--output myfile.txt,yourfile.txt". 7. *Hash options.* If an option is bound to an associative array, a string of the form "name=value" is expected as the next option, or right within the option separated with an "=" sign: ``` double[string] tuningParms; getopt(args, "tune", &tuningParms); ``` Invoking the program with e.g. "--tune=alpha=0.5 --tune beta=0.6" will set `tuningParms` to [ "alpha" : 0.5, "beta" : 0.6 ]. Alternatively you can set [`arraySep`](#arraySep) as the element separator: ``` double[string] tuningParms; arraySep = ","; // defaults to "", meaning one element per parameter getopt(args, "tune", &tuningParms); ``` With the above code you can invoke the program with "--tune=alpha=0.5,beta=0.6", or "--tune alpha=0.5,beta=0.6". In general, the keys and values can be of any parsable types. 8. *Callback options.* An option can be bound to a function or delegate with the signature `void function()`, `void function(string option)`, `void function(string option, string value)`, or their delegate equivalents. * If the callback doesn't take any arguments, the callback is invoked whenever the option is seen. * If the callback takes one string argument, the option string (without the leading dash(es)) is passed to the callback. After that, the option string is considered handled and removed from the options array. ``` void main(string[] args) { uint verbosityLevel = 1; void myHandler(string option) { if (option == "quiet") { verbosityLevel = 0; } else { assert(option == "verbose"); verbosityLevel = 2; } } getopt(args, "verbose", &myHandler, "quiet", &myHandler); } ``` * If the callback takes two string arguments, the option string is handled as an option with one argument, and parsed accordingly. The option and its value are passed to the callback. After that, whatever was passed to the callback is considered handled and removed from the list. ``` int main(string[] args) { uint verbosityLevel = 1; bool handlerFailed = false; void myHandler(string option, string value) { switch (value) { case "quiet": verbosityLevel = 0; break; case "verbose": verbosityLevel = 2; break; case "shouting": verbosityLevel = verbosityLevel.max; break; default : stderr.writeln("Unknown verbosity level ", value); handlerFailed = true; break; } } getopt(args, "verbosity", &myHandler); return handlerFailed ? 1 : 0; } ``` Options with multiple names Sometimes option synonyms are desirable, e.g. "--verbose", "--loquacious", and "--garrulous" should have the same effect. Such alternate option names can be included in the option specification, using "|" as a separator: ``` bool verbose; getopt(args, "verbose|loquacious|garrulous", &verbose); ``` Case By default options are case-insensitive. You can change that behavior by passing `getopt` the `caseSensitive` directive like this: ``` bool foo, bar; getopt(args, std.getopt.config.caseSensitive, "foo", &foo, "bar", &bar); ``` In the example above, "--foo" and "--bar" are recognized, but "--Foo", "--Bar", "--FOo", "--bAr", etc. are rejected. The directive is active until the end of `getopt`, or until the converse directive `caseInsensitive` is encountered: ``` bool foo, bar; getopt(args, std.getopt.config.caseSensitive, "foo", &foo, std.getopt.config.caseInsensitive, "bar", &bar); ``` The option "--Foo" is rejected due to `std.getopt.config.caseSensitive`, but not "--Bar", "--bAr" etc. because the directive `std.getopt.config.caseInsensitive` turned sensitivity off before option "bar" was parsed. Short versus long options Traditionally, programs accepted single-letter options preceded by only one dash (e.g. `-t`). `getopt` accepts such parameters seamlessly. When used with a double-dash (e.g. `--t`), a single-letter option behaves the same as a multi-letter option. When used with a single dash, a single-letter option is accepted. To set `timeout` to `5`, use either of the following: `--timeout=5`, `--timeout 5`, `--t=5`, `--t 5`, `-t5`, or `-t 5`. Forms such as `-timeout=5` will be not accepted. For more details about short options, refer also to the next section. Bundling Single-letter options can be bundled together, i.e. "-abc" is the same as `"-a -b -c"`. By default, this option is turned off. You can turn it on with the `std.getopt.config.bundling` directive: ``` bool foo, bar; getopt(args, std.getopt.config.bundling, "foo|f", &foo, "bar|b", &bar); ``` In case you want to only enable bundling for some of the parameters, bundling can be turned off with `std.getopt.config.noBundling`. Required An option can be marked as required. If that option is not present in the arguments an exception will be thrown. ``` bool foo, bar; getopt(args, std.getopt.config.required, "foo|f", &foo, "bar|b", &bar); ``` Only the option directly following `std.getopt.config.required` is required. Passing unrecognized options through If an application needs to do its own processing of whichever arguments `getopt` did not understand, it can pass the `std.getopt.config.passThrough` directive to `getopt`: ``` bool foo, bar; getopt(args, std.getopt.config.passThrough, "foo", &foo, "bar", &bar); ``` An unrecognized option such as "--baz" will be found untouched in `args` after `getopt` returns. Help Information Generation If an option string is followed by another string, this string serves as a description for this option. The `getopt` function returns a struct of type `GetoptResult`. This return value contains information about all passed options as well a `bool GetoptResult.helpWanted` flag indicating whether information about these options was requested. The `getopt` function always adds an option for `--help|-h` to set the flag if the option is seen on the command line. Options Terminator A lone double-dash terminates `getopt` gathering. It is used to separate program options from other parameters (e.g., options to be passed to another program). Invoking the example above with `"--foo -- --bar"` parses foo but leaves "--bar" in `args`. The double-dash itself is removed from the argument array unless the `std.getopt.config.keepEndOfOptions` directive is given. Examples: ``` auto args = ["prog", "--foo", "-b"]; bool foo; bool bar; auto rslt = getopt(args, "foo|f", "Some information about foo.", &foo, "bar|b", "Some help message about bar.", &bar); if (rslt.helpWanted) { defaultGetoptPrinter("Some information about the program.", rslt.options); } ``` enum **config**: int; Configuration options for `getopt`. You can pass them to `getopt` in any position, except in between an option string and its bound pointer. **caseSensitive** Turn case sensitivity on **caseInsensitive** Turn case sensitivity off (default) **bundling** Turn bundling on **noBundling** Turn bundling off (default) **passThrough** Pass unrecognized arguments through **noPassThrough** Signal unrecognized arguments as errors (default) **stopOnFirstNonOption** Stop at first argument that does not look like an option **keepEndOfOptions** Do not erase the endOfOptions separator from args **required** Make the next option a required option struct **GetoptResult**; The result of the `getopt` function. `helpWanted` is set if the option `--help` or `-h` was passed to the option parser. bool **helpWanted**; Flag indicating if help was requested Option[] **options**; All possible options struct **Option**; Information about an option. string **optShort**; The short symbol for this option string **optLong**; The long symbol for this option string **help**; The description of this option bool **required**; If a option is required, not passing it will result in an error dchar **optionChar**; The option character (default '-'). Defaults to '-' but it can be assigned to prior to calling `getopt`. string **endOfOptions**; The string that conventionally marks the end of all options (default '--'). Defaults to "--" but can be assigned to prior to calling `getopt`. Assigning an empty string to `endOfOptions` effectively disables it. dchar **assignChar**; The assignment character used in options with parameters (default '='). Defaults to '=' but can be assigned to prior to calling `getopt`. string **arraySep**; When set to "", parameters to array and associative array receivers are treated as an individual argument. That is, only one argument is appended or inserted per appearance of the option switch. If `arraySep` is set to something else, then each parameter is first split by the separator, and the individual pieces are treated as arguments to the same option. Defaults to "" but can be assigned to prior to calling `getopt`. void **defaultGetoptPrinter**(string text, Option[] opt); This function prints the passed `Option`s and text in an aligned manner on `stdout`. The passed text will be printed first, followed by a newline, then the short and long version of every option will be printed. The short and long version will be aligned to the longest option of every `Option` passed. If the option is required, then "Required:" will be printed after the long version of the `Option`. If a help message is present it will be printed next. The format is illustrated by this code: ``` foreach (it; opt) { writefln("%*s %*s%s%s", lengthOfLongestShortOption, it.optShort, lengthOfLongestLongOption, it.optLong, it.required ? " Required: " : " ", it.help); } ``` Parameters: | | | | --- | --- | | string `text` | The text to printed at the beginning of the help output. | | Option[] `opt` | The `Option` extracted from the `getopt` parameter. | void **defaultGetoptFormatter**(Output)(Output output, string text, Option[] opt, string style = "%\*s %\*s%\*s%s\x0a"); This function writes the passed text and `Option` into an output range in the manner described in the documentation of function `defaultGetoptPrinter`, unless the style option is used. Parameters: | | | | --- | --- | | Output `output` | The output range used to write the help information. | | string `text` | The text to print at the beginning of the help output. | | Option[] `opt` | The `Option` extracted from the `getopt` parameter. | | string `style` | The manner in which to display the output of each `Option.` |
programming_docs
d core.stdcpp.typeinfo core.stdcpp.typeinfo ==================== Interface to C++ License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com) Source [core/stdcpp/typeinfo.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/typeinfo.d) d std.parallelism std.parallelism =============== `std.parallelism` implements high-level primitives for SMP parallelism. These include parallel foreach, parallel reduce, parallel eager map, pipelining and future/promise parallelism. `std.parallelism` is recommended when the same operation is to be executed in parallel on different data, or when a function is to be executed in a background thread and its result returned to a well-defined main thread. For communication between arbitrary threads, see `std.concurrency`. `std.parallelism` is based on the concept of a `Task`. A `Task` is an object that represents the fundamental unit of work in this library and may be executed in parallel with any other `Task`. Using `Task` directly allows programming with a future/promise paradigm. All other supported parallelism paradigms (parallel foreach, map, reduce, pipelining) represent an additional level of abstraction over `Task`. They automatically create one or more `Task` objects, or closely related types that are conceptually identical but not part of the public API. After creation, a `Task` may be executed in a new thread, or submitted to a `TaskPool` for execution. A `TaskPool` encapsulates a task queue and its worker threads. Its purpose is to efficiently map a large number of `Task`s onto a smaller number of threads. A task queue is a FIFO queue of `Task` objects that have been submitted to the `TaskPool` and are awaiting execution. A worker thread is a thread that is associated with exactly one task queue. It executes the `Task` at the front of its queue when the queue has work available, or sleeps when no work is available. Each task queue is associated with zero or more worker threads. If the result of a `Task` is needed before execution by a worker thread has begun, the `Task` can be removed from the task queue and executed immediately in the thread where the result is needed. Warning Unless marked as `@trusted` or `@safe`, artifacts in this module allow implicit data sharing between threads and cannot guarantee that client code is free from low level data races. Source [std/parallelism.d](https://github.com/dlang/phobos/blob/master/std/parallelism.d) Author David Simcha License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt) struct **Task**(alias fun, Args...); `Task` represents the fundamental unit of work. A `Task` may be executed in parallel with any other `Task`. Using this struct directly allows future/promise parallelism. In this paradigm, a function (or delegate or other callable) is executed in a thread other than the one it was called from. The calling thread does not block while the function is being executed. A call to `workForce`, `yieldForce`, or `spinForce` is used to ensure that the `Task` has finished executing and to obtain the return value, if any. These functions and `done` also act as full memory barriers, meaning that any memory writes made in the thread that executed the `Task` are guaranteed to be visible in the calling thread after one of these functions returns. The [`std.parallelism.task`](std_parallelism#task) and [`std.parallelism.scopedTask`](std_parallelism#scopedTask) functions can be used to create an instance of this struct. See `task` for usage examples. Function results are returned from `yieldForce`, `spinForce` and `workForce` by ref. If `fun` returns by ref, the reference will point to the returned reference of `fun`. Otherwise it will point to a field in this struct. Copying of this struct is disabled, since it would provide no useful semantics. If you want to pass this struct around, you should do so by reference or pointer. Bugs: Changes to `ref` and `out` arguments are not propagated to the call site, only to `args` in this struct. alias **args** = \_args[1 .. \_\_dollar]; The arguments the function was called with. Changes to `out` and `ref` arguments will be visible here. alias **ReturnType** = typeof(fun(\_args)); The return type of the function called by this `Task`. This can be `void`. @property ref @trusted ReturnType **spinForce**(); If the `Task` isn't started yet, execute it in the current thread. If it's done, return its return value, if any. If it's in progress, busy spin until it's done, then return the return value. If it threw an exception, rethrow that exception. This function should be used when you expect the result of the `Task` to be available on a timescale shorter than that of an OS context switch. @property ref @trusted ReturnType **yieldForce**(); If the `Task` isn't started yet, execute it in the current thread. If it's done, return its return value, if any. If it's in progress, wait on a condition variable. If it threw an exception, rethrow that exception. This function should be used for expensive functions, as waiting on a condition variable introduces latency, but avoids wasted CPU cycles. @property ref @trusted ReturnType **workForce**(); If this `Task` was not started yet, execute it in the current thread. If it is finished, return its result. If it is in progress, execute any other `Task` from the `TaskPool` instance that this `Task` was submitted to until this one is finished. If it threw an exception, rethrow that exception. If no other tasks are available or this `Task` was executed using `executeInNewThread`, wait on a condition variable. @property @trusted bool **done**(); Returns `true` if the `Task` is finished executing. Throws: Rethrows any exception thrown during the execution of the `Task`. @trusted void **executeInNewThread**(); @trusted void **executeInNewThread**(int priority); Create a new thread for executing this `Task`, execute it in the newly created thread, then terminate the thread. This can be used for future/promise parallelism. An explicit priority may be given to the `Task`. If one is provided, its value is forwarded to `core.thread.Thread.priority`. See [`std.parallelism.task`](std_parallelism#task) for usage example. auto **task**(alias fun, Args...)(Args args); Creates a `Task` on the GC heap that calls an alias. This may be executed via `Task.executeInNewThread` or by submitting to a [`std.parallelism.TaskPool`](std_parallelism#TaskPool). A globally accessible instance of `TaskPool` is provided by [`std.parallelism.taskPool`](std_parallelism#taskPool). Returns: A pointer to the `Task`. Example ``` // Read two files into memory at the same time. import std.file; void main() { // Create and execute a Task for reading // foo.txt. auto file1Task = task!read("foo.txt"); file1Task.executeInNewThread(); // Read bar.txt in parallel. auto file2Data = read("bar.txt"); // Get the results of reading foo.txt. auto file1Data = file1Task.yieldForce; } ``` ``` // Sorts an array using a parallel quick sort algorithm. // The first partition is done serially. Both recursion // branches are then executed in parallel. // // Timings for sorting an array of 1,000,000 doubles on // an Athlon 64 X2 dual core machine: // // This implementation: 176 milliseconds. // Equivalent serial implementation: 280 milliseconds void parallelSort(T)(T[] data) { // Sort small subarrays serially. if (data.length < 100) { std.algorithm.sort(data); return; } // Partition the array. swap(data[$ / 2], data[$ - 1]); auto pivot = data[$ - 1]; bool lessThanPivot(T elem) { return elem < pivot; } auto greaterEqual = partition!lessThanPivot(data[0..$ - 1]); swap(data[$ - greaterEqual.length - 1], data[$ - 1]); auto less = data[0..$ - greaterEqual.length - 1]; greaterEqual = data[$ - greaterEqual.length..$]; // Execute both recursion branches in parallel. auto recurseTask = task!parallelSort(greaterEqual); taskPool.put(recurseTask); parallelSort(less); recurseTask.yieldForce; } ``` auto **task**(F, Args...)(F delegateOrFp, Args args) Constraints: if (is(typeof(delegateOrFp(args))) && !isSafeTask!F); Creates a `Task` on the GC heap that calls a function pointer, delegate, or class/struct with overloaded opCall. Example ``` // Read two files in at the same time again, // but this time use a function pointer instead // of an alias to represent std.file.read. import std.file; void main() { // Create and execute a Task for reading // foo.txt. auto file1Task = task(&read!string, "foo.txt", size_t.max); file1Task.executeInNewThread(); // Read bar.txt in parallel. auto file2Data = read("bar.txt"); // Get the results of reading foo.txt. auto file1Data = file1Task.yieldForce; } ``` Notes This function takes a non-scope delegate, meaning it can be used with closures. If you can't allocate a closure due to objects on the stack that have scoped destruction, see `scopedTask`, which takes a scope delegate. @trusted auto **task**(F, Args...)(F fun, Args args) Constraints: if (is(typeof(fun(args))) && isSafeTask!F); Version of `task` usable from `@safe` code. Usage mechanics are identical to the non-@safe case, but safety introduces some restrictions: 1. `fun` must be @safe or @trusted. 2. `F` must not have any unshared aliasing as defined by [`std.traits.hasUnsharedAliasing`](std_traits#hasUnsharedAliasing). This means it may not be an unshared delegate or a non-shared class or struct with overloaded `opCall`. This also precludes accepting template alias parameters. 3. `Args` must not have unshared aliasing. 4. `fun` must not return by reference. 5. The return type must not have unshared aliasing unless `fun` is `pure` or the `Task` is executed via `executeInNewThread` instead of using a `TaskPool`. auto **scopedTask**(alias fun, Args...)(Args args); auto **scopedTask**(F, Args...)(scope F delegateOrFp, Args args) Constraints: if (is(typeof(delegateOrFp(args))) && !isSafeTask!F); @trusted auto **scopedTask**(F, Args...)(F fun, Args args) Constraints: if (is(typeof(fun(args))) && isSafeTask!F); These functions allow the creation of `Task` objects on the stack rather than the GC heap. The lifetime of a `Task` created by `scopedTask` cannot exceed the lifetime of the scope it was created in. `scopedTask` might be preferred over `task`: 1. When a `Task` that calls a delegate is being created and a closure cannot be allocated due to objects on the stack that have scoped destruction. The delegate overload of `scopedTask` takes a `scope` delegate. 2. As a micro-optimization, to avoid the heap allocation associated with `task` or with the creation of a closure. Usage is otherwise identical to `task`. Notes `Task` objects created using `scopedTask` will automatically call `Task.yieldForce` in their destructor if necessary to ensure the `Task` is complete before the stack frame they reside on is destroyed. alias **totalCPUs** = \_\_lazilyInitializedConstant!(immutable(uint), 4294967295u, totalCPUsImpl).\_\_lazilyInitializedConstant; The total number of CPU cores available on the current machine, as reported by the operating system. class **TaskPool**; This class encapsulates a task queue and a set of worker threads. Its purpose is to efficiently map a large number of `Task`s onto a smaller number of threads. A task queue is a FIFO queue of `Task` objects that have been submitted to the `TaskPool` and are awaiting execution. A worker thread is a thread that executes the `Task` at the front of the queue when one is available and sleeps when the queue is empty. This class should usually be used via the global instantiation available via the [`std.parallelism.taskPool`](std_parallelism#taskPool) property. Occasionally it is useful to explicitly instantiate a `TaskPool`: 1. When you want `TaskPool` instances with multiple priorities, for example a low priority pool and a high priority pool. 2. When the threads in the global task pool are waiting on a synchronization primitive (for example a mutex), and you want to parallelize the code that needs to run before these threads can be resumed. Note The worker threads in this pool will not stop until `stop` or `finish` is called, even if the main thread has finished already. This may lead to programs that never end. If you do not want this behaviour, you can set `isDaemon` to true. @trusted this(); Default constructor that initializes a `TaskPool` with `totalCPUs` - 1 worker threads. The minus 1 is included because the main thread will also be available to do work. Note On single-core machines, the primitives provided by `TaskPool` operate transparently in single-threaded mode. @trusted this(size\_t nWorkers); Allows for custom number of worker threads. ParallelForeach!R **parallel**(R)(R range, size\_t workUnitSize); ParallelForeach!R **parallel**(R)(R range); Implements a parallel foreach loop over a range. This works by implicitly creating and submitting one `Task` to the `TaskPool` for each worker thread. A work unit is a set of consecutive elements of `range` to be processed by a worker thread between communication with any other thread. The number of elements processed per work unit is controlled by the `workUnitSize` parameter. Smaller work units provide better load balancing, but larger work units avoid the overhead of communicating with other threads frequently to fetch the next work unit. Large work units also avoid false sharing in cases where the range is being modified. The less time a single iteration of the loop takes, the larger `workUnitSize` should be. For very expensive loop bodies, `workUnitSize` should be 1. An overload that chooses a default work unit size is also available. Example ``` // Find the logarithm of every number from 1 to // 10_000_000 in parallel. auto logs = new double[10_000_000]; // Parallel foreach works with or without an index // variable. It can be iterate by ref if range.front // returns by ref. // Iterate over logs using work units of size 100. foreach (i, ref elem; taskPool.parallel(logs, 100)) { elem = log(i + 1.0); } // Same thing, but use the default work unit size. // // Timings on an Athlon 64 X2 dual core machine: // // Parallel foreach: 388 milliseconds // Regular foreach: 619 milliseconds foreach (i, ref elem; taskPool.parallel(logs)) { elem = log(i + 1.0); } ``` Notes The memory usage of this implementation is guaranteed to be constant in `range.length`. Breaking from a parallel foreach loop via a break, labeled break, labeled continue, return or goto statement throws a `ParallelForeachError`. In the case of non-random access ranges, parallel foreach buffers lazily to an array of size `workUnitSize` before executing the parallel portion of the loop. The exception is that, if a parallel foreach is executed over a range returned by `asyncBuf` or `map`, the copying is elided and the buffers are simply swapped. In this case `workUnitSize` is ignored and the work unit size is set to the buffer size of `range`. A memory barrier is guaranteed to be executed on exit from the loop, so that results produced by all threads are visible in the calling thread. **Exception Handling**: When at least one exception is thrown from inside a parallel foreach loop, the submission of additional `Task` objects is terminated as soon as possible, in a non-deterministic manner. All executing or enqueued work units are allowed to complete. Then, all exceptions that were thrown by any work unit are chained using `Throwable.next` and rethrown. The order of the exception chaining is non-deterministic. template **amap**(functions...) auto **amap**(Args...)(Args args) Constraints: if (isRandomAccessRange!(Args[0])); Eager parallel map. The eagerness of this function means it has less overhead than the lazily evaluated `TaskPool.map` and should be preferred where the memory requirements of eagerness are acceptable. `functions` are the functions to be evaluated, passed as template alias parameters in a style similar to [`std.algorithm.iteration.map`](std_algorithm_iteration#map). The first argument must be a random access range. For performance reasons, amap will assume the range elements have not yet been initialized. Elements will be overwritten without calling a destructor nor doing an assignment. As such, the range must not contain meaningful data: either un-initialized objects, or objects in their `.init` state. ``` auto numbers = iota(100_000_000.0); // Find the square roots of numbers. // // Timings on an Athlon 64 X2 dual core machine: // // Parallel eager map: 0.802 s // Equivalent serial implementation: 1.768 s auto squareRoots = taskPool.amap!sqrt(numbers); ``` Immediately after the range argument, an optional work unit size argument may be provided. Work units as used by `amap` are identical to those defined for parallel foreach. If no work unit size is provided, the default work unit size is used. ``` // Same thing, but make work unit size 100. auto squareRoots = taskPool.amap!sqrt(numbers, 100); ``` An output range for returning the results may be provided as the last argument. If one is not provided, an array of the proper type will be allocated on the garbage collected heap. If one is provided, it must be a random access range with assignable elements, must have reference semantics with respect to assignment to its elements, and must have the same length as the input range. Writing to adjacent elements from different threads must be safe. ``` // Same thing, but explicitly allocate an array // to return the results in. The element type // of the array may be either the exact type // returned by functions or an implicit conversion // target. auto squareRoots = new float[numbers.length]; taskPool.amap!sqrt(numbers, squareRoots); // Multiple functions, explicit output range, and // explicit work unit size. auto results = new Tuple!(float, real)[numbers.length]; taskPool.amap!(sqrt, log)(numbers, 100, results); ``` Note A memory barrier is guaranteed to be executed after all results are written but before returning so that results produced by all threads are visible in the calling thread. Tips To perform the mapping operation in place, provide the same range for the input and output range. To parallelize the copying of a range with expensive to evaluate elements to an array, pass an identity function (a function that just returns whatever argument is provided to it) to `amap`. **Exception Handling**: When at least one exception is thrown from inside the map functions, the submission of additional `Task` objects is terminated as soon as possible, in a non-deterministic manner. All currently executing or enqueued work units are allowed to complete. Then, all exceptions that were thrown from any work unit are chained using `Throwable.next` and rethrown. The order of the exception chaining is non-deterministic. template **map**(functions...) auto **map**(S)(S source, size\_t bufSize = 100, size\_t workUnitSize = size\_t.max) Constraints: if (isInputRange!S); A semi-lazy parallel map that can be used for pipelining. The map functions are evaluated for the first `bufSize` elements and stored in a buffer and made available to `popFront`. Meanwhile, in the background a second buffer of the same size is filled. When the first buffer is exhausted, it is swapped with the second buffer and filled while the values from what was originally the second buffer are read. This implementation allows for elements to be written to the buffer without the need for atomic operations or synchronization for each write, and enables the mapping function to be evaluated efficiently in parallel. `map` has more overhead than the simpler procedure used by `amap` but avoids the need to keep all results in memory simultaneously and works with non-random access ranges. Parameters: | | | | --- | --- | | S `source` | The [input range](std_range_primitives#isInputRange) to be mapped. If `source` is not random access it will be lazily buffered to an array of size `bufSize` before the map function is evaluated. (For an exception to this rule, see Notes.) | | size\_t `bufSize` | The size of the buffer to store the evaluated elements. | | size\_t `workUnitSize` | The number of elements to evaluate in a single `Task`. Must be less than or equal to `bufSize`, and should be a fraction of `bufSize` such that all worker threads can be used. If the default of size\_t.max is used, workUnitSize will be set to the pool-wide default. | Returns: An input range representing the results of the map. This range has a length iff `source` has a length. Notes If a range returned by `map` or `asyncBuf` is used as an input to `map`, then as an optimization the copying from the output buffer of the first range to the input buffer of the second range is elided, even though the ranges returned by `map` and `asyncBuf` are non-random access ranges. This means that the `bufSize` parameter passed to the current call to `map` will be ignored and the size of the buffer will be the buffer size of `source`. Example ``` // Pipeline reading a file, converting each line // to a number, taking the logarithms of the numbers, // and performing the additions necessary to find // the sum of the logarithms. auto lineRange = File("numberList.txt").byLine(); auto dupedLines = std.algorithm.map!"a.idup"(lineRange); auto nums = taskPool.map!(to!double)(dupedLines); auto logs = taskPool.map!log10(nums); double sum = 0; foreach (elem; logs) { sum += elem; } ``` **Exception Handling**: Any exceptions thrown while iterating over `source` or computing the map function are re-thrown on a call to `popFront` or, if thrown during construction, are simply allowed to propagate to the caller. In the case of exceptions thrown while computing the map function, the exceptions are chained as in `TaskPool.amap`. auto **asyncBuf**(S)(S source, size\_t bufSize = 100) Constraints: if (isInputRange!S); Given a `source` range that is expensive to iterate over, returns an [input range](std_range_primitives#isInputRange) that asynchronously buffers the contents of `source` into a buffer of `bufSize` elements in a worker thread, while making previously buffered elements from a second buffer, also of size `bufSize`, available via the range interface of the returned object. The returned range has a length iff `hasLength!S`. `asyncBuf` is useful, for example, when performing expensive operations on the elements of ranges that represent data on a disk or network. Example ``` import std.conv, std.stdio; void main() { // Fetch lines of a file in a background thread // while processing previously fetched lines, // dealing with byLine's buffer recycling by // eagerly duplicating every line. auto lines = File("foo.txt").byLine(); auto duped = std.algorithm.map!"a.idup"(lines); // Fetch more lines in the background while we // process the lines already read into memory // into a matrix of doubles. double[][] matrix; auto asyncReader = taskPool.asyncBuf(duped); foreach (line; asyncReader) { auto ls = line.split("\t"); matrix ~= to!(double[])(ls); } } ``` **Exception Handling**: Any exceptions thrown while iterating over `source` are re-thrown on a call to `popFront` or, if thrown during construction, simply allowed to propagate to the caller. auto **asyncBuf**(C1, C2)(C1 next, C2 empty, size\_t initialBufSize = 0, size\_t nBuffers = 100) Constraints: if (is(typeof(C2.init()) : bool) && (Parameters!C1.length == 1) && (Parameters!C2.length == 0) && isArray!(Parameters!C1[0])); Given a callable object `next` that writes to a user-provided buffer and a second callable object `empty` that determines whether more data is available to write via `next`, returns an input range that asynchronously calls `next` with a set of size `nBuffers` of buffers and makes the results available in the order they were obtained via the input range interface of the returned object. Similarly to the input range overload of `asyncBuf`, the first half of the buffers are made available via the range interface while the second half are filled and vice-versa. Parameters: | | | | --- | --- | | C1 `next` | A callable object that takes a single argument that must be an array with mutable elements. When called, `next` writes data to the array provided by the caller. | | C2 `empty` | A callable object that takes no arguments and returns a type implicitly convertible to `bool`. This is used to signify that no more data is available to be obtained by calling `next`. | | size\_t `initialBufSize` | The initial size of each buffer. If `next` takes its array by reference, it may resize the buffers. | | size\_t `nBuffers` | The number of buffers to cycle through when calling `next`. | Example ``` // Fetch lines of a file in a background // thread while processing previously fetched // lines, without duplicating any lines. auto file = File("foo.txt"); void next(ref char[] buf) { file.readln(buf); } // Fetch more lines in the background while we // process the lines already read into memory // into a matrix of doubles. double[][] matrix; auto asyncReader = taskPool.asyncBuf(&next, &file.eof); foreach (line; asyncReader) { auto ls = line.split("\t"); matrix ~= to!(double[])(ls); } ``` **Exception Handling**: Any exceptions thrown while iterating over `range` are re-thrown on a call to `popFront`. Warning Using the range returned by this function in a parallel foreach loop will not work because buffers may be overwritten while the task that processes them is in queue. This is checked for at compile time and will result in a static assertion failure. template **reduce**(functions...) auto **reduce**(Args...)(Args args); Parallel reduce on a random access range. Except as otherwise noted, usage is similar to [`std.algorithm.iteration.reduce`](std_algorithm_iteration#reduce). There is also [`fold`](#fold) which does the same thing with a different parameter order. This function works by splitting the range to be reduced into work units, which are slices to be reduced in parallel. Once the results from all work units are computed, a final serial reduction is performed on these results to compute the final answer. Therefore, care must be taken to choose the seed value appropriately. Because the reduction is being performed in parallel, `functions` must be associative. For notational simplicity, let # be an infix operator representing `functions`. Then, (a # b) # c must equal a # (b # c). Floating point addition is not associative even though addition in exact arithmetic is. Summing floating point numbers using this function may give different results than summing serially. However, for many practical purposes floating point addition can be treated as associative. Note that, since `functions` are assumed to be associative, additional optimizations are made to the serial portion of the reduction algorithm. These take advantage of the instruction level parallelism of modern CPUs, in addition to the thread-level parallelism that the rest of this module exploits. This can lead to better than linear speedups relative to [`std.algorithm.iteration.reduce`](std_algorithm_iteration#reduce), especially for fine-grained benchmarks like dot products. An explicit seed may be provided as the first argument. If provided, it is used as the seed for all work units and for the final reduction of results from all work units. Therefore, if it is not the identity value for the operation being performed, results may differ from those generated by [`std.algorithm.iteration.reduce`](std_algorithm_iteration#reduce) or depending on how many work units are used. The next argument must be the range to be reduced. ``` // Find the sum of squares of a range in parallel, using // an explicit seed. // // Timings on an Athlon 64 X2 dual core machine: // // Parallel reduce: 72 milliseconds // Using std.algorithm.reduce instead: 181 milliseconds auto nums = iota(10_000_000.0f); auto sumSquares = taskPool.reduce!"a + b"( 0.0, std.algorithm.map!"a * a"(nums) ); ``` If no explicit seed is provided, the first element of each work unit is used as a seed. For the final reduction, the result from the first work unit is used as the seed. ``` // Find the sum of a range in parallel, using the first // element of each work unit as the seed. auto sum = taskPool.reduce!"a + b"(nums); ``` An explicit work unit size may be specified as the last argument. Specifying too small a work unit size will effectively serialize the reduction, as the final reduction of the result of each work unit will dominate computation time. If `TaskPool.size` for this instance is zero, this parameter is ignored and one work unit is used. ``` // Use a work unit size of 100. auto sum2 = taskPool.reduce!"a + b"(nums, 100); // Work unit size of 100 and explicit seed. auto sum3 = taskPool.reduce!"a + b"(0.0, nums, 100); ``` Parallel reduce supports multiple functions, like `std.algorithm.reduce`. ``` // Find both the min and max of nums. auto minMax = taskPool.reduce!(min, max)(nums); assert(minMax[0] == reduce!min(nums)); assert(minMax[1] == reduce!max(nums)); ``` **Exception Handling**: After this function is finished executing, any exceptions thrown are chained together via `Throwable.next` and rethrown. The chaining order is non-deterministic. See Also: [`fold`](#fold) is functionally equivalent to [`reduce`](#reduce) except the range parameter comes first and there is no need to use [`tuple`](std_typecons#tuple) for multiple seeds. template **fold**(functions...) auto **fold**(Args...)(Args args); Implements the homonym function (also known as `accumulate`, `compress`, `inject`, or `foldl`) present in various programming languages of functional flavor. `fold` is functionally equivalent to [`reduce`](#reduce) except the range parameter comes first and there is no need to use [`tuple`](std_typecons#tuple) for multiple seeds. There may be one or more callable entities (`functions` argument) to apply. Parameters: | | | | --- | --- | | Args `args` | Just the range to fold over; or the range and one seed per function; or the range, one seed per function, and the work unit size | Returns: The accumulated result as a single value for single function and as a tuple of values for multiple functions See Also: Similar to [`std.algorithm.iteration.fold`](std_algorithm_iteration#fold), `fold` is a wrapper around [`reduce`](#reduce). Example ``` static int adder(int a, int b) { return a + b; } static int multiplier(int a, int b) { return a * b; } // Just the range auto x = taskPool.fold!adder([1, 2, 3, 4]); assert(x == 10); // The range and the seeds (0 and 1 below; also note multiple // functions in this example) auto y = taskPool.fold!(adder, multiplier)([1, 2, 3, 4], 0, 1); assert(y[0] == 10); assert(y[1] == 24); // The range, the seed (0), and the work unit size (20) auto z = taskPool.fold!adder([1, 2, 3, 4], 0, 20); assert(z == 10); ``` const nothrow @property @safe size\_t **workerIndex**(); Gets the index of the current thread relative to this `TaskPool`. Any thread not in this pool will receive an index of 0. The worker threads in this pool receive unique indices of 1 through `this.size`. This function is useful for maintaining worker-local resources. Example ``` // Execute a loop that computes the greatest common // divisor of every number from 0 through 999 with // 42 in parallel. Write the results out to // a set of files, one for each thread. This allows // results to be written out without any synchronization. import std.conv, std.range, std.numeric, std.stdio; void main() { auto filesHandles = new File[taskPool.size + 1]; scope(exit) { foreach (ref handle; fileHandles) { handle.close(); } } foreach (i, ref handle; fileHandles) { handle = File("workerResults" ~ to!string(i) ~ ".txt"); } foreach (num; parallel(iota(1_000))) { auto outHandle = fileHandles[taskPool.workerIndex]; outHandle.writeln(num, '\t', gcd(num, 42)); } } ``` struct **WorkerLocalStorage**(T); Struct for creating worker-local storage. Worker-local storage is thread-local storage that exists only for worker threads in a given `TaskPool` plus a single thread outside the pool. It is allocated on the garbage collected heap in a way that avoids false sharing, and doesn't necessarily have global scope within any thread. It can be accessed from any worker thread in the `TaskPool` that created it, and one thread outside this `TaskPool`. All threads outside the pool that created a given instance of worker-local storage share a single slot. Since the underlying data for this struct is heap-allocated, this struct has reference semantics when passed between functions. The main uses cases for `WorkerLocalStorageStorage` are: 1. Performing parallel reductions with an imperative, as opposed to functional, programming style. In this case, it's useful to treat `WorkerLocalStorageStorage` as local to each thread for only the parallel portion of an algorithm. 2. Recycling temporary buffers across iterations of a parallel foreach loop. Example ``` // Calculate pi as in our synopsis example, but // use an imperative instead of a functional style. immutable n = 1_000_000_000; immutable delta = 1.0L / n; auto sums = taskPool.workerLocalStorage(0.0L); foreach (i; parallel(iota(n))) { immutable x = ( i - 0.5L ) * delta; immutable toAdd = delta / ( 1.0 + x * x ); sums.get += toAdd; } // Add up the results from each worker thread. real pi = 0; foreach (threadResult; sums.toRange) { pi += 4.0L * threadResult; } ``` @property ref auto **get**(this Qualified)(); Get the current thread's instance. Returns by ref. Note that calling `get` from any thread outside the `TaskPool` that created this instance will return the same reference, so an instance of worker-local storage should only be accessed from one thread outside the pool that created it. If this rule is violated, undefined behavior will result. If assertions are enabled and `toRange` has been called, then this WorkerLocalStorage instance is no longer worker-local and an assertion failure will result when calling this method. This is not checked when assertions are disabled for performance reasons. @property void **get**(T val); Assign a value to the current thread's instance. This function has the same caveats as its overload. @property WorkerLocalStorageRange!T **toRange**(); Returns a range view of the values for all threads, which can be used to further process the results of each thread after running the parallel part of your algorithm. Do not use this method in the parallel portion of your algorithm. Calling this function sets a flag indicating that this struct is no longer worker-local, and attempting to use the `get` method again will result in an assertion failure if assertions are enabled. struct **WorkerLocalStorageRange**(T); Range primitives for worker-local storage. The purpose of this is to access results produced by each worker thread from a single thread once you are no longer using the worker-local storage from multiple threads. Do not use this struct in the parallel portion of your algorithm. The proper way to instantiate this object is to call `WorkerLocalStorage.toRange`. Once instantiated, this object behaves as a finite random-access range with assignable, lvalue elements and a length equal to the number of worker threads in the `TaskPool` that created it plus 1. WorkerLocalStorage!T **workerLocalStorage**(T)(lazy T initialVal = T.init); Creates an instance of worker-local storage, initialized with a given value. The value is `lazy` so that you can, for example, easily create one instance of a class for each worker. For usage example, see the `WorkerLocalStorage` struct. @trusted void **stop**(); Signals to all worker threads to terminate as soon as they are finished with their current `Task`, or immediately if they are not executing a `Task`. `Task`s that were in queue will not be executed unless a call to `Task.workForce`, `Task.yieldForce` or `Task.spinForce` causes them to be executed. Use only if you have waited on every `Task` and therefore know the queue is empty, or if you speculatively executed some tasks and no longer need the results. @trusted void **finish**(bool blocking = false); Signals worker threads to terminate when the queue becomes empty. If blocking argument is true, wait for all worker threads to terminate before returning. This option might be used in applications where task results are never consumed-- e.g. when `TaskPool` is employed as a rudimentary scheduler for tasks which communicate by means other than return values. Warning Calling this function with `blocking = true` from a worker thread that is a member of the same `TaskPool` that `finish` is being called on will result in a deadlock. const pure nothrow @property @safe size\_t **size**(); Returns the number of worker threads in the pool. void **put**(alias fun, Args...)(ref Task!(fun, Args) task) Constraints: if (!isSafeReturn!(typeof(task))); void **put**(alias fun, Args...)(Task!(fun, Args)\* task) Constraints: if (!isSafeReturn!(typeof(\*task))); Put a `Task` object on the back of the task queue. The `Task` object may be passed by pointer or reference. Example ``` import std.file; // Create a task. auto t = task!read("foo.txt"); // Add it to the queue to be executed. taskPool.put(t); ``` Notes @trusted overloads of this function are called for `Task`s if [`std.traits.hasUnsharedAliasing`](std_traits#hasUnsharedAliasing) is false for the `Task`'s return type or the function the `Task` executes is `pure`. `Task` objects that meet all other requirements specified in the `@trusted` overloads of `task` and `scopedTask` may be created and executed from `@safe` code via `Task.executeInNewThread` but not via `TaskPool`. While this function takes the address of variables that may be on the stack, some overloads are marked as @trusted. `Task` includes a destructor that waits for the task to complete before destroying the stack frame it is allocated on. Therefore, it is impossible for the stack frame to be destroyed before the task is complete and no longer referenced by a `TaskPool`. @property @trusted bool **isDaemon**(); @property @trusted void **isDaemon**(bool newVal); These properties control whether the worker threads are daemon threads. A daemon thread is automatically terminated when all non-daemon threads have terminated. A non-daemon thread will prevent a program from terminating as long as it has not terminated. If any `TaskPool` with non-daemon threads is active, either `stop` or `finish` must be called on it before the program can terminate. The worker treads in the `TaskPool` instance returned by the `taskPool` property are daemon by default. The worker threads of manually instantiated task pools are non-daemon by default. Note For a size zero pool, the getter arbitrarily returns true and the setter has no effect. @property @trusted int **priority**(); @property @trusted void **priority**(int newPriority); These functions allow getting and setting the OS scheduling priority of the worker threads in this `TaskPool`. They forward to `core.thread.Thread.priority`, so a given priority value here means the same thing as an identical priority value in `core.thread`. Note For a size zero pool, the getter arbitrarily returns `core.thread.Thread.PRIORITY_MIN` and the setter has no effect. @property @trusted TaskPool **taskPool**(); Returns a lazily initialized global instantiation of `TaskPool`. This function can safely be called concurrently from multiple non-worker threads. The worker threads in this pool are daemon threads, meaning that it is not necessary to call `TaskPool.stop` or `TaskPool.finish` before terminating the main thread. @property @trusted uint **defaultPoolThreads**(); @property @trusted void **defaultPoolThreads**(uint newVal); These properties get and set the number of worker threads in the `TaskPool` instance returned by `taskPool`. The default value is `totalCPUs` - 1. Calling the setter after the first call to `taskPool` does not changes number of worker threads in the instance returned by `taskPool`. ParallelForeach!R **parallel**(R)(R range); ParallelForeach!R **parallel**(R)(R range, size\_t workUnitSize); Convenience functions that forwards to `taskPool.parallel`. The purpose of these is to make parallel foreach less verbose and more readable. Example ``` // Find the logarithm of every number from // 1 to 1_000_000 in parallel, using the // default TaskPool instance. auto logs = new double[1_000_000]; foreach (i, ref elem; parallel(logs)) { elem = log(i + 1.0); } ```
programming_docs
d core.stdc.fenv core.stdc.fenv ============== D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<fenv.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/fenv.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly Source [core/stdc/fenv.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/fenv.d) Standards: ISO/IEC 9899:1999 (E) **FE\_INVALID** **FE\_DENORMAL** non-standard **FE\_DIVBYZERO** **FE\_OVERFLOW** **FE\_UNDERFLOW** **FE\_INEXACT** **FE\_ALL\_EXCEPT** **FE\_TONEAREST** **FE\_DOWNWARD** **FE\_UPWARD** **FE\_TOWARDZERO** enum fenv\_t\* **FE\_DFL\_ENV**; nothrow @nogc @system int **feclearexcept**(int excepts); nothrow @nogc @system int **fetestexcept**(int excepts); nothrow @nogc @system int **feholdexcept**(fenv\_t\* envp); nothrow @nogc @system int **fegetexceptflag**(fexcept\_t\* flagp, int excepts); nothrow @nogc @system int **fesetexceptflag**(scope const fexcept\_t\* flagp, int excepts); nothrow @nogc @system int **fegetround**(); nothrow @nogc @system int **fesetround**(int round); nothrow @nogc @system int **fegetenv**(fenv\_t\* envp); nothrow @nogc @system int **fesetenv**(scope const fenv\_t\* envp); nothrow @nogc @system int **feraiseexcept**(int excepts); nothrow @nogc @system int **feupdateenv**(scope const fenv\_t\* envp); d std.bigint std.bigint ========== Arbitrary-precision ('bignum') arithmetic. Performance is optimized for numbers below ~1000 decimal digits. For X86 machines, highly optimised assembly routines are used. The following algorithms are currently implemented: * Karatsuba multiplication * Squaring is optimized independently of multiplication * Divide-and-conquer division * Binary exponentiation For very large numbers, consider using the [GMP library](http://gmplib.org) instead. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Don Clugston Source [std/bigint.d](https://github.com/dlang/phobos/blob/master/std/bigint.d) struct **BigInt**; A struct representing an arbitrary precision integer. All arithmetic operations are supported, except unsigned shift right (`>>>`). Bitwise operations (`|`, `&`, `^`, `~`) are supported, and behave as if BigInt was an infinite length 2's complement number. BigInt implements value semantics using copy-on-write. This means that assignment is cheap, but operations such as x++ will cause heap allocation. (But note that for most bigint operations, heap allocation is inevitable anyway.) Examples: ``` BigInt a = "9588669891916142"; BigInt b = "7452469135154800"; auto c = a * b; writeln(c); // BigInt("71459266416693160362545788781600") auto d = b * a; writeln(d); // BigInt("71459266416693160362545788781600") writeln(d); // c d = c * BigInt("794628672112"); writeln(d); // BigInt("56783581982794522489042432639320434378739200") auto e = c + d; writeln(e); // BigInt("56783581982865981755459125799682980167520800") auto f = d + c; writeln(f); // e auto g = f - c; writeln(g); // d g = f - d; writeln(g); // c e = 12345678; g = c + e; auto h = g / b; auto i = g % b; writeln(h); // a writeln(i); // e BigInt j = "-0x9A56_57f4_7B83_AB78"; BigInt k = j; j ^^= 11; writeln(k^^11); // j ``` this(Range)(Range s) Constraints: if (isBidirectionalRange!Range && isSomeChar!(ElementType!Range) && !isInfinite!Range && !isNarrowString!Range); pure this(Range)(Range s) Constraints: if (isNarrowString!Range); Construct a `BigInt` from a decimal or hexadecimal string. The number must be in the form of a decimal or hex literal. It may have a leading `+` or `-` sign, followed by `0x` or `0X` if hexadecimal. Underscores are permitted in any location after the `0x` and/or the sign of the number. Parameters: | | | | --- | --- | | Range `s` | a finite bidirectional range of any character type | Throws: [`std.conv.ConvException`](std_conv#ConvException) if the string doesn't represent a valid number this(Range)(bool isNegative, Range magnitude) Constraints: if (isInputRange!Range && isUnsigned!(ElementType!Range) && (hasLength!Range || isForwardRange!Range) && !isInfinite!Range); Construct a `BigInt` from a sign and a magnitude. The magnitude is an [input range](std_range_primitives#isInputRange) of unsigned integers that satisfies either [`std.range.primitives.hasLength`](std_range_primitives#hasLength) or [`std.range.primitives.isForwardRange`](std_range_primitives#isForwardRange). The first (leftmost) element of the magnitude is considered the most significant. Parameters: | | | | --- | --- | | bool `isNegative` | true for negative, false for non-negative (ignored when magnitude is zero) | | Range `magnitude` | a finite range of unsigned integers | Examples: ``` ubyte[] magnitude = [1, 2, 3, 4, 5, 6]; auto b1 = BigInt(false, magnitude); writeln(cast(long)b1); // 0x01_02_03_04_05_06L auto b2 = BigInt(true, magnitude); writeln(cast(long)b2); // -0x01_02_03_04_05_06L ``` pure nothrow @safe this(T)(T x) Constraints: if (isIntegral!T); Construct a `BigInt` from a built-in integral type. Examples: ``` ulong data = 1_000_000_000_000; auto bigData = BigInt(data); writeln(bigData); // BigInt("1_000_000_000_000") ``` pure nothrow @safe this(T)(T x) Constraints: if (is(immutable(T) == immutable(BigInt))); Construct a `BigInt` from another `BigInt`. Examples: ``` const(BigInt) b1 = BigInt("1_234_567_890"); BigInt b2 = BigInt(b1); writeln(b2); // BigInt("1_234_567_890") ``` pure nothrow @safe BigInt **opAssign**(T)(T x) Constraints: if (isIntegral!T); Assignment from built-in integer types. Examples: ``` auto b = BigInt("123"); b = 456; writeln(b); // BigInt("456") ``` pure @nogc @safe BigInt **opAssign**(T : BigInt)(T x); Assignment from another BigInt. Examples: ``` auto b1 = BigInt("123"); auto b2 = BigInt("456"); b2 = b1; writeln(b2); // BigInt("123") ``` pure nothrow @safe BigInt **opOpAssign**(string op, T)(T y) Constraints: if ((op == "+" || op == "-" || op == "\*" || op == "/" || op == "%" || op == ">>" || op == "<<" || op == "^^" || op == "|" || op == "&" || op == "^") && isIntegral!T); Implements assignment operators from built-in integers of the form `BigInt op= integer`. Examples: ``` auto b = BigInt("1_000_000_000"); b += 12345; writeln(b); // BigInt("1_000_012_345") b /= 5; writeln(b); // BigInt("200_002_469") ``` pure nothrow @safe BigInt **opOpAssign**(string op, T)(T y) Constraints: if ((op == "+" || op == "-" || op == "\*" || op == "|" || op == "&" || op == "^" || op == "/" || op == "%") && is(T : BigInt)); Implements assignment operators of the form `BigInt op= BigInt`. Examples: ``` auto x = BigInt("123"); auto y = BigInt("321"); x += y; writeln(x); // BigInt("444") ``` const pure nothrow @safe BigInt **opBinary**(string op, T)(T y) Constraints: if ((op == "+" || op == "\*" || op == "-" || op == "|" || op == "&" || op == "^" || op == "/" || op == "%") && is(T : BigInt)); Implements binary operators between `BigInt`s. Examples: ``` auto x = BigInt("123"); auto y = BigInt("456"); BigInt z = x * y; writeln(z); // BigInt("56088") ``` const pure nothrow @safe BigInt **opBinary**(string op, T)(T y) Constraints: if ((op == "+" || op == "\*" || op == "-" || op == "/" || op == "|" || op == "&" || op == "^" || op == ">>" || op == "<<" || op == "^^") && isIntegral!T); Implements binary operators between `BigInt`'s and built-in integers. Examples: ``` auto x = BigInt("123"); x *= 300; writeln(x); // BigInt("36900") ``` const pure nothrow @safe auto **opBinary**(string op, T)(T y) Constraints: if (op == "%" && isIntegral!T); Implements a narrowing remainder operation with built-in integer types. This binary operator returns a narrower, built-in integer type where applicable, according to the following table. | | | | | | | --- | --- | --- | --- | --- | | `BigInt` | `%` | `uint` | → | `long` | | `BigInt` | `%` | `long` | → | `long` | | `BigInt` | `%` | `ulong` | → | `BigInt` | | `BigInt` | `%` | other type | → | `int` | Examples: ``` auto x = BigInt("1_000_000_500"); long l = 1_000_000L; ulong ul = 2_000_000UL; int i = 500_000; short s = 30_000; assert(is(typeof(x % l) == long) && x % l == 500L); assert(is(typeof(x % ul) == BigInt) && x % ul == BigInt(500)); assert(is(typeof(x % i) == int) && x % i == 500); assert(is(typeof(x % s) == int) && x % s == 10500); ``` const pure nothrow @safe BigInt **opBinaryRight**(string op, T)(T y) Constraints: if ((op == "+" || op == "\*" || op == "|" || op == "&" || op == "^") && isIntegral!T); const pure nothrow @safe BigInt **opBinaryRight**(string op, T)(T y) Constraints: if (op == "-" && isIntegral!T); const pure nothrow @safe T **opBinaryRight**(string op, T)(T x) Constraints: if ((op == "%" || op == "/") && isIntegral!T); Implements operators with built-in integers on the left-hand side and `BigInt` on the right-hand side. Examples: ``` auto x = BigInt("100"); BigInt y = 123 + x; writeln(y); // BigInt("223") BigInt z = 123 - x; writeln(z); // BigInt("23") // Dividing a built-in integer type by BigInt always results in // something that fits in a built-in type, so the built-in type is // returned, not BigInt. assert(is(typeof(1000 / x) == int)); writeln(1000 / x); // 10 ``` const pure nothrow @safe BigInt **opUnary**(string op)() Constraints: if (op == "+" || op == "-" || op == "~"); pure nothrow @safe BigInt **opUnary**(string op)() Constraints: if (op == "++" || op == "--"); Implements `BigInt` unary operators. Examples: ``` auto x = BigInt("1234"); writeln(-x); // BigInt("-1234") ++x; writeln(x); // BigInt("1235") ``` const pure @nogc @safe bool **opEquals**()(auto ref const BigInt y); const pure nothrow @nogc @safe bool **opEquals**(T)(const T y) Constraints: if (isIntegral!T); const nothrow @nogc bool **opEquals**(T)(const T y) Constraints: if (isFloatingPoint!T); Implements `BigInt` equality test with other `BigInt`'s and built-in numeric types. Examples: ``` // Note that when comparing a BigInt to a float or double the // full precision of the BigInt is always considered, unlike // when comparing an int to a float or a long to a double. assert(BigInt(123456789) != cast(float) 123456789); ``` const pure nothrow @nogc @safe T **opCast**(T : bool)(); Implements casting to `bool`. Examples: ``` // Non-zero values are regarded as true auto x = BigInt("1"); auto y = BigInt("10"); assert(x); assert(y); // Zero value is regarded as false auto z = BigInt("0"); assert(!z); ``` const pure @safe T **opCast**(T : ulong)(); Implements casting to integer types. Throws: [`std.conv.ConvOverflowException`](std_conv#ConvOverflowException) if the number exceeds the target type's range. Examples: ``` import std.conv : to, ConvOverflowException; import std.exception : assertThrown; writeln(BigInt("0").to!int); // 0 writeln(BigInt("0").to!ubyte); // 0 writeln(BigInt("255").to!ubyte); // 255 assertThrown!ConvOverflowException(BigInt("256").to!ubyte); assertThrown!ConvOverflowException(BigInt("-1").to!ubyte); ``` const nothrow @nogc @safe T **opCast**(T)() Constraints: if (isFloatingPoint!T); Implements casting to floating point types. Examples: ``` writeln(0x1.abcd_e8p+124f); // cast(float)BigInt("0x1abc_de80_0000_0000_0000_0000_0000_0000") // cast(double)BigInt("0x1abc_def1_2345_6000_0000_0000_0000_0000") writeln(0x1.abcd_ef12_3456p+124); // cast(real)BigInt("0x1abc_def1_2345_6000_0000_0000_0000_0000") writeln(0x1.abcd_ef12_3456p+124L); writeln(-0x1.3456_78p+108f); // cast(float)BigInt("-0x1345_6780_0000_0000_0000_0000_0000") // cast(double)BigInt("-0x1345_678a_bcde_f000_0000_0000_0000") writeln(-0x1.3456_78ab_cdefp+108); // cast(real)BigInt("-0x1345_678a_bcde_f000_0000_0000_0000") writeln(-0x1.3456_78ab_cdefp+108L); ``` Examples: Rounding when casting to floating point ``` // BigInts whose values cannot be exactly represented as float/double/real // are rounded when cast to float/double/real. When cast to float or // double or 64-bit real the rounding is strictly defined. When cast // to extended-precision real the rounding rules vary by environment. // BigInts that fall somewhere between two non-infinite floats/doubles // are rounded to the closer value when cast to float/double. writeln(0x1.aaa_aaep+28f); // cast(float)BigInt(0x1aaa_aae7) writeln(0x1.aaa_ab0p+28f); // cast(float)BigInt(0x1aaa_aaff) writeln(-0x1.aaaaaep+28f); // cast(float)BigInt(-0x1aaa_aae7) writeln(-0x1.aaaab0p+28f); // cast(float)BigInt(-0x1aaa_aaff) writeln(0x1.aaa_aaaa_aaaa_aa00p+60); // cast(double)BigInt(0x1aaa_aaaa_aaaa_aa77) writeln(0x1.aaa_aaaa_aaaa_ab00p+60); // cast(double)BigInt(0x1aaa_aaaa_aaaa_aaff) writeln(-0x1.aaa_aaaa_aaaa_aa00p+60); // cast(double)BigInt(-0x1aaa_aaaa_aaaa_aa77) writeln(-0x1.aaa_aaaa_aaaa_ab00p+60); // cast(double)BigInt(-0x1aaa_aaaa_aaaa_aaff) // BigInts that fall exactly between two non-infinite floats/doubles // are rounded away from zero when cast to float/double. (Note that // in most environments this is NOT the same rounding rule rule used // when casting int/long to float/double.) writeln(0x1.aaa_ab0p+28f); // cast(float)BigInt(0x1aaa_aaf0) writeln(-0x1.aaaab0p+28f); // cast(float)BigInt(-0x1aaa_aaf0) writeln(0x1.aaa_aaaa_aaaa_ab00p+60); // cast(double)BigInt(0x1aaa_aaaa_aaaa_aa80) writeln(-0x1.aaa_aaaa_aaaa_ab00p+60); // cast(double)BigInt(-0x1aaa_aaaa_aaaa_aa80) // BigInts that are bounded on one side by the largest positive or // most negative finite float/double and on the other side by infinity // or -infinity are rounded as if in place of infinity was the value // `2^^(T.max_exp)` when cast to float/double. // cast(float)BigInt("999_999_999_999_999_999_999_999_999_999_999_999_999") writeln(float.infinity); // cast(float)BigInt("-999_999_999_999_999_999_999_999_999_999_999_999_999") writeln(-float.infinity); assert(double.infinity > cast(double) BigInt("999_999_999_999_999_999_999_999_999_999_999_999_999")); assert(real.infinity > cast(real) BigInt("999_999_999_999_999_999_999_999_999_999_999_999_999")); ``` const pure nothrow @nogc T **opCast**(T)() Constraints: if (is(immutable(T) == immutable(BigInt))); Implements casting to/from qualified `BigInt`'s. Warning Casting to/from `const` or `immutable` may break type system guarantees. Use with care. Examples: ``` const(BigInt) x = BigInt("123"); BigInt y = cast() x; // cast away const writeln(y); // x ``` const pure nothrow @nogc @safe int **opCmp**(ref const BigInt y); const pure nothrow @nogc @safe int **opCmp**(T)(const T y) Constraints: if (isIntegral!T); const nothrow @nogc @safe int **opCmp**(T)(const T y) Constraints: if (isFloatingPoint!T); const pure nothrow @nogc @safe int **opCmp**(T : BigInt)(const T y); Implements 3-way comparisons of `BigInt` with `BigInt` or `BigInt` with built-in numeric types. Examples: ``` auto x = BigInt("100"); auto y = BigInt("10"); int z = 50; const int w = 200; assert(y < x); assert(x > z); assert(z > y); assert(x < w); ``` Examples: ``` auto x = BigInt("0x1abc_de80_0000_0000_0000_0000_0000_0000"); BigInt y = x - 1; BigInt z = x + 1; double d = 0x1.abcde8p124; assert(y < d); assert(z > d); assert(x >= d && x <= d); // Note that when comparing a BigInt to a float or double the // full precision of the BigInt is always considered, unlike // when comparing an int to a float or a long to a double. assert(BigInt(123456789) < cast(float) 123456789); ``` const pure nothrow @nogc @safe long **toLong**(); Returns: The value of this `BigInt` as a `long`, or `long.max`/`long.min` if outside the representable range. Examples: ``` auto b = BigInt("12345"); long l = b.toLong(); writeln(l); // 12345 ``` const pure nothrow @nogc @safe int **toInt**(); Returns: The value of this `BigInt` as an `int`, or `int.max`/`int.min` if outside the representable range. Examples: ``` auto big = BigInt("5_000_000"); auto i = big.toInt(); writeln(i); // 5_000_000 // Numbers that are too big to fit into an int will be clamped to int.max. auto tooBig = BigInt("5_000_000_000"); i = tooBig.toInt(); writeln(i); // int.max ``` const pure nothrow @nogc @property @safe size\_t **uintLength**(); Number of significant `uint`s which are used in storing this number. The absolute value of this `BigInt` is always < 232\*uintLength const pure nothrow @nogc @property @safe size\_t **ulongLength**(); Number of significant `ulong`s which are used in storing this number. The absolute value of this `BigInt` is always < 264\*ulongLength const void **toString**(Writer)(ref scope Writer sink, string formatString); const void **toString**(Writer)(ref scope Writer sink, ref scope const FormatSpec!char f); const void **toString**(scope void delegate(const(char)[]) sink, string formatString); const void **toString**(scope void delegate(const(char)[]) sink, ref scope const FormatSpec!char f); Convert the `BigInt` to `string`, passing it to the given sink. Parameters: | | | | --- | --- | | Writer `sink` | An OutputRange for accepting possibly piecewise segments of the formatted string. | | string `formatString` | A format string specifying the output format. Available output formats:| "d" | Decimal | | "o" | Octal | | "x" | Hexadecimal, lower case | | "X" | Hexadecimal, upper case | | "s" | Default formatting (same as "d") | | null | Default formatting (same as "d") | | Examples: `toString` is rarely directly invoked; the usual way of using it is via [`std.format.format`](std_format#format): ``` import std.format : format; auto x = BigInt("1_000_000"); x *= 12345; writeln(format("%d", x)); // "12345000000" writeln(format("%x", x)); // "2_dfd1c040" writeln(format("%X", x)); // "2_DFD1C040" writeln(format("%o", x)); // "133764340100" ``` const pure nothrow @nogc @safe size\_t **toHash**(); Returns: A unique hash of the `BigInt`'s value suitable for use in a hash table. Examples: `toHash` is rarely directly invoked; it is implicitly used when BigInt is used as the key of an associative array. ``` string[BigInt] aa; aa[BigInt(123)] = "abc"; aa[BigInt(456)] = "def"; writeln(aa[BigInt(123)]); // "abc" writeln(aa[BigInt(456)]); // "def" ``` const T **getDigit**(T = ulong)(size\_t n) Constraints: if (is(T == ulong) || is(T == uint)); Gets the nth number in the underlying representation that makes up the whole `BigInt`. Parameters: | | | | --- | --- | | T | the type to view the underlying representation as | | size\_t `n` | The nth number to retrieve. Must be less than [`ulongLength`](#ulongLength) or [`uintLength`](#uintLength) with respect to `T`. | Returns: The nth `ulong` in the representation of this `BigInt`. Examples: ``` auto a = BigInt("1000"); writeln(a.ulongLength()); // 1 writeln(a.getDigit(0)); // 1000 writeln(a.uintLength()); // 1 writeln(a.getDigit!uint(0)); // 1000 auto b = BigInt("2_000_000_000_000_000_000_000_000_000"); writeln(b.ulongLength()); // 2 writeln(b.getDigit(0)); // 4584946418820579328 writeln(b.getDigit(1)); // 108420217 writeln(b.uintLength()); // 3 writeln(b.getDigit!uint(0)); // 3489660928 writeln(b.getDigit!uint(1)); // 1067516025 writeln(b.getDigit!uint(2)); // 108420217 ``` pure nothrow @safe string **toDecimalString**(const(BigInt) x); Parameters: | | | | --- | --- | | const(BigInt) `x` | The `BigInt` to convert to a decimal `string`. | Returns: A `string` that represents the `BigInt` as a decimal number. Examples: ``` auto x = BigInt("123"); x *= 1000; x += 456; auto xstr = x.toDecimalString(); writeln(xstr); // "123456" ``` @safe string **toHex**(const(BigInt) x); Parameters: | | | | --- | --- | | const(BigInt) `x` | The `BigInt` to convert to a hexadecimal `string`. | Returns: A `string` that represents the `BigInt` as a hexadecimal (base 16) number in upper case. Examples: ``` auto x = BigInt("123"); x *= 1000; x += 456; auto xstr = x.toHex(); writeln(xstr); // "1E240" ``` Unsigned!T **absUnsign**(T)(T x) Constraints: if (isIntegral!T); Returns the absolute value of x converted to the corresponding unsigned type. Parameters: | | | | --- | --- | | T `x` | The integral value to return the absolute value of. | Returns: The absolute value of x. Examples: ``` writeln((-1).absUnsign); // 1 writeln(1.absUnsign); // 1 ``` pure nothrow @safe void **divMod**(const BigInt dividend, const BigInt divisor, out BigInt quotient, out BigInt remainder); Finds the quotient and remainder for the given dividend and divisor in one operation. Parameters: | | | | --- | --- | | BigInt `dividend` | the [`BigInt`](#BigInt) to divide | | BigInt `divisor` | the [`BigInt`](#BigInt) to divide the dividend by | | BigInt `quotient` | is set to the result of the division | | BigInt `remainder` | is set to the remainder of the division | Examples: ``` auto a = BigInt(123); auto b = BigInt(25); BigInt q, r; divMod(a, b, q, r); writeln(q); // 4 writeln(r); // 23 writeln(q * b + r); // a ``` pure nothrow @safe BigInt **powmod**(BigInt base, BigInt exponent, BigInt modulus); Fast power modulus calculation for [`BigInt`](#BigInt) operands. Parameters: | | | | --- | --- | | BigInt `base` | the [`BigInt`](#BigInt) is basic operands. | | BigInt `exponent` | the [`BigInt`](#BigInt) is power exponent of base. | | BigInt `modulus` | the [`BigInt`](#BigInt) is modules to be modular of base ^ exponent. | Returns: The power modulus value of (base ^ exponent) % modulus. Examples: for powmod ``` BigInt base = BigInt("123456789012345678901234567890"); BigInt exponent = BigInt("1234567890123456789012345678901234567"); BigInt modulus = BigInt("1234567"); BigInt result = powmod(base, exponent, modulus); writeln(result); // 359079 ```
programming_docs
d core.thread.osthread core.thread.osthread ==================== The osthread module provides low-level, OS-dependent code for thread creation and management. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak Source [core/thread/osthread.d](https://github.com/dlang/druntime/blob/master/src/core/thread/osthread.d) class **Thread**: core.thread.threadbase.ThreadBase; This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example. pure nothrow @nogc @safe this(void function() fn, size\_t sz = 0); Initializes a thread object which is associated with a static D function. Parameters: | | | | --- | --- | | void function() `fn` | The thread function. | | size\_t `sz` | The stack size for this thread. | In fn must not be null. pure nothrow @nogc @safe this(void delegate() dg, size\_t sz = 0); Initializes a thread object which is associated with a dynamic D function. Parameters: | | | | --- | --- | | void delegate() `dg` | The thread function. | | size\_t `sz` | The stack size for this thread. | In dg must not be null. static nothrow @nogc @safe Thread **getThis**(); Provides a reference to the calling thread. Returns: The thread object representing the calling thread. The result of deleting this object is undefined. If the current thread is not attached to the runtime, a null reference is returned. final nothrow Thread **start**(); Starts the thread and invokes the function or delegate passed upon construction. In This routine may only be called once per thread instance. Throws: ThreadException if the thread fails to start. final Throwable **join**(bool rethrow = true); Waits for this thread to complete. If the thread terminated as the result of an unhandled exception, this exception will be rethrown. Parameters: | | | | --- | --- | | bool `rethrow` | Rethrow any unhandled exception which may have caused this thread to terminate. | Throws: ThreadException if the operation fails. Any exception not handled by the joined thread. Returns: Any exception not handled by this thread if rethrow = false, null otherwise. static pure nothrow @nogc @property @trusted int **PRIORITY\_MIN**(); The minimum scheduling priority that may be set for a thread. On systems where multiple scheduling policies are defined, this value represents the minimum valid priority for the scheduling policy of the process. static pure nothrow @nogc @property @trusted const(int) **PRIORITY\_MAX**(); The maximum scheduling priority that may be set for a thread. On systems where multiple scheduling policies are defined, this value represents the maximum valid priority for the scheduling policy of the process. static pure nothrow @nogc @property @trusted int **PRIORITY\_DEFAULT**(); The default scheduling priority that is set for a thread. On systems where multiple scheduling policies are defined, this value represents the default priority for the scheduling policy of the process. final @property int **priority**(); Gets the scheduling priority for the associated thread. Note Getting the priority of a thread that already terminated might return the default priority. Returns: The scheduling priority of this thread. final @property void **priority**(int val); Sets the scheduling priority for the associated thread. Note Setting the priority of a thread that already terminated might have no effect. Parameters: | | | | --- | --- | | int `val` | The new scheduling priority of this thread. | final nothrow @nogc @property bool **isRunning**(); Tests whether this thread is running. Returns: true if the thread is running, false if not. static nothrow @nogc void **sleep**(Duration val); Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system. Parameters: | | | | --- | --- | | Duration `val` | The minimum duration the calling thread should be suspended. | In period must be non-negative. Example ``` Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds ``` static nothrow @nogc void **yield**(); Forces a context switch to occur away from the calling thread. nothrow @nogc void **thread\_setGCSignals**(int suspendSignalNo, int resumeSignalNo); Instruct the thread module, when initialized, to use a different set of signals besides SIGUSR1 and SIGUSR2 for suspension and resumption of threads. This function should be called at most once, prior to thread\_init(). This function is Posix-only. Thread **thread\_attachThis**(); Registers the calling thread for use with the D Runtime. If this routine is called for a thread which is already registered, no action is performed. NOTE This routine does not run thread-local static constructors when called. If full functionality as a D thread is desired, the following function must be called after thread\_attachThis: extern (C) void rt\_moduleTlsCtor(); alias **getpid** = core.sys.posix.unistd.**getpid**; Returns the process ID of the calling process, which is guaranteed to be unique on the system. This call is always successful. Example ``` writefln("Current process id: %s", getpid()); ``` nothrow void **thread\_suspendAll**(); Suspend all threads but the calling thread for "stop the world" garbage collection runs. This function may be called multiple times, and must be followed by a matching number of calls to thread\_resumeAll before processing is resumed. Throws: ThreadError if the suspend operation fails for a running thread. @nogc void **thread\_init**(); Initializes the thread module. This function must be called by the garbage collector on startup and before any other thread routines are called. @nogc void **thread\_term**(); Terminates the thread module. No other thread routine may be called afterwards. nothrow @nogc ThreadID **createLowLevelThread**(void delegate() nothrow dg, uint stacksize = 0, void delegate() nothrow cbDllUnload = null); Create a thread not under control of the runtime, i.e. TLS module constructors are not run and the GC does not suspend it during a collection. Parameters: | | | | --- | --- | | void delegate() nothrow `dg` | delegate to execute in the created thread. | | uint `stacksize` | size of the stack of the created thread. The default of 0 will select the platform-specific default size. | | void delegate() nothrow `cbDllUnload` | Windows only: if running in a dynamically loaded DLL, this delegate will be called if the DLL is supposed to be unloaded, but the thread is still running. The thread must be terminated via `joinLowLevelThread` by the callback. | Returns: the platform specific thread ID of the new thread. If an error occurs, `ThreadID.init` is returned. nothrow @nogc void **joinLowLevelThread**(ThreadID tid); Wait for a thread created with `createLowLevelThread` to terminate. Note In a Windows DLL, if this function is called via DllMain with argument DLL\_PROCESS\_DETACH, the thread is terminated forcefully without proper cleanup as a deadlock would happen otherwise. Parameters: | | | | --- | --- | | ThreadID `tid` | the thread ID returned by `createLowLevelThread`. | d std.container.util std.container.util ================== This module contains some common utilities used by containers. This module is a submodule of [`std.container`](std_container). Source [std/container/util.d](https://github.com/dlang/phobos/blob/master/std/container/util.d) License: Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE\_1\_0.txt or copy at [boost.org/LICENSE\_1\_0.txt](http://boost.org/LICENSE_1_0.txt)). Authors: [Andrei Alexandrescu](http://erdani.com) template **make**(T) if (is(T == struct) || is(T == class)) Returns an initialized object. This function is mainly for eliminating construction differences between structs and classes. It allows code to not worry about whether the type it's constructing is a struct or a class. Examples: ``` import std.algorithm.comparison : equal; import std.container; auto arr = make!(Array!int)([4, 2, 3, 1]); assert(equal(arr[], [4, 2, 3, 1])); auto rbt = make!(RedBlackTree!(int, "a > b"))([4, 2, 3, 1]); assert(equal(rbt[], [4, 3, 2, 1])); alias makeList = make!(SList!int); auto slist = makeList(1, 2, 3); assert(equal(slist[], [1, 2, 3])); ``` template **make**(alias Container, Args...) if (!is(Container)) Convenience function for constructing a generic container. Examples: forbid construction from infinite range ``` import std.container.array : Array; import std.range : only, repeat; import std.range.primitives : isInfinite; static assert(__traits(compiles, { auto arr = make!Array(only(5)); })); static assert(!__traits(compiles, { auto arr = make!Array(repeat(5)); })); ``` Examples: ``` import std.algorithm.comparison : equal; import std.container.array, std.container.rbtree, std.container.slist; import std.range : iota; auto arr = make!Array(iota(5)); assert(equal(arr[], [0, 1, 2, 3, 4])); auto rbtmax = make!(RedBlackTree, "a > b")(iota(5)); assert(equal(rbtmax[], [4, 3, 2, 1, 0])); auto rbtmin = make!RedBlackTree(4, 1, 3, 2); assert(equal(rbtmin[], [1, 2, 3, 4])); alias makeList = make!SList; auto list = makeList(1, 7, 42); assert(equal(list[], [1, 7, 42])); ``` d core.stdc.stdarg core.stdc.stdarg ================ D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<stdarg.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdarg.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Walter Bright, Hauke Duden Standards: ISO/IEC 9899:1999 (E) Source [core/stdc/stdarg.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/stdarg.d) alias **va\_list** = \_\_va\_list\_tag\*; The argument pointer type. public import core.internal.vararg.sysv\_x64 : **\_\_va\_list**, **\_\_va\_list\_tag**; The argument pointer type. void **va\_start**(T)(out va\_list ap, ref T parmn); Initialize ap. parmn should be the last named parameter. T **va\_arg**(T)(ref va\_list ap); Retrieve and return the next value that is of type T. void **va\_arg**(T)(ref va\_list ap, ref T parmn); Retrieve and store in parmn the next value that is of type T. nothrow @nogc @system void **va\_end**(va\_list ap); End use of ap. nothrow @nogc @system void **va\_copy**(out va\_list dest, va\_list src, void\* storage = alloca(\_\_va\_list\_tag.sizeof)); Make a copy of ap. d std.bitmanip std.bitmanip ============ Bit-level manipulation facilities. | Category | Functions | | --- | --- | | Bit constructs | [`BitArray`](#BitArray) [`bitfields`](#bitfields) [`bitsSet`](#bitsSet) | | Endianness conversion | [`bigEndianToNative`](#bigEndianToNative) [`littleEndianToNative`](#littleEndianToNative) [`nativeToBigEndian`](#nativeToBigEndian) [`nativeToLittleEndian`](#nativeToLittleEndian) [`swapEndian`](#swapEndian) | | Integral ranges | [`append`](#append) [`peek`](#peek) [`read`](#read) [`write`](#write) | | Floating-Point manipulation | [`DoubleRep`](#DoubleRep) [`FloatRep`](#FloatRep) | | Tagging | [`taggedClassRef`](#taggedClassRef) [`taggedPointer`](#taggedPointer) | License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com), [Andrei Alexandrescu](http://erdani.org), [Jonathan M Davis](http://jmdavisprog.com), Alex Rønne Petersen, Damian Ziemba, Amaury SECHET Source [std/bitmanip.d](https://github.com/dlang/phobos/blob/master/std/bitmanip.d) template **bitfields**(T...) Allows creating bit fields inside structs and classes. The type of a bit field can be any integral type or enumerated type. The most efficient type to store in bitfields is bool, followed by unsigned types, followed by signed types. See Also: [`std.typecons.BitFlags`](std_typecons#BitFlags) Examples: Create a bitfield pack of eight bits, which fit in one ubyte. The bitfields are allocated starting from the least significant bit, i.e. x occupies the two least significant bits of the bitfields storage. ``` struct A { int a; mixin(bitfields!( uint, "x", 2, int, "y", 3, uint, "z", 2, bool, "flag", 1)); } A obj; obj.x = 2; obj.z = obj.x; writeln(obj.x); // 2 writeln(obj.y); // 0 writeln(obj.z); // 2 writeln(obj.flag); // false ``` Examples: The sum of all bit lengths in one bitfield instantiation must be exactly 8, 16, 32, or 64. If padding is needed, just allocate one bitfield with an empty name. ``` struct A { mixin(bitfields!( bool, "flag1", 1, bool, "flag2", 1, uint, "", 6)); } A a; writeln(a.flag1); // 0 a.flag1 = 1; writeln(a.flag1); // 1 a.flag1 = 0; writeln(a.flag1); // 0 ``` Examples: enums can be used too ``` enum ABC { A, B, C } struct EnumTest { mixin(bitfields!( ABC, "x", 2, bool, "y", 1, ubyte, "z", 5)); } ``` enum auto **taggedPointer**(T : T\*, string name, Ts...); This string mixin generator allows one to create tagged pointers inside structs and classes. A tagged pointer uses the bits known to be zero in a normal pointer or class reference to store extra information. For example, a pointer to an integer must be 4-byte aligned, so there are 2 bits that are always known to be zero. One can store a 2-bit integer there. The example above creates a tagged pointer in the struct A. The pointer is of type `uint*` as specified by the first argument, and is named x, as specified by the second argument. Following arguments works the same way as `bitfield`'s. The bitfield must fit into the bits known to be zero because of the pointer alignment. Examples: ``` struct A { int a; mixin(taggedPointer!( uint*, "x", bool, "b1", 1, bool, "b2", 1)); } A obj; obj.x = new uint; obj.b1 = true; obj.b2 = false; ``` template **taggedClassRef**(T, string name, Ts...) if (is(T == class)) This string mixin generator allows one to create tagged class reference inside structs and classes. A tagged class reference uses the bits known to be zero in a normal class reference to store extra information. For example, a pointer to an integer must be 4-byte aligned, so there are 2 bits that are always known to be zero. One can store a 2-bit integer there. The example above creates a tagged reference to an Object in the struct A. This expects the same parameters as `taggedPointer`, except the first argument which must be a class type instead of a pointer type. Examples: ``` struct A { int a; mixin(taggedClassRef!( Object, "o", uint, "i", 2)); } A obj; obj.o = new Object(); obj.i = 3; ``` struct **FloatRep**; Allows manipulating the fraction, exponent, and sign parts of a float separately. The definition is: ``` struct FloatRep { union { float value; mixin(bitfields!( uint, "fraction", 23, ubyte, "exponent", 8, bool, "sign", 1)); } enum uint bias = 127, fractionBits = 23, exponentBits = 8, signBits = 1; } ``` Examples: ``` FloatRep rep = {value: 0}; writeln(rep.fraction); // 0 writeln(rep.exponent); // 0 assert(!rep.sign); rep.value = 42; writeln(rep.fraction); // 2621440 writeln(rep.exponent); // 132 assert(!rep.sign); rep.value = 10; writeln(rep.fraction); // 2097152 writeln(rep.exponent); // 130 ``` Examples: ``` FloatRep rep = {value: 1}; writeln(rep.fraction); // 0 writeln(rep.exponent); // 127 assert(!rep.sign); rep.exponent = 126; writeln(rep.value); // 0.5 rep.exponent = 130; writeln(rep.value); // 8 ``` Examples: ``` FloatRep rep = {value: 1}; rep.value = -0.5; writeln(rep.fraction); // 0 writeln(rep.exponent); // 126 assert(rep.sign); rep.value = -1. / 3; writeln(rep.fraction); // 2796203 writeln(rep.exponent); // 125 assert(rep.sign); ``` struct **DoubleRep**; Allows manipulating the fraction, exponent, and sign parts of a double separately. The definition is: ``` struct DoubleRep { union { double value; mixin(bitfields!( ulong, "fraction", 52, ushort, "exponent", 11, bool, "sign", 1)); } enum uint bias = 1023, signBits = 1, fractionBits = 52, exponentBits = 11; } ``` Examples: ``` DoubleRep rep = {value: 0}; writeln(rep.fraction); // 0 writeln(rep.exponent); // 0 assert(!rep.sign); rep.value = 42; writeln(rep.fraction); // 1407374883553280 writeln(rep.exponent); // 1028 assert(!rep.sign); rep.value = 10; writeln(rep.fraction); // 1125899906842624 writeln(rep.exponent); // 1026 ``` Examples: ``` DoubleRep rep = {value: 1}; writeln(rep.fraction); // 0 writeln(rep.exponent); // 1023 assert(!rep.sign); rep.exponent = 1022; writeln(rep.value); // 0.5 rep.exponent = 1026; writeln(rep.value); // 8 ``` Examples: ``` DoubleRep rep = {value: 1}; rep.value = -0.5; writeln(rep.fraction); // 0 writeln(rep.exponent); // 1022 assert(rep.sign); rep.value = -1. / 3; writeln(rep.fraction); // 1501199875790165 writeln(rep.exponent); // 1021 assert(rep.sign); ``` Examples: Reading ``` DoubleRep x; x.value = 1.0; assert(x.fraction == 0 && x.exponent == 1023 && !x.sign); x.value = -0.5; assert(x.fraction == 0 && x.exponent == 1022 && x.sign); x.value = 0.5; assert(x.fraction == 0 && x.exponent == 1022 && !x.sign); ``` Examples: Writing ``` DoubleRep x; x.fraction = 1125899906842624; x.exponent = 1025; x.sign = true; writeln(x.value); // -5.0 ``` struct **BitArray**; A dynamic array of bits. Each bit in a `BitArray` can be manipulated individually or by the standard bitwise operators `&`, `|`, `^`, `~`, `>>`, `<<` and also by other effective member functions; most of them work relative to the `BitArray`'s dimension (see [`dim`](#dim)), instead of its [`length`](#length). Examples: Slicing & bitsSet ``` import std.algorithm.comparison : equal; import std.range : iota; bool[] buf = new bool[64 * 3]; buf[0 .. 64] = true; BitArray b = BitArray(buf); assert(b.bitsSet.equal(iota(0, 64))); b <<= 64; assert(b.bitsSet.equal(iota(64, 128))); ``` Examples: Concatenation and appending ``` import std.algorithm.comparison : equal; auto b = BitArray([1, 0]); b ~= true; writeln(b[2]); // 1 b ~= BitArray([0, 1]); auto c = BitArray([1, 0, 1, 0, 1]); writeln(b); // c assert(b.bitsSet.equal([0, 2, 4])); ``` Examples: Bit flipping ``` import std.algorithm.comparison : equal; auto b = BitArray([1, 1, 0, 1]); b &= BitArray([0, 1, 1, 0]); assert(b.bitsSet.equal([1])); b.flip; assert(b.bitsSet.equal([0, 2, 3])); ``` Examples: String format of bitarrays ``` import std.format : format; auto b = BitArray([1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]); writeln(format("%b", b)); // "1_00001111_00001111" ``` Examples: ``` import std.format : format; BitArray b; b = BitArray([]); writeln(format("%s", b)); // "[]" assert(format("%b", b) is null); b = BitArray([1]); writeln(format("%s", b)); // "[1]" writeln(format("%b", b)); // "1" b = BitArray([0, 0, 0, 0]); writeln(format("%b", b)); // "0000" b = BitArray([0, 0, 0, 0, 1, 1, 1, 1]); writeln(format("%s", b)); // "[0, 0, 0, 0, 1, 1, 1, 1]" writeln(format("%b", b)); // "00001111" b = BitArray([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]); writeln(format("%s", b)); // "[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]" writeln(format("%b", b)); // "00001111_00001111" b = BitArray([1, 0, 0, 0, 0, 1, 1, 1, 1]); writeln(format("%b", b)); // "1_00001111" b = BitArray([1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]); writeln(format("%b", b)); // "1_00001111_00001111" ``` pure nothrow this(in bool[] ba); Creates a `BitArray` from a `bool` array, such that `bool` values read from left to right correspond to subsequent bits in the `BitArray`. Parameters: | | | | --- | --- | | bool[] `ba` | Source array of `bool` values. | Examples: ``` import std.algorithm.comparison : equal; bool[] input = [true, false, false, true, true]; auto a = BitArray(input); writeln(a.length); // 5 assert(a.bitsSet.equal([0, 3, 4])); // This also works because an implicit cast to bool[] occurs for this array. auto b = BitArray([0, 0, 1]); writeln(b.length); // 3 assert(b.bitsSet.equal([2])); ``` Examples: ``` import std.algorithm.comparison : equal; import std.array : array; import std.range : iota, repeat; BitArray a = true.repeat(70).array; writeln(a.length); // 70 assert(a.bitsSet.equal(iota(0, 70))); ``` pure nothrow @nogc this(void[] v, size\_t numbits); Creates a `BitArray` from the raw contents of the source array. The source array is not copied but simply acts as the underlying array of bits, which stores data as `size_t` units. That means a particular care should be taken when passing an array of a type different than `size_t`, firstly because its length should be a multiple of `size_t.sizeof`, and secondly because how the bits are mapped: ``` size_t[] source = [1, 2, 3, 3424234, 724398, 230947, 389492]; enum sbits = size_t.sizeof * 8; auto ba = BitArray(source, source.length * sbits); foreach (n; 0 .. source.length * sbits) { auto nth_bit = cast(bool) (source[n / sbits] & (1L << (n % sbits))); assert(ba[n] == nth_bit); } ``` The least significant bit in any `size_t` unit is the starting bit of this unit, and the most significant bit is the last bit of this unit. Therefore, passing e.g. an array of `int`s may result in a different `BitArray` depending on the processor's endianness. This constructor is the inverse of [`opCast`](#opCast). Parameters: | | | | --- | --- | | void[] `v` | Source array. `v.length` must be a multple of `size_t.sizeof`. | | size\_t `numbits` | Number of bits to be mapped from the source array, i.e. length of the created `BitArray`. | Examples: ``` import std.algorithm.comparison : equal; auto a = BitArray([1, 0, 0, 1, 1]); // Inverse of the cast. auto v = cast(void[]) a; auto b = BitArray(v, a.length); writeln(b.length); // 5 assert(b.bitsSet.equal([0, 3, 4])); // a and b share the underlying data. a[0] = 0; writeln(b[0]); // 0 writeln(a); // b ``` Examples: ``` import std.algorithm.comparison : equal; size_t[] source = [0b1100, 0b0011]; enum sbits = size_t.sizeof * 8; auto ba = BitArray(source, source.length * sbits); // The least significant bit in each unit is this unit's starting bit. assert(ba.bitsSet.equal([2, 3, sbits, sbits + 1])); ``` Examples: ``` // Example from the doc for this constructor. static immutable size_t[] sourceData = [1, 0b101, 3, 3424234, 724398, 230947, 389492]; size_t[] source = sourceData.dup; enum sbits = size_t.sizeof * 8; auto ba = BitArray(source, source.length * sbits); foreach (n; 0 .. source.length * sbits) { auto nth_bit = cast(bool) (source[n / sbits] & (1L << (n % sbits))); writeln(ba[n]); // nth_bit } // Example of mapping only part of the array. import std.algorithm.comparison : equal; auto bc = BitArray(source, sbits + 1); assert(bc.bitsSet.equal([0, sbits])); // Source array has not been modified. writeln(source); // sourceData ``` const pure nothrow @nogc @property @safe size\_t **dim**(); Returns: Dimension i.e. the number of native words backing this `BitArray`. Technically, this is the length of the underlying array storing bits, which is equal to `ceil(length / (size_t.sizeof * 8))`, as bits are packed into `size_t` units. const pure nothrow @nogc @property @safe size\_t **length**(); Returns: Number of bits in the `BitArray`. pure nothrow @property @system size\_t **length**(size\_t newlen); Sets the amount of bits in the `BitArray`. Warning: increasing length may overwrite bits in the final word of the current underlying data regardless of whether it is shared between BitArray objects. i.e. D dynamic array extension semantics are not followed. const pure nothrow @nogc bool **opIndex**(size\_t i); Gets the `i`'th bit in the `BitArray`. Examples: ``` static void fun(const BitArray arr) { auto x = arr[0]; writeln(x); // 1 } BitArray a; a.length = 3; a[0] = 1; fun(a); ``` pure nothrow @nogc bool **opIndexAssign**(bool b, size\_t i); Sets the `i`'th bit in the `BitArray`. pure nothrow @nogc void **opSliceAssign**(bool val); Sets all the values in the `BitArray` to the value specified by `val`. Examples: ``` import std.algorithm.comparison : equal; auto b = BitArray([1, 0, 1, 0, 1, 1]); b[] = true; // all bits are set assert(b.bitsSet.equal([0, 1, 2, 3, 4, 5])); b[] = false; // none of the bits are set assert(b.bitsSet.empty); ``` pure nothrow @nogc void **opSliceAssign**(bool val, size\_t start, size\_t end); Sets the bits of a slice of `BitArray` starting at index `start` and ends at index ($D end - 1) with the values specified by `val`. Examples: ``` import std.algorithm.comparison : equal; import std.range : iota; import std.stdio; auto b = BitArray([1, 0, 0, 0, 1, 1, 0]); b[1 .. 3] = true; assert(b.bitsSet.equal([0, 1, 2, 4, 5])); bool[72] bitArray; auto b1 = BitArray(bitArray); b1[63 .. 67] = true; assert(b1.bitsSet.equal([63, 64, 65, 66])); b1[63 .. 67] = false; assert(b1.bitsSet.empty); b1[0 .. 64] = true; assert(b1.bitsSet.equal(iota(0, 64))); b1[0 .. 64] = false; assert(b1.bitsSet.empty); bool[256] bitArray2; auto b2 = BitArray(bitArray2); b2[3 .. 245] = true; assert(b2.bitsSet.equal(iota(3, 245))); b2[3 .. 245] = false; assert(b2.bitsSet.empty); ``` pure nothrow @nogc void **flip**(); Flips all the bits in the `BitArray` Examples: ``` import std.algorithm.comparison : equal; import std.range : iota; // positions 0, 2, 4 are set auto b = BitArray([1, 0, 1, 0, 1, 0]); b.flip(); // after flipping, positions 1, 3, 5 are set assert(b.bitsSet.equal([1, 3, 5])); bool[270] bits; auto b1 = BitArray(bits); b1.flip(); assert(b1.bitsSet.equal(iota(0, 270))); ``` pure nothrow @nogc void **flip**(size\_t i); Flips a single bit, specified by `pos` Examples: ``` auto ax = BitArray([1, 0, 0, 1]); ax.flip(0); writeln(ax[0]); // 0 bool[200] y; y[90 .. 130] = true; auto ay = BitArray(y); ay.flip(100); writeln(ay[100]); // 0 ``` const pure nothrow @nogc size\_t **count**(); Counts all the set bits in the `BitArray` Examples: ``` auto a = BitArray([0, 1, 1, 0, 0, 1, 1]); writeln(a.count); // 4 BitArray b; writeln(b.count); // 0 bool[200] boolArray; boolArray[45 .. 130] = true; auto c = BitArray(boolArray); writeln(c.count); // 85 ``` const pure nothrow @property BitArray **dup**(); Duplicates the `BitArray` and its contents. Examples: ``` BitArray a; BitArray b; a.length = 3; a[0] = 1; a[1] = 0; a[2] = 1; b = a.dup; writeln(b.length); // 3 foreach (i; 0 .. 3) writeln(b[i]); // (((i ^ 1) & 1) ? true : false) ``` int **opApply**(scope int delegate(ref bool) dg); const int **opApply**(scope int delegate(bool) dg); int **opApply**(scope int delegate(size\_t, ref bool) dg); const int **opApply**(scope int delegate(size\_t, bool) dg); Support for `foreach` loops for `BitArray`. Examples: ``` bool[] ba = [1,0,1]; auto a = BitArray(ba); int i; foreach (b;a) { switch (i) { case 0: assert(b == true); break; case 1: assert(b == false); break; case 2: assert(b == true); break; default: assert(0); } i++; } foreach (j,b;a) { switch (j) { case 0: assert(b == true); break; case 1: assert(b == false); break; case 2: assert(b == true); break; default: assert(0); } } ``` pure nothrow @nogc @property BitArray **reverse**(); Reverses the bits of the `BitArray`. Examples: ``` BitArray b; bool[5] data = [1,0,1,1,0]; b = BitArray(data); b.reverse; foreach (i; 0 .. data.length) writeln(b[i]); // data[4 - i] ``` pure nothrow @nogc @property BitArray **sort**(); Sorts the `BitArray`'s elements. Examples: ``` size_t x = 0b1100011000; auto ba = BitArray(10, &x); ba.sort; foreach (i; 0 .. 6) writeln(ba[i]); // false foreach (i; 6 .. 10) writeln(ba[i]); // true ``` const pure nothrow @nogc bool **opEquals**(ref const BitArray a2); Support for operators == and != for `BitArray`. Examples: ``` bool[] ba = [1,0,1,0,1]; bool[] bb = [1,0,1]; bool[] bc = [1,0,1,0,1,0,1]; bool[] bd = [1,0,1,1,1]; bool[] be = [1,0,1,0,1]; bool[] bf = [1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; bool[] bg = [1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]; auto a = BitArray(ba); auto b = BitArray(bb); auto c = BitArray(bc); auto d = BitArray(bd); auto e = BitArray(be); auto f = BitArray(bf); auto g = BitArray(bg); assert(a != b); assert(a != c); assert(a != d); writeln(a); // e assert(f != g); ``` const pure nothrow @nogc int **opCmp**(BitArray a2); Supports comparison operators for `BitArray`. Examples: ``` bool[] ba = [1,0,1,0,1]; bool[] bb = [1,0,1]; bool[] bc = [1,0,1,0,1,0,1]; bool[] bd = [1,0,1,1,1]; bool[] be = [1,0,1,0,1]; bool[] bf = [1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]; bool[] bg = [1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]; auto a = BitArray(ba); auto b = BitArray(bb); auto c = BitArray(bc); auto d = BitArray(bd); auto e = BitArray(be); auto f = BitArray(bf); auto g = BitArray(bg); assert(a > b); assert(a >= b); assert(a < c); assert(a <= c); assert(a < d); assert(a <= d); writeln(a); // e assert(a <= e); assert(a >= e); assert(f < g); assert(g <= g); ``` const pure nothrow @nogc size\_t **toHash**(); Support for hashing for `BitArray`. inout pure nothrow @nogc inout(void)[] **opCast**(T : const(void[]))(); Convert to `void[]`. inout pure nothrow @nogc inout(size\_t)[] **opCast**(T : const(size\_t[]))(); Convert to `size_t[]`. Examples: ``` import std.array : array; import std.range : repeat, take; // bit array with 300 elements auto a = BitArray(true.repeat.take(300).array); size_t[] v = cast(size_t[]) a; const blockSize = size_t.sizeof * 8; writeln(v.length); // (a.length + blockSize - 1) / blockSize ``` const pure nothrow BitArray **opUnary**(string op)() Constraints: if (op == "~"); Support for unary operator ~ for `BitArray`. Examples: ``` bool[] ba = [1,0,1,0,1]; auto a = BitArray(ba); BitArray b = ~a; writeln(b[0]); // 0 writeln(b[1]); // 1 writeln(b[2]); // 0 writeln(b[3]); // 1 writeln(b[4]); // 0 ``` const pure nothrow BitArray **opBinary**(string op)(const BitArray e2) Constraints: if (op == "-" || op == "&" || op == "|" || op == "^"); Support for binary bitwise operators for `BitArray`. Examples: ``` static bool[] ba = [1,0,1,0,1]; static bool[] bb = [1,0,1,1,0]; auto a = BitArray(ba); auto b = BitArray(bb); BitArray c = a & b; writeln(c[0]); // 1 writeln(c[1]); // 0 writeln(c[2]); // 1 writeln(c[3]); // 0 writeln(c[4]); // 0 ``` Examples: ``` bool[] ba = [1,0,1,0,1]; bool[] bb = [1,0,1,1,0]; auto a = BitArray(ba); auto b = BitArray(bb); BitArray c = a | b; writeln(c[0]); // 1 writeln(c[1]); // 0 writeln(c[2]); // 1 writeln(c[3]); // 1 writeln(c[4]); // 1 ``` Examples: ``` bool[] ba = [1,0,1,0,1]; bool[] bb = [1,0,1,1,0]; auto a = BitArray(ba); auto b = BitArray(bb); BitArray c = a ^ b; writeln(c[0]); // 0 writeln(c[1]); // 0 writeln(c[2]); // 0 writeln(c[3]); // 1 writeln(c[4]); // 1 ``` Examples: ``` bool[] ba = [1,0,1,0,1]; bool[] bb = [1,0,1,1,0]; auto a = BitArray(ba); auto b = BitArray(bb); BitArray c = a - b; writeln(c[0]); // 0 writeln(c[1]); // 0 writeln(c[2]); // 0 writeln(c[3]); // 0 writeln(c[4]); // 1 ``` pure nothrow @nogc BitArray **opOpAssign**(string op)(const BitArray e2) Constraints: if (op == "-" || op == "&" || op == "|" || op == "^"); Support for operator op= for `BitArray`. Examples: ``` bool[] ba = [1,0,1,0,1,1,0,1,0,1]; bool[] bb = [1,0,1,1,0]; auto a = BitArray(ba); auto b = BitArray(bb); BitArray c = a; c.length = 5; c &= b; writeln(a[5]); // 1 writeln(a[6]); // 0 writeln(a[7]); // 1 writeln(a[8]); // 0 writeln(a[9]); // 1 ``` Examples: ``` bool[] ba = [1,0,1,0,1]; bool[] bb = [1,0,1,1,0]; auto a = BitArray(ba); auto b = BitArray(bb); a &= b; writeln(a[0]); // 1 writeln(a[1]); // 0 writeln(a[2]); // 1 writeln(a[3]); // 0 writeln(a[4]); // 0 ``` Examples: ``` bool[] ba = [1,0,1,0,1]; bool[] bb = [1,0,1,1,0]; auto a = BitArray(ba); auto b = BitArray(bb); a |= b; writeln(a[0]); // 1 writeln(a[1]); // 0 writeln(a[2]); // 1 writeln(a[3]); // 1 writeln(a[4]); // 1 ``` Examples: ``` bool[] ba = [1,0,1,0,1]; bool[] bb = [1,0,1,1,0]; auto a = BitArray(ba); auto b = BitArray(bb); a ^= b; writeln(a[0]); // 0 writeln(a[1]); // 0 writeln(a[2]); // 0 writeln(a[3]); // 1 writeln(a[4]); // 1 ``` Examples: ``` bool[] ba = [1,0,1,0,1]; bool[] bb = [1,0,1,1,0]; auto a = BitArray(ba); auto b = BitArray(bb); a -= b; writeln(a[0]); // 0 writeln(a[1]); // 0 writeln(a[2]); // 0 writeln(a[3]); // 0 writeln(a[4]); // 1 ``` pure nothrow BitArray **opOpAssign**(string op)(bool b) Constraints: if (op == "~"); pure nothrow BitArray **opOpAssign**(string op)(BitArray b) Constraints: if (op == "~"); Support for operator ~= for `BitArray`. Warning: This will overwrite a bit in the final word of the current underlying data regardless of whether it is shared between BitArray objects. i.e. D dynamic array concatenation semantics are not followed Examples: ``` bool[] ba = [1,0,1,0,1]; auto a = BitArray(ba); BitArray b; b = (a ~= true); writeln(a[0]); // 1 writeln(a[1]); // 0 writeln(a[2]); // 1 writeln(a[3]); // 0 writeln(a[4]); // 1 writeln(a[5]); // 1 writeln(b); // a ``` Examples: ``` bool[] ba = [1,0]; bool[] bb = [0,1,0]; auto a = BitArray(ba); auto b = BitArray(bb); BitArray c; c = (a ~= b); writeln(a.length); // 5 writeln(a[0]); // 1 writeln(a[1]); // 0 writeln(a[2]); // 0 writeln(a[3]); // 1 writeln(a[4]); // 0 writeln(c); // a ``` const pure nothrow BitArray **opBinary**(string op)(bool b) Constraints: if (op == "~"); const pure nothrow BitArray **opBinaryRight**(string op)(bool b) Constraints: if (op == "~"); const pure nothrow BitArray **opBinary**(string op)(BitArray b) Constraints: if (op == "~"); Support for binary operator ~ for `BitArray`. Examples: ``` bool[] ba = [1,0]; bool[] bb = [0,1,0]; auto a = BitArray(ba); auto b = BitArray(bb); BitArray c; c = (a ~ b); writeln(c.length); // 5 writeln(c[0]); // 1 writeln(c[1]); // 0 writeln(c[2]); // 0 writeln(c[3]); // 1 writeln(c[4]); // 0 c = (a ~ true); writeln(c.length); // 3 writeln(c[0]); // 1 writeln(c[1]); // 0 writeln(c[2]); // 1 c = (false ~ a); writeln(c.length); // 3 writeln(c[0]); // 0 writeln(c[1]); // 1 writeln(c[2]); // 0 ``` pure nothrow @nogc void **opOpAssign**(string op)(size\_t nbits) Constraints: if (op == "<<"); Operator `<<=` support. Shifts all the bits in the array to the left by the given number of bits. The leftmost bits are dropped, and 0's are appended to the end to fill up the vacant bits. Warning: unused bits in the final word up to the next word boundary may be overwritten by this operation. It does not attempt to preserve bits past the end of the array. pure nothrow @nogc void **opOpAssign**(string op)(size\_t nbits) Constraints: if (op == ">>"); Operator `>>=` support. Shifts all the bits in the array to the right by the given number of bits. The rightmost bits are dropped, and 0's are inserted at the back to fill up the vacant bits. Warning: unused bits in the final word up to the next word boundary may be overwritten by this operation. It does not attempt to preserve bits past the end of the array. Examples: ``` import std.format : format; auto b = BitArray([1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1]); b <<= 1; writeln(format("%b", b)); // "01100_10101101" b >>= 1; writeln(format("%b", b)); // "11001_01011010" b <<= 4; writeln(format("%b", b)); // "00001_10010101" b >>= 5; writeln(format("%b", b)); // "10010_10100000" b <<= 13; writeln(format("%b", b)); // "00000_00000000" b = BitArray([1, 0, 1, 1, 0, 1, 1, 1]); b >>= 8; writeln(format("%b", b)); // "00000000" ``` const void **toString**(W)(ref W sink, ref scope const FormatSpec!char fmt) Constraints: if (isOutputRange!(W, char)); Return a string representation of this BitArray. Two format specifiers are supported: - **%s** which prints the bits as an array, and - **%b** which prints the bits as 8-bit byte packets separated with an underscore. Parameters: | | | | --- | --- | | W `sink` | A `char` accepting [output range](std_range_primitives#isOutputRange). | | FormatSpec!char `fmt` | A [`std.format.FormatSpec`](std_format#FormatSpec) which controls how the data is displayed. | Examples: ``` import std.format : format; auto b = BitArray([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]); auto s1 = format("%s", b); writeln(s1); // "[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]" auto s2 = format("%b", b); writeln(s2); // "00001111_00001111" ``` const nothrow @property auto **bitsSet**(); Return a lazy range of the indices of set bits. Examples: ``` import std.algorithm.comparison : equal; auto b1 = BitArray([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]); assert(b1.bitsSet.equal([4, 5, 6, 7, 12, 13, 14, 15])); BitArray b2; b2.length = 1000; b2[333] = true; b2[666] = true; b2[999] = true; assert(b2.bitsSet.equal([333, 666, 999])); ``` pure nothrow @nogc @safe T **swapEndian**(T)(const T val) Constraints: if (isIntegral!T || isSomeChar!T || isBoolean!T); Swaps the endianness of the given integral value or character. Examples: ``` writeln(42.swapEndian); // 704643072 assert(42.swapEndian.swapEndian == 42); // reflexive writeln(1.swapEndian); // 16777216 writeln(true.swapEndian); // true writeln(byte(10).swapEndian); // 10 writeln(char(10).swapEndian); // 10 writeln(ushort(10).swapEndian); // 2560 writeln(long(10).swapEndian); // 720575940379279360 writeln(ulong(10).swapEndian); // 720575940379279360 ``` pure nothrow @nogc @safe auto **nativeToBigEndian**(T)(const T val) Constraints: if (canSwapEndianness!T); Converts the given value from the native endianness to big endian and returns it as a `ubyte[n]` where `n` is the size of the given type. Returning a `ubyte[n]` helps prevent accidentally using a swapped value as a regular one (and in the case of floating point values, it's necessary, because the FPU will mess up any swapped floating point values. So, you can't actually have swapped floating point values as floating point values). `real` is not supported, because its size is implementation-dependent and therefore could vary from machine to machine (which could make it unusable if you tried to transfer it to another machine). Examples: ``` int i = 12345; ubyte[4] swappedI = nativeToBigEndian(i); writeln(i); // bigEndianToNative!int(swappedI) float f = 123.45f; ubyte[4] swappedF = nativeToBigEndian(f); writeln(f); // bigEndianToNative!float(swappedF) const float cf = 123.45f; ubyte[4] swappedCF = nativeToBigEndian(cf); writeln(cf); // bigEndianToNative!float(swappedCF) double d = 123.45; ubyte[8] swappedD = nativeToBigEndian(d); writeln(d); // bigEndianToNative!double(swappedD) const double cd = 123.45; ubyte[8] swappedCD = nativeToBigEndian(cd); writeln(cd); // bigEndianToNative!double(swappedCD) ``` pure nothrow @nogc @safe T **bigEndianToNative**(T, size\_t n)(ubyte[n] val) Constraints: if (canSwapEndianness!T && (n == T.sizeof)); Converts the given value from big endian to the native endianness and returns it. The value is given as a `ubyte[n]` where `n` is the size of the target type. You must give the target type as a template argument, because there are multiple types with the same size and so the type of the argument is not enough to determine the return type. Taking a `ubyte[n]` helps prevent accidentally using a swapped value as a regular one (and in the case of floating point values, it's necessary, because the FPU will mess up any swapped floating point values. So, you can't actually have swapped floating point values as floating point values). Examples: ``` ushort i = 12345; ubyte[2] swappedI = nativeToBigEndian(i); writeln(i); // bigEndianToNative!ushort(swappedI) dchar c = 'D'; ubyte[4] swappedC = nativeToBigEndian(c); writeln(c); // bigEndianToNative!dchar(swappedC) ``` pure nothrow @nogc @safe auto **nativeToLittleEndian**(T)(const T val) Constraints: if (canSwapEndianness!T); Converts the given value from the native endianness to little endian and returns it as a `ubyte[n]` where `n` is the size of the given type. Returning a `ubyte[n]` helps prevent accidentally using a swapped value as a regular one (and in the case of floating point values, it's necessary, because the FPU will mess up any swapped floating point values. So, you can't actually have swapped floating point values as floating point values). Examples: ``` int i = 12345; ubyte[4] swappedI = nativeToLittleEndian(i); writeln(i); // littleEndianToNative!int(swappedI) double d = 123.45; ubyte[8] swappedD = nativeToLittleEndian(d); writeln(d); // littleEndianToNative!double(swappedD) ``` pure nothrow @nogc @safe T **littleEndianToNative**(T, size\_t n)(ubyte[n] val) Constraints: if (canSwapEndianness!T && (n == T.sizeof)); Converts the given value from little endian to the native endianness and returns it. The value is given as a `ubyte[n]` where `n` is the size of the target type. You must give the target type as a template argument, because there are multiple types with the same size and so the type of the argument is not enough to determine the return type. Taking a `ubyte[n]` helps prevent accidentally using a swapped value as a regular one (and in the case of floating point values, it's necessary, because the FPU will mess up any swapped floating point values. So, you can't actually have swapped floating point values as floating point values). `real` is not supported, because its size is implementation-dependent and therefore could vary from machine to machine (which could make it unusable if you tried to transfer it to another machine). Examples: ``` ushort i = 12345; ubyte[2] swappedI = nativeToLittleEndian(i); writeln(i); // littleEndianToNative!ushort(swappedI) dchar c = 'D'; ubyte[4] swappedC = nativeToLittleEndian(c); writeln(c); // littleEndianToNative!dchar(swappedC) ``` T **peek**(T, Endian endianness = Endian.bigEndian, R)(R range) Constraints: if (canSwapEndianness!T && isForwardRange!R && is(ElementType!R : const(ubyte))); T **peek**(T, Endian endianness = Endian.bigEndian, R)(R range, size\_t index) Constraints: if (canSwapEndianness!T && isForwardRange!R && hasSlicing!R && is(ElementType!R : const(ubyte))); T **peek**(T, Endian endianness = Endian.bigEndian, R)(R range, size\_t\* index) Constraints: if (canSwapEndianness!T && isForwardRange!R && hasSlicing!R && is(ElementType!R : const(ubyte))); Takes a range of `ubyte`s and converts the first `T.sizeof` bytes to `T`. The value returned is converted from the given endianness to the native endianness. The range is not consumed. Parameters: | | | | --- | --- | | T | The integral type to convert the first `T.sizeof` bytes to. | | endianness | The endianness that the bytes are assumed to be in. | | R `range` | The range to read from. | | size\_t `index` | The index to start reading from (instead of starting at the front). If index is a pointer, then it is updated to the index after the bytes read. The overloads with index are only available if `hasSlicing!R` is `true`. | Examples: ``` ubyte[] buffer = [1, 5, 22, 9, 44, 255, 8]; writeln(buffer.peek!uint()); // 17110537 writeln(buffer.peek!ushort()); // 261 writeln(buffer.peek!ubyte()); // 1 writeln(buffer.peek!uint(2)); // 369700095 writeln(buffer.peek!ushort(2)); // 5641 writeln(buffer.peek!ubyte(2)); // 22 size_t index = 0; writeln(buffer.peek!ushort(&index)); // 261 writeln(index); // 2 writeln(buffer.peek!uint(&index)); // 369700095 writeln(index); // 6 writeln(buffer.peek!ubyte(&index)); // 8 writeln(index); // 7 ``` Examples: ``` import std.algorithm.iteration : filter; ubyte[] buffer = [1, 5, 22, 9, 44, 255, 7]; auto range = filter!"true"(buffer); writeln(range.peek!uint()); // 17110537 writeln(range.peek!ushort()); // 261 writeln(range.peek!ubyte()); // 1 ``` T **read**(T, Endian endianness = Endian.bigEndian, R)(ref R range) Constraints: if (canSwapEndianness!T && isInputRange!R && is(ElementType!R : const(ubyte))); Takes a range of `ubyte`s and converts the first `T.sizeof` bytes to `T`. The value returned is converted from the given endianness to the native endianness. The `T.sizeof` bytes which are read are consumed from the range. Parameters: | | | | --- | --- | | T | The integral type to convert the first `T.sizeof` bytes to. | | endianness | The endianness that the bytes are assumed to be in. | | R `range` | The range to read from. | Examples: ``` import std.range.primitives : empty; ubyte[] buffer = [1, 5, 22, 9, 44, 255, 8]; writeln(buffer.length); // 7 writeln(buffer.read!ushort()); // 261 writeln(buffer.length); // 5 writeln(buffer.read!uint()); // 369700095 writeln(buffer.length); // 1 writeln(buffer.read!ubyte()); // 8 assert(buffer.empty); ``` void **write**(T, Endian endianness = Endian.bigEndian, R)(R range, const T value, size\_t index) Constraints: if (canSwapEndianness!T && isForwardRange!R && hasSlicing!R && is(ElementType!R : ubyte)); void **write**(T, Endian endianness = Endian.bigEndian, R)(R range, const T value, size\_t\* index) Constraints: if (canSwapEndianness!T && isForwardRange!R && hasSlicing!R && is(ElementType!R : ubyte)); Takes an integral value, converts it to the given endianness, and writes it to the given range of `ubyte`s as a sequence of `T.sizeof` `ubyte`s starting at index. `hasSlicing!R` must be `true`. Parameters: | | | | --- | --- | | T | The integral type to convert the first `T.sizeof` bytes to. | | endianness | The endianness to write the bytes in. | | R `range` | The range to write to. | | T `value` | The value to write. | | size\_t `index` | The index to start writing to. If index is a pointer, then it is updated to the index after the bytes read. | Examples: ``` ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0]; buffer.write!uint(29110231u, 0); writeln(buffer); // [1, 188, 47, 215, 0, 0, 0, 0] buffer.write!ushort(927, 0); writeln(buffer); // [3, 159, 47, 215, 0, 0, 0, 0] buffer.write!ubyte(42, 0); writeln(buffer); // [42, 159, 47, 215, 0, 0, 0, 0] ``` Examples: ``` ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0]; buffer.write!uint(142700095u, 2); writeln(buffer); // [0, 0, 8, 129, 110, 63, 0, 0, 0] buffer.write!ushort(19839, 2); writeln(buffer); // [0, 0, 77, 127, 110, 63, 0, 0, 0] buffer.write!ubyte(132, 2); writeln(buffer); // [0, 0, 132, 127, 110, 63, 0, 0, 0] ``` Examples: ``` ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0]; size_t index = 0; buffer.write!ushort(261, &index); writeln(buffer); // [1, 5, 0, 0, 0, 0, 0, 0] writeln(index); // 2 buffer.write!uint(369700095u, &index); writeln(buffer); // [1, 5, 22, 9, 44, 255, 0, 0] writeln(index); // 6 buffer.write!ubyte(8, &index); writeln(buffer); // [1, 5, 22, 9, 44, 255, 8, 0] writeln(index); // 7 ``` Examples: bool ``` ubyte[] buffer = [0, 0]; buffer.write!bool(false, 0); writeln(buffer); // [0, 0] buffer.write!bool(true, 0); writeln(buffer); // [1, 0] buffer.write!bool(true, 1); writeln(buffer); // [1, 1] buffer.write!bool(false, 1); writeln(buffer); // [1, 0] size_t index = 0; buffer.write!bool(false, &index); writeln(buffer); // [0, 0] writeln(index); // 1 buffer.write!bool(true, &index); writeln(buffer); // [0, 1] writeln(index); // 2 ``` Examples: char(8-bit) ``` ubyte[] buffer = [0, 0, 0]; buffer.write!char('a', 0); writeln(buffer); // [97, 0, 0] buffer.write!char('b', 1); writeln(buffer); // [97, 98, 0] size_t index = 0; buffer.write!char('a', &index); writeln(buffer); // [97, 98, 0] writeln(index); // 1 buffer.write!char('b', &index); writeln(buffer); // [97, 98, 0] writeln(index); // 2 buffer.write!char('c', &index); writeln(buffer); // [97, 98, 99] writeln(index); // 3 ``` Examples: wchar (16bit - 2x ubyte) ``` ubyte[] buffer = [0, 0, 0, 0]; buffer.write!wchar('ą', 0); writeln(buffer); // [1, 5, 0, 0] buffer.write!wchar('”', 2); writeln(buffer); // [1, 5, 32, 29] size_t index = 0; buffer.write!wchar('ć', &index); writeln(buffer); // [1, 7, 32, 29] writeln(index); // 2 buffer.write!wchar('ą', &index); writeln(buffer); // [1, 7, 1, 5] writeln(index); // 4 ``` Examples: dchar (32bit - 4x ubyte) ``` ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0]; buffer.write!dchar('ą', 0); writeln(buffer); // [0, 0, 1, 5, 0, 0, 0, 0] buffer.write!dchar('”', 4); writeln(buffer); // [0, 0, 1, 5, 0, 0, 32, 29] size_t index = 0; buffer.write!dchar('ć', &index); writeln(buffer); // [0, 0, 1, 7, 0, 0, 32, 29] writeln(index); // 4 buffer.write!dchar('ą', &index); writeln(buffer); // [0, 0, 1, 7, 0, 0, 1, 5] writeln(index); // 8 ``` Examples: float (32bit - 4x ubyte) ``` ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0]; buffer.write!float(32.0f, 0); writeln(buffer); // [66, 0, 0, 0, 0, 0, 0, 0] buffer.write!float(25.0f, 4); writeln(buffer); // [66, 0, 0, 0, 65, 200, 0, 0] size_t index = 0; buffer.write!float(25.0f, &index); writeln(buffer); // [65, 200, 0, 0, 65, 200, 0, 0] writeln(index); // 4 buffer.write!float(32.0f, &index); writeln(buffer); // [65, 200, 0, 0, 66, 0, 0, 0] writeln(index); // 8 ``` Examples: double (64bit - 8x ubyte) ``` ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; buffer.write!double(32.0, 0); writeln(buffer); // [64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] buffer.write!double(25.0, 8); writeln(buffer); // [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0] size_t index = 0; buffer.write!double(25.0, &index); writeln(buffer); // [64, 57, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0] writeln(index); // 8 buffer.write!double(32.0, &index); writeln(buffer); // [64, 57, 0, 0, 0, 0, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0] writeln(index); // 16 ``` Examples: enum ``` ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; enum Foo { one = 10, two = 20, three = 30 } buffer.write!Foo(Foo.one, 0); writeln(buffer); // [0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0] buffer.write!Foo(Foo.two, 4); writeln(buffer); // [0, 0, 0, 10, 0, 0, 0, 20, 0, 0, 0, 0] buffer.write!Foo(Foo.three, 8); writeln(buffer); // [0, 0, 0, 10, 0, 0, 0, 20, 0, 0, 0, 30] size_t index = 0; buffer.write!Foo(Foo.three, &index); writeln(buffer); // [0, 0, 0, 30, 0, 0, 0, 20, 0, 0, 0, 30] writeln(index); // 4 buffer.write!Foo(Foo.one, &index); writeln(buffer); // [0, 0, 0, 30, 0, 0, 0, 10, 0, 0, 0, 30] writeln(index); // 8 buffer.write!Foo(Foo.two, &index); writeln(buffer); // [0, 0, 0, 30, 0, 0, 0, 10, 0, 0, 0, 20] writeln(index); // 12 ``` Examples: enum - float ``` ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0]; enum Float: float { one = 32.0f, two = 25.0f } buffer.write!Float(Float.one, 0); writeln(buffer); // [66, 0, 0, 0, 0, 0, 0, 0] buffer.write!Float(Float.two, 4); writeln(buffer); // [66, 0, 0, 0, 65, 200, 0, 0] size_t index = 0; buffer.write!Float(Float.two, &index); writeln(buffer); // [65, 200, 0, 0, 65, 200, 0, 0] writeln(index); // 4 buffer.write!Float(Float.one, &index); writeln(buffer); // [65, 200, 0, 0, 66, 0, 0, 0] writeln(index); // 8 ``` Examples: enum - double ``` ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; enum Double: double { one = 32.0, two = 25.0 } buffer.write!Double(Double.one, 0); writeln(buffer); // [64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] buffer.write!Double(Double.two, 8); writeln(buffer); // [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0] size_t index = 0; buffer.write!Double(Double.two, &index); writeln(buffer); // [64, 57, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0] writeln(index); // 8 buffer.write!Double(Double.one, &index); writeln(buffer); // [64, 57, 0, 0, 0, 0, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0] writeln(index); // 16 ``` Examples: enum - real ``` ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; enum Real: real { one = 32.0, two = 25.0 } static assert(!__traits(compiles, buffer.write!Real(Real.one))); ``` void **append**(T, Endian endianness = Endian.bigEndian, R)(R range, const T value) Constraints: if (canSwapEndianness!T && isOutputRange!(R, ubyte)); Takes an integral value, converts it to the given endianness, and appends it to the given range of `ubyte`s (using `put`) as a sequence of `T.sizeof` `ubyte`s starting at index. `hasSlicing!R` must be `true`. Parameters: | | | | --- | --- | | T | The integral type to convert the first `T.sizeof` bytes to. | | endianness | The endianness to write the bytes in. | | R `range` | The range to append to. | | T `value` | The value to append. | Examples: ``` import std.array; auto buffer = appender!(const ubyte[])(); buffer.append!ushort(261); writeln(buffer.data); // [1, 5] buffer.append!uint(369700095u); writeln(buffer.data); // [1, 5, 22, 9, 44, 255] buffer.append!ubyte(8); writeln(buffer.data); // [1, 5, 22, 9, 44, 255, 8] ``` Examples: bool ``` import std.array : appender; auto buffer = appender!(const ubyte[])(); buffer.append!bool(true); writeln(buffer.data); // [1] buffer.append!bool(false); writeln(buffer.data); // [1, 0] ``` Examples: char wchar dchar ``` import std.array : appender; auto buffer = appender!(const ubyte[])(); buffer.append!char('a'); writeln(buffer.data); // [97] buffer.append!char('b'); writeln(buffer.data); // [97, 98] buffer.append!wchar('ą'); writeln(buffer.data); // [97, 98, 1, 5] buffer.append!dchar('ą'); writeln(buffer.data); // [97, 98, 1, 5, 0, 0, 1, 5] ``` Examples: float double ``` import std.array : appender; auto buffer = appender!(const ubyte[])(); buffer.append!float(32.0f); writeln(buffer.data); // [66, 0, 0, 0] buffer.append!double(32.0); writeln(buffer.data); // [66, 0, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0] ``` Examples: enum ``` import std.array : appender; auto buffer = appender!(const ubyte[])(); enum Foo { one = 10, two = 20, three = 30 } buffer.append!Foo(Foo.one); writeln(buffer.data); // [0, 0, 0, 10] buffer.append!Foo(Foo.two); writeln(buffer.data); // [0, 0, 0, 10, 0, 0, 0, 20] buffer.append!Foo(Foo.three); writeln(buffer.data); // [0, 0, 0, 10, 0, 0, 0, 20, 0, 0, 0, 30] ``` Examples: enum - bool ``` import std.array : appender; auto buffer = appender!(const ubyte[])(); enum Bool: bool { bfalse = false, btrue = true, } buffer.append!Bool(Bool.btrue); writeln(buffer.data); // [1] buffer.append!Bool(Bool.bfalse); writeln(buffer.data); // [1, 0] buffer.append!Bool(Bool.btrue); writeln(buffer.data); // [1, 0, 1] ``` Examples: enum - float ``` import std.array : appender; auto buffer = appender!(const ubyte[])(); enum Float: float { one = 32.0f, two = 25.0f } buffer.append!Float(Float.one); writeln(buffer.data); // [66, 0, 0, 0] buffer.append!Float(Float.two); writeln(buffer.data); // [66, 0, 0, 0, 65, 200, 0, 0] ``` Examples: enum - double ``` import std.array : appender; auto buffer = appender!(const ubyte[])(); enum Double: double { one = 32.0, two = 25.0 } buffer.append!Double(Double.one); writeln(buffer.data); // [64, 64, 0, 0, 0, 0, 0, 0] buffer.append!Double(Double.two); writeln(buffer.data); // [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0] ``` Examples: enum - real ``` import std.array : appender; auto buffer = appender!(const ubyte[])(); enum Real: real { one = 32.0, two = 25.0 } static assert(!__traits(compiles, buffer.append!Real(Real.one))); ``` pure nothrow @nogc auto **bitsSet**(T)(const T value) Constraints: if (isIntegral!T); Range that iterates the indices of the set bits in `value`. Index 0 corresponds to the least significant bit. For signed integers, the highest index corresponds to the sign bit. Examples: ``` import std.algorithm.comparison : equal; import std.range : iota; assert(bitsSet(1).equal([0])); assert(bitsSet(5).equal([0, 2])); assert(bitsSet(-1).equal(iota(32))); assert(bitsSet(int.min).equal([31])); ```
programming_docs
d Declarations Declarations ============ **Contents** 1. [Declaration Syntax](#declaration_syntax) 1. [Pointers to Functions](#pointers-to-functions) 2. [C-Style Declarations](#c-style-declarations) 3. [Declaring Multiple Symbols](#declaring-multiple-symbols) 2. [Implicit Type Inference](#auto-declaration) 3. [Alias Declarations](#alias) 4. [Extern Declarations](#extern) 5. [Void Initializations](#void_init) 6. [Global and Static Initializers](#global_static_init) 7. [Type Qualifiers vs. Storage Classes](#typequal_vs_storageclass) ``` Declaration: FuncDeclaration VarDeclarations AliasDeclaration AggregateDeclaration EnumDeclaration ImportDeclaration ConditionalDeclaration StaticForeachDeclaration StaticAssert ``` ``` VarDeclarations: StorageClassesopt BasicType Declarators ; AutoDeclaration Declarators: DeclaratorInitializer DeclaratorInitializer , DeclaratorIdentifierList DeclaratorInitializer: VarDeclarator VarDeclarator TemplateParametersopt = Initializer AltDeclarator AltDeclarator = Initializer DeclaratorIdentifierList: DeclaratorIdentifier DeclaratorIdentifier , DeclaratorIdentifierList DeclaratorIdentifier: VarDeclaratorIdentifier AltDeclaratorIdentifier VarDeclaratorIdentifier: Identifier Identifier TemplateParametersopt = Initializer AltDeclaratorIdentifier: TypeSuffixes Identifier AltDeclaratorSuffixesopt TypeSuffixes Identifier AltDeclaratorSuffixesopt = Initializer TypeSuffixesopt Identifier AltDeclaratorSuffixes TypeSuffixesopt Identifier AltDeclaratorSuffixes = Initializer Declarator: VarDeclarator AltDeclarator VarDeclarator: TypeSuffixesopt Identifier AltDeclarator: TypeSuffixesopt Identifier AltDeclaratorSuffixes TypeSuffixesopt ( AltDeclaratorInner ) TypeSuffixesopt ( AltDeclaratorInner ) AltFuncDeclaratorSuffix TypeSuffixesopt ( AltDeclaratorInner ) AltDeclaratorSuffixes AltDeclaratorInner: TypeSuffixesopt Identifier TypeSuffixesopt Identifier AltFuncDeclaratorSuffix AltDeclarator AltDeclaratorSuffixes: AltDeclaratorSuffix AltDeclaratorSuffix AltDeclaratorSuffixes AltDeclaratorSuffix: [ ] [ AssignExpression ] [ Type ] AltFuncDeclaratorSuffix: Parameters MemberFunctionAttributesopt ``` ``` StorageClasses: StorageClass StorageClass StorageClasses StorageClass: LinkageAttribute AlignAttribute deprecated enum static extern abstract final override synchronized auto scope const immutable inout shared __gshared Property nothrow pure ref ``` ``` Initializer: VoidInitializer NonVoidInitializer NonVoidInitializer: ExpInitializer ArrayInitializer StructInitializer ExpInitializer: AssignExpression ArrayInitializer: [ ArrayMemberInitializationsopt ] ArrayMemberInitializations: ArrayMemberInitialization ArrayMemberInitialization , ArrayMemberInitialization , ArrayMemberInitializations ArrayMemberInitialization: NonVoidInitializer AssignExpression : NonVoidInitializer StructInitializer: { StructMemberInitializersopt } StructMemberInitializers: StructMemberInitializer StructMemberInitializer , StructMemberInitializer , StructMemberInitializers StructMemberInitializer: NonVoidInitializer Identifier : NonVoidInitializer ``` Declaration Syntax ------------------ Declaration syntax generally reads right to left, including arrays: ``` int x; // x is an int int* x; // x is a pointer to int int** x; // x is a pointer to a pointer to int int[] x; // x is an array of ints int*[] x; // x is an array of pointers to ints int[]* x; // x is a pointer to an array of ints int[3] x; // x is a static array of 3 ints int[3][5] x; // x is a static array of 5 static arrays of 3 ints int[3]*[5] x; // x is a static array of 5 pointers to static arrays of 3 ints ``` ### Pointers to Functions Pointers to functions are declared using the `function` keyword: ``` int function(char) x; // x is a pointer to // a function taking a char argument // and returning an int int function(char)[] x; // x is an array of // pointers to functions // taking a char argument // and returning an int ``` ### C-Style Declarations C-style array, function pointer and pointer to array declarations are deprecated: ``` int x[3]; // x is a static array of 3 ints int x[3][5]; // x is a static array of 3 arrays of 5 ints int (*x[5])[3]; // x is a static array of 5 pointers to static arrays of 3 ints int (*x)(char); // x is a pointer to a function taking a char argument // and returning an int int (*[] x)(char); // x is an array of pointers to functions // taking a char argument and returning an int ``` ### Declaring Multiple Symbols In a declaration declaring multiple symbols, all the declarations must be of the same type: ``` int x,y; // x and y are ints int* x,y; // x and y are pointers to ints int[] x,y; // x and y are arrays of ints // invalid C-style declarations int x,*y; // error, multiple types int x[],y; // error, multiple types ``` Implicit Type Inference ----------------------- ``` AutoDeclaration: StorageClasses AutoAssignments ; AutoAssignments: AutoAssignment AutoAssignments , AutoAssignment AutoAssignment: Identifier TemplateParametersopt = Initializer ``` If a declaration starts with a *StorageClass* and has a *NonVoidInitializer* from which the type can be inferred, the type on the declaration can be omitted. ``` static x = 3; // x is type int auto y = 4u; // y is type uint auto s = "Apollo"; // s is type immutable(char)[] i.e., string class C { ... } auto c = new C(); // c is a handle to an instance of class C ``` The *NonVoidInitializer* cannot contain forward references (this restriction may be removed in the future). The implicitly inferred type is statically bound to the declaration at compile time, not run time. An [*ArrayLiteral*](expression#ArrayLiteral) is inferred to be a dynamic array type rather than a static array: ``` auto v = ["resistance", "is", "useless"]; // type is string[], not string[3] ``` Alias Declarations ------------------ ``` AliasDeclaration: alias StorageClassesopt BasicType Declarators ; alias StorageClassesopt BasicType FuncDeclarator ; alias AliasAssignments ; AliasAssignments: AliasAssignment AliasAssignments , AliasAssignment AliasAssignment: Identifier TemplateParametersopt = StorageClassesopt Type Identifier TemplateParametersopt = FunctionLiteral Identifier TemplateParametersopt = StorageClassesopt BasicType Parameters MemberFunctionAttributesopt ``` *AliasDeclaration*s create a symbol that is an alias for another type, and can be used anywhere that other type may appear. ``` alias myint = abc.Foo.bar; ``` Aliased types are semantically identical to the types they are aliased to. The debugger cannot distinguish between them, and there is no difference as far as function overloading is concerned. For example: ``` alias myint = int; void foo(int x) { ... } void foo(myint m) { ... } // error, multiply defined function foo ``` A symbol can be declared as an *alias* of another symbol. For example: ``` import planets; alias myAlbedo = planets.albedo; ... int len = myAlbedo("Saturn"); // actually calls planets.albedo() ``` The following alias declarations are valid: ``` template Foo2(T) { alias t = T; } alias t1 = Foo2!(int); alias t2 = Foo2!(int).t; alias t3 = t1.t; alias t4 = t2; t1.t v1; // v1 is type int t2 v2; // v2 is type int t3 v3; // v3 is type int t4 v4; // v4 is type int alias Fun = int(string p); int fun(string){return 0;} static assert(is(typeof(fun) == Fun)); alias MemberFun1 = int() const; alias MemberFun2 = const int(); // leading attributes apply to the func, not the return type static assert(is(MemberFun1 == MemberFun2)); ``` Aliased symbols are useful as a shorthand for a long qualified symbol name, or as a way to redirect references from one symbol to another: ``` version (Win32) { alias myfoo = win32.foo; } version (linux) { alias myfoo = linux.bar; } ``` Aliasing can be used to `import` a symbol from an import into the current scope: ``` alias strlen = string.strlen; ``` Aliases can also `import` a set of overloaded functions, that can be overloaded with functions in the current scope: ``` class A { int foo(int a) { return 1; } } class B : A { int foo( int a, uint b ) { return 2; } } class C : B { int foo( int a ) { return 3; } alias foo = B.foo; } class D : C { } void test() { D b = new D(); int i; i = b.foo(1, 2u); // calls B.foo i = b.foo(1); // calls C.foo } ``` **Note:** Type aliases can sometimes look indistinguishable from alias declarations: ``` alias abc = foo.bar; // is it a type or a symbol? ``` The distinction is made in the semantic analysis pass. Aliases cannot be used for expressions: ``` struct S { static int i; static int j; } alias a = S.i; // OK, `S.i` is a symbol alias b = S.j; // OK. `S.j` is also a symbol alias c = a + b; // illegal, `a + b` is an expression a = 2; // sets `S.i` to `2` b = 4; // sets `S.j` to `4` ``` Extern Declarations ------------------- Variable declarations with the storage class `extern` are not allocated storage within the module. They must be defined in some other object file with a matching name which is then linked in. An `extern` declaration can optionally be followed by an `extern` [linkage attribute](attribute#linkage). If there is no linkage attribute it defaults to `extern(D)`: ``` // variable allocated and initialized in this module with C linkage extern(C) int foo; // variable allocated outside this module with C linkage // (e.g. in a statically linked C library or another module) extern extern(C) int bar; ``` **Best Practices:** 1. The primary usefulness of *Extern Declarations* is to connect with global variables declarations and functions in C or C++ files. Void Initializations -------------------- ``` VoidInitializer: void ``` Normally, variables are initialized either with an explicit [*Initializer*](#Initializer) or are set to the default value for the type of the variable. If the *Initializer* is `void`, however, the variable is not initialized. If its value is used before it is set, undefined program behavior will result. **Undefined Behavior:** If a void initialized variable's value is used before it is set, the behavior is undefined. ``` void foo() { int x = void; writeln(x); // will print garbage } ``` **Best Practices:** 1. Void initializers are useful when a static array is on the stack, but may only be partially used, such as as a temporary buffer. Void initializers will potentially speed up the code, but they introduce risk, since one must ensure that array elements are always set before read. 2. The same is true for structs. 3. Use of void initializers is rarely useful for individual local variables, as a modern optimizer will remove the dead store of its initialization if it is initialized later. 4. For hot code paths, it is worth profiling to see if the void initializer actually improves results. Global and Static Initializers ------------------------------ The [*Initializer*](#Initializer) for a global or static variable must be evaluatable at compile time. Runtime initialization is done with static constructors. **Implementation Defined:** 1. Whether some pointers can be initialized with the addresses of other functions or data. Type Qualifiers vs. Storage Classes ----------------------------------- Type qualifer and storage classes are distinct. A *type qualifier* creates a derived type from an existing base type, and the resulting type may be used to create multiple instances of that type. For example, the `immutable` type qualifier can be used to create variables of immutable type, such as: ``` immutable(int) x; // typeof(x) == immutable(int) immutable(int)[] y; // typeof(y) == immutable(int)[] // typeof(y[0]) == immutable(int) // Type constructors create new types that can be aliased: alias ImmutableInt = immutable(int); ImmutableInt z; // typeof(z) == immutable(int) ``` A *storage class*, on the other hand, does not create a new type, but describes only the kind of storage used by the variable or function being declared. For example, a member function can be declared with the `const` storage class to indicate that it does not modify its implicit `this` argument: ``` struct S { int x; int method() const { //x++; // Error: this method is const and cannot modify this.x return x; // OK: we can still read this.x } } ``` Although some keywords can be used both as a type qualifier and a storage class, there are some storage classes that cannot be used to construct new types, such as `ref`: ``` // ref declares the parameter x to be passed by reference void func(ref int x) { x++; // so modifications to x will be visible in the caller } void main() { auto x = 1; func(x); assert(x == 2); // However, ref is not a type qualifier, so the following is illegal: ref(int) y; // Error: ref is not a type qualifier. } ``` Functions can also be declared as `ref`, meaning their return value is passed by reference: ``` ref int func2() { static int y = 0; return y; } void main() { func2() = 2; // The return value of func2() can be modified. assert(func2() == 2); // However, the reference returned by func2() does not propagate to // variables, because the 'ref' only applies to the return value itself, // not to any subsequent variable created from it: auto x = func2(); static assert(is(typeof(x) == int)); // N.B.: *not* ref(int); // there is no such type as ref(int). x++; assert(x == 3); assert(func2() == 2); // x is not a reference to what func2() returned; it // does not inherit the ref storage class from func2(). } ``` Some keywords, such as `const`, can be used both as a type qualifier and a storage class. The distinction is determined by the syntax where it appears. ``` struct S { /* Is const here a type qualifier or a storage class? * Is the return value const(int), or is this a const function that returns * (mutable) int? */ const int* func() // a const function { ++p; // error, this.p is const return p; // error, cannot convert const(int)* to int* } const(int)* func() // a function returning a pointer to a const int { ++p; // ok, this.p is mutable return p; // ok, int* can be implicitly converted to const(int)* } int* p; } ``` **Best Practices:** To avoid confusion, the type qualifier syntax with parentheses should be used for return types, and function storage classes should be written on the right-hand side of the declaration instead of the left-hand side where it may be visually confused with the return type: ``` struct S { // Now it is clear that the 'const' here applies to the return type: const(int) func1() { return 1; } // And it is clear that the 'const' here applies to the function: int func2() const { return 1; } } ``` d std.meta std.meta ======== Templates to manipulate [template parameter sequences](https://dlang.org/spec/template.html#variadic-templates) (also known as *alias sequences*). Some operations on alias sequences are built into the language, such as `S[i]`, which accesses the element at index `i` in the sequence. `S[low .. high]` returns a new alias sequence that is a slice of the old one. For more information, see [Compile-time Sequences](https://dlang.org/ctarguments.html). **Note:** Several templates in this module use or operate on eponymous templates that take a single argument and evaluate to a boolean constant. Such templates are referred to as *template predicates*. | Category | Templates | | --- | --- | | Building blocks | [`Alias`](#Alias) [`AliasSeq`](#AliasSeq) [`aliasSeqOf`](#aliasSeqOf) | | Alias sequence filtering | [`Erase`](#Erase) [`EraseAll`](#EraseAll) [`Filter`](#Filter) [`NoDuplicates`](#NoDuplicates) [`Stride`](#Stride) | | Alias sequence type hierarchy | [`DerivedToFront`](#DerivedToFront) [`MostDerived`](#MostDerived) | | Alias sequence transformation | [`Repeat`](#Repeat) [`Replace`](#Replace) [`ReplaceAll`](#ReplaceAll) [`Reverse`](#Reverse) [`staticMap`](#staticMap) [`staticSort`](#staticSort) | | Alias sequence searching | [`allSatisfy`](#allSatisfy) [`anySatisfy`](#anySatisfy) [`staticIndexOf`](#staticIndexOf) | | Template predicates | [`templateAnd`](#templateAnd) [`templateNot`](#templateNot) [`templateOr`](#templateOr) [`staticIsSorted`](#staticIsSorted) | | Template instantiation | [`ApplyLeft`](#ApplyLeft) [`ApplyRight`](#ApplyRight) [`Instantiate`](#Instantiate) | References Based on ideas in Table 3.1 from [Modern C++ Design](http://amazon.com/exec/obidos/ASIN/0201704315/ref=ase_classicempire/102-2957199-2585768), Andrei Alexandrescu (Addison-Wesley Professional, 2001) License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com), [David Nadlinger](http://klickverbot.at) Source [std/meta.d](https://github.com/dlang/phobos/blob/master/std/meta.d) template **AliasSeq**(TList...) Creates a sequence of zero or more aliases. This is most commonly used as template parameters or arguments. In previous versions of Phobos, this was known as `TypeTuple`. Examples: ``` import std.meta; alias TL = AliasSeq!(int, double); int foo(TL td) // same as int foo(int, double); { return td[0] + cast(int) td[1]; } ``` Examples: ``` alias TL = AliasSeq!(int, double); alias Types = AliasSeq!(TL, char); static assert(is(Types == AliasSeq!(int, double, char))); ``` Examples: ``` // Creates a compile-time sequence of function call expressions // that each call `func` with the next variadic template argument template Map(alias func, args...) { auto ref lazyItem() {return func(args[0]);} static if (args.length == 1) { alias Map = lazyItem; } else { // recurse alias Map = AliasSeq!(lazyItem, Map!(func, args[1 .. $])); } } static void test(int a, int b) { writeln(a); // 4 writeln(b); // 16 } static int a = 2; static int b = 4; test(Map!(i => i ^^ 2, a, b)); writeln(a); // 2 writeln(b); // 4 test(Map!((ref i) => i *= i, a, b)); writeln(a); // 4 writeln(b); // 16 static void testRef(ref int a, ref int b) { writeln(a++); // 16 writeln(b++); // 256 } testRef(Map!(function ref(ref i) => i *= i, a, b)); writeln(a); // 17 writeln(b); // 257 ``` template **Alias**(alias a) template **Alias**(T) Allows `alias`ing of any single symbol, type or compile-time expression. Not everything can be directly aliased. An alias cannot be declared of - for example - a literal: ``` alias a = 4; //Error ``` With this template any single entity can be aliased: ``` alias b = Alias!4; //OK ``` See Also: To alias more than one thing at once, use [`AliasSeq`](#AliasSeq). Examples: ``` // Without Alias this would fail if Args[0] was e.g. a value and // some logic would be needed to detect when to use enum instead alias Head(Args...) = Alias!(Args[0]); alias Tail(Args...) = Args[1 .. $]; alias Blah = AliasSeq!(3, int, "hello"); static assert(Head!Blah == 3); static assert(is(Head!(Tail!Blah) == int)); static assert((Tail!Blah)[1] == "hello"); ``` Examples: ``` alias a = Alias!(123); static assert(a == 123); enum abc = 1; alias b = Alias!(abc); static assert(b == 1); alias c = Alias!(3 + 4); static assert(c == 7); alias concat = (s0, s1) => s0 ~ s1; alias d = Alias!(concat("Hello", " World!")); static assert(d == "Hello World!"); alias e = Alias!(int); static assert(is(e == int)); alias f = Alias!(AliasSeq!(int)); static assert(!is(typeof(f[0]))); //not an AliasSeq static assert(is(f == int)); auto g = 6; alias h = Alias!g; ++h; writeln(g); // 7 ``` enum auto **staticIndexOf**(T, TList...); enum auto **staticIndexOf**(alias T, TList...); Returns the index of the first occurrence of T in the sequence TList. If not found, -1 is returned. Examples: ``` import std.stdio; void foo() { writefln("The index of long is %s", staticIndexOf!(long, AliasSeq!(int, long, double))); // prints: The index of long is 1 } ``` template **Erase**(T, TList...) template **Erase**(alias T, TList...) Returns an `AliasSeq` created from TList with the first occurrence, if any, of T removed. Examples: ``` alias Types = AliasSeq!(int, long, double, char); alias TL = Erase!(long, Types); static assert(is(TL == AliasSeq!(int, double, char))); ``` template **EraseAll**(T, TList...) template **EraseAll**(alias T, TList...) Returns an `AliasSeq` created from TList with the all occurrences, if any, of T removed. Examples: ``` alias Types = AliasSeq!(int, long, long, int); alias TL = EraseAll!(long, Types); static assert(is(TL == AliasSeq!(int, int))); ``` template **NoDuplicates**(TList...) Returns an `AliasSeq` created from TList with the all duplicate types removed. Examples: ``` alias Types = AliasSeq!(int, long, long, int, float); alias TL = NoDuplicates!(Types); static assert(is(TL == AliasSeq!(int, long, float))); ``` template **Replace**(T, U, TList...) template **Replace**(alias T, U, TList...) template **Replace**(T, alias U, TList...) template **Replace**(alias T, alias U, TList...) Returns an `AliasSeq` created from TList with the first occurrence of T, if found, replaced with U. Examples: ``` alias Types = AliasSeq!(int, long, long, int, float); alias TL = Replace!(long, char, Types); static assert(is(TL == AliasSeq!(int, char, long, int, float))); ``` template **ReplaceAll**(T, U, TList...) template **ReplaceAll**(alias T, U, TList...) template **ReplaceAll**(T, alias U, TList...) template **ReplaceAll**(alias T, alias U, TList...) Returns an `AliasSeq` created from TList with all occurrences of T, if found, replaced with U. Examples: ``` alias Types = AliasSeq!(int, long, long, int, float); alias TL = ReplaceAll!(long, char, Types); static assert(is(TL == AliasSeq!(int, char, char, int, float))); ``` template **Reverse**(TList...) Returns an `AliasSeq` created from TList with the order reversed. Examples: ``` alias Types = AliasSeq!(int, long, long, int, float, byte, ubyte, short, ushort, uint); alias TL = Reverse!(Types); static assert(is(TL == AliasSeq!(uint, ushort, short, ubyte, byte, float, int, long, long, int))); ``` template **MostDerived**(T, TList...) Returns the type from TList that is the most derived from type T. If none are found, T is returned. Examples: ``` class A { } class B : A { } class C : B { } alias Types = AliasSeq!(A, C, B); MostDerived!(Object, Types) x; // x is declared as type C static assert(is(typeof(x) == C)); ``` template **DerivedToFront**(TList...) Returns an `AliasSeq` with the elements of TList sorted so that the most derived types come first. Examples: ``` class A { } class B : A { } class C : B { } alias Types = AliasSeq!(A, C, B); alias TL = DerivedToFront!(Types); static assert(is(TL == AliasSeq!(C, B, A))); ``` template **staticMap**(alias F, Args...) Evaluates to `AliasSeq!(F!(T[0]), F!(T[1]), ..., F!(T[$ - 1]))`. Examples: ``` import std.traits : Unqual; alias TL = staticMap!(Unqual, int, const int, immutable int, uint, ubyte, byte, short, ushort); static assert(is(TL == AliasSeq!(int, int, int, uint, ubyte, byte, short, ushort))); ``` template **allSatisfy**(alias F, T...) Tests whether all given items satisfy a template predicate, i.e. evaluates to `F!(T[0]) && F!(T[1]) && ... && F!(T[$ - 1])`. Evaluation is *not* short-circuited if a false result is encountered; the template predicate must be instantiable with all the given items. Examples: ``` import std.traits : isIntegral; static assert(!allSatisfy!(isIntegral, int, double)); static assert( allSatisfy!(isIntegral, int, long)); ``` template **anySatisfy**(alias F, T...) Tests whether any given items satisfy a template predicate, i.e. evaluates to `F!(T[0]) || F!(T[1]) || ... || F!(T[$ - 1])`. Evaluation is short-circuited if a true result is encountered; the template predicate must be instantiable with one of the given items. Examples: ``` import std.traits : isIntegral; static assert(!anySatisfy!(isIntegral, string, double)); static assert( anySatisfy!(isIntegral, int, double)); ``` template **Filter**(alias pred, TList...) Filters an `AliasSeq` using a template predicate. Returns an `AliasSeq` of the elements which satisfy the predicate. Examples: ``` import std.traits : isNarrowString, isUnsigned; alias Types1 = AliasSeq!(string, wstring, dchar[], char[], dstring, int); alias TL1 = Filter!(isNarrowString, Types1); static assert(is(TL1 == AliasSeq!(string, wstring, char[]))); alias Types2 = AliasSeq!(int, byte, ubyte, dstring, dchar, uint, ulong); alias TL2 = Filter!(isUnsigned, Types2); static assert(is(TL2 == AliasSeq!(ubyte, uint, ulong))); ``` template **templateNot**(alias pred) Negates the passed template predicate. Examples: ``` import std.traits : isPointer; alias isNoPointer = templateNot!isPointer; static assert(!isNoPointer!(int*)); static assert(allSatisfy!(isNoPointer, string, char, float)); ``` template **templateAnd**(Preds...) Combines several template predicates using logical AND, i.e. constructs a new predicate which evaluates to true for a given input T if and only if all of the passed predicates are true for T. The predicates are evaluated from left to right, aborting evaluation in a short-cut manner if a false result is encountered, in which case the latter instantiations do not need to compile. Examples: ``` import std.traits : isNumeric, isUnsigned; alias storesNegativeNumbers = templateAnd!(isNumeric, templateNot!isUnsigned); static assert(storesNegativeNumbers!int); static assert(!storesNegativeNumbers!string && !storesNegativeNumbers!uint); // An empty sequence of predicates always yields true. alias alwaysTrue = templateAnd!(); static assert(alwaysTrue!int); ``` template **templateOr**(Preds...) Combines several template predicates using logical OR, i.e. constructs a new predicate which evaluates to true for a given input T if and only at least one of the passed predicates is true for T. The predicates are evaluated from left to right, aborting evaluation in a short-cut manner if a true result is encountered, in which case the latter instantiations do not need to compile. Examples: ``` import std.traits : isPointer, isUnsigned; alias isPtrOrUnsigned = templateOr!(isPointer, isUnsigned); static assert( isPtrOrUnsigned!uint && isPtrOrUnsigned!(short*)); static assert(!isPtrOrUnsigned!int && !isPtrOrUnsigned!(string)); // An empty sequence of predicates never yields true. alias alwaysFalse = templateOr!(); static assert(!alwaysFalse!int); ``` template **aliasSeqOf**(alias iter) if (isIterable!(typeof(iter)) && !isInfinite!(typeof(iter))) Converts any foreach-iterable entity (e.g. an input range) to an alias sequence. Parameters: | | | | --- | --- | | iter | the entity to convert into an `AliasSeq`. It must be able to be able to be iterated over using a [foreach-statement](https://dlang.org/spec/statement.html#foreach-statement). | Returns: An `AliasSeq` containing the values produced by iterating over `iter`. Examples: ``` import std.algorithm.iteration : map; import std.algorithm.sorting : sort; import std.string : capitalize; struct S { int a; int c; int b; } alias capMembers = aliasSeqOf!([__traits(allMembers, S)].sort().map!capitalize()); static assert(capMembers[0] == "A"); static assert(capMembers[1] == "B"); static assert(capMembers[2] == "C"); ``` Examples: ``` static immutable REF = [0, 1, 2, 3]; foreach (I, V; aliasSeqOf!([0, 1, 2, 3])) { static assert(V == I); static assert(V == REF[I]); } ``` template **ApplyLeft**(alias Template, args...) template **ApplyRight**(alias Template, args...) [Partially applies](http://en.wikipedia.org/wiki/Partial_application) Template by binding its first (left) or last (right) arguments to args. Behaves like the identity function when args is empty. Parameters: | | | | --- | --- | | Template | template to partially apply | | args | arguments to bind | Returns: Template with arity smaller than or equal to Template Examples: ``` // enum bool isImplicitlyConvertible(From, To) import std.traits : isImplicitlyConvertible; static assert(allSatisfy!( ApplyLeft!(isImplicitlyConvertible, ubyte), short, ushort, int, uint, long, ulong)); static assert(is(Filter!(ApplyRight!(isImplicitlyConvertible, short), ubyte, string, short, float, int) == AliasSeq!(ubyte, short))); ``` Examples: ``` import std.traits : hasMember, ifTestable; struct T1 { bool foo; } struct T2 { struct Test { bool opCast(T : bool)() { return true; } } Test foo; } static assert(allSatisfy!(ApplyRight!(hasMember, "foo"), T1, T2)); static assert(allSatisfy!(ApplyRight!(ifTestable, a => a.foo), T1, T2)); ``` Examples: ``` import std.traits : Largest; alias Types = AliasSeq!(byte, short, int, long); static assert(is(staticMap!(ApplyLeft!(Largest, short), Types) == AliasSeq!(short, short, int, long))); static assert(is(staticMap!(ApplyLeft!(Largest, int), Types) == AliasSeq!(int, int, int, long))); ``` Examples: ``` import std.traits : FunctionAttribute, SetFunctionAttributes; static void foo() @system; static int bar(int) @system; alias SafeFunctions = AliasSeq!( void function() @safe, int function(int) @safe); static assert(is(staticMap!(ApplyRight!( SetFunctionAttributes, "D", FunctionAttribute.safe), typeof(&foo), typeof(&bar)) == SafeFunctions)); ``` template **Repeat**(size\_t n, TList...) Creates an `AliasSeq` which repeats `TList` exactly `n` times. Examples: ``` alias ImInt0 = Repeat!(0, int); static assert(is(ImInt0 == AliasSeq!())); alias ImInt1 = Repeat!(1, immutable(int)); static assert(is(ImInt1 == AliasSeq!(immutable(int)))); alias Real3 = Repeat!(3, real); static assert(is(Real3 == AliasSeq!(real, real, real))); alias Real12 = Repeat!(4, Real3); static assert(is(Real12 == AliasSeq!(real, real, real, real, real, real, real, real, real, real, real, real))); alias Composite = AliasSeq!(uint, int); alias Composite2 = Repeat!(2, Composite); static assert(is(Composite2 == AliasSeq!(uint, int, uint, int))); alias ImInt10 = Repeat!(10, int); static assert(is(ImInt10 == AliasSeq!(int, int, int, int, int, int, int, int, int, int))); ``` Examples: ``` auto staticArray(T, size_t n)(Repeat!(n, T) elems) { T[n] a = [elems]; return a; } auto a = staticArray!(long, 3)(3, 1, 4); assert(is(typeof(a) == long[3])); writeln(a); // [3, 1, 4] ``` template **staticSort**(alias cmp, Seq...) Sorts an [`AliasSeq`](#AliasSeq) using `cmp`. Parameters cmp = A template that returns a `bool` (if its first argument is less than the second one) or an `int` (-1 means less than, 0 means equal, 1 means greater than) Seq = The [`AliasSeq`](#AliasSeq) to sort Returns: The sorted alias sequence Examples: ``` alias Nums = AliasSeq!(7, 2, 3, 23); enum Comp(int N1, int N2) = N1 < N2; static assert(AliasSeq!(2, 3, 7, 23) == staticSort!(Comp, Nums)); ``` Examples: ``` alias Types = AliasSeq!(uint, short, ubyte, long, ulong); enum Comp(T1, T2) = __traits(isUnsigned, T2) - __traits(isUnsigned, T1); static assert(is(AliasSeq!(uint, ubyte, ulong, short, long) == staticSort!(Comp, Types))); ``` template **staticIsSorted**(alias cmp, Seq...) Checks if an [`AliasSeq`](#AliasSeq) is sorted according to `cmp`. Parameters cmp = A template that returns a `bool` (if its first argument is less than the second one) or an `int` (-1 means less than, 0 means equal, 1 means greater than) Seq = The [`AliasSeq`](#AliasSeq) to check Returns: `true` if `Seq` is sorted; otherwise `false` Examples: ``` enum Comp(int N1, int N2) = N1 < N2; static assert( staticIsSorted!(Comp, 2, 2)); static assert( staticIsSorted!(Comp, 2, 3, 7, 23)); static assert(!staticIsSorted!(Comp, 7, 2, 3, 23)); ``` Examples: ``` enum Comp(T1, T2) = __traits(isUnsigned, T2) - __traits(isUnsigned, T1); static assert( staticIsSorted!(Comp, uint, ubyte, ulong, short, long)); static assert(!staticIsSorted!(Comp, uint, short, ubyte, long, ulong)); ``` template **Stride**(int stepSize, Args...) if (stepSize != 0) Selects a subset of `Args` by stepping with fixed `stepSize` over the sequence. A negative `stepSize` starts iteration with the last element. Parameters: | | | | --- | --- | | stepSize | Number of elements to increment on each iteration. Can't be `0`. | | Args | Template arguments. | Returns: An `AliasSeq` filtered by the selected stride. Examples: ``` static assert(is(Stride!(1, short, int, long) == AliasSeq!(short, int, long))); static assert(is(Stride!(2, short, int, long) == AliasSeq!(short, long))); static assert(is(Stride!(-1, short, int, long) == AliasSeq!(long, int, short))); static assert(is(Stride!(-2, short, int, long) == AliasSeq!(long, short))); alias attribs = AliasSeq!(short, int, long, ushort, uint, ulong); static assert(is(Stride!(3, attribs) == AliasSeq!(short, ushort))); static assert(is(Stride!(3, attribs[1 .. $]) == AliasSeq!(int, uint))); static assert(is(Stride!(-3, attribs) == AliasSeq!(ulong, long))); ``` template **Instantiate**(alias Template, Params...) Instantiates the given template with the given parameters. Used to work around syntactic limitations of D with regard to instantiating a template from an alias sequence (e.g. `T[0]!(...)` is not valid) or a template returning another template (e.g. `Foo!(Bar)!(Baz)` is not allowed). Parameters: | | | | --- | --- | | Template | The template to instantiate. | | Params | The parameters with which to instantiate the template. | Returns: The instantiated template. Examples: ``` // ApplyRight combined with Instantiate can be used to apply various // templates to the same parameters. import std.string : leftJustify, center, rightJustify; alias functions = staticMap!(ApplyRight!(Instantiate, string), leftJustify, center, rightJustify); string result = ""; static foreach (f; functions) { { auto x = &f; // not a template, but a function instantiation result ~= x("hello", 7); result ~= ";"; } } writeln(result); // "hello ; hello ; hello;" ```
programming_docs
d etc.c.odbc.sqlext etc.c.odbc.sqlext ================= Declarations for interfacing with the ODBC library. Adapted with minimal changes from the work of David L. Davis (refer to the [original announcement](http://forum.dlang.org/post/cfk7ql&dollar;1p4n&dollar;[email protected])). `etc.c.odbc.sqlext` corresponds to the `sqlext.h` C header file. See Also: [ODBC API Reference on MSN Online](https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/odbc-api-reference) d Template Mixins Template Mixins =============== **Contents** 1. [Mixin Scope](#mixin_scope) A *TemplateMixin* takes an arbitrary set of declarations from the body of a *TemplateDeclaration* and inserts them into the current context. ``` TemplateMixinDeclaration: mixin template Identifier TemplateParameters Constraintopt { DeclDefsopt } TemplateMixin: mixin MixinTemplateName TemplateArgumentsopt Identifieropt ; MixinTemplateName: . MixinQualifiedIdentifier MixinQualifiedIdentifier Typeof . MixinQualifiedIdentifier MixinQualifiedIdentifier: Identifier Identifier . MixinQualifiedIdentifier TemplateInstance . MixinQualifiedIdentifier ``` A *TemplateMixin* can occur in declaration lists of modules, classes, structs, unions, and as a statement. The *MixinTemplateName* refers to a *TemplateDeclaration* or *TemplateMixinDeclaration*. If the *TemplateDeclaration* has no parameters, the mixin form that has no !(*TemplateArgumentList*) can be used. Unlike a template instantiation, a template mixin's body is evaluated within the scope where the mixin appears, not where the template declaration is defined. It is analogous to cutting and pasting the body of the template into the location of the mixin into a [nested scope](#mixin_scope). It is useful for injecting parameterized ‘boilerplate’ code, as well as for creating templated nested functions, which is not possible with template instantiations. ``` mixin template Foo() { int x = 5; } mixin Foo; struct Bar { mixin Foo; } void test() { writefln("x = %d", x); // prints 5 { Bar b; int x = 3; writefln("b.x = %d", b.x); // prints 5 writefln("x = %d", x); // prints 3 { mixin Foo; writefln("x = %d", x); // prints 5 x = 4; writefln("x = %d", x); // prints 4 } writefln("x = %d", x); // prints 3 } writefln("x = %d", x); // prints 5 } ``` Mixins can be parameterized: ``` mixin template Foo(T) { T x = 5; } mixin Foo!(int); // create x of type int ``` Mixins can add virtual functions to a class: ``` mixin template Foo() { void func() { writeln("Foo.func()"); } } class Bar { mixin Foo; } class Code : Bar { override void func() { writeln("Code.func()"); } } void test() { Bar b = new Bar(); b.func(); // calls Foo.func() b = new Code(); b.func(); // calls Code.func() } ``` Mixins are evaluated in the scope of where they appear, not the scope of the template declaration: ``` int y = 3; mixin template Foo() { int abc() { return y; } } void test() { int y = 8; mixin Foo; // local y is picked up, not global y assert(abc() == 8); } ``` Mixins can parameterize symbols using alias parameters: ``` mixin template Foo(alias b) { int abc() { return b; } } void test() { int y = 8; mixin Foo!(y); assert(abc() == 8); } ``` This example uses a mixin to implement a generic Duff's device for an arbitrary statement (in this case, the arbitrary statement is in bold). A nested function is generated as well as a delegate literal, these can be inlined by the compiler: ``` mixin template duffs_device(alias id1, alias id2, alias s) { void duff_loop() { if (id1 < id2) { typeof(id1) n = (id2 - id1 + 7) / 8; switch ((id2 - id1) % 8) { case 0: do { s(); goto case; case 7: s(); goto case; case 6: s(); goto case; case 5: s(); goto case; case 4: s(); goto case; case 3: s(); goto case; case 2: s(); goto case; case 1: s(); continue; default: assert(0, "Impossible"); } while (--n > 0); } } } } void foo() { writeln("foo"); } void test() { int i = 1; int j = 11; mixin duffs_device!(i, j, delegate { foo(); }); duff_loop(); // executes foo() 10 times } ``` Mixin Scope ----------- The declarations in a mixin are placed in a nested scope and then ‘imported’ into the surrounding scope. If the name of a declaration in a mixin is the same as a declaration in the surrounding scope, the surrounding declaration overrides the mixin one: ``` int x = 3; mixin template Foo() { int x = 5; int y = 5; } mixin Foo; int y = 3; void test() { writefln("x = %d", x); // prints 3 writefln("y = %d", y); // prints 3 } ``` If two different mixins are put in the same scope, and each define a declaration with the same name, there is an ambiguity error when the declaration is referenced: ``` mixin template Foo() { int x = 5; void func(int x) { } } mixin template Bar() { int x = 4; void func(long x) { } } mixin Foo; mixin Bar; void test() { import std.stdio : writefln; writefln("x = %d", x); // error, x is ambiguous func(1); // error, func is ambiguous } ``` The call to `func()` is ambiguous because Foo.func and Bar.func are in different scopes. If a mixin has an *Identifier*, it can be used to disambiguate between conflicting symbols: ``` int x = 6; mixin template Foo() { int x = 5; int y = 7; void func() { } } mixin template Bar() { int x = 4; void func() { } } mixin Foo F; mixin Bar B; void test() { writefln("y = %d", y); // prints 7 writefln("x = %d", x); // prints 6 writefln("F.x = %d", F.x); // prints 5 writefln("B.x = %d", B.x); // prints 4 F.func(); // calls Foo.func B.func(); // calls Bar.func } ``` Alias declarations can be used to overload together functions declared in different mixins: ``` mixin template Foo() { void func(int x) { } } mixin template Bar() { void func(long x) { } } mixin Foo!() F; mixin Bar!() B; alias func = F.func; alias func = B.func; void main() { func(1); // calls B.func func(1L); // calls F.func } ``` A mixin has its own scope, even if a declaration is overridden by the enclosing one: ``` int x = 4; mixin template Foo() { int x = 5; int bar() { return x; } } mixin Foo; void test() { writefln("x = %d", x); // prints 4 writefln("bar() = %d", bar()); // prints 5 } ``` d std.numeric std.numeric =========== This module is a port of a growing fragment of the numeric header in Alexander Stepanov's [Standard Template Library](https://en.wikipedia.org/wiki/Standard_Template_Library), with a few additions. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Andrei Alexandrescu](http://erdani.org), Don Clugston, Robert Jacques, Ilya Yaroshenko Source [std/numeric.d](https://github.com/dlang/phobos/blob/master/std/numeric.d) enum **CustomFloatFlags**: int; Format flags for CustomFloat. **signed** Adds a sign bit to allow for signed numbers. **storeNormalized** Store values in normalized form by default. The actual precision of the significand is extended by 1 bit by assuming an implicit leading bit of 1 instead of 0. i.e. `1.nnnn` instead of `0.nnnn`. True for all [IEE754](https://en.wikipedia.org/wiki/IEEE_floating_point) types **allowDenorm** Stores the significand in [IEEE754 denormalized](https://en.wikipedia.org/wiki/IEEE_754-1985#Denormalized_numbers) form when the exponent is 0. Required to express the value 0. **infinity** Allows the storage of [IEEE754 infinity](https://en.wikipedia.org/wiki/IEEE_754-1985#Positive_and_negative_infinity) values. **nan** Allows the storage of [IEEE754 Not a Number](https://en.wikipedia.org/wiki/NaN) values. **probability** If set, select an exponent bias such that max\_exp = 1. i.e. so that the maximum value is >= 1.0 and < 2.0. Ignored if the exponent bias is manually specified. **negativeUnsigned** If set, unsigned custom floats are assumed to be negative. **allowDenormZeroOnly** If set, 0 is the only allowed [IEEE754 denormalized](https://en.wikipedia.org/wiki/IEEE_754-1985#Denormalized_numbers) number. Requires allowDenorm and storeNormalized. **ieee** Include all of the [IEEE754](https://en.wikipedia.org/wiki/IEEE_floating_point) options. **none** Include none of the above options. template **CustomFloat**(uint bits) if (bits == 8 || bits == 16 || bits == 32 || bits == 64 || bits == 80) template **CustomFloat**(uint precision, uint exponentWidth, CustomFloatFlags flags = CustomFloatFlags.ieee) if (((flags & flags.signed) + precision + exponentWidth) % 8 == 0 && (precision + exponentWidth > 0)) struct **CustomFloat**(uint precision, uint exponentWidth, CustomFloatFlags flags, uint bias) if (isCorrectCustomFloat(precision, exponentWidth, flags)); Allows user code to define custom floating-point formats. These formats are for storage only; all operations on them are performed by first implicitly extracting them to `real` first. After the operation is completed the result can be stored in a custom floating-point value via assignment. Examples: ``` import std.math : sin, cos; // Define a 16-bit floating point values CustomFloat!16 x; // Using the number of bits CustomFloat!(10, 5) y; // Using the precision and exponent width CustomFloat!(10, 5,CustomFloatFlags.ieee) z; // Using the precision, exponent width and format flags CustomFloat!(10, 5,CustomFloatFlags.ieee, 15) w; // Using the precision, exponent width, format flags and exponent offset bias // Use the 16-bit floats mostly like normal numbers w = x*y - 1; // Functions calls require conversion z = sin(+x) + cos(+y); // Use unary plus to concisely convert to a real z = sin(x.get!float) + cos(y.get!float); // Or use get!T z = sin(cast(float) x) + cos(cast(float) y); // Or use cast(T) to explicitly convert // Define a 8-bit custom float for storing probabilities alias Probability = CustomFloat!(4, 4, CustomFloatFlags.ieee^CustomFloatFlags.probability^CustomFloatFlags.signed ); auto p = Probability(0.5); ``` template **FPTemporary**(F) if (isFloatingPoint!F) Defines the fastest type to use when storing temporaries of a calculation intended to ultimately yield a result of type `F` (where `F` must be one of `float`, `double`, or `real`). When doing a multi-step computation, you may want to store intermediate results as `FPTemporary!F`. The necessity of `FPTemporary` stems from the optimized floating-point operations and registers present in virtually all processors. When adding numbers in the example above, the addition may in fact be done in `real` precision internally. In that case, storing the intermediate `result` in `double format` is not only less precise, it is also (surprisingly) slower, because a conversion from `real` to `double` is performed every pass through the loop. This being a lose-lose situation, `FPTemporary!F` has been defined as the *fastest* type to use for calculations at precision `F`. There is no need to define a type for the *most accurate* calculations, as that is always `real`. Finally, there is no guarantee that using `FPTemporary!F` will always be fastest, as the speed of floating-point calculations depends on very many factors. Examples: ``` import std.math : approxEqual; // Average numbers in an array double avg(in double[] a) { if (a.length == 0) return 0; FPTemporary!double result = 0; foreach (e; a) result += e; return result / a.length; } auto a = [1.0, 2.0, 3.0]; assert(approxEqual(avg(a), 2)); ``` template **secantMethod**(alias fun) Implements the [secant method](http://tinyurl.com/2zb9yr) for finding a root of the function `fun` starting from points `[xn_1, x_n]` (ideally close to the root). `Num` may be `float`, `double`, or `real`. Examples: ``` import std.math : approxEqual, cos; float f(float x) { return cos(x) - x*x*x; } auto x = secantMethod!(f)(0f, 1f); assert(approxEqual(x, 0.865474)); ``` T **findRoot**(T, DF, DT)(scope DF f, const T a, const T b, scope DT tolerance) Constraints: if (isFloatingPoint!T && is(typeof(tolerance(T.init, T.init)) : bool) && is(typeof(f(T.init)) == R, R) && isFloatingPoint!R); T **findRoot**(T, DF)(scope DF f, const T a, const T b); Find a real root of a real function f(x) via bracketing. Given a function `f` and a range `[a .. b]` such that `f(a)` and `f(b)` have opposite signs or at least one of them equals ±0, returns the value of `x` in the range which is closest to a root of `f(x)`. If `f(x)` has more than one root in the range, one will be chosen arbitrarily. If `f(x)` returns NaN, NaN will be returned; otherwise, this algorithm is guaranteed to succeed. Uses an algorithm based on TOMS748, which uses inverse cubic interpolation whenever possible, otherwise reverting to parabolic or secant interpolation. Compared to TOMS748, this implementation improves worst-case performance by a factor of more than 100, and typical performance by a factor of 2. For 80-bit reals, most problems require 8 to 15 calls to `f(x)` to achieve full machine precision. The worst-case performance (pathological cases) is approximately twice the number of bits. References "On Enclosing Simple Roots of Nonlinear Equations", G. Alefeld, F.A. Potra, Yixun Shi, Mathematics of Computation 61, pp733-744 (1993). Fortran code available from [www.netlib.org](http://%20www.netlib.org) as algorithm TOMS478. Tuple!(T, T, R, R) **findRoot**(T, R, DF, DT)(scope DF f, const T ax, const T bx, const R fax, const R fbx, scope DT tolerance) Constraints: if (isFloatingPoint!T && is(typeof(tolerance(T.init, T.init)) : bool) && is(typeof(f(T.init)) == R) && isFloatingPoint!R); Tuple!(T, T, R, R) **findRoot**(T, R, DF)(scope DF f, const T ax, const T bx, const R fax, const R fbx); T **findRoot**(T, R)(scope R delegate(T) f, const T a, const T b, scope bool delegate(T lo, T hi) tolerance = (T a, T b) => false); Find root of a real function f(x) by bracketing, allowing the termination condition to be specified. Parameters: | | | | --- | --- | | DF `f` | Function to be analyzed | | T `ax` | Left bound of initial range of `f` known to contain the root. | | T `bx` | Right bound of initial range of `f` known to contain the root. | | R `fax` | Value of `f(ax)`. | | R `fbx` | Value of `f(bx)`. `fax` and `fbx` should have opposite signs. (`f(ax)` and `f(bx)` are commonly known in advance.) | | DT `tolerance` | Defines an early termination condition. Receives the current upper and lower bounds on the root. The delegate must return `true` when these bounds are acceptable. If this function always returns `false`, full machine precision will be achieved. | Returns: A tuple consisting of two ranges. The first two elements are the range (in `x`) of the root, while the second pair of elements are the corresponding function values at those points. If an exact root was found, both of the first two elements will contain the root, and the second pair of elements will be 0. Tuple!(T, "x", Unqual!(ReturnType!DF), "y", T, "error") **findLocalMin**(T, DF)(scope DF f, const T ax, const T bx, const T relTolerance = sqrt(T.epsilon), const T absTolerance = sqrt(T.epsilon)) Constraints: if (isFloatingPoint!T && \_\_traits(compiles, () { T \_ = DF.init(T.init); } )); Find a real minimum of a real function `f(x)` via bracketing. Given a function `f` and a range `(ax .. bx)`, returns the value of `x` in the range which is closest to a minimum of `f(x)`. `f` is never evaluted at the endpoints of `ax` and `bx`. If `f(x)` has more than one minimum in the range, one will be chosen arbitrarily. If `f(x)` returns NaN or -Infinity, `(x, f(x), NaN)` will be returned; otherwise, this algorithm is guaranteed to succeed. Parameters: | | | | --- | --- | | DF `f` | Function to be analyzed | | T `ax` | Left bound of initial range of f known to contain the minimum. | | T `bx` | Right bound of initial range of f known to contain the minimum. | | T `relTolerance` | Relative tolerance. | | T `absTolerance` | Absolute tolerance. | Preconditions `ax` and `bx` shall be finite reals. `relTolerance` shall be normal positive real. `absTolerance` shall be normal positive real no less then `T.epsilon*2`. Returns: A tuple consisting of `x`, `y = f(x)` and `error = 3 * (absTolerance * fabs(x) + relTolerance)`. The method used is a combination of golden section search and successive parabolic interpolation. Convergence is never much slower than that for a Fibonacci search. References "Algorithms for Minimization without Derivatives", Richard Brent, Prentice-Hall, Inc. (1973) See Also: [`findRoot`](#findRoot), [`std.math.isNormal`](std_math#isNormal) Examples: ``` import std.math : approxEqual; auto ret = findLocalMin((double x) => (x-4)^^2, -1e7, 1e7); assert(ret.x.approxEqual(4.0)); assert(ret.y.approxEqual(0.0)); ``` CommonType!(ElementType!Range1, ElementType!Range2) **euclideanDistance**(Range1, Range2)(Range1 a, Range2 b) Constraints: if (isInputRange!Range1 && isInputRange!Range2); CommonType!(ElementType!Range1, ElementType!Range2) **euclideanDistance**(Range1, Range2, F)(Range1 a, Range2 b, F limit) Constraints: if (isInputRange!Range1 && isInputRange!Range2); Computes [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance) between input ranges `a` and `b`. The two ranges must have the same length. The three-parameter version stops computation as soon as the distance is greater than or equal to `limit` (this is useful to save computation if a small distance is sought). CommonType!(ElementType!Range1, ElementType!Range2) **dotProduct**(Range1, Range2)(Range1 a, Range2 b) Constraints: if (isInputRange!Range1 && isInputRange!Range2 && !(isArray!Range1 && isArray!Range2)); CommonType!(F1, F2) **dotProduct**(F1, F2)(in F1[] avector, in F2[] bvector); F **dotProduct**(F, uint N)(ref scope const F[N] a, ref scope const F[N] b) Constraints: if (N <= 16); Computes the [dot product](https://en.wikipedia.org/wiki/Dot_product) of input ranges `a` and `b`. The two ranges must have the same length. If both ranges define length, the check is done once; otherwise, it is done at each iteration. CommonType!(ElementType!Range1, ElementType!Range2) **cosineSimilarity**(Range1, Range2)(Range1 a, Range2 b) Constraints: if (isInputRange!Range1 && isInputRange!Range2); Computes the [cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity) of input ranges `a` and `b`. The two ranges must have the same length. If both ranges define length, the check is done once; otherwise, it is done at each iteration. If either range has all-zero elements, return 0. bool **normalize**(R)(R range, ElementType!R sum = 1) Constraints: if (isForwardRange!R); Normalizes values in `range` by multiplying each element with a number chosen such that values sum up to `sum`. If elements in `range` sum to zero, assigns `sum / range.length` to all. Normalization makes sense only if all elements in `range` are positive. `normalize` assumes that is the case without checking it. Returns: `true` if normalization completed normally, `false` if all elements in `range` were zero or if `range` is empty. Examples: ``` double[] a = []; assert(!normalize(a)); a = [ 1.0, 3.0 ]; assert(normalize(a)); writeln(a); // [0.25, 0.75] assert(normalize!(typeof(a))(a, 50)); // a = [12.5, 37.5] a = [ 0.0, 0.0 ]; assert(!normalize(a)); writeln(a); // [0.5, 0.5] ``` ElementType!Range **sumOfLog2s**(Range)(Range r) Constraints: if (isInputRange!Range && isFloatingPoint!(ElementType!Range)); Compute the sum of binary logarithms of the input range `r`. The error of this method is much smaller than with a naive sum of log2. Examples: ``` import std.math : isNaN; writeln(sumOfLog2s(new double[0])); // 0 writeln(sumOfLog2s([0.0L])); // -real.infinity writeln(sumOfLog2s([-0.0L])); // -real.infinity writeln(sumOfLog2s([2.0L])); // 1 assert(sumOfLog2s([-2.0L]).isNaN()); assert(sumOfLog2s([real.nan]).isNaN()); assert(sumOfLog2s([-real.nan]).isNaN()); writeln(sumOfLog2s([real.infinity])); // real.infinity assert(sumOfLog2s([-real.infinity]).isNaN()); writeln(sumOfLog2s([0.25, 0.25, 0.25, 0.125])); // -9 ``` ElementType!Range **entropy**(Range)(Range r) Constraints: if (isInputRange!Range); ElementType!Range **entropy**(Range, F)(Range r, F max) Constraints: if (isInputRange!Range && !is(CommonType!(ElementType!Range, F) == void)); Computes [entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory)) of input range `r` in bits. This function assumes (without checking) that the values in `r` are all in `[0, 1]`. For the entropy to be meaningful, often `r` should be normalized too (i.e., its values should sum to 1). The two-parameter version stops evaluating as soon as the intermediate result is greater than or equal to `max`. CommonType!(ElementType!Range1, ElementType!Range2) **kullbackLeiblerDivergence**(Range1, Range2)(Range1 a, Range2 b) Constraints: if (isInputRange!Range1 && isInputRange!Range2); Computes the [Kullback-Leibler divergence](https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence) between input ranges `a` and `b`, which is the sum `ai * log(ai / bi)`. The base of logarithm is 2. The ranges are assumed to contain elements in `[0, 1]`. Usually the ranges are normalized probability distributions, but this is not required or checked by `kullbackLeiblerDivergence`. If any element `bi` is zero and the corresponding element `ai` nonzero, returns infinity. (Otherwise, if `ai == 0 && bi == 0`, the term `ai * log(ai / bi)` is considered zero.) If the inputs are normalized, the result is positive. Examples: ``` import std.math : approxEqual; double[] p = [ 0.0, 0, 0, 1 ]; writeln(kullbackLeiblerDivergence(p, p)); // 0 double[] p1 = [ 0.25, 0.25, 0.25, 0.25 ]; writeln(kullbackLeiblerDivergence(p1, p1)); // 0 writeln(kullbackLeiblerDivergence(p, p1)); // 2 writeln(kullbackLeiblerDivergence(p1, p)); // double.infinity double[] p2 = [ 0.2, 0.2, 0.2, 0.4 ]; assert(approxEqual(kullbackLeiblerDivergence(p1, p2), 0.0719281)); assert(approxEqual(kullbackLeiblerDivergence(p2, p1), 0.0780719)); ``` CommonType!(ElementType!Range1, ElementType!Range2) **jensenShannonDivergence**(Range1, Range2)(Range1 a, Range2 b) Constraints: if (isInputRange!Range1 && isInputRange!Range2 && is(CommonType!(ElementType!Range1, ElementType!Range2))); CommonType!(ElementType!Range1, ElementType!Range2) **jensenShannonDivergence**(Range1, Range2, F)(Range1 a, Range2 b, F limit) Constraints: if (isInputRange!Range1 && isInputRange!Range2 && is(typeof(CommonType!(ElementType!Range1, ElementType!Range2).init >= F.init) : bool)); Computes the [Jensen-Shannon divergence](https://en.wikipedia.org/wiki/Jensen%E2%80%93Shannon_divergence) between `a` and `b`, which is the sum `(ai * log(2 * ai / (ai + bi)) + bi * log(2 * bi / (ai + bi))) / 2`. The base of logarithm is 2. The ranges are assumed to contain elements in `[0, 1]`. Usually the ranges are normalized probability distributions, but this is not required or checked by `jensenShannonDivergence`. If the inputs are normalized, the result is bounded within `[0, 1]`. The three-parameter version stops evaluations as soon as the intermediate result is greater than or equal to `limit`. Examples: ``` import std.math : approxEqual; double[] p = [ 0.0, 0, 0, 1 ]; writeln(jensenShannonDivergence(p, p)); // 0 double[] p1 = [ 0.25, 0.25, 0.25, 0.25 ]; writeln(jensenShannonDivergence(p1, p1)); // 0 assert(approxEqual(jensenShannonDivergence(p1, p), 0.548795)); double[] p2 = [ 0.2, 0.2, 0.2, 0.4 ]; assert(approxEqual(jensenShannonDivergence(p1, p2), 0.0186218)); assert(approxEqual(jensenShannonDivergence(p2, p1), 0.0186218)); assert(approxEqual(jensenShannonDivergence(p2, p1, 0.005), 0.00602366)); ``` F **gapWeightedSimilarity**(alias comp = "a == b", R1, R2, F)(R1 s, R2 t, F lambda) Constraints: if (isRandomAccessRange!R1 && hasLength!R1 && isRandomAccessRange!R2 && hasLength!R2); The so-called "all-lengths gap-weighted string kernel" computes a similarity measure between `s` and `t` based on all of their common subsequences of all lengths. Gapped subsequences are also included. To understand what `gapWeightedSimilarity(s, t, lambda)` computes, consider first the case `lambda = 1` and the strings `s = ["Hello", "brave", "new", "world"]` and `t = ["Hello", "new", "world"]`. In that case, `gapWeightedSimilarity` counts the following matches: 1. three matches of length 1, namely `"Hello"`, `"new"`, and `"world"`; 2. three matches of length 2, namely (`"Hello", "new"`), (`"Hello", "world"`), and (`"new", "world"`); 3. one match of length 3, namely (`"Hello", "new", "world"`). The call `gapWeightedSimilarity(s, t, 1)` simply counts all of these matches and adds them up, returning 7. ``` string[] s = ["Hello", "brave", "new", "world"]; string[] t = ["Hello", "new", "world"]; assert(gapWeightedSimilarity(s, t, 1) == 7); ``` Note how the gaps in matching are simply ignored, for example (`"Hello", "new"`) is deemed as good a match as (`"new", "world"`). This may be too permissive for some applications. To eliminate gapped matches entirely, use `lambda = 0`: ``` string[] s = ["Hello", "brave", "new", "world"]; string[] t = ["Hello", "new", "world"]; assert(gapWeightedSimilarity(s, t, 0) == 4); ``` The call above eliminated the gapped matches (`"Hello", "new"`), (`"Hello", "world"`), and (`"Hello", "new", "world"`) from the tally. That leaves only 4 matches. The most interesting case is when gapped matches still participate in the result, but not as strongly as ungapped matches. The result will be a smooth, fine-grained similarity measure between the input strings. This is where values of `lambda` between 0 and 1 enter into play: gapped matches are *exponentially penalized with the number of gaps* with base `lambda`. This means that an ungapped match adds 1 to the return value; a match with one gap in either string adds `lambda` to the return value; ...; a match with a total of `n` gaps in both strings adds `pow(lambda, n)` to the return value. In the example above, we have 4 matches without gaps, 2 matches with one gap, and 1 match with three gaps. The latter match is (`"Hello", "world"`), which has two gaps in the first string and one gap in the second string, totaling to three gaps. Summing these up we get `4 + 2 * lambda + pow(lambda, 3)`. ``` string[] s = ["Hello", "brave", "new", "world"]; string[] t = ["Hello", "new", "world"]; assert(gapWeightedSimilarity(s, t, 0.5) == 4 + 0.5 * 2 + 0.125); ``` `gapWeightedSimilarity` is useful wherever a smooth similarity measure between sequences allowing for approximate matches is needed. The examples above are given with words, but any sequences with elements comparable for equality are allowed, e.g. characters or numbers. `gapWeightedSimilarity` uses a highly optimized dynamic programming implementation that needs `16 * min(s.length, t.length)` extra bytes of memory and Ο(`s.length * t.length`) time to complete. Select!(isFloatingPoint!F, F, double) **gapWeightedSimilarityNormalized**(alias comp = "a == b", R1, R2, F)(R1 s, R2 t, F lambda, F sSelfSim = F.init, F tSelfSim = F.init) Constraints: if (isRandomAccessRange!R1 && hasLength!R1 && isRandomAccessRange!R2 && hasLength!R2); The similarity per `gapWeightedSimilarity` has an issue in that it grows with the lengths of the two strings, even though the strings are not actually very similar. For example, the range `["Hello", "world"]` is increasingly similar with the range `["Hello", "world", "world", "world",...]` as more instances of `"world"` are appended. To prevent that, `gapWeightedSimilarityNormalized` computes a normalized version of the similarity that is computed as `gapWeightedSimilarity(s, t, lambda) / sqrt(gapWeightedSimilarity(s, t, lambda) * gapWeightedSimilarity(s, t, lambda))`. The function `gapWeightedSimilarityNormalized` (a so-called normalized kernel) is bounded in `[0, 1]`, reaches `0` only for ranges that don't match in any position, and `1` only for identical ranges. The optional parameters `sSelfSim` and `tSelfSim` are meant for avoiding duplicate computation. Many applications may have already computed `gapWeightedSimilarity(s, s, lambda)` and/or `gapWeightedSimilarity(t, t, lambda)`. In that case, they can be passed as `sSelfSim` and `tSelfSim`, respectively. Examples: ``` import std.math : approxEqual, sqrt; string[] s = ["Hello", "brave", "new", "world"]; string[] t = ["Hello", "new", "world"]; writeln(gapWeightedSimilarity(s, s, 1)); // 15 writeln(gapWeightedSimilarity(t, t, 1)); // 7 writeln(gapWeightedSimilarity(s, t, 1)); // 7 assert(approxEqual(gapWeightedSimilarityNormalized(s, t, 1), 7.0 / sqrt(15.0 * 7), 0.01)); ``` struct **GapWeightedSimilarityIncremental**(Range, F = double) if (isRandomAccessRange!Range && hasLength!Range); GapWeightedSimilarityIncremental!(R, F) **gapWeightedSimilarityIncremental**(R, F)(R r1, R r2, F penalty); Similar to `gapWeightedSimilarity`, just works in an incremental manner by first revealing the matches of length 1, then gapped matches of length 2, and so on. The memory requirement is Ο(`s.length * t.length`). The time complexity is Ο(`s.length * t.length`) time for computing each step. Continuing on the previous example: The implementation is based on the pseudocode in Fig. 4 of the paper ["Efficient Computation of Gapped Substring Kernels on Large Alphabets"](http://jmlr.csail.mit.edu/papers/volume6/rousu05a/rousu05a.pdf) by Rousu et al., with additional algorithmic and systems-level optimizations. Examples: ``` string[] s = ["Hello", "brave", "new", "world"]; string[] t = ["Hello", "new", "world"]; auto simIter = gapWeightedSimilarityIncremental(s, t, 1.0); assert(simIter.front == 3); // three 1-length matches simIter.popFront(); assert(simIter.front == 3); // three 2-length matches simIter.popFront(); assert(simIter.front == 1); // one 3-length match simIter.popFront(); assert(simIter.empty); // no more match ``` this(Range s, Range t, F lambda); Constructs an object given two ranges `s` and `t` and a penalty `lambda`. Constructor completes in Ο(`s.length * t.length`) time and computes all matches of length 1. ref GapWeightedSimilarityIncremental **opSlice**(); Returns: `this`. void **popFront**(); Computes the match of the popFront length. Completes in Ο(`s.length * t.length`) time. @property F **front**(); Returns: The gapped similarity at the current match length (initially 1, grows with each call to `popFront`). @property bool **empty**(); Returns: Whether there are more matches. T **gcd**(T)(T a, T b) Constraints: if (isIntegral!T); auto **gcd**(T)(T a, T b) Constraints: if (!isIntegral!T && is(typeof(T.init % T.init)) && is(typeof(T.init == 0 || T.init > 0))); Computes the greatest common divisor of `a` and `b` by using an efficient algorithm such as [Euclid's](https://en.wikipedia.org/wiki/Euclidean_algorithm) or [Stein's](https://en.wikipedia.org/wiki/Binary_GCD_algorithm) algorithm. Parameters: | | | | --- | --- | | T | Any numerical type that supports the modulo operator `%`. If bit-shifting `<<` and `>>` are also supported, Stein's algorithm will be used; otherwise, Euclid's algorithm is used as a fallback. | Returns: The greatest common divisor of the given arguments. Examples: ``` writeln(gcd(2 * 5 * 7 * 7, 5 * 7 * 11)); // 5 * 7 const int a = 5 * 13 * 23 * 23, b = 13 * 59; writeln(gcd(a, b)); // 13 ``` class **Fft**; A class for performing fast Fourier transforms of power of two sizes. This class encapsulates a large amount of state that is reusable when performing multiple FFTs of sizes smaller than or equal to that specified in the constructor. This results in substantial speedups when performing multiple FFTs with a known maximum size. However, a free function API is provided for convenience if you need to perform a one-off FFT. References [en.wikipedia.org/wiki/Cooley%E2%80%93Tukey\_FFT\_algorithm](http://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm) this(size\_t size); Create an `Fft` object for computing fast Fourier transforms of power of two sizes of `size` or smaller. `size` must be a power of two. const Complex!F[] **fft**(F = double, R)(R range) Constraints: if (isFloatingPoint!F && isRandomAccessRange!R); Compute the Fourier transform of range using the Ο(`N log N`) Cooley-Tukey Algorithm. `range` must be a random-access range with slicing and a length equal to `size` as provided at the construction of this object. The contents of range can be either numeric types, which will be interpreted as pure real values, or complex types with properties or members `.re` and `.im` that can be read. Note Pure real FFTs are automatically detected and the relevant optimizations are performed. Returns: An array of complex numbers representing the transformed data in the frequency domain. Conventions The exponent is negative and the factor is one, i.e., output[j] := sum[ exp(-2 PI i j k / N) input[k] ]. const void **fft**(Ret, R)(R range, Ret buf) Constraints: if (isRandomAccessRange!Ret && isComplexLike!(ElementType!Ret) && hasSlicing!Ret); Same as the overload, but allows for the results to be stored in a user- provided buffer. The buffer must be of the same length as range, must be a random-access range, must have slicing, and must contain elements that are complex-like. This means that they must have a .re and a .im member or property that can be both read and written and are floating point numbers. const Complex!F[] **inverseFft**(F = double, R)(R range) Constraints: if (isRandomAccessRange!R && isComplexLike!(ElementType!R) && isFloatingPoint!F); Computes the inverse Fourier transform of a range. The range must be a random access range with slicing, have a length equal to the size provided at construction of this object, and contain elements that are either of type std.complex.Complex or have essentially the same compile-time interface. Returns: The time-domain signal. Conventions The exponent is positive and the factor is 1/N, i.e., output[j] := (1 / N) sum[ exp(+2 PI i j k / N) input[k] ]. const void **inverseFft**(Ret, R)(R range, Ret buf) Constraints: if (isRandomAccessRange!Ret && isComplexLike!(ElementType!Ret) && hasSlicing!Ret); Inverse FFT that allows a user-supplied buffer to be provided. The buffer must be a random access range with slicing, and its elements must be some complex-like type. Complex!F[] **fft**(F = double, R)(R range); void **fft**(Ret, R)(R range, Ret buf); Complex!F[] **inverseFft**(F = double, R)(R range); void **inverseFft**(Ret, R)(R range, Ret buf); Convenience functions that create an `Fft` object, run the FFT or inverse FFT and return the result. Useful for one-off FFTs. Note In addition to convenience, these functions are slightly more efficient than manually creating an Fft object for a single use, as the Fft object is deterministically destroyed before these functions return. pure nothrow @nogc @safe size\_t **decimalToFactorial**(ulong decimal, ref ubyte[21] fac); This function transforms `decimal` value into a value in the factorial number system stored in `fac`. A factorial number is constructed as: `fac[0] * 0! + fac[1] * 1! + ... fac[20] * 20!` Parameters: | | | | --- | --- | | ulong `decimal` | The decimal value to convert into the factorial number system. | | ubyte[21] `fac` | The array to store the factorial number. The array is of size 21 as `ulong.max` requires 21 digits in the factorial number system. | Returns: A variable storing the number of digits of the factorial number stored in `fac`. Examples: ``` ubyte[21] fac; size_t idx = decimalToFactorial(2982, fac); writeln(fac[0]); // 4 writeln(fac[1]); // 0 writeln(fac[2]); // 4 writeln(fac[3]); // 1 writeln(fac[4]); // 0 writeln(fac[5]); // 0 writeln(fac[6]); // 0 ```
programming_docs
d std.algorithm.comparison std.algorithm.comparison ======================== This is a submodule of [`std.algorithm`](std_algorithm). It contains generic comparison algorithms. Cheat Sheet| Function Name | Description | | [`among`](#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` | | [`castSwitch`](#castSwitch) | `(new A()).castSwitch((A a)=>1,(B b)=>2)` returns `1`. | | [`clamp`](#clamp) | `clamp(1, 3, 6)` returns `3`. `clamp(4, 3, 6)` returns `4`. | | [`cmp`](#cmp) | `cmp("abc", "abcd")` is `-1`, `cmp("abc", "aba")` is `1`, and `cmp("abc", "abc")` is `0`. | | [`either`](#either) | Return first parameter `p` that passes an `if (p)` test, e.g. `either(0, 42, 43)` returns `42`. | | [`equal`](#equal) | Compares ranges for element-by-element equality, e.g. `equal([1, 2, 3], [1.0, 2.0, 3.0])` returns `true`. | | [`isPermutation`](#isPermutation) | `isPermutation([1, 2], [2, 1])` returns `true`. | | [`isSameLength`](#isSameLength) | `isSameLength([1, 2, 3], [4, 5, 6])` returns `true`. | | [`levenshteinDistance`](#levenshteinDistance) | `levenshteinDistance("kitten", "sitting")` returns `3` by using the [Levenshtein distance algorithm](https://en.wikipedia.org/wiki/Levenshtein_distance). | | [`levenshteinDistanceAndPath`](#levenshteinDistanceAndPath) | `levenshteinDistanceAndPath("kitten", "sitting")` returns `tuple(3, "snnnsni")` by using the [Levenshtein distance algorithm](https://en.wikipedia.org/wiki/Levenshtein_distance). | | [`max`](#max) | `max(3, 4, 2)` returns `4`. | | [`min`](#min) | `min(3, 4, 2)` returns `2`. | | [`mismatch`](#mismatch) | `mismatch("oh hi", "ohayo")` returns `tuple(" hi", "ayo")`. | | [`predSwitch`](#predSwitch) | `2.predSwitch(1, "one", 2, "two", 3, "three")` returns `"two"`. | License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: [Andrei Alexandrescu](http://erdani.com) Source [std/algorithm/comparison.d](https://github.com/dlang/phobos/blob/master/std/algorithm/comparison.d) uint **among**(alias pred = (a, b) => a == b, Value, Values...)(Value value, Values values) Constraints: if (Values.length != 0); template **among**(values...) if (isExpressionTuple!values) 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. Parameters: | | | | --- | --- | | pred | The predicate used to compare the values. | | Value `value` | The value to search for. | | Values `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: [find](std_algorithm_searching#find) and [canFind](std_algorithm_searching#canFind) for finding a value in a range. Examples: ``` assert(3.among(1, 42, 24, 3, 2)); if (auto pos = "bar".among("foo", "bar", "baz")) writeln(pos); // 2 else assert(false); // 42 is larger than 24 writeln(42.among!((lhs, rhs) => lhs > rhs)(43, 24, 100)); // 2 ``` Examples: Alternatively, `values` can be passed at compile-time, allowing for a more efficient search, but one that only supports matching on equality: ``` assert(3.among!(2, 3, 4)); writeln("bar".among!("foo", "bar", "baz")); // 2 ``` auto **castSwitch**(choices...)(Object switchObject); 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. `SwitchError` will also be thrown if not all the choices are void and a void choice was executed without throwing anything. Parameters: | | | | --- | --- | | 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 `switchObject` is null. | | Object `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. Examples: ``` 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: writeln(results[0]); // "A with a value of 1" // B has no handler - it is handled by the handler of I: writeln(results[1]); // "derived from I" // null is handled by the null handler: writeln(results[2]); // "null reference" ``` Examples: Using with void handlers: ``` 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); }, )(); ``` auto **clamp**(T1, T2, T3)(T1 val, T2 lower, T3 upper) Constraints: if (is(typeof(max(min(val, upper), lower)))); Clamps a value into the given bounds. This function is equivalent to `max(lower, min(upper, val))`. Parameters: | | | | --- | --- | | T1 `val` | The value to clamp. | | T2 `lower` | The lower bound of the clamp. | | T3 `upper` | The upper bound of the clamp. | Returns: Returns `val`, if it is between `lower` and `upper`. Otherwise returns the nearest of the two. Examples: ``` writeln(clamp(2, 1, 3)); // 2 writeln(clamp(0, 1, 3)); // 1 writeln(clamp(4, 1, 3)); // 3 writeln(clamp(1, 1, 1)); // 1 writeln(clamp(5, -1, 2u)); // 2 ``` auto **cmp**(R1, R2)(R1 r1, R2 r2) Constraints: if (isInputRange!R1 && isInputRange!R2); int **cmp**(alias pred, R1, R2)(R1 r1, R2 r2) Constraints: if (isInputRange!R1 && isInputRange!R2); Performs a lexicographical comparison on two [input ranges](std_range_primitives#isInputRange). 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`. Parameters: | | | | --- | --- | | pred | Predicate used for comparison. Without a predicate specified the ordering implied by `opCmp` is used. | | R1 `r1` | The first range. | | R2 `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. Examples: ``` int result; result = cmp("abc", "abc"); writeln(result); // 0 result = cmp("", ""); writeln(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); writeln(result); // 0 result = cmp("aaa"d, "aaa"d); writeln(result); // 0 result = cmp(cast(int[])[], cast(int[])[]); writeln(result); // 0 result = cmp([1, 2, 3], [1, 2, 3]); writeln(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); ``` Examples: Example predicate that compares individual elements in reverse lexical order ``` int result; result = cmp!"a > b"("abc", "abc"); writeln(result); // 0 result = cmp!"a > b"("", ""); writeln(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); writeln(result); // 0 result = cmp("aaa"d, "aaa"d); writeln(result); // 0 result = cmp!"a > b"(cast(int[])[], cast(int[])[]); writeln(result); // 0 result = cmp!"a > b"([1, 2, 3], [1, 2, 3]); writeln(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); ``` template **equal**(alias pred = "a == b") Compares two ranges for equality, as defined by predicate `pred` (which is `==` by default). Examples: ``` import std.algorithm.comparison : equal; import std.math : approxEqual; 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.005, 2, 4, 3]; assert(equal!approxEqual(b[], c[])); ``` Examples: 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. ``` 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) )); ``` bool **equal**(Range1, Range2)(Range1 r1, Range2 r2) Constraints: if (isInputRange!Range1 && isInputRange!Range2 && !(isInfinite!Range1 && isInfinite!Range2) && is(typeof(binaryFun!pred(r1.front, r2.front)))); Compares two ranges for equality. The ranges may have different element types, as long as `pred(r1.front, r2.front)` evaluates to `bool`. Performs Ο(`min(r1.length, r2.length)`) evaluations of `pred`. 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 two ranges are different kinds of UTF code unit (`char`, `wchar`, or `dchar`), then the arrays are compared using UTF decoding to avoid accidentally integer-promoting units. Parameters: | | | | --- | --- | | Range1 `r1` | The first range to be compared. | | Range2 `r2` | The second range to be compared. | Returns: `true` if and only if the two ranges compare equal element for element, according to binary predicate `pred`. enum **EditOp**: char; Encodes [edit operations](http://realityinteractive.com/rgrzywinski/archives/000249.html) 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 `"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. Examples: ``` with(EditOp) { // [none, none, none, insert, insert, insert] writeln(levenshteinDistanceAndPath("foo", "foobar")[1]); // [substitute, none, substitute, none, none, remove] writeln(levenshteinDistanceAndPath("banana", "fazan")[1]); } ``` **none** Current items are equal; no editing is necessary. **substitute** Substitute current item in target with current item in source. **insert** Insert current item from the source into the target. **remove** Remove current item from the target. size\_t **levenshteinDistance**(alias equals = (a, b) => a == b, Range1, Range2)(Range1 s, Range2 t) Constraints: if (isForwardRange!Range1 && isForwardRange!Range2); size\_t **levenshteinDistance**(alias equals = (a, b) => a == b, Range1, Range2)(auto ref Range1 s, auto ref Range2 t) Constraints: if (isConvertibleToString!Range1 || isConvertibleToString!Range2); Returns the [Levenshtein distance](http://wikipedia.org/wiki/Levenshtein_distance) between `s` and `t`. The Levenshtein distance computes the minimal amount of edit operations necessary to transform `s` into `t`. Performs Ο(`s.length * t.length`) evaluations of `equals` and occupies Ο(`min(s.length, t.length)`) storage. Parameters: | | | | --- | --- | | equals | The binary predicate to compare the elements of the two ranges. | | Range1 `s` | The original range. | | Range2 `t` | The transformation target | Returns: The minimal number of edits to transform s into t. Does not allocate GC memory. Examples: ``` import std.algorithm.iteration : filter; import std.uni : toUpper; writeln(levenshteinDistance("cat", "rat")); // 1 writeln(levenshteinDistance("parks", "spark")); // 2 writeln(levenshteinDistance("abcde", "abcde")); // 0 writeln(levenshteinDistance("abcde", "abCde")); // 1 writeln(levenshteinDistance("kitten", "sitting")); // 3 assert(levenshteinDistance!((a, b) => toUpper(a) == toUpper(b)) ("parks", "SPARK") == 2); writeln(levenshteinDistance("parks".filter!"true", "spark".filter!"true")); // 2 writeln(levenshteinDistance("ID", "I♥D")); // 1 ``` Tuple!(size\_t, EditOp[]) **levenshteinDistanceAndPath**(alias equals = (a, b) => a == b, Range1, Range2)(Range1 s, Range2 t) Constraints: if (isForwardRange!Range1 && isForwardRange!Range2); Tuple!(size\_t, EditOp[]) **levenshteinDistanceAndPath**(alias equals = (a, b) => a == b, Range1, Range2)(auto ref Range1 s, auto ref Range2 t) Constraints: if (isConvertibleToString!Range1 || isConvertibleToString!Range2); Returns the Levenshtein distance and the edit path between `s` and `t`. Parameters: | | | | --- | --- | | equals | The binary predicate to compare the elements of the two ranges. | | Range1 `s` | The original range. | | Range2 `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. Examples: ``` string a = "Saturday", b = "Sundays"; auto p = levenshteinDistanceAndPath(a, b); writeln(p[0]); // 4 assert(equal(p[1], "nrrnsnnni")); ``` auto **max**(T...)(T args) Constraints: if (T.length >= 2 && !is(CommonType!T == void)); Iterates the passed arguments and returns the maximum value. Parameters: | | | | --- | --- | | T `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 [`std.algorithm.searching.maxElement`](std_algorithm_searching#maxElement) for examples on how to cope with NaNs. See Also: [`std.algorithm.searching.maxElement`](std_algorithm_searching#maxElement) Examples: ``` int a = 5; short b = 6; double c = 2; auto d = max(a, b); assert(is(typeof(d) == int)); writeln(d); // 6 auto e = min(a, b, c); assert(is(typeof(e) == double)); writeln(e); // 2 ``` auto **min**(T...)(T args) Constraints: if (T.length >= 2 && !is(CommonType!T == void)); Iterates the passed arguments and returns the minimum value. Parameters: | | | | --- | --- | | T `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 [`std.algorithm.searching.minElement`](std_algorithm_searching#minElement) for examples on how to cope with NaNs. See Also: [`std.algorithm.searching.minElement`](std_algorithm_searching#minElement) Examples: ``` int a = 5; short b = 6; double c = 2; auto d = min(a, b); static assert(is(typeof(d) == int)); writeln(d); // 5 auto e = min(a, b, c); static assert(is(typeof(e) == double)); writeln(e); // 2 ulong f = 0xffff_ffff_ffff; const uint g = min(f, 0xffff_0000); writeln(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)); writeln(min(h, i)); // 100 ``` Examples: With arguments of mixed signedness, the return type is the one that can store the lowest values. ``` int a = -10; uint f = 10; static assert(is(typeof(min(a, f)) == int)); writeln(min(a, f)); // -10 ``` Examples: User-defined types that support comparison with < are supported. ``` import std.datetime; writeln(min(Date(2012, 12, 21), Date(1982, 1, 4))); // Date(1982, 1, 4) writeln(min(Date(1982, 1, 4), Date(2012, 12, 21))); // Date(1982, 1, 4) writeln(min(Date(1982, 1, 4), Date.min)); // Date.min writeln(min(Date.min, Date(1982, 1, 4))); // Date.min writeln(min(Date(1982, 1, 4), Date.max)); // Date(1982, 1, 4) writeln(min(Date.max, Date(1982, 1, 4))); // Date(1982, 1, 4) writeln(min(Date.min, Date.max)); // Date.min writeln(min(Date.max, Date.min)); // Date.min ``` Tuple!(Range1, Range2) **mismatch**(alias pred = "a == b", Range1, Range2)(Range1 r1, Range2 r2) Constraints: if (isInputRange!Range1 && isInputRange!Range2); Sequentially compares elements in `r1` and `r2` 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 Ο(`min(r1.length, r2.length)`) evaluations of `pred`. Examples: ``` 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[]); writeln(m[0]); // x[3 .. &dollar;] writeln(m[1]); // y[3 .. &dollar;] ``` auto **predSwitch**(alias pred = "a == b", T, R...)(T switchExpression, lazy R choices); 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. Parameters: | | | | --- | --- | | T `switchExpression` | The first argument for the predicate. | | R `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 `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. `SwitchError` is also thrown if a void return expression was executed without throwing anything. Examples: ``` string res = 2.predSwitch!"a < b"( 1, "less than 1", 5, "less than 5", 10, "less than 10", "greater or equal to 10"); writeln(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 ); } writeln(factorial(3)); // 6 //Void return expressions are allowed if they always throw: import std.exception : assertThrown; assertThrown!Exception(factorial(-9)); ``` bool **isSameLength**(Range1, Range2)(Range1 r1, Range2 r2) Constraints: if (isInputRange!Range1 && isInputRange!Range2); Checks if the two 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 both ranges have a length member, this function is Ο(`1`). Otherwise, this function is Ο(`min(r1.length, r2.length)`). Infinite ranges are considered of the same length. An infinite range has never the same length as a finite range. Parameters: | | | | --- | --- | | Range1 `r1` | a finite [input range](std_range_primitives#isInputRange) | | Range2 `r2` | a finite [input range](std_range_primitives#isInputRange) | Returns: `true` if both ranges have the same length, `false` otherwise. Examples: ``` assert(isSameLength([1, 2, 3], [4, 5, 6])); assert(isSameLength([0.3, 90.4, 23.7, 119.2], [42.6, 23.6, 95.5, 6.3])); assert(isSameLength("abc", "xyz")); int[] a; int[] b; assert(isSameLength(a, b)); assert(!isSameLength([1, 2, 3], [4, 5])); assert(!isSameLength([0.3, 90.4, 23.7], [42.6, 23.6, 95.5, 6.3])); assert(!isSameLength("abcd", "xyz")); ``` bool **isPermutation**(Flag!"allocateGC" allocateGC, Range1, Range2)(Range1 r1, Range2 r2) Constraints: if (allocateGC == Yes.allocateGC && isForwardRange!Range1 && isForwardRange!Range2 && !isInfinite!Range1 && !isInfinite!Range2); bool **isPermutation**(alias pred = "a == b", Range1, Range2)(Range1 r1, Range2 r2) Constraints: if (is(typeof(binaryFun!pred)) && isForwardRange!Range1 && isForwardRange!Range2 && !isInfinite!Range1 && !isInfinite!Range2); 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 [`std.functional.binaryFun`](std_functional#binaryFun) for more details on how to define `pred`. Non-allocating forward range option: Ο(`n^2`) Non-allocating forward range option with custom `pred`: Ο(`n^2`) Allocating forward range option: amortized Ο(`r1.length`) + Ο(`r2.length`) Parameters: | | | | --- | --- | | pred | an optional parameter to change how equality is defined | | allocateGC | `Yes.allocateGC`/`No.allocateGC` | | Range1 `r1` | A finite [forward range](std_range_primitives#isForwardRange) | | Range2 `r2` | A finite [forward range](std_range_primitives#isForwardRange) | Returns: `true` if all of the elements in `r1` appear the same number of times in `r2`. Otherwise, returns `false`. Examples: ``` 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])); ``` CommonType!(T, Ts) **either**(alias pred = (a) => a, T, Ts...)(T first, lazy Ts alternatives) Constraints: if (alternatives.length >= 1 && !is(CommonType!(T, Ts) == void) && allSatisfy!(ifTestable, T, Ts)); 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](https://issues.dlang.org/show_bug.cgi?id=12647). Returns: The first argument that passes the test `pred`. Examples: ``` const a = 1; const b = 2; auto ab = either(a, b); static assert(is(typeof(ab) == const(int))); writeln(ab); // a auto c = 2; const d = 3; auto cd = either!(a => a == 3)(c, d); // use predicate static assert(is(typeof(cd) == int)); writeln(cd); // d auto e = 0; const f = 2; auto ef = either(e, f); static assert(is(typeof(ef) == int)); writeln(ef); // f ``` Examples: ``` immutable p = 1; immutable q = 2; auto pq = either(p, q); static assert(is(typeof(pq) == immutable(int))); writeln(pq); // p writeln(either(3, 4)); // 3 writeln(either(0, 4)); // 4 writeln(either(0, 0)); // 0 writeln(either("", "a")); // "" ``` Examples: ``` string r = null; writeln(either(r, "a")); // "a" writeln(either("a", "")); // "a" immutable s = [1, 2]; writeln(either(s, s)); // s writeln(either([0, 1], [1, 2])); // [0, 1] writeln(either([0, 1], [1])); // [0, 1] writeln(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"))); ```
programming_docs
d std.experimental.allocator.building_blocks.allocator_list std.experimental.allocator.building\_blocks.allocator\_list =========================================================== Source [std/experimental/allocator/building\_blocks/allocator\_list.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/allocator_list.d) struct **AllocatorList**(Factory, BookkeepingAllocator = GCAllocator); template **AllocatorList**(alias factoryFunction, BookkeepingAllocator = GCAllocator) Given an [object factory](https://en.wikipedia.org/wiki/Factory_(object-oriented_programming)) of type `Factory` or a factory function `factoryFunction`, and optionally also `BookkeepingAllocator` as a supplemental allocator for bookkeeping, `AllocatorList` creates an allocator that lazily creates as many allocators are needed for satisfying client allocation requests. An embedded list builds a most-recently-used strategy: the most recent allocators used in calls to either `allocate`, `owns` (successful calls only), or `deallocate` are tried for new allocations in order of their most recent use. Thus, although core operations take in theory Ο(`k`) time for `k` allocators in current use, in many workloads the factor is sublinear. Details of the actual strategy may change in future releases. `AllocatorList` is primarily intended for coarse-grained handling of allocators, i.e. the number of allocators in the list is expected to be relatively small compared to the number of allocations handled by each allocator. However, the per-allocator overhead is small so using `AllocatorList` with a large number of allocators should be satisfactory as long as the most-recently-used strategy is fast enough for the application. `AllocatorList` makes an effort to return allocated memory back when no longer used. It does so by destroying empty allocators. However, in order to avoid thrashing (excessive creation/destruction of allocators under certain use patterns), it keeps unused allocators for a while. Parameters: | | | | --- | --- | | factoryFunction | A function or template function (including function literals). New allocators are created by calling `factoryFunction(n)` with strictly positive numbers `n`. Delegates that capture their enviroment are not created amid concerns regarding garbage creation for the environment. When the factory needs state, a `Factory` object should be used. | | BookkeepingAllocator | Allocator used for storing bookkeeping data. The size of bookkeeping data is proportional to the number of allocators. If `BookkeepingAllocator` is `NullAllocator`, then `AllocatorList` is "ouroboros-style", i.e. it keeps the bookkeeping data in memory obtained from the allocators themselves. Note that for ouroboros-style management, the size `n` passed to `make` will be occasionally different from the size requested by client code. | | Factory | Type of a factory object that returns new allocators on a need basis. For an object `sweatshop` of type `Factory`, `sweatshop(n)` should return an allocator able to allocate at least `n` bytes (i.e. `Factory` must define `opCall(size_t)` to return an allocator object). Usually the capacity of allocators created should be much larger than `n` such that an allocator can be used for many subsequent allocations. `n` is passed only to ensure the minimum necessary for the next allocation. The factory object is allowed to hold state, which will be stored inside `AllocatorList` as a direct `public` member called `factory`. | Examples: ``` import std.algorithm.comparison : max; import std.experimental.allocator.building_blocks.free_list : ContiguousFreeList; import std.experimental.allocator.building_blocks.null_allocator : NullAllocator; import std.experimental.allocator.building_blocks.region : Region; import std.experimental.allocator.building_blocks.segregator : Segregator; import std.experimental.allocator.gc_allocator : GCAllocator; import std.experimental.allocator.mmap_allocator : MmapAllocator; // Ouroboros allocator list based upon 4MB regions, fetched directly from // mmap. All memory is released upon destruction. alias A1 = AllocatorList!((n) => Region!MmapAllocator(max(n, 1024 * 4096)), NullAllocator); // Allocator list based upon 4MB regions, fetched from the garbage // collector. All memory is released upon destruction. alias A2 = AllocatorList!((n) => Region!GCAllocator(max(n, 1024 * 4096))); // Ouroboros allocator list based upon 4MB regions, fetched from the garbage // collector. Memory is left to the collector. alias A3 = AllocatorList!( (n) => Region!NullAllocator(new ubyte[max(n, 1024 * 4096)]), NullAllocator); // Allocator list that creates one freelist for all objects alias A4 = Segregator!( 64, AllocatorList!( (n) => ContiguousFreeList!(NullAllocator, 0, 64)( cast(ubyte[])(GCAllocator.instance.allocate(4096)))), GCAllocator); A4 a; auto small = a.allocate(64); assert(small); a.deallocate(small); auto b1 = a.allocate(1024 * 8192); assert(b1 !is null); // still works due to overdimensioning b1 = a.allocate(1024 * 10); writeln(b1.length); // 1024 * 10 ``` alias **Allocator** = typeof(Factory.init(1)); Alias for `typeof(Factory()(1))`, i.e. the type of the individual allocators. BookkeepingAllocator **bkalloc**; If `BookkeepingAllocator` is not `NullAllocator`, `bkalloc` is defined and accessible. this(ref Factory plant); this(Factory plant); Constructs an `AllocatorList` given a factory object. This constructor is defined only if `Factory` has state. enum uint **alignment**; The alignment offered. void[] **allocate**(size\_t s); Allocate a block of size `s`. First tries to allocate from the existing list of already-created allocators. If neither can satisfy the request, creates a new allocator by calling `make(s)` and delegates the request to it. However, if the allocation fresh off a newly created allocator fails, subsequent calls to `allocate` will not cause more calls to `make`. void[] **alignedAllocate**(size\_t s, uint theAlignment); Allocate a block of size `s` with alignment `a`. First tries to allocate from the existing list of already-created allocators. If neither can satisfy the request, creates a new allocator by calling `make(s + a - 1)` and delegates the request to it. However, if the allocation fresh off a newly created allocator fails, subsequent calls to `alignedAllocate` will not cause more calls to `make`. Ternary **owns**(void[] b); Defined only if `Allocator` defines `owns`. Tries each allocator in turn, in most-recently-used order. If the owner is found, it is moved to the front of the list as a side effect under the assumption it will be used soon. Returns: `Ternary.yes` if one allocator was found to return `Ternary.yes`, `Ternary.no` if all component allocators returned `Ternary.no`, and `Ternary.unknown` if no allocator returned `Ternary.yes` and at least one returned `Ternary.unknown`. bool **expand**(ref void[] b, size\_t delta); Defined only if `Allocator.expand` is defined. Finds the owner of `b` and calls `expand` for it. The owner is not brought to the head of the list. bool **reallocate**(ref void[] b, size\_t s); Defined only if `Allocator.reallocate` is defined. Finds the owner of `b` and calls `reallocate` for it. If that fails, calls the global `reallocate`, which allocates a new block and moves memory. bool **deallocate**(void[] b); Defined if `Allocator.deallocate` and `Allocator.owns` are defined. bool **deallocateAll**(); Defined only if `Allocator.owns` and `Allocator.deallocateAll` are defined. const pure nothrow @nogc @safe Ternary **empty**(); Returns `Ternary.yes` if no allocators are currently active, `Ternary.no` otherwise. This methods never returns `Ternary.unknown`. d core.simd core.simd ========= Builtin SIMD intrinsics Source [core/simd.d](https://github.com/dlang/druntime/blob/master/src/core/simd.d) License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com), template **Vector**(T) Create a vector type. Parameters T = one of double[2], float[4], void[16], byte[16], ubyte[16], short[8], ushort[8], int[4], uint[4], long[2], ulong[2]. For 256 bit vectors, one of double[4], float[8], void[32], byte[32], ubyte[32], short[16], ushort[16], int[8], uint[8], long[4], ulong[4] alias **void16** = \_\_vector(void[16]); alias **double2** = \_\_vector(double[2]); alias **float4** = \_\_vector(float[4]); alias **byte16** = \_\_vector(byte[16]); alias **ubyte16** = \_\_vector(ubyte[16]); alias **short8** = \_\_vector(short[8]); alias **ushort8** = \_\_vector(ushort[8]); alias **int4** = \_\_vector(int[4]); alias **uint4** = \_\_vector(uint[4]); alias **long2** = \_\_vector(long[2]); alias **ulong2** = \_\_vector(ulong[2]); enum **XMM**: int; XMM opcodes that conform to the following: opcode xmm1,xmm2/mem and do not have side effects (i.e. do not write to memory). pure nothrow @nogc @safe void16 **\_\_simd**(XMM opcode, void16 op1, void16 op2); Generate two operand instruction with XMM 128 bit operands. This is a compiler magic function - it doesn't behave like regular D functions. Parameters opcode = any of the XMM opcodes; it must be a compile time constant op1 = first operand op2 = second operand Returns: result of opcode Examples: ``` float4 a; a = cast(float4)__simd(XMM.PXOR, a, a); ``` pure nothrow @nogc @safe void16 **\_\_simd**(XMM opcode, void16 op1); Unary SIMD instructions. pure nothrow @nogc @safe void16 **\_\_simd**(XMM opcode, double d); pure nothrow @nogc @safe void16 **\_\_simd**(XMM opcode, float f); Examples: ``` float4 a; a = cast(float4)__simd(XMM.LODSS, a); ``` pure nothrow @nogc @safe void16 **\_\_simd**(XMM opcode, void16 op1, void16 op2, ubyte imm8); For instructions: CMPPD, CMPSS, CMPSD, CMPPS, PSHUFD, PSHUFHW, PSHUFLW, BLENDPD, BLENDPS, DPPD, DPPS, MPSADBW, PBLENDW, ROUNDPD, ROUNDPS, ROUNDSD, ROUNDSS Parameters opcode = any of the above XMM opcodes; it must be a compile time constant op1 = first operand op2 = second operand imm8 = third operand; must be a compile time constant Returns: result of opcode Examples: ``` float4 a; a = cast(float4)__simd(XMM.CMPPD, a, a, 0x7A); ``` pure nothrow @nogc @safe void16 **\_\_simd\_ib**(XMM opcode, void16 op1, ubyte imm8); For instructions with the imm8 version: PSLLD, PSLLQ, PSLLW, PSRAD, PSRAW, PSRLD, PSRLQ, PSRLW, PSRLDQ, PSLLDQ Parameters opcode = any of the XMM opcodes; it must be a compile time constant op1 = first operand imm8 = second operand; must be a compile time constant Returns: result of opcode Examples: ``` float4 a; a = cast(float4) __simd_ib(XMM.PSRLQ, a, 0x7A); ``` pure nothrow @nogc @safe void16 **\_\_simd\_sto**(XMM opcode, void16 op1, void16 op2); For "store" operations of the form: op1 op= op2 Returns: op2 These cannot be marked as pure, as semantic() doesn't check them. pure nothrow @nogc @safe void16 **\_\_simd\_sto**(XMM opcode, double op1, void16 op2); pure nothrow @nogc @safe void16 **\_\_simd\_sto**(XMM opcode, float op1, void16 op2); Examples: ``` void16 a; float f = 1; double d = 1; cast(void)__simd_sto(XMM.STOUPS, a, a); cast(void)__simd_sto(XMM.STOUPS, f, a); cast(void)__simd_sto(XMM.STOUPS, d, a); ``` void **prefetch**(bool writeFetch, ubyte locality)(const(void)\* address); Emit prefetch instruction. Parameters: | | | | --- | --- | | const(void)\* `address` | address to be prefetched | | writeFetch | true for write fetch, false for read fetch | | locality | 0..3 (0 meaning least local, 3 meaning most local) | Note The Intel mappings are: | **writeFetch** | **locality** | **Instruction** | | --- | --- | --- | | false | 0 | prefetchnta | | false | 1 | prefetch2 | | false | 2 | prefetch1 | | false | 3 | prefetch0 | | true | 0 | prefetchw | | true | 1 | prefetchw | | true | 2 | prefetchw | | true | 3 | prefetchw | V **loadUnaligned**(V)(const V\* p) Constraints: if (is(V == void16) || is(V == byte16) || is(V == ubyte16) || is(V == short8) || is(V == ushort8) || is(V == int4) || is(V == uint4) || is(V == long2) || is(V == ulong2) || is(V == double2) || is(V == float4)); Load unaligned vector from address. This is a compiler intrinsic. Parameters: | | | | --- | --- | | V\* `p` | pointer to vector | Returns: vector V **storeUnaligned**(V)(V\* p, V value) Constraints: if (is(V == void16) || is(V == byte16) || is(V == ubyte16) || is(V == short8) || is(V == ushort8) || is(V == int4) || is(V == uint4) || is(V == long2) || is(V == ulong2) || is(V == double2) || is(V == float4)); Store vector to unaligned address. This is a compiler intrinsic. Parameters: | | | | --- | --- | | V\* `p` | pointer to vector | | V `value` | value to store | Returns: value d rt.cast_ rt.cast\_ ========= Implementation of array assignment support routines. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Walter Bright, Sean Kelly pure nothrow @nogc Object **\_d\_toObject**(return void\* p); Given a pointer: If it is an Object, return that Object. If it is an interface, return the Object implementing the interface. If it is null, return null. Else, undefined crash pure nothrow @nogc void\* **\_d\_interface\_cast**(void\* p, ClassInfo c); Attempts to cast Object o to class c. Returns o if successful, null if not. d std.experimental.typecons std.experimental.typecons ========================= This module implements experimental additions/modifications to [`std.typecons`](std_typecons). Use this module to test out new functionality for [`std.typecons.wrap`](std_typecons#wrap) which allows for a struct to be wrapped against an interface; the implementation in [`std.typecons`](std_typecons) only allows for classes to use the wrap functionality. Source [std/experimental/typecons.d](https://github.com/dlang/phobos/blob/master/std/experimental/typecons.d) License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: [Andrei Alexandrescu](http://erdani.org), [Bartosz Milewski](http://bartoszmilewski.wordpress.com), Don Clugston, Shin Fujishiro, Kenji Hara template **wrap**(Targets...) if (Targets.length >= 1 && allSatisfy!(isInterface, Targets)) auto **wrap**(Source)(inout Source src) Constraints: if (implementsInterface!(Source, Targets)); Wrap src in an anonymous class implementing Targets. wrap creates an internal wrapper class which implements the interfaces in `Targets` using the methods of `src`, then returns a GC-allocated instance of it. Source can be either a `class` or a `struct`, but it must *structurally conform* with all the Targets interfaces; i.e. it must provide concrete methods with compatible signatures of those in Targets. If Source is a `struct` then wrapping/unwrapping will create a copy; it is not possible to affect the original `struct` through the wrapper. The returned object additionally supports [`unwrap`](#unwrap). Note If Targets has only one entry and Source is a class which explicitly implements it, wrap simply returns src upcasted to `Targets[0]`. Bugs: wrap does not support interfaces which take their own type as either a parameter type or return type in any of its methods. See Also: [`unwrap`](#unwrap) for examples inout(Target) **unwrap**(Target, Source)(inout Source src); Extract object previously wrapped by [`wrap`](#wrap). Parameters: | | | | --- | --- | | Target | type of wrapped object | | Source `src` | wrapper object returned by [`wrap`](#wrap) | Returns: the wrapped object, or null if src is not a wrapper created by [`wrap`](#wrap) and Target is a class Throws: [`std.conv.ConvException`](std_conv#ConvException) when attempting to extract a struct which is not the wrapped type See Also: [`wrap`](#wrap) Examples: ``` interface Quack { int quack(); @property int height(); } interface Flyer { @property int height(); } class Duck : Quack { int quack() { return 1; } @property int height() { return 10; } } class Human { int quack() { return 2; } @property int height() { return 20; } } struct HumanStructure { int quack() { return 3; } @property int height() { return 30; } } Duck d1 = new Duck(); Human h1 = new Human(); HumanStructure hs1; interface Refreshable { int refresh(); } // does not have structural conformance static assert(!__traits(compiles, d1.wrap!Refreshable)); static assert(!__traits(compiles, h1.wrap!Refreshable)); static assert(!__traits(compiles, hs1.wrap!Refreshable)); // strict upcast Quack qd = d1.wrap!Quack; assert(qd is d1); assert(qd.quack() == 1); // calls Duck.quack // strict downcast Duck d2 = qd.unwrap!Duck; assert(d2 is d1); // structural upcast Quack qh = h1.wrap!Quack; Quack qhs = hs1.wrap!Quack; assert(qh.quack() == 2); // calls Human.quack assert(qhs.quack() == 3); // calls HumanStructure.quack // structural downcast Human h2 = qh.unwrap!Human; HumanStructure hs2 = qhs.unwrap!HumanStructure; assert(h2 is h1); assert(hs2 is hs1); // structural upcast (two steps) Quack qx = h1.wrap!Quack; // Human -> Quack Quack qxs = hs1.wrap!Quack; // HumanStructure -> Quack Flyer fx = qx.wrap!Flyer; // Quack -> Flyer Flyer fxs = qxs.wrap!Flyer; // Quack -> Flyer assert(fx.height == 20); // calls Human.height assert(fxs.height == 30); // calls HumanStructure.height // strucural downcast (two steps) Quack qy = fx.unwrap!Quack; // Flyer -> Quack Quack qys = fxs.unwrap!Quack; // Flyer -> Quack Human hy = qy.unwrap!Human; // Quack -> Human HumanStructure hys = qys.unwrap!HumanStructure; // Quack -> HumanStructure assert(hy is h1); assert(hys is hs1); // strucural downcast (one step) Human hz = fx.unwrap!Human; // Flyer -> Human HumanStructure hzs = fxs.unwrap!HumanStructure; // Flyer -> HumanStructure assert(hz is h1); assert(hzs is hs1); ``` Examples: ``` import std.traits : functionAttributes, FunctionAttribute; interface A { int run(); } interface B { int stop(); @property int status(); } class X { int run() { return 1; } int stop() { return 2; } @property int status() { return 3; } } auto x = new X(); auto ab = x.wrap!(A, B); A a = ab; B b = ab; writeln(a.run()); // 1 writeln(b.stop()); // 2 writeln(b.status); // 3 static assert(functionAttributes!(typeof(ab).status) & FunctionAttribute.property); ``` template **Final**(T) Final!T **makeFinal**(T)(T t); Type constructor for final (aka head-const) variables. Final variables cannot be directly mutated or rebound, but references reached through the variable are typed with their original mutability. It is equivalent to `final` variables in D1 and Java, as well as `readonly` variables in C#. When `T` is a `const` or `immutable` type, `Final` aliases to `T`. Examples: `Final` can be used to create class references which cannot be rebound: ``` static class A { int i; this(int i) pure nothrow @nogc @safe { this.i = i; } } auto a = makeFinal(new A(42)); writeln(a.i); // 42 //a = new A(24); // Reassignment is illegal, a.i = 24; // But fields are still mutable. writeln(a.i); // 24 ``` Examples: `Final` can also be used to create read-only data fields without using transitive immutability: ``` static class A { int i; this(int i) pure nothrow @nogc @safe { this.i = i; } } static class B { Final!A a; this(A a) pure nothrow @nogc @safe { this.a = a; // Construction, thus allowed. } } auto b = new B(new A(42)); writeln(b.a.i); // 42 // b.a = new A(24); // Reassignment is illegal, b.a.i = 24; // but `a` is still mutable. writeln(b.a.i); // 24 ``` d core.stdc.stdlib core.stdc.stdlib ================ D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<stdlib.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdlib.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly Standards: ISO/IEC 9899:1999 (E) Source [src/core/stdc/stdlib.d](https://github.com/dlang/druntime/blob/master/src/src/core/stdc/stdlib.d) alias **\_compare\_fp\_t** = extern (C) int function(const(void\*), const(void\*)) @system; nothrow @nogc @system inout(void)\* **bsearch**(const void\* key, inout(void)\* base, size\_t nmemb, size\_t size, \_compare\_fp\_t compar); nothrow @nogc @system void **qsort**(void\* base, size\_t nmemb, size\_t size, \_compare\_fp\_t compar); struct **div\_t**; struct **ldiv\_t**; struct **lldiv\_t**; enum int **EXIT\_SUCCESS**; enum int **EXIT\_FAILURE**; enum int **MB\_CUR\_MAX**; enum int **RAND\_MAX**; nothrow @nogc @system double **atof**(scope const char\* nptr); nothrow @nogc @system int **atoi**(scope const char\* nptr); nothrow @nogc @system c\_long **atol**(scope const char\* nptr); nothrow @nogc @system long **atoll**(scope const char\* nptr); nothrow @nogc @system double **strtod**(scope inout(char)\* nptr, scope inout(char)\*\* endptr); nothrow @nogc @system float **strtof**(scope inout(char)\* nptr, scope inout(char)\*\* endptr); nothrow @nogc @system c\_long **strtol**(scope inout(char)\* nptr, scope inout(char)\*\* endptr, int base); nothrow @nogc @system long **strtoll**(scope inout(char)\* nptr, scope inout(char)\*\* endptr, int base); nothrow @nogc @system c\_ulong **strtoul**(scope inout(char)\* nptr, scope inout(char)\*\* endptr, int base); nothrow @nogc @system ulong **strtoull**(scope inout(char)\* nptr, scope inout(char)\*\* endptr, int base); nothrow @nogc @system real **strtold**(scope inout(char)\* nptr, scope inout(char)\*\* endptr); Added to Bionic since Lollipop. nothrow @nogc @trusted int **rand**(); These two were added to Bionic in Lollipop. nothrow @nogc @trusted void **srand**(uint seed); nothrow @nogc @system void\* **malloc**(size\_t size); nothrow @nogc @system void\* **calloc**(size\_t nmemb, size\_t size); nothrow @nogc @system void\* **realloc**(void\* ptr, size\_t size); nothrow @nogc @system void **free**(void\* ptr); nothrow @nogc @safe void **abort**(); nothrow @nogc @system void **exit**(int status); nothrow @nogc @system int **atexit**(void function() func); nothrow @nogc @system void **\_Exit**(int status); nothrow @nogc @system char\* **getenv**(scope const char\* name); nothrow @nogc @**system** int **system**(scope const char\* string); pure nothrow @nogc @trusted int **abs**(int j); pure nothrow @nogc @trusted c\_long **labs**(c\_long j); pure nothrow @nogc @trusted long **llabs**(long j); nothrow @nogc @trusted div\_t **div**(int numer, int denom); nothrow @nogc @trusted ldiv\_t **ldiv**(c\_long numer, c\_long denom); nothrow @nogc @trusted lldiv\_t **lldiv**(long numer, long denom); nothrow @nogc @system int **mblen**(scope const char\* s, size\_t n); nothrow @nogc @system int **mbtowc**(scope wchar\_t\* pwc, scope const char\* s, size\_t n); nothrow @nogc @system int **wctomb**(scope char\* s, wchar\_t wc); nothrow @nogc @system size\_t **mbstowcs**(scope wchar\_t\* pwcs, scope const char\* s, size\_t n); nothrow @nogc @system size\_t **wcstombs**(scope char\* s, scope const wchar\_t\* pwcs, size\_t n); pure nothrow @nogc @system void\* **alloca**(size\_t size);
programming_docs
d std.uuid std.uuid ======== A [UUID](http://en.wikipedia.org/wiki/Universally_unique_identifier), or [Universally unique identifier](http://en.wikipedia.org/wiki/Universally_unique_identifier), is intended to uniquely identify information in a distributed environment without significant central coordination. It can be used to tag objects with very short lifetimes, or to reliably identify very persistent objects across a network. | Category | Functions | | --- | --- | | Parsing UUIDs | [*parseUUID*](#parseUUID) [*UUID*](#UUID) [*UUIDParsingException*](#UUIDParsingException) [*uuidRegex*](#uuidRegex) | | Generating UUIDs | [*sha1UUID*](#sha1UUID) [*randomUUID*](#randomUUID) [*md5UUID*](#md5UUID) | | Using UUIDs | [*UUID.uuidVersion*](#uuidVersion) [*UUID.variant*](#variant) [*UUID.toString*](#toString) [*UUID.data*](#data) [*UUID.swap*](#swap) [*UUID.opEquals*](#opEquals) [*UUID.opCmp*](#opCmp) [*UUID.toHash*](#toHash) | | UUID namespaces | [*dnsNamespace*](#dnsNamespace) [*urlNamespace*](#urlNamespace) [*oidNamespace*](#oidNamespace) [*x500Namespace*](#x500Namespace) | UUIDs have many applications. Some examples follow: Databases may use UUIDs to identify rows or records in order to ensure that they are unique across different databases, or for publication/subscription services. Network messages may be identified with a UUID to ensure that different parts of a message are put back together again. Distributed computing may use UUIDs to identify a remote procedure call. Transactions and classes involved in serialization may be identified by UUIDs. Microsoft's component object model (COM) uses UUIDs to distinguish different software component interfaces. UUIDs are inserted into documents from Microsoft Office programs. UUIDs identify audio or video streams in the Advanced Systems Format (ASF). UUIDs are also a basis for OIDs (object identifiers), and URNs (uniform resource name). An attractive feature of UUIDs when compared to alternatives is their relative small size, of 128 bits, or 16 bytes. Another is that the creation of UUIDs does not require a centralized authority. When UUIDs are generated by one of the defined mechanisms, they are either guaranteed to be unique, different from all other generated UUIDs (that is, it has never been generated before and it will never be generated again), or it is extremely likely to be unique (depending on the mechanism). For efficiency, UUID is implemented as a struct. UUIDs are therefore empty if not explicitly initialized. An UUID is empty if [`UUID.empty`](#empty) is true. Empty UUIDs are equal to `UUID.init`, which is a UUID with all 16 bytes set to 0. Use UUID's constructors or the UUID generator functions to get an initialized UUID. This is a port of [boost.uuid](http://www.boost.org/doc/libs/1_42_0/libs/uuid/uuid.html) from the Boost project with some minor additions and API changes for a more D-like API. Standards: [RFC 4122](http://www.ietf.org/rfc/rfc4122.txt) See Also: <http://en.wikipedia.org/wiki/Universally_unique_identifier> License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Johannes Pfau Source [std/uuid.d](https://github.com/dlang/phobos/blob/master/std/uuid.d) Examples: ``` import std.uuid; UUID[] ids; ids ~= randomUUID(); ids ~= md5UUID("test.name.123"); ids ~= sha1UUID("test.name.123"); foreach (entry; ids) { writeln(entry.variant); // UUID.Variant.rfc4122 } writeln(ids[0].uuidVersion); // UUID.Version.randomNumberBased writeln(ids[1].toString()); // "22390768-cced-325f-8f0f-cfeaa19d0ccd" assert(ids[1].data == [34, 57, 7, 104, 204, 237, 50, 95, 143, 15, 207, 234, 161, 157, 12, 205]); UUID id; assert(id.empty); ``` struct **UUID**; Examples: ``` UUID id; assert(id.empty); id = randomUUID; assert(!id.empty); id = UUID(cast(ubyte[16]) [138, 179, 6, 14, 44, 186, 79, 35, 183, 76, 181, 45, 179, 189, 251, 70]); writeln(id.toString()); // "8ab3060e-2cba-4f23-b74c-b52db3bdfb46" ``` enum **Variant**: int; RFC 4122 defines different internal data layouts for UUIDs. These are the UUID formats supported by this module. It's possible to read, compare and use all these Variants, but UUIDs generated by this module will always be in rfc4122 format. Note Do not confuse this with [`std.variant.Variant`](std_variant#Variant). **ncs** NCS backward compatibility **rfc4122** Defined in RFC 4122 document **microsoft** Microsoft Corporation backward compatibility **future** Reserved for future use enum **Version**: int; RFC 4122 defines different UUID versions. The version shows how a UUID was generated, e.g. a version 4 UUID was generated from a random number, a version 3 UUID from an MD5 hash of a name. Note All of these UUID versions can be read and processed by `std.uuid`, but only version 3, 4 and 5 UUIDs can be generated. **unknown** Unknown version **timeBased** Version 1 **dceSecurity** Version 2 **nameBasedMD5** Version 3 (Name based + MD5) **randomNumberBased** Version 4 (Random) **nameBasedSHA1** Version 5 (Name based + SHA-1) ubyte[16] **data**; It is sometimes useful to get or set the 16 bytes of a UUID directly. Note UUID uses a 16-ubyte representation for the UUID data. RFC 4122 defines a UUID as a special structure in big-endian format. These 16-ubytes always equal the big-endian structure defined in RFC 4122. Example ``` auto rawData = uuid.data; //get data rawData[0] = 1; //modify uuid.data = rawData; //set data uuid.data[1] = 2; //modify directly ``` pure nothrow @nogc @safe this(ref scope const ubyte[16] uuidData); pure nothrow @nogc @safe this(const ubyte[16] uuidData); Construct a UUID struct from the 16 byte representation of a UUID. Examples: ``` enum ubyte[16] data = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; auto uuid = UUID(data); enum ctfe = UUID(data); writeln(uuid.data); // data writeln(ctfe.data); // data ``` pure @safe this(T...)(T uuidData) Constraints: if (uuidData.length == 16 && allSatisfy!(isIntegral, T)); Construct a UUID struct from the 16 byte representation of a UUID. Variadic constructor to allow a simpler syntax, see examples. You need to pass exactly 16 ubytes. Examples: ``` auto tmp = UUID(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15); assert(tmp.data == cast(ubyte[16])[0,1,2,3,4,5,6,7,8,9,10,11, 12,13,14,15]); ``` this(T)(in T[] uuid) Constraints: if (isSomeChar!(Unqual!T)); Parse a UUID from its canonical string form. An UUID in its canonical form looks like this: 8ab3060e-2cba-4f23-b74c-b52db3bdfb46 Throws: [`UUIDParsingException`](#UUIDParsingException) if the input is invalid CTFE This function is supported in CTFE code. Note that error messages caused by a malformed UUID parsed at compile time can be cryptic, but errors are detected and reported at compile time. Note This is a strict parser. It only accepts the pattern above. It doesn't support any leading or trailing characters. It only accepts characters used for hex numbers and the string must have hyphens exactly like above. For a less strict parser, see [`parseUUID`](#parseUUID) Examples: ``` auto id = UUID("8AB3060E-2cba-4f23-b74c-b52db3bdfb46"); assert(id.data == [138, 179, 6, 14, 44, 186, 79, 35, 183, 76, 181, 45, 179, 189, 251, 70]); writeln(id.toString()); // "8ab3060e-2cba-4f23-b74c-b52db3bdfb46" //Can also be used in CTFE, for example as UUID literals: enum ctfeID = UUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46"); //here parsing is done at compile time, no runtime overhead! ``` const pure nothrow @nogc @property @trusted bool **empty**(); Returns true if and only if the UUID is equal to {00000000-0000-0000-0000-000000000000} Examples: ``` UUID id; assert(id.empty); id = UUID("00000000-0000-0000-0000-000000000001"); assert(!id.empty); ``` const pure nothrow @nogc @property @safe Variant **variant**(); RFC 4122 defines different internal data layouts for UUIDs. Returns the format used by this UUID. Note Do not confuse this with [`std.variant.Variant`](std_variant#Variant). The type of this property is [`std.uuid.UUID.Variant`](#Variant). See Also: [`UUID.Variant`](#Variant) Examples: ``` assert(UUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46").variant == UUID.Variant.rfc4122); ``` const pure nothrow @nogc @property @safe Version **uuidVersion**(); RFC 4122 defines different UUID versions. The version shows how a UUID was generated, e.g. a version 4 UUID was generated from a random number, a version 3 UUID from an MD5 hash of a name. Returns the version used by this UUID. See Also: [`UUID.Version`](#Version) Examples: ``` assert(UUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46").uuidVersion == UUID.Version.randomNumberBased); ``` pure nothrow @nogc @safe void **swap**(ref UUID rhs); Swap the data of this UUID with the data of rhs. Examples: ``` immutable ubyte[16] data = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; UUID u1; UUID u2 = UUID(data); u1.swap(u2); writeln(u1); // UUID(data) writeln(u2); // UUID.init ``` const pure nothrow @nogc @safe bool **opEquals**(const UUID s); const pure nothrow @nogc @safe bool **opEquals**(ref scope const UUID s); const pure nothrow @nogc @safe int **opCmp**(const UUID s); const pure nothrow @nogc @safe int **opCmp**(ref scope const UUID s); pure nothrow @nogc @safe UUID **opAssign**(const UUID s); pure nothrow @nogc @safe UUID **opAssign**(ref scope const UUID s); const pure nothrow @nogc @safe size\_t **toHash**(); All of the standard numeric operators are defined for the UUID struct. Examples: ``` //compare UUIDs writeln(UUID("00000000-0000-0000-0000-000000000000")); // UUID.init //UUIDs in associative arrays: int[UUID] test = [UUID("8a94f585-d180-44f7-8929-6fca0189c7d0") : 1, UUID("7c351fd4-b860-4ee3-bbdc-7f79f3dfb00a") : 2, UUID("9ac0a4e5-10ee-493a-86fc-d29eeb82ecc1") : 3]; writeln(test[UUID("9ac0a4e5-10ee-493a-86fc-d29eeb82ecc1")]); // 3 //UUIDS can be sorted: import std.algorithm; UUID[] ids = [UUID("8a94f585-d180-44f7-8929-6fca0189c7d0"), UUID("7c351fd4-b860-4ee3-bbdc-7f79f3dfb00a"), UUID("9ac0a4e5-10ee-493a-86fc-d29eeb82ecc1")]; sort(ids); ``` const void **toString**(Writer)(scope Writer sink); Write the UUID into `sink` as an ASCII string in the canonical form, which is 36 characters in the form "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" Parameters: | | | | --- | --- | | Writer `sink` | OutputRange or writeable array at least 36 entries long | const pure nothrow @trusted string **toString**(); Return the UUID as a string in the canonical form. Examples: ``` immutable str = "8ab3060e-2cba-4f23-b74c-b52db3bdfb46"; auto id = UUID(str); writeln(id.toString()); // str ``` pure nothrow @nogc @safe UUID **md5UUID**(const(char[]) name, const UUID namespace = UUID.init); pure nothrow @nogc @safe UUID **md5UUID**(const(ubyte[]) data, const UUID namespace = UUID.init); This function generates a name based (Version 3) UUID from a namespace UUID and a name. If no namespace UUID was passed, the empty UUID `UUID.init` is used. Note The default namespaces ([`dnsNamespace`](#dnsNamespace), ...) defined by this module should be used when appropriate. RFC 4122 recommends to use Version 5 UUIDs (SHA-1) instead of Version 3 UUIDs (MD5) for new applications. CTFE CTFE is not supported. Note RFC 4122 isn't very clear on how UUIDs should be generated from names. It is possible that different implementations return different UUIDs for the same input, so be warned. The implementation for UTF-8 strings and byte arrays used by `std.uuid` is compatible with Boost's implementation. `std.uuid` guarantees that the same input to this function will generate the same output at any time, on any system (this especially means endianness doesn't matter). Note This function does not provide overloads for wstring and dstring, as there's no clear answer on how that should be implemented. It could be argued, that string, wstring and dstring input should have the same output, but that wouldn't be compatible with Boost, which generates different output for strings and wstrings. It's always possible to pass wstrings and dstrings by using the ubyte[] function overload (but be aware of endianness issues!). Examples: ``` //Use default UUID.init namespace auto simpleID = md5UUID("test.uuid.any.string"); //use a name-based id as namespace auto namespace = md5UUID("my.app"); auto id = md5UUID("some-description", namespace); ``` pure nothrow @nogc @safe UUID **sha1UUID**(scope const(char)[] name, scope const UUID namespace = UUID.init); pure nothrow @nogc @safe UUID **sha1UUID**(scope const(ubyte)[] data, scope const UUID namespace = UUID.init); This function generates a name based (Version 5) UUID from a namespace UUID and a name. If no namespace UUID was passed, the empty UUID `UUID.init` is used. Note The default namespaces ([`dnsNamespace`](#dnsNamespace), ...) defined by this module should be used when appropriate. CTFE CTFE is not supported. Note RFC 4122 isn't very clear on how UUIDs should be generated from names. It is possible that different implementations return different UUIDs for the same input, so be warned. The implementation for UTF-8 strings and byte arrays used by `std.uuid` is compatible with Boost's implementation. `std.uuid` guarantees that the same input to this function will generate the same output at any time, on any system (this especially means endianness doesn't matter). Note This function does not provide overloads for wstring and dstring, as there's no clear answer on how that should be implemented. It could be argued, that string, wstring and dstring input should have the same output, but that wouldn't be compatible with Boost, which generates different output for strings and wstrings. It's always possible to pass wstrings and dstrings by using the ubyte[] function overload (but be aware of endianness issues!). Examples: ``` //Use default UUID.init namespace auto simpleID = sha1UUID("test.uuid.any.string"); //use a name-based id as namespace auto namespace = sha1UUID("my.app"); auto id = sha1UUID("some-description", namespace); ``` @safe UUID **randomUUID**(); UUID **randomUUID**(RNG)(ref RNG randomGen) Constraints: if (isInputRange!RNG && isIntegral!(ElementType!RNG)); This function generates a random number based UUID from a random number generator. This function is not supported at compile time. Parameters: | | | | --- | --- | | RNG `randomGen` | uniform RNG | See Also: [`std.random.isUniformRNG`](std_random#isUniformRNG) Examples: ``` import std.random : Xorshift192, unpredictableSeed; //simple call auto uuid = randomUUID(); //provide a custom RNG. Must be seeded manually. Xorshift192 gen; gen.seed(unpredictableSeed); auto uuid3 = randomUUID(gen); ``` UUID **parseUUID**(T)(T uuidString) Constraints: if (isSomeString!T); UUID **parseUUID**(Range)(ref Range uuidRange) Constraints: if (isInputRange!Range && isSomeChar!(ElementType!Range)); This is a less strict parser compared to the parser used in the UUID constructor. It enforces the following rules: * hex numbers are always two hexdigits([0-9a-fA-F]) * there must be exactly 16 such pairs in the input, not less, not more * there can be exactly one dash between two hex-pairs, but not more * there can be multiple characters enclosing the 16 hex pairs, as long as these characters do not contain [0-9a-fA-F] Note Like most parsers, it consumes its argument. This means: ``` string s = "8AB3060E-2CBA-4F23-b74c-B52Db3BDFB46"; parseUUID(s); assert(s == ""); ``` Throws: [`UUIDParsingException`](#UUIDParsingException) if the input is invalid CTFE This function is supported in CTFE code. Note that error messages caused by a malformed UUID parsed at compile time can be cryptic, but errors are detected and reported at compile time. Examples: ``` auto id = parseUUID("8AB3060E-2CBA-4F23-b74c-B52Db3BDFB46"); //no dashes id = parseUUID("8ab3060e2cba4f23b74cb52db3bdfb46"); //dashes at different positions id = parseUUID("8a-b3-06-0e2cba4f23b74c-b52db3bdfb-46"); //leading / trailing characters id = parseUUID("{8ab3060e-2cba-4f23-b74c-b52db3bdfb46}"); //unicode id = parseUUID("ü8ab3060e2cba4f23b74cb52db3bdfb46ü"); //multiple trailing/leading characters id = parseUUID("///8ab3060e2cba4f23b74cb52db3bdfb46||"); //Can also be used in CTFE, for example as UUID literals: enum ctfeID = parseUUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46"); //here parsing is done at compile time, no runtime overhead! ``` enum UUID **dnsNamespace**; Default namespace from RFC 4122 Name string is a fully-qualified domain name enum UUID **urlNamespace**; Default namespace from RFC 4122 Name string is a URL enum UUID **oidNamespace**; Default namespace from RFC 4122 Name string is an ISO OID enum UUID **x500Namespace**; Default namespace from RFC 4122 Name string is an X.500 DN (in DER or a text output format) enum string **uuidRegex**; Regex string to extract UUIDs from text. Examples: ``` import std.algorithm; import std.regex; string test = "Lorem ipsum dolor sit amet, consetetur "~ "6ba7b814-9dad-11d1-80b4-00c04fd430c8 sadipscing \n"~ "elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore \r\n"~ "magna aliquyam erat, sed diam voluptua. "~ "8ab3060e-2cba-4f23-b74c-b52db3bdfb46 At vero eos et accusam et "~ "justo duo dolores et ea rebum."; auto r = regex(uuidRegex, "g"); UUID[] found; foreach (c; match(test, r)) { found ~= UUID(c.hit); } assert(found == [ UUID("6ba7b814-9dad-11d1-80b4-00c04fd430c8"), UUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46"), ]); ``` class **UUIDParsingException**: object.Exception; This exception is thrown if an error occurs when parsing a UUID from a string. Examples: ``` import std.exception : collectException; const inputUUID = "this-is-an-invalid-uuid"; auto ex = collectException!UUIDParsingException(UUID(inputUUID)); assert(ex !is null); // check that exception was thrown writeln(ex.input); // inputUUID writeln(ex.position); // 0 writeln(ex.reason); // UUIDParsingException.Reason.tooLittle ``` enum **Reason**: int; Reason **reason**; The reason why parsing the UUID string failed (if known) **unknown** **tooLittle** The passed in input was correct, but more input was expected. **tooMuch** The input data is too long (There's no guarantee the first part of the data is valid) **invalidChar** Encountered an invalid character string **input**; The original input string which should have been parsed. size\_t **position**; The position in the input string where the error occurred. d core.runtime core.runtime ============ The runtime module exposes information specific to the D runtime code. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) Authors: Sean Kelly Source [runtime.d](https://github.com/dlang/druntime/blob/master/src/core/runtime.d) Documentation [https://dlang.org/phobos/core\_runtime.html](core_runtime) void\* **rt\_loadLibrary**(const char\* name); C interface for Runtime.loadLibrary int **rt\_unloadLibrary**(void\* ptr); C interface for Runtime.unloadLibrary, returns 1/0 instead of bool int **rt\_init**(); C interface for Runtime.initialize, returns 1/0 instead of bool int **rt\_term**(); C interface for Runtime.terminate, returns 1/0 instead of bool struct **UnitTestResult**; This type is returned by the module unit test handler to indicate testing results. size\_t **executed**; Number of modules which were tested size\_t **passed**; Number of modules passed the unittests bool **runMain**; Should the main function be run or not? This is ignored if any tests failed. bool **summarize**; Should we print a summary of the results? const bool **opCast**(T : bool)(); Simple check for whether execution should continue after unit tests have been run. Works with legacy code that expected a bool return. Returns: true if execution should continue after testing is complete, false if not. enum UnitTestResult **pass**; Simple return code that says unit tests pass, and main should be run enum UnitTestResult **fail**; Simple return code that says unit tests failed. alias **ModuleUnitTester** = bool function(); Legacy module unit test handler alias **ExtendedModuleUnitTester** = UnitTestResult function(); Module unit test handler struct **CArgs**; Stores the unprocessed arguments supplied when the process was started. int **argc**; The argument count. char\*\* **argv**; The arguments as a C array of strings. struct **Runtime**; This struct encapsulates all functionality related to the underlying runtime module for the calling context. static bool **initialize**(); Initializes the runtime. This call is to be used in instances where the standard program initialization process is not executed. This is most often in shared libraries or in libraries linked to a C program. If the runtime was already successfully initialized this returns true. Each call to initialize must be paired by a call to [`terminate`](#terminate). Returns: true if initialization succeeded or false if initialization failed. static bool **terminate**(); Terminates the runtime. This call is to be used in instances where the standard program termination process will not be not executed. This is most often in shared libraries or in libraries linked to a C program. If the runtime was not successfully initialized the function returns false. Returns: true if termination succeeded or false if termination failed. static @property string[] **args**(); Returns the arguments supplied when the process was started. Returns: The arguments supplied when this process was started. static @nogc @property CArgs **cArgs**(); Returns the unprocessed C arguments supplied when the process was started. Use this when you need to supply argc and argv to C libraries. Returns: A [`CArgs`](#CArgs) struct with the arguments supplied when this process was started. Example ``` import core.runtime; // A C library function requiring char** arguments extern(C) void initLibFoo(int argc, char** argv); void main() { auto args = Runtime.cArgs; initLibFoo(args.argc, args.argv); } ``` void\* **loadLibrary**()(scope const char[] name); Locates a dynamic library with the supplied library name and dynamically loads it into the caller's address space. If the library contains a D runtime it will be integrated with the current runtime. Parameters: | | | | --- | --- | | char[] `name` | The name of the dynamic library to load. | Returns: A reference to the library or null on error. bool **unloadLibrary**()(void\* p); Unloads the dynamic library referenced by p. If this library contains a D runtime then any necessary finalization or cleanup of that runtime will be performed. Parameters: | | | | --- | --- | | void\* `p` | A reference to the library to unload. | static @property void **traceHandler**(TraceHandler h); Overrides the default trace mechanism with a user-supplied version. A trace represents the context from which an exception was thrown, and the trace handler will be called when this occurs. The pointer supplied to this routine indicates the base address from which tracing should occur. If the supplied pointer is null then the trace routine should determine an appropriate calling context from which to begin the trace. Parameters: | | | | --- | --- | | TraceHandler `h` | The new trace handler. Set to null to use the default handler. | static @property TraceHandler **traceHandler**(); Gets the current trace handler. Returns: The current trace handler or null if none has been set. static @property void **collectHandler**(CollectHandler h); Overrides the default collect hander with a user-supplied version. This routine will be called for each resource object that is finalized in a non-deterministic manner--typically during a garbage collection cycle. If the supplied routine returns true then the object's dtor will called as normal, but if the routine returns false than the dtor will not be called. The default behavior is for all object dtors to be called. Parameters: | | | | --- | --- | | CollectHandler `h` | The new collect handler. Set to null to use the default handler. | static @property CollectHandler **collectHandler**(); Gets the current collect handler. Returns: The current collect handler or null if none has been set. static @property void **extendedModuleUnitTester**(ExtendedModuleUnitTester h); static @property void **moduleUnitTester**(ModuleUnitTester h); Overrides the default module unit tester with a user-supplied version. This routine will be called once on program initialization. The return value of this routine indicates to the runtime whether the tests ran without error. There are two options for handlers. The `bool` version is deprecated but will be kept for legacy support. Returning `true` from the handler is equivalent to returning `UnitTestResult.pass` from the extended version. Returning `false` from the handler is equivalent to returning `UnitTestResult.fail` from the extended version. See the documentation for `UnitTestResult` to see how you should set up the return structure. See the documentation for `runModuleUnitTests` for how the default algorithm works, or read the example below. Parameters: | | | | --- | --- | | ExtendedModuleUnitTester `h` | The new unit tester. Set both to null to use the default unit tester. | Example ``` shared static this() { import core.runtime; Runtime.extendedModuleUnitTester = &customModuleUnitTester; } UnitTestResult customModuleUnitTester() { import std.stdio; writeln("Using customModuleUnitTester"); // Do the same thing as the default moduleUnitTester: UnitTestResult result; foreach (m; ModuleInfo) { if (m) { auto fp = m.unitTest; if (fp) { ++result.executed; try { fp(); ++result.passed; } catch (Throwable e) { writeln(e); } } } } if (result.executed != result.passed) { result.runMain = false; // don't run main result.summarize = true; // print failure } else { result.runMain = true; // all UT passed result.summarize = false; // be quiet about it. } return result; } ``` static @property ModuleUnitTester **moduleUnitTester**(); Gets the current legacy module unit tester. This property should not be used, but is supported for legacy purposes. Note that if the extended unit test handler is set, this handler will be ignored. Returns: The current legacy module unit tester handler or null if none has been set. static @property ExtendedModuleUnitTester **extendedModuleUnitTester**(); Gets the current module unit tester. This handler overrides any legacy module unit tester set by the moduleUnitTester property. Returns: The current module unit tester handler or null if none has been set. void **dmd\_coverSourcePath**(string path); Set source file path for coverage reports. Parameters: | | | | --- | --- | | string `path` | The new path name. | Note This is a dmd specific setting. void **dmd\_coverDestPath**(string path); Set output path for coverage reports. Parameters: | | | | --- | --- | | string `path` | The new path name. | Note This is a dmd specific setting. void **dmd\_coverSetMerge**(bool flag); Enable merging of coverage reports with existing data. Parameters: | | | | --- | --- | | bool `flag` | enable/disable coverage merge mode | Note This is a dmd specific setting. void **trace\_setlogfilename**(string name); Set the output file name for profile reports (-profile switch). An empty name will set the output to stdout. Parameters: | | | | --- | --- | | string `name` | file name | Note This is a dmd specific setting. void **trace\_setdeffilename**(string name); Set the output file name for the optimized profile linker DEF file (-profile switch). An empty name will set the output to stdout. Parameters: | | | | --- | --- | | string `name` | file name | Note This is a dmd specific setting. void **profilegc\_setlogfilename**(string name); Set the output file name for memory profile reports (-profile=gc switch). An empty name will set the output to stdout. Parameters: | | | | --- | --- | | string `name` | file name | Note This is a dmd specific setting. UnitTestResult **runModuleUnitTests**(); This routine is called by the runtime to run module unit tests on startup. The user-supplied unit tester will be called if one has been set, otherwise all unit tests will be run in sequence. If the extended unittest handler is registered, this function returns the result from that handler directly. If a legacy boolean returning custom handler is used, `false` maps to `UnitTestResult.fail`, and `true` maps to `UnitTestResult.pass`. This was the original behavior of the unit testing system. If no unittest custom handlers are registered, the following algorithm is executed (the behavior can be affected by the `--DRT-testmode` switch below): 1. Execute any unittests present. For each that fails, print the stack trace and continue. 2. If no unittests were present, set summarize to false, and runMain to true. 3. Otherwise, set summarize to true, and runMain to false. See the documentation for `UnitTestResult` for details on how the runtime treats the return value from this function. If the switch `--DRT-testmode` is passed to the executable, it can have one of 3 values: 1. "run-main": even if unit tests are run (and all pass), runMain is set to true. 2. "test-or-main": any unit tests present will cause the program to summarize the results and exit regardless of the result. This is the default. 3. "test-only", runMain is set to false, even with no tests present. This command-line parameter does not affect custom unit test handlers. Returns: A `UnitTestResult` struct indicating the result of running unit tests. Throwable.TraceInfo **defaultTraceHandler**(void\* ptr = null); Get the default `Throwable.TraceInfo` implementation for the platform This functions returns a trace handler, allowing to inspect the current stack trace. Parameters: | | | | --- | --- | | void\* `ptr` | (Windows only) The context to get the stack trace from. When `null` (the default), start from the current frame. | Returns: A `Throwable.TraceInfo` implementation suitable to iterate over the stack, or `null`. If called from a finalizer (destructor), always returns `null` as trace handlers allocate. Examples: Example of a simple program printing its stack trace ``` import core.runtime; import core.stdc.stdio; void main() { auto trace = defaultTraceHandler(null); foreach (line; trace) { printf("%.*s\n", cast(int)line.length, line.ptr); } } ```
programming_docs
d std.uni std.uni ======= The `std.uni` module provides an implementation of fundamental Unicode algorithms and data structures. This doesn't include UTF encoding and decoding primitives, see [`std.utf.decode`](std_utf#decode) and [`std.utf.encode`](std_utf#encode) in [`std.utf`](std_utf) for this functionality. | Category | Functions | | --- | --- | | Decode | [`byCodePoint`](#byCodePoint) [`byGrapheme`](#byGrapheme) [`decodeGrapheme`](#decodeGrapheme) [`graphemeStride`](#graphemeStride) | | Comparison | [`icmp`](#icmp) [`sicmp`](#sicmp) | | Classification | [`isAlpha`](#isAlpha) [`isAlphaNum`](#isAlphaNum) [`isCodepointSet`](#isCodepointSet) [`isControl`](#isControl) [`isFormat`](#isFormat) [`isGraphical`](#isGraphical) [`isIntegralPair`](#isIntegralPair) [`isMark`](#isMark) [`isNonCharacter`](#isNonCharacter) [`isNumber`](#isNumber) [`isPrivateUse`](#isPrivateUse) [`isPunctuation`](#isPunctuation) [`isSpace`](#isSpace) [`isSurrogate`](#isSurrogate) [`isSurrogateHi`](#isSurrogateHi) [`isSurrogateLo`](#isSurrogateLo) [`isSymbol`](#isSymbol) [`isWhite`](#isWhite) | | Normalization | [`NFC`](#NFC) [`NFD`](#NFD) [`NFKD`](#NFKD) [`NormalizationForm`](#NormalizationForm) [`normalize`](#normalize) | | Decompose | [`decompose`](#decompose) [`decomposeHangul`](#decomposeHangul) [`UnicodeDecomposition`](#UnicodeDecomposition) | | Compose | [`compose`](#compose) [`composeJamo`](#composeJamo) | | Sets | [`CodepointInterval`](#CodepointInterval) [`CodepointSet`](#CodepointSet) [`InversionList`](#InversionList) [`unicode`](#unicode) | | Trie | [`codepointSetTrie`](#codepointSetTrie) [`CodepointSetTrie`](#CodepointSetTrie) [`codepointTrie`](#codepointTrie) [`CodepointTrie`](#CodepointTrie) [`toTrie`](#toTrie) [`toDelegate`](#toDelegate) | | Casing | [`asCapitalized`](#asCapitalized) [`asLowerCase`](#asLowerCase) [`asUpperCase`](#asUpperCase) [`isLower`](#isLower) [`isUpper`](#isUpper) [`toLower`](#toLower) [`toLowerInPlace`](#toLowerInPlace) [`toUpper`](#toUpper) [`toUpperInPlace`](#toUpperInPlace) | | Utf8Matcher | [`isUtfMatcher`](#isUtfMatcher) [`MatcherConcept`](#MatcherConcept) [`utfMatcher`](#utfMatcher) | | Separators | [`lineSep`](#lineSep) [`nelSep`](#nelSep) [`paraSep`](#paraSep) | | Building blocks | [`allowedIn`](#allowedIn) [`combiningClass`](#combiningClass) [`Grapheme`](#Grapheme) | All primitives listed operate on Unicode characters and sets of characters. For functions which operate on ASCII characters and ignore Unicode [characters](#Character), see [`std.ascii`](std_ascii). For definitions of Unicode [character](#Character), [code point](#Code%20point) and other terms used throughout this module see the [terminology](#Terminology) section below. The focus of this module is the core needs of developing Unicode-aware applications. To that effect it provides the following optimized primitives: * Character classification by category and common properties: [`isAlpha`](#isAlpha), [`isWhite`](#isWhite) and others. * Case-insensitive string comparison ([`sicmp`](#sicmp), [`icmp`](#icmp)). * Converting text to any of the four normalization forms via [`normalize`](#normalize). * Decoding ([`decodeGrapheme`](#decodeGrapheme)) and iteration ([`byGrapheme`](#byGrapheme), [`graphemeStride`](#graphemeStride)) by user-perceived characters, that is by [`Grapheme`](#Grapheme) clusters. * Decomposing and composing of individual character(s) according to canonical or compatibility rules, see [`compose`](#compose) and [`decompose`](#decompose), including the specific version for Hangul syllables [`composeJamo`](#composeJamo) and [`decomposeHangul`](#decomposeHangul). It's recognized that an application may need further enhancements and extensions, such as less commonly known algorithms, or tailoring existing ones for region specific needs. To help users with building any extra functionality beyond the core primitives, the module provides: * [`CodepointSet`](#CodepointSet), a type for easy manipulation of sets of characters. Besides the typical set algebra it provides an unusual feature: a D source code generator for detection of [code points](#Code%20point) in this set. This is a boon for meta-programming parser frameworks, and is used internally to power classification in small sets like [`isWhite`](#isWhite). * A way to construct optimal packed multi-stage tables also known as a special case of [Trie](https://en.wikipedia.org/wiki/Trie). The functions [`codepointTrie`](#codepointTrie), [`codepointSetTrie`](#codepointSetTrie) construct custom tries that map dchar to value. The end result is a fast and predictable Ο(`1`) lookup that powers functions like [`isAlpha`](#isAlpha) and [`combiningClass`](#combiningClass), but for user-defined data sets. * A useful technique for Unicode-aware parsers that perform character classification of encoded [code points](#Code%20point) is to avoid unnecassary decoding at all costs. [`utfMatcher`](#utfMatcher) provides an improvement over the usual workflow of decode-classify-process, combining the decoding and classification steps. By extracting necessary bits directly from encoded [code units](#Code%20unit) matchers achieve significant performance improvements. See [`MatcherConcept`](#MatcherConcept) for the common interface of UTF matchers. * Generally useful building blocks for customized normalization: [`combiningClass`](#combiningClass) for querying combining class and [`allowedIn`](#allowedIn) for testing the Quick\_Check property of a given normalization form. * Access to a large selection of commonly used sets of [code points](#Code%20point). [Supported sets](#Unicode%20properties) include Script, Block and General Category. The exact contents of a set can be observed in the CLDR utility, on the [property index](http://www.unicode.org/cldr/utility/properties.jsp) page of the Unicode website. See [`unicode`](#unicode) for easy and (optionally) compile-time checked set queries. ### Synopsis ``` import std.uni; void main() { // initialize code point sets using script/block or property name // now 'set' contains code points from both scripts. auto set = unicode("Cyrillic") | unicode("Armenian"); // same thing but simpler and checked at compile-time auto ascii = unicode.ASCII; auto currency = unicode.Currency_Symbol; // easy set ops auto a = set & ascii; assert(a.empty); // as it has no intersection with ascii a = set | ascii; auto b = currency - a; // subtract all ASCII, Cyrillic and Armenian // some properties of code point sets assert(b.length > 45); // 46 items in Unicode 6.1, even more in 6.2 // testing presence of a code point in a set // is just fine, it is O(logN) assert(!b['$']); assert(!b['\u058F']); // Armenian dram sign assert(b['¥']); // building fast lookup tables, these guarantee O(1) complexity // 1-level Trie lookup table essentially a huge bit-set ~262Kb auto oneTrie = toTrie!1(b); // 2-level far more compact but typically slightly slower auto twoTrie = toTrie!2(b); // 3-level even smaller, and a bit slower yet auto threeTrie = toTrie!3(b); assert(oneTrie['£']); assert(twoTrie['£']); assert(threeTrie['£']); // build the trie with the most sensible trie level // and bind it as a functor auto cyrillicOrArmenian = toDelegate(set); auto balance = find!(cyrillicOrArmenian)("Hello ընկեր!"); assert(balance == "ընկեր!"); // compatible with bool delegate(dchar) bool delegate(dchar) bindIt = cyrillicOrArmenian; // Normalization string s = "Plain ascii (and not only), is always normalized!"; assert(s is normalize(s));// is the same string string nonS = "A\u0308ffin"; // A ligature auto nS = normalize(nonS); // to NFC, the W3C endorsed standard assert(nS == "Äffin"); assert(nS != nonS); string composed = "Äffin"; assert(normalize!NFD(composed) == "A\u0308ffin"); // to NFKD, compatibility decomposition useful for fuzzy matching/searching assert(normalize!NFKD("2¹⁰") == "210"); } ``` ### Terminology The following is a list of important Unicode notions and definitions. Any conventions used specifically in this module alone are marked as such. The descriptions are based on the formal definition as found in [chapter three of The Unicode Standard Core Specification.](http://www.unicode.org/versions/Unicode6.2.0/ch03.pdf) *Abstract character* A unit of information used for the organization, control, or representation of textual data. Note that: * When representing data, the nature of that data is generally symbolic as opposed to some other kind of data (for example, visual). * An abstract character has no concrete form and should not be confused with a [glyph](#Glyph). * An abstract character does not necessarily correspond to what a user thinks of as a “character” and should not be confused with a [`Grapheme`](#Grapheme). * The abstract characters encoded (see Encoded character) are known as Unicode abstract characters. * Abstract characters not directly encoded by the Unicode Standard can often be represented by the use of combining character sequences. *Canonical decomposition* The decomposition of a character or character sequence that results from recursively applying the canonical mappings found in the Unicode Character Database and these described in Conjoining Jamo Behavior (section 12 of [Unicode Conformance](http://www.unicode.org/uni2book/ch03.pdf)). *Canonical composition* The precise definition of the Canonical composition is the algorithm as specified in [Unicode Conformance](http://www.unicode.org/uni2book/ch03.pdf) section 11. Informally it's the process that does the reverse of the canonical decomposition with the addition of certain rules that e.g. prevent legacy characters from appearing in the composed result. *Canonical equivalent* Two character sequences are said to be canonical equivalents if their full canonical decompositions are identical. *Character* Typically differs by context. For the purpose of this documentation the term *character* implies *encoded character*, that is, a code point having an assigned abstract character (a symbolic meaning). *Code point* Any value in the Unicode codespace; that is, the range of integers from 0 to 10FFFF (hex). Not all code points are assigned to encoded characters. *Code unit* The minimal bit combination that can represent a unit of encoded text for processing or interchange. Depending on the encoding this could be: 8-bit code units in the UTF-8 (`char`), 16-bit code units in the UTF-16 (`wchar`), and 32-bit code units in the UTF-32 (`dchar`). *Note that in UTF-32, a code unit is a code point and is represented by the D `dchar` type.* *Combining character* A character with the General Category of Combining Mark(M). * All characters with non-zero canonical combining class are combining characters, but the reverse is not the case: there are combining characters with a zero combining class. * These characters are not normally used in isolation unless they are being described. They include such characters as accents, diacritics, Hebrew points, Arabic vowel signs, and Indic matras. *Combining class* A numerical value used by the Unicode Canonical Ordering Algorithm to determine which sequences of combining marks are to be considered canonically equivalent and which are not. *Compatibility decomposition* The decomposition of a character or character sequence that results from recursively applying both the compatibility mappings and the canonical mappings found in the Unicode Character Database, and those described in Conjoining Jamo Behavior no characters can be further decomposed. *Compatibility equivalent* Two character sequences are said to be compatibility equivalents if their full compatibility decompositions are identical. *Encoded character* An association (or mapping) between an abstract character and a code point. *Glyph* The actual, concrete image of a glyph representation having been rasterized or otherwise imaged onto some display surface. *Grapheme base* A character with the property Grapheme\_Base, or any standard Korean syllable block. *Grapheme cluster* Defined as the text between grapheme boundaries as specified by Unicode Standard Annex #29, [Unicode text segmentation](http://www.unicode.org/reports/tr29/). Important general properties of a grapheme: * The grapheme cluster represents a horizontally segmentable unit of text, consisting of some grapheme base (which may consist of a Korean syllable) together with any number of nonspacing marks applied to it. * A grapheme cluster typically starts with a grapheme base and then extends across any subsequent sequence of nonspacing marks. A grapheme cluster is most directly relevant to text rendering and processes such as cursor placement and text selection in editing, but may also be relevant to comparison and searching. * For many processes, a grapheme cluster behaves as if it was a single character with the same properties as its grapheme base. Effectively, nonspacing marks apply *graphically* to the base, but do not change its properties. This module defines a number of primitives that work with graphemes: [`Grapheme`](#Grapheme), [`decodeGrapheme`](#decodeGrapheme) and [`graphemeStride`](#graphemeStride). All of them are using *extended grapheme* boundaries as defined in the aforementioned standard annex. *Nonspacing mark* A combining character with the General Category of Nonspacing Mark (Mn) or Enclosing Mark (Me). *Spacing mark* A combining character that is not a nonspacing mark. ### Normalization The concepts of [canonical equivalent](#Canonical%20equivalent) or [compatibility equivalent](#Compatibility%20equivalent) characters in the Unicode Standard make it necessary to have a full, formal definition of equivalence for Unicode strings. String equivalence is determined by a process called normalization, whereby strings are converted into forms which are compared directly for identity. This is the primary goal of the normalization process, see the function [`normalize`](#normalize) to convert into any of the four defined forms. A very important attribute of the Unicode Normalization Forms is that they must remain stable between versions of the Unicode Standard. A Unicode string normalized to a particular Unicode Normalization Form in one version of the standard is guaranteed to remain in that Normalization Form for implementations of future versions of the standard. The Unicode Standard specifies four normalization forms. Informally, two of these forms are defined by maximal decomposition of equivalent sequences, and two of these forms are defined by maximal *composition* of equivalent sequences. * Normalization Form D (NFD): The [canonical decomposition](#Canonical%20decomposition) of a character sequence. * Normalization Form KD (NFKD): The [compatibility decomposition](#Compatibility%20decomposition) of a character sequence. * Normalization Form C (NFC): The canonical composition of the [canonical decomposition](#Canonical%20decomposition) of a coded character sequence. * Normalization Form KC (NFKC): The canonical composition of the [compatibility decomposition](#Compatibility%20decomposition) of a character sequence The choice of the normalization form depends on the particular use case. NFC is the best form for general text, since it's more compatible with strings converted from legacy encodings. NFKC is the preferred form for identifiers, especially where there are security concerns. NFD and NFKD are the most useful for internal processing. ### Construction of lookup tables The Unicode standard describes a set of algorithms that depend on having the ability to quickly look up various properties of a code point. Given the the codespace of about 1 million [code points](#Code%20point), it is not a trivial task to provide a space-efficient solution for the multitude of properties. Common approaches such as hash-tables or binary search over sorted code point intervals (as in [`InversionList`](#InversionList)) are insufficient. Hash-tables have enormous memory footprint and binary search over intervals is not fast enough for some heavy-duty algorithms. The recommended solution (see Unicode Implementation Guidelines) is using multi-stage tables that are an implementation of the [Trie](http://en.wikipedia.org/wiki/Trie) data structure with integer keys and a fixed number of stages. For the remainder of the section this will be called a fixed trie. The following describes a particular implementation that is aimed for the speed of access at the expense of ideal size savings. Taking a 2-level Trie as an example the principle of operation is as follows. Split the number of bits in a key (code point, 21 bits) into 2 components (e.g. 15 and 8). The first is the number of bits in the index of the trie and the other is number of bits in each page of the trie. The layout of the trie is then an array of size 2^^bits-of-index followed an array of memory chunks of size 2^^bits-of-page/bits-per-element. The number of pages is variable (but not less then 1) unlike the number of entries in the index. The slots of the index all have to contain a number of a page that is present. The lookup is then just a couple of operations - slice the upper bits, lookup an index for these, take a page at this index and use the lower bits as an offset within this page. Assuming that pages are laid out consequently in one array at `pages`, the pseudo-code is: ``` auto elemsPerPage = (2 ^^ bits_per_page) / Value.sizeOfInBits; pages[index[n >> bits_per_page]][n & (elemsPerPage - 1)]; ``` Where if `elemsPerPage` is a power of 2 the whole process is a handful of simple instructions and 2 array reads. Subsequent levels of the trie are introduced by recursing on this notion - the index array is treated as values. The number of bits in index is then again split into 2 parts, with pages over 'current-index' and the new 'upper-index'. For completeness a level 1 trie is simply an array. The current implementation takes advantage of bit-packing values when the range is known to be limited in advance (such as `bool`). See also [`BitPacked`](#BitPacked) for enforcing it manually. The major size advantage however comes from the fact that multiple **identical pages on every level are merged** by construction. The process of constructing a trie is more involved and is hidden from the user in a form of the convenience functions [`codepointTrie`](#codepointTrie), [`codepointSetTrie`](#codepointSetTrie) and the even more convenient [`toTrie`](#toTrie). In general a set or built-in AA with `dchar` type can be turned into a trie. The trie object in this module is read-only (immutable); it's effectively frozen after construction. ### Unicode properties This is a full list of Unicode properties accessible through [`unicode`](#unicode) with specific helpers per category nested within. Consult the [CLDR utility](http://www.unicode.org/cldr/utility/properties.jsp) when in doubt about the contents of a particular set. General category sets listed below are only accessible with the [`unicode`](#unicode) shorthand accessor. **General category** | Abb. | Long form | Abb. | Long form | Abb. | Long form | | L | Letter | Cn | Unassigned | Po | Other\_Punctuation | | Ll | Lowercase\_Letter | Co | Private\_Use | Ps | Open\_Punctuation | | Lm | Modifier\_Letter | Cs | Surrogate | S | Symbol | | Lo | Other\_Letter | N | Number | Sc | Currency\_Symbol | | Lt | Titlecase\_Letter | Nd | Decimal\_Number | Sk | Modifier\_Symbol | | Lu | Uppercase\_Letter | Nl | Letter\_Number | Sm | Math\_Symbol | | M | Mark | No | Other\_Number | So | Other\_Symbol | | Mc | Spacing\_Mark | P | Punctuation | Z | Separator | | Me | Enclosing\_Mark | Pc | Connector\_Punctuation | Zl | Line\_Separator | | Mn | Nonspacing\_Mark | Pd | Dash\_Punctuation | Zp | Paragraph\_Separator | | C | Other | Pe | Close\_Punctuation | Zs | Space\_Separator | | Cc | Control | Pf | Final\_Punctuation | - | Any | | Cf | Format | Pi | Initial\_Punctuation | - | ASCII | Sets for other commonly useful properties that are accessible with [`unicode`](#unicode): **Common binary properties**| Name | Name | Name | | Alphabetic | Ideographic | Other\_Uppercase | | ASCII\_Hex\_Digit | IDS\_Binary\_Operator | Pattern\_Syntax | | Bidi\_Control | ID\_Start | Pattern\_White\_Space | | Cased | IDS\_Trinary\_Operator | Quotation\_Mark | | Case\_Ignorable | Join\_Control | Radical | | Dash | Logical\_Order\_Exception | Soft\_Dotted | | Default\_Ignorable\_Code\_Point | Lowercase | STerm | | Deprecated | Math | Terminal\_Punctuation | | Diacritic | Noncharacter\_Code\_Point | Unified\_Ideograph | | Extender | Other\_Alphabetic | Uppercase | | Grapheme\_Base | Other\_Default\_Ignorable\_Code\_Point | Variation\_Selector | | Grapheme\_Extend | Other\_Grapheme\_Extend | White\_Space | | Grapheme\_Link | Other\_ID\_Continue | XID\_Continue | | Hex\_Digit | Other\_ID\_Start | XID\_Start | | Hyphen | Other\_Lowercase | | ID\_Continue | Other\_Math | Below is the table with block names accepted by [`unicode.block`](#unicode.block). Note that the shorthand version [`unicode`](#unicode) requires "In" to be prepended to the names of blocks so as to disambiguate scripts and blocks. **Blocks**| Aegean Numbers | Ethiopic Extended | Mongolian | | Alchemical Symbols | Ethiopic Extended-A | Musical Symbols | | Alphabetic Presentation Forms | Ethiopic Supplement | Myanmar | | Ancient Greek Musical Notation | General Punctuation | Myanmar Extended-A | | Ancient Greek Numbers | Geometric Shapes | New Tai Lue | | Ancient Symbols | Georgian | NKo | | Arabic | Georgian Supplement | Number Forms | | Arabic Extended-A | Glagolitic | Ogham | | Arabic Mathematical Alphabetic Symbols | Gothic | Ol Chiki | | Arabic Presentation Forms-A | Greek and Coptic | Old Italic | | Arabic Presentation Forms-B | Greek Extended | Old Persian | | Arabic Supplement | Gujarati | Old South Arabian | | Armenian | Gurmukhi | Old Turkic | | Arrows | Halfwidth and Fullwidth Forms | Optical Character Recognition | | Avestan | Hangul Compatibility Jamo | Oriya | | Balinese | Hangul Jamo | Osmanya | | Bamum | Hangul Jamo Extended-A | Phags-pa | | Bamum Supplement | Hangul Jamo Extended-B | Phaistos Disc | | Basic Latin | Hangul Syllables | Phoenician | | Batak | Hanunoo | Phonetic Extensions | | Bengali | Hebrew | Phonetic Extensions Supplement | | Block Elements | High Private Use Surrogates | Playing Cards | | Bopomofo | High Surrogates | Private Use Area | | Bopomofo Extended | Hiragana | Rejang | | Box Drawing | Ideographic Description Characters | Rumi Numeral Symbols | | Brahmi | Imperial Aramaic | Runic | | Braille Patterns | Inscriptional Pahlavi | Samaritan | | Buginese | Inscriptional Parthian | Saurashtra | | Buhid | IPA Extensions | Sharada | | Byzantine Musical Symbols | Javanese | Shavian | | Carian | Kaithi | Sinhala | | Chakma | Kana Supplement | Small Form Variants | | Cham | Kanbun | Sora Sompeng | | Cherokee | Kangxi Radicals | Spacing Modifier Letters | | CJK Compatibility | Kannada | Specials | | CJK Compatibility Forms | Katakana | Sundanese | | CJK Compatibility Ideographs | Katakana Phonetic Extensions | Sundanese Supplement | | CJK Compatibility Ideographs Supplement | Kayah Li | Superscripts and Subscripts | | CJK Radicals Supplement | Kharoshthi | Supplemental Arrows-A | | CJK Strokes | Khmer | Supplemental Arrows-B | | CJK Symbols and Punctuation | Khmer Symbols | Supplemental Mathematical Operators | | CJK Unified Ideographs | Lao | Supplemental Punctuation | | CJK Unified Ideographs Extension A | Latin-1 Supplement | Supplementary Private Use Area-A | | CJK Unified Ideographs Extension B | Latin Extended-A | Supplementary Private Use Area-B | | CJK Unified Ideographs Extension C | Latin Extended Additional | Syloti Nagri | | CJK Unified Ideographs Extension D | Latin Extended-B | Syriac | | Combining Diacritical Marks | Latin Extended-C | Tagalog | | Combining Diacritical Marks for Symbols | Latin Extended-D | Tagbanwa | | Combining Diacritical Marks Supplement | Lepcha | Tags | | Combining Half Marks | Letterlike Symbols | Tai Le | | Common Indic Number Forms | Limbu | Tai Tham | | Control Pictures | Linear B Ideograms | Tai Viet | | Coptic | Linear B Syllabary | Tai Xuan Jing Symbols | | Counting Rod Numerals | Lisu | Takri | | Cuneiform | Low Surrogates | Tamil | | Cuneiform Numbers and Punctuation | Lycian | Telugu | | Currency Symbols | Lydian | Thaana | | Cypriot Syllabary | Mahjong Tiles | Thai | | Cyrillic | Malayalam | Tibetan | | Cyrillic Extended-A | Mandaic | Tifinagh | | Cyrillic Extended-B | Mathematical Alphanumeric Symbols | Transport And Map Symbols | | Cyrillic Supplement | Mathematical Operators | Ugaritic | | Deseret | Meetei Mayek | Unified Canadian Aboriginal Syllabics | | Devanagari | Meetei Mayek Extensions | Unified Canadian Aboriginal Syllabics Extended | | Devanagari Extended | Meroitic Cursive | Vai | | Dingbats | Meroitic Hieroglyphs | Variation Selectors | | Domino Tiles | Miao | Variation Selectors Supplement | | Egyptian Hieroglyphs | Miscellaneous Mathematical Symbols-A | Vedic Extensions | | Emoticons | Miscellaneous Mathematical Symbols-B | Vertical Forms | | Enclosed Alphanumerics | Miscellaneous Symbols | Yijing Hexagram Symbols | | Enclosed Alphanumeric Supplement | Miscellaneous Symbols and Arrows | Yi Radicals | | Enclosed CJK Letters and Months | Miscellaneous Symbols And Pictographs | Yi Syllables | | Enclosed Ideographic Supplement | Miscellaneous Technical | | Ethiopic | Modifier Tone Letters | Below is the table with script names accepted by [`unicode.script`](#unicode.script) and by the shorthand version [`unicode`](#unicode): **Scripts**| Arabic | Hanunoo | Old\_Italic | | Armenian | Hebrew | Old\_Persian | | Avestan | Hiragana | Old\_South\_Arabian | | Balinese | Imperial\_Aramaic | Old\_Turkic | | Bamum | Inherited | Oriya | | Batak | Inscriptional\_Pahlavi | Osmanya | | Bengali | Inscriptional\_Parthian | Phags\_Pa | | Bopomofo | Javanese | Phoenician | | Brahmi | Kaithi | Rejang | | Braille | Kannada | Runic | | Buginese | Katakana | Samaritan | | Buhid | Kayah\_Li | Saurashtra | | Canadian\_Aboriginal | Kharoshthi | Sharada | | Carian | Khmer | Shavian | | Chakma | Lao | Sinhala | | Cham | Latin | Sora\_Sompeng | | Cherokee | Lepcha | Sundanese | | Common | Limbu | Syloti\_Nagri | | Coptic | Linear\_B | Syriac | | Cuneiform | Lisu | Tagalog | | Cypriot | Lycian | Tagbanwa | | Cyrillic | Lydian | Tai\_Le | | Deseret | Malayalam | Tai\_Tham | | Devanagari | Mandaic | Tai\_Viet | | Egyptian\_Hieroglyphs | Meetei\_Mayek | Takri | | Ethiopic | Meroitic\_Cursive | Tamil | | Georgian | Meroitic\_Hieroglyphs | Telugu | | Glagolitic | Miao | Thaana | | Gothic | Mongolian | Thai | | Greek | Myanmar | Tibetan | | Gujarati | New\_Tai\_Lue | Tifinagh | | Gurmukhi | Nko | Ugaritic | | Han | Ogham | Vai | | Hangul | Ol\_Chiki | Yi | Below is the table of names accepted by [`unicode.hangulSyllableType`](#unicode.hangulSyllableType). **Hangul syllable type**| Abb. | Long form | | L | Leading\_Jamo | | LV | LV\_Syllable | | LVT | LVT\_Syllable | | T | Trailing\_Jamo | | V | Vowel\_Jamo | References [ASCII Table](http://www.digitalmars.com/d/ascii-table.html), [Wikipedia](http://en.wikipedia.org/wiki/Unicode), [The Unicode Consortium](http://www.unicode.org), [Unicode normalization forms](http://www.unicode.org/reports/tr15/), [Unicode text segmentation](http://www.unicode.org/reports/tr29/) [Unicode Implementation Guidelines](http://www.unicode.org/uni2book/ch05.pdf) [Unicode Conformance](http://www.unicode.org/uni2book/ch03.pdf) Trademarks Unicode(tm) is a trademark of Unicode, Inc. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Dmitry Olshansky Source [std/uni/package.d](https://github.com/dlang/phobos/blob/master/std/uni/package.d) Standards: [Unicode v6.2](http://www.unicode.org/versions/Unicode6.2.0/) enum dchar **lineSep**; Constant [code point](#Code%20point) (0x2028) - line separator. enum dchar **paraSep**; Constant [code point](#Code%20point) (0x2029) - paragraph separator. enum dchar **nelSep**; Constant [code point](#Code%20point) (0x0085) - next line. template **isCodepointSet**(T) Tests if T is some kind a set of code points. Intended for template constraints. enum auto **isIntegralPair**(T, V = uint); Tests if `T` is a pair of integers that implicitly convert to `V`. The following code must compile for any pair `T`: ``` (T x){ V a = x[0]; V b = x[1];} ``` The following must not compile: ``` (T x){ V c = x[2];} ``` alias **CodepointSet** = InversionList!(GcPolicy).InversionList; The recommended default type for set of [code points](#Code%20point). For details, see the current implementation: [`InversionList`](#InversionList). struct **CodepointInterval**; The recommended type of [`std.typecons.Tuple`](std_typecons#Tuple) to represent [a, b) intervals of [code points](#Code%20point). As used in [`InversionList`](#InversionList). Any interval type should pass [`isIntegralPair`](#isIntegralPair) trait. struct **InversionList**(SP = GcPolicy); `InversionList` is a set of [code points](#Code%20point) represented as an array of open-right [a, b) intervals (see [`CodepointInterval`](#CodepointInterval) above). The name comes from the way the representation reads left to right. For instance a set of all values [10, 50), [80, 90), plus a singular value 60 looks like this: ``` 10, 50, 60, 61, 80, 90 ``` The way to read this is: start with negative meaning that all numbers smaller then the next one are not present in this set (and positive - the contrary). Then switch positive/negative after each number passed from left to right. This way negative spans until 10, then positive until 50, then negative until 60, then positive until 61, and so on. As seen this provides a space-efficient storage of highly redundant data that comes in long runs. A description which Unicode [character](#Character) properties fit nicely. The technique itself could be seen as a variation on [RLE encoding](https://en.wikipedia.org/wiki/Run-length_encoding). Sets are value types (just like `int` is) thus they are never aliased. Example ``` auto a = CodepointSet('a', 'z'+1); auto b = CodepointSet('A', 'Z'+1); auto c = a; a = a | b; assert(a == CodepointSet('A', 'Z'+1, 'a', 'z'+1)); assert(a != c); ``` See also [`unicode`](#unicode) for simpler construction of sets from predefined ones. Memory usage is 8 bytes per each contiguous interval in a set. The value semantics are achieved by using the [COW](http://en.wikipedia.org/wiki/Copy-on-write) technique and thus it's not safe to cast this type to shared. Note It's not recommended to rely on the template parameters or the exact type of a current [code point](#Code%20point) set in `std.uni`. The type and parameters may change when the standard allocators design is finalized. Use [`isCodepointSet`](#isCodepointSet) with templates or just stick with the default alias [`CodepointSet`](#CodepointSet) throughout the whole code base. pure this(Set)(Set set) Constraints: if (isCodepointSet!Set); Construct from another code point set of any type. pure this(Range)(Range intervals) Constraints: if (isForwardRange!Range && isIntegralPair!(ElementType!Range)); Construct a set from a forward range of code point intervals. this()(uint[] intervals...); Construct a set from plain values of code point intervals. Examples: ``` import std.algorithm.comparison : equal; auto set = CodepointSet('a', 'z'+1, 'а', 'я'+1); foreach (v; 'a'..'z'+1) assert(set[v]); // Cyrillic lowercase interval foreach (v; 'а'..'я'+1) assert(set[v]); //specific order is not required, intervals may interesect auto set2 = CodepointSet('а', 'я'+1, 'a', 'd', 'b', 'z'+1); //the same end result assert(set2.byInterval.equal(set.byInterval)); // test constructor this(Range)(Range intervals) auto chessPiecesWhite = CodepointInterval(9812, 9818); auto chessPiecesBlack = CodepointInterval(9818, 9824); auto set3 = CodepointSet([chessPiecesWhite, chessPiecesBlack]); foreach (v; '♔'..'♟'+1) assert(set3[v]); ``` @property scope auto **byInterval**(); Get range that spans all of the [code point](#Code%20point) intervals in this [`InversionList`](#InversionList). const bool **opIndex**(uint val); Tests the presence of code point `val` in this set. Examples: ``` auto gothic = unicode.Gothic; // Gothic letter ahsa assert(gothic['\U00010330']); // no ascii in Gothic obviously assert(!gothic['$']); ``` @property size\_t **length**(); Number of [code points](#Code%20point) in this set This **opBinary**(string op, U)(U rhs) Constraints: if (isCodepointSet!U || is(U : dchar)); Sets support natural syntax for set algebra, namely: | Operator | Math notation | Description | | --- | --- | --- | | & | a ∩ b | intersection | | | | a ∪ b | union | | - | a ∖ b | subtraction | | ~ | a ~ b | symmetric set difference i.e. (a ∪ b) \ (a ∩ b) | Examples: ``` import std.algorithm.comparison : equal; import std.range : iota; auto lower = unicode.LowerCase; auto upper = unicode.UpperCase; auto ascii = unicode.ASCII; assert((lower & upper).empty); // no intersection auto lowerASCII = lower & ascii; assert(lowerASCII.byCodepoint.equal(iota('a', 'z'+1))); // throw away all of the lowercase ASCII writeln((ascii - lower).length); // 128 - 26 auto onlyOneOf = lower ~ ascii; assert(!onlyOneOf['Δ']); // not ASCII and not lowercase assert(onlyOneOf['$']); // ASCII and not lowercase assert(!onlyOneOf['a']); // ASCII and lowercase assert(onlyOneOf['я']); // not ASCII but lowercase // throw away all cased letters from ASCII auto noLetters = ascii - (lower | upper); writeln(noLetters.length); // 128 - 26 * 2 ``` ref This **opOpAssign**(string op, U)(U rhs) Constraints: if (isCodepointSet!U || is(U : dchar)); The 'op=' versions of the above overloaded operators. const bool **opBinaryRight**(string op : "in", U)(U ch) Constraints: if (is(U : dchar)); Tests the presence of codepoint `ch` in this set, the same as [`opIndex`](#opIndex). Examples: ``` assert('я' in unicode.Cyrillic); assert(!('z' in unicode.Cyrillic)); ``` auto **opUnary**(string op : "!")(); Obtains a set that is the inversion of this set. See Also: [`inverted`](#inverted) @property auto **byCodepoint**(); A range that spans each [code point](#Code%20point) in this set. Examples: ``` import std.algorithm.comparison : equal; import std.range : iota; auto set = unicode.ASCII; set.byCodepoint.equal(iota(0, 0x80)); ``` void **toString**(Writer)(scope Writer sink, ref scope const FormatSpec!char fmt); Obtain a textual representation of this InversionList in form of open-right intervals. The formatting flag is applied individually to each value, for example: - **%s** and **%d** format the intervals as a [low .. high) range of integrals - **%x** formats the intervals as a [low .. high) range of lowercase hex characters - **%X** formats the intervals as a [low .. high) range of uppercase hex characters Examples: ``` import std.conv : to; import std.format : format; import std.uni : unicode; assert(unicode.Cyrillic.to!string == "[1024..1157) [1159..1320) [7467..7468) [7544..7545) [11744..11776) [42560..42648) [42655..42656)"); // The specs '%s' and '%d' are equivalent to the to!string call above. writeln(format("%d", unicode.Cyrillic)); // unicode.Cyrillic.to!string assert(format("%#x", unicode.Cyrillic) == "[0x400..0x485) [0x487..0x528) [0x1d2b..0x1d2c) [0x1d78..0x1d79) [0x2de0..0x2e00) " ~"[0xa640..0xa698) [0xa69f..0xa6a0)"); assert(format("%#X", unicode.Cyrillic) == "[0X400..0X485) [0X487..0X528) [0X1D2B..0X1D2C) [0X1D78..0X1D79) [0X2DE0..0X2E00) " ~"[0XA640..0XA698) [0XA69F..0XA6A0)"); ``` ref auto **add**()(uint a, uint b); Add an interval [a, b) to this set. Examples: ``` CodepointSet someSet; someSet.add('0', '5').add('A','Z'+1); someSet.add('5', '9'+1); assert(someSet['0']); assert(someSet['5']); assert(someSet['9']); assert(someSet['Z']); ``` @property auto **inverted**(); Obtains a set that is the inversion of this set. See the '!' [`opUnary`](#opUnary) for the same but using operators. Examples: ``` auto set = unicode.ASCII; // union with the inverse gets all of the code points in the Unicode writeln((set | set.inverted).length); // 0x110000 // no intersection with the inverse assert((set & set.inverted).empty); ``` string **toSourceCode**(string funcName = ""); Generates string with D source code of unary function with name of `funcName` taking a single `dchar` argument. If `funcName` is empty the code is adjusted to be a lambda function. The function generated tests if the [code point](#Code%20point) passed belongs to this set or not. The result is to be used with string mixin. The intended usage area is aggressive optimization via meta programming in parser generators and the like. Note Use with care for relatively small or regular sets. It could end up being slower then just using multi-staged tables. Example ``` import std.stdio; // construct set directly from [a, b&dollar;RPAREN intervals auto set = CodepointSet(10, 12, 45, 65, 100, 200); writeln(set); writeln(set.toSourceCode("func")); ``` The above outputs something along the lines of: ``` bool func(dchar ch) @safe pure nothrow @nogc { if (ch < 45) { if (ch == 10 || ch == 11) return true; return false; } else if (ch < 65) return true; else { if (ch < 100) return false; if (ch < 200) return true; return false; } } ``` const @property bool **empty**(); True if this set doesn't contain any [code points](#Code%20point). Examples: ``` CodepointSet emptySet; writeln(emptySet.length); // 0 assert(emptySet.empty); ``` template **codepointSetTrie**(sizes...) if (sumOfIntegerTuple!sizes == 21) A shorthand for creating a custom multi-level fixed Trie from a `CodepointSet`. `sizes` are numbers of bits per level, with the most significant bits used first. Note The sum of `sizes` must be equal 21. See Also: [`toTrie`](#toTrie), which is even simpler. Example ``` { import std.stdio; auto set = unicode("Number"); auto trie = codepointSetTrie!(8, 5, 8)(set); writeln("Input code points to test:"); foreach (line; stdin.byLine) { int count=0; foreach (dchar ch; line) if (trie[ch])// is number count++; writefln("Contains %d number code points.", count); } } ``` template **CodepointSetTrie**(sizes...) if (sumOfIntegerTuple!sizes == 21) Type of Trie generated by codepointSetTrie function. template **codepointTrie**(T, sizes...) if (sumOfIntegerTuple!sizes == 21) template **CodepointTrie**(T, sizes...) if (sumOfIntegerTuple!sizes == 21) A slightly more general tool for building fixed `Trie` for the Unicode data. Specifically unlike `codepointSetTrie` it's allows creating mappings of `dchar` to an arbitrary type `T`. Note Overload taking `CodepointSet`s will naturally convert only to bool mapping `Trie`s. CodepointTrie is the type of Trie as generated by codepointTrie function. auto **codepointTrie**()(T[dchar] map, T defValue = T.init); auto **codepointTrie**(R)(R range, T defValue = T.init) Constraints: if (isInputRange!R && is(typeof(ElementType!R.init[0]) : T) && is(typeof(ElementType!R.init[1]) : dchar)); struct **MatcherConcept**; Conceptual type that outlines the common properties of all UTF Matchers. Note For illustration purposes only, every method call results in assertion failure. Use [`utfMatcher`](#utfMatcher) to obtain a concrete matcher for UTF-8 or UTF-16 encodings. bool **match**(Range)(ref Range inp) Constraints: if (isRandomAccessRange!Range && is(ElementType!Range : char)); bool **skip**(Range)(ref Range inp) Constraints: if (isRandomAccessRange!Range && is(ElementType!Range : char)); bool **test**(Range)(ref Range inp) Constraints: if (isRandomAccessRange!Range && is(ElementType!Range : char)); Perform a semantic equivalent 2 operations: decoding a [code point](#Code%20point) at front of `inp` and testing if it belongs to the set of [code points](#Code%20point) of this matcher. The effect on `inp` depends on the kind of function called: Match. If the codepoint is found in the set then range `inp` is advanced by its size in [code units](#Code%20unit), otherwise the range is not modifed. Skip. The range is always advanced by the size of the tested [code point](#Code%20point) regardless of the result of test. Test. The range is left unaffected regardless of the result of test. Examples: ``` string truth = "2² = 4"; auto m = utfMatcher!char(unicode.Number); assert(m.match(truth)); // '2' is a number all right assert(truth == "² = 4"); // skips on match assert(m.match(truth)); // so is the superscript '2' assert(!m.match(truth)); // space is not a number assert(truth == " = 4"); // unaffected on no match assert(!m.skip(truth)); // same test ... assert(truth == "= 4"); // but skips a codepoint regardless assert(!m.test(truth)); // '=' is not a number assert(truth == "= 4"); // test never affects argument ``` @property auto **subMatcher**(Lengths...)(); Advanced feature - provide direct access to a subset of matcher based a set of known encoding lengths. Lengths are provided in [code units](#Code%20unit). The sub-matcher then may do less operations per any `test`/`match`. Use with care as the sub-matcher won't match any [code points](#Code%20point) that have encoded length that doesn't belong to the selected set of lengths. Also the sub-matcher object references the parent matcher and must not be used past the liftetime of the latter. Another caveat of using sub-matcher is that skip is not available preciesly because sub-matcher doesn't detect all lengths. enum auto **isUtfMatcher**(M, C); Test if `M` is an UTF Matcher for ranges of `Char`. auto **utfMatcher**(Char, Set)(Set set) Constraints: if (isCodepointSet!Set); Constructs a matcher object to classify [code points](#Code%20point) from the `set` for encoding that has `Char` as code unit. See [`MatcherConcept`](#MatcherConcept) for API outline. auto **toTrie**(size\_t level, Set)(Set set) Constraints: if (isCodepointSet!Set); Convenience function to construct optimal configurations for packed Trie from any `set` of [code points](#Code%20point). The parameter `level` indicates the number of trie levels to use, allowed values are: 1, 2, 3 or 4. Levels represent different trade-offs speed-size wise. Level 1 is fastest and the most memory hungry (a bit array). Level 4 is the slowest and has the smallest footprint. See the [Synopsis](#Synopsis) section for example. Note Level 4 stays very practical (being faster and more predictable) compared to using direct lookup on the `set` itself. auto **toDelegate**(Set)(Set set) Constraints: if (isCodepointSet!Set); Builds a `Trie` with typically optimal speed-size trade-off and wraps it into a delegate of the following type: `bool delegate(dchar ch)`. Effectively this creates a 'tester' lambda suitable for algorithms like std.algorithm.find that take unary predicates. See the [Synopsis](#Synopsis) section for example. struct **unicode**; A single entry point to lookup Unicode [code point](#Code%20point) sets by name or alias of a block, script or general category. It uses well defined standard rules of property name lookup. This includes fuzzy matching of names, so that 'White\_Space', 'white-SpAce' and 'whitespace' are all considered equal and yield the same set of white space [characters](#Character). pure @property auto **opDispatch**(string name)(); Performs the lookup of set of [code points](#Code%20point) with compile-time correctness checking. This short-cut version combines 3 searches: across blocks, scripts, and common binary properties. Note that since scripts and blocks overlap the usual trick to disambiguate is used - to get a block use `unicode.InBlockName`, to search a script use `unicode.ScriptName`. See Also: [`block`](#block), [`script`](#script) and (not included in this search) [`hangulSyllableType`](#hangulSyllableType). auto **opCall**(C)(scope const C[] name) Constraints: if (is(C : dchar)); The same lookup across blocks, scripts, or binary properties, but performed at run-time. This version is provided for cases where `name` is not known beforehand; otherwise compile-time checked [`opDispatch`](#opDispatch) is typically a better choice. See the [table of properties](#Unicode%20properties) for available sets. struct **block**; Narrows down the search for sets of [code points](#Code%20point) to all Unicode blocks. Note Here block names are unambiguous as no scripts are searched and thus to search use simply `unicode.block.BlockName` notation. See [table of properties](#Unicode%20properties) for available sets. See Also: [table of properties](#Unicode%20properties). Examples: ``` // use .block for explicitness writeln(unicode.block.Greek_and_Coptic); // unicode.InGreek_and_Coptic ``` struct **script**; Narrows down the search for sets of [code points](#Code%20point) to all Unicode scripts. See the [table of properties](#Unicode%20properties) for available sets. Examples: ``` auto arabicScript = unicode.script.arabic; auto arabicBlock = unicode.block.arabic; // there is an intersection between script and block assert(arabicBlock['؁']); assert(arabicScript['؁']); // but they are different assert(arabicBlock != arabicScript); writeln(arabicBlock); // unicode.inArabic writeln(arabicScript); // unicode.arabic ``` struct **hangulSyllableType**; Fetch a set of [code points](#Code%20point) that have the given hangul syllable type. Other non-binary properties (once supported) follow the same notation - `unicode.propertyName.propertyValue` for compile-time checked access and `unicode.propertyName(propertyValue)` for run-time checked one. See the [table of properties](#Unicode%20properties) for available sets. Examples: ``` // L here is syllable type not Letter as in unicode.L short-cut auto leadingVowel = unicode.hangulSyllableType("L"); // check that some leading vowels are present foreach (vowel; '\u1110'..'\u115F') assert(leadingVowel[vowel]); writeln(leadingVowel); // unicode.hangulSyllableType.L ``` CodepointSet **parseSet**(Range)(ref Range range, bool casefold = false) Constraints: if (isInputRange!Range && is(ElementType!Range : dchar)); Parse unicode codepoint set from given `range` using standard regex syntax '[...]'. The range is advanced skiping over regex set definition. `casefold` parameter determines if the set should be casefolded - that is include both lower and upper case versions for any letters in the set. pure @safe size\_t **graphemeStride**(C)(scope const C[] input, size\_t index) Constraints: if (is(C : dchar)); Computes the length of grapheme cluster starting at `index`. Both the resulting length and the `index` are measured in [code units](#Code%20unit). Parameters: | | | | --- | --- | | C | type that is implicitly convertible to `dchars` | | C[] `input` | array of grapheme clusters | | size\_t `index` | starting index into `input[]` | Returns: length of grapheme cluster Examples: ``` writeln(graphemeStride(" ", 1)); // 1 // A + combing ring above string city = "A\u030Arhus"; size_t first = graphemeStride(city, 0); assert(first == 3); //\u030A has 2 UTF-8 code units writeln(city[0 .. first]); // "A\u030A" writeln(city[first .. $]); // "rhus" ``` Grapheme **decodeGrapheme**(Input)(ref Input inp) Constraints: if (isInputRange!Input && is(immutable(ElementType!Input) == immutable(dchar))); Reads one full grapheme cluster from an [input range](std_range_primitives#isInputRange) of dchar `inp`. For examples see the [`Grapheme`](#Grapheme) below. Note This function modifies `inp` and thus `inp` must be an L-value. auto **byGrapheme**(Range)(Range range) Constraints: if (isInputRange!Range && is(immutable(ElementType!Range) == immutable(dchar))); Iterate a string by [`Grapheme`](#Grapheme). Useful for doing string manipulation that needs to be aware of graphemes. See Also: [`byCodePoint`](#byCodePoint) Examples: ``` import std.algorithm.comparison : equal; import std.range.primitives : walkLength; import std.range : take, drop; auto text = "noe\u0308l"; // noël using e + combining diaeresis assert(text.walkLength == 5); // 5 code points auto gText = text.byGrapheme; assert(gText.walkLength == 4); // 4 graphemes assert(gText.take(3).equal("noe\u0308".byGrapheme)); assert(gText.drop(3).equal("l".byGrapheme)); ``` auto **byCodePoint**(Range)(Range range) Constraints: if (isInputRange!Range && is(immutable(ElementType!Range) == immutable(Grapheme))); auto **byCodePoint**(Range)(Range range) Constraints: if (isInputRange!Range && is(immutable(ElementType!Range) == immutable(dchar))); Lazily transform a range of [`Grapheme`](#Grapheme)s to a range of code points. Useful for converting the result to a string after doing operations on graphemes. If passed in a range of code points, returns a range with equivalent capabilities. Examples: ``` import std.array : array; import std.conv : text; import std.range : retro; string s = "noe\u0308l"; // noël // reverse it and convert the result to a string string reverse = s.byGrapheme .array .retro .byCodePoint .text; assert(reverse == "le\u0308on"); // lëon ``` struct **Grapheme**; A structure designed to effectively pack [characters](#Character) of a [grapheme cluster](#Grapheme%20cluster). `Grapheme` has value semantics so 2 copies of a `Grapheme` always refer to distinct objects. In most actual scenarios a `Grapheme` fits on the stack and avoids memory allocation overhead for all but quite long clusters. See Also: [`decodeGrapheme`](#decodeGrapheme), [`graphemeStride`](#graphemeStride) this(C)(scope const C[] chars...) Constraints: if (is(C : dchar)); this(Input)(Input seq) Constraints: if (!isDynamicArray!Input && isInputRange!Input && is(ElementType!Input : dchar)); Ctor const pure nothrow @nogc @trusted dchar **opIndex**(size\_t index); Gets a [code point](#Code%20point) at the given index in this cluster. pure nothrow @nogc @trusted void **opIndexAssign**(dchar ch, size\_t index); Writes a [code point](#Code%20point) `ch` at given index in this cluster. Warning Use of this facility may invalidate grapheme cluster, see also [`Grapheme.valid`](#Grapheme.valid). Examples: ``` auto g = Grapheme("A\u0302"); writeln(g[0]); // 'A' assert(g.valid); g[1] = '~'; // ASCII tilda is not a combining mark writeln(g[1]); // '~' assert(!g.valid); ``` pure nothrow @nogc @safe SliceOverIndexed!Grapheme **opSlice**(size\_t a, size\_t b) return; pure nothrow @nogc @safe SliceOverIndexed!Grapheme **opSlice**() return; Random-access range over Grapheme's [characters](#Character). Warning Invalidates when this Grapheme leaves the scope, attempts to use it then would lead to memory corruption. const pure nothrow @nogc @property @safe size\_t **length**(); Grapheme cluster length in [code points](#Code%20point). ref @trusted auto **opOpAssign**(string op)(dchar ch); Append [character](#Character) `ch` to this grapheme. Warning Use of this facility may invalidate grapheme cluster, see also `valid`. See Also: [`Grapheme.valid`](#Grapheme.valid) Examples: ``` import std.algorithm.comparison : equal; auto g = Grapheme("A"); assert(g.valid); g ~= '\u0301'; assert(g[].equal("A\u0301")); assert(g.valid); g ~= "B"; // not a valid grapheme cluster anymore assert(!g.valid); // still could be useful though assert(g[].equal("A\u0301B")); ``` ref auto **opOpAssign**(string op, Input)(scope Input inp) Constraints: if (isInputRange!Input && is(ElementType!Input : dchar)); Append all [characters](#Character) from the input range `inp` to this Grapheme. @property bool **valid**()(); True if this object contains valid extended grapheme cluster. Decoding primitives of this module always return a valid `Grapheme`. Appending to and direct manipulation of grapheme's [characters](#Character) may render it no longer valid. Certain applications may chose to use Grapheme as a "small string" of any [code points](#Code%20point) and ignore this property entirely. int **sicmp**(S1, S2)(scope S1 r1, scope S2 r2) Constraints: if (isInputRange!S1 && isSomeChar!(ElementEncodingType!S1) && isInputRange!S2 && isSomeChar!(ElementEncodingType!S2)); Does basic case-insensitive comparison of `r1` and `r2`. This function uses simpler comparison rule thus achieving better performance than [`icmp`](#icmp). However keep in mind the warning below. Parameters: | | | | --- | --- | | S1 `r1` | an [input range](std_range_primitives#isInputRange) of characters | | S2 `r2` | an [input range](std_range_primitives#isInputRange) of characters | Returns: An `int` that is 0 if the strings match, <0 if `r1` is lexicographically "less" than `r2`, >0 if `r1` is lexicographically "greater" than `r2` Warning This function only handles 1:1 [code point](#Code%20point) mapping and thus is not sufficient for certain alphabets like German, Greek and few others. See Also: [`icmp`](#icmp) [`std.algorithm.comparison.cmp`](std_algorithm_comparison#cmp) Examples: ``` writeln(sicmp("Август", "авгусТ")); // 0 // Greek also works as long as there is no 1:M mapping in sight writeln(sicmp("ΌΎ", "όύ")); // 0 // things like the following won't get matched as equal // Greek small letter iota with dialytika and tonos assert(sicmp("ΐ", "\u03B9\u0308\u0301") != 0); // while icmp has no problem with that writeln(icmp("ΐ", "\u03B9\u0308\u0301")); // 0 writeln(icmp("ΌΎ", "όύ")); // 0 ``` int **icmp**(S1, S2)(S1 r1, S2 r2) Constraints: if (isForwardRange!S1 && isSomeChar!(ElementEncodingType!S1) && isForwardRange!S2 && isSomeChar!(ElementEncodingType!S2)); Does case insensitive comparison of `r1` and `r2`. Follows the rules of full case-folding mapping. This includes matching as equal german ß with "ss" and other 1:M [code point](#Code%20point) mappings unlike [`sicmp`](#sicmp). The cost of `icmp` being pedantically correct is slightly worse performance. Parameters: | | | | --- | --- | | S1 `r1` | a forward range of characters | | S2 `r2` | a forward range of characters | Returns: An `int` that is 0 if the strings match, <0 if `str1` is lexicographically "less" than `str2`, >0 if `str1` is lexicographically "greater" than `str2` See Also: [`sicmp`](#sicmp) [`std.algorithm.comparison.cmp`](std_algorithm_comparison#cmp) Examples: ``` writeln(icmp("Rußland", "Russland")); // 0 writeln(icmp("ᾩ -> \u1F70\u03B9", "\u1F61\u03B9 -> ᾲ")); // 0 ``` Examples: By using [`std.utf.byUTF`](std_utf#byUTF) and its aliases, GC allocations via auto-decoding and thrown exceptions can be avoided, making `icmp` `@safe @nogc nothrow pure`. ``` import std.utf : byDchar; writeln(icmp("Rußland".byDchar, "Russland".byDchar)); // 0 writeln(icmp("ᾩ -> \u1F70\u03B9".byDchar, "\u1F61\u03B9 -> ᾲ".byDchar)); // 0 ``` pure nothrow @nogc @safe ubyte **combiningClass**(dchar ch); Returns the [combining class](#Combining%20class) of `ch`. Examples: ``` // shorten the code alias CC = combiningClass; // combining tilda writeln(CC('\u0303')); // 230 // combining ring below writeln(CC('\u0325')); // 220 // the simple consequence is that "tilda" should be // placed after a "ring below" in a sequence ``` enum **UnicodeDecomposition**: int; Unicode character decomposition type. **Canonical** Canonical decomposition. The result is canonically equivalent sequence. **Compatibility** Compatibility decomposition. The result is compatibility equivalent sequence. Note Compatibility decomposition is a **lossy** conversion, typically suitable only for fuzzy matching and internal processing. pure nothrow @safe dchar **compose**(dchar first, dchar second); Try to canonically compose 2 [characters](#Character). Returns the composed [character](#Character) if they do compose and dchar.init otherwise. The assumption is that `first` comes before `second` in the original text, usually meaning that the first is a starter. Note Hangul syllables are not covered by this function. See `composeJamo` below. Examples: ``` writeln(compose('A', '\u0308')); // '\u00C4' writeln(compose('A', 'B')); // dchar.init writeln(compose('C', '\u0301')); // '\u0106' // note that the starter is the first one // thus the following doesn't compose writeln(compose('\u0308', 'A')); // dchar.init ``` @safe Grapheme **decompose**(UnicodeDecomposition decompType = Canonical)(dchar ch); Returns a full [Canonical](#Canonical%20decomposition) (by default) or [Compatibility](#Compatibility%20decomposition) decomposition of [character](#Character) `ch`. If no decomposition is available returns a [`Grapheme`](#Grapheme) with the `ch` itself. Note This function also decomposes hangul syllables as prescribed by the standard. See Also: [`decomposeHangul`](#decomposeHangul) for a restricted version that takes into account only hangul syllables but no other decompositions. Examples: ``` import std.algorithm.comparison : equal; writeln(compose('A', '\u0308')); // '\u00C4' writeln(compose('A', 'B')); // dchar.init writeln(compose('C', '\u0301')); // '\u0106' // note that the starter is the first one // thus the following doesn't compose writeln(compose('\u0308', 'A')); // dchar.init assert(decompose('Ĉ')[].equal("C\u0302")); assert(decompose('D')[].equal("D")); assert(decompose('\uD4DC')[].equal("\u1111\u1171\u11B7")); assert(decompose!Compatibility('¹')[].equal("1")); ``` @safe Grapheme **decomposeHangul**(dchar ch); Decomposes a Hangul syllable. If `ch` is not a composed syllable then this function returns [`Grapheme`](#Grapheme) containing only `ch` as is. Examples: ``` import std.algorithm.comparison : equal; assert(decomposeHangul('\uD4DB')[].equal("\u1111\u1171\u11B6")); ``` pure nothrow @nogc @safe dchar **composeJamo**(dchar lead, dchar vowel, dchar trailing = (dchar).init); Try to compose hangul syllable out of a leading consonant (`lead`), a `vowel` and optional `trailing` consonant jamos. On success returns the composed LV or LVT hangul syllable. If any of `lead` and `vowel` are not a valid hangul jamo of the respective [character](#Character) class returns dchar.init. Examples: ``` writeln(composeJamo('\u1111', '\u1171', '\u11B6')); // '\uD4DB' // leaving out T-vowel, or passing any codepoint // that is not trailing consonant composes an LV-syllable writeln(composeJamo('\u1111', '\u1171')); // '\uD4CC' writeln(composeJamo('\u1111', '\u1171', ' ')); // '\uD4CC' writeln(composeJamo('\u1111', 'A')); // dchar.init writeln(composeJamo('A', '\u1171')); // dchar.init ``` enum **NormalizationForm**: int; Enumeration type for normalization forms, passed as template parameter for functions like [`normalize`](#normalize). **NFC** **NFD** **NFKC** **NFKD** Shorthand aliases from values indicating normalization forms. inout(C)[] **normalize**(NormalizationForm norm = NFC, C)(inout(C)[] input); Returns `input` string normalized to the chosen form. Form C is used by default. For more information on normalization forms see the [normalization section](#Normalization). Note In cases where the string in question is already normalized, it is returned unmodified and no memory allocation happens. Examples: ``` // any encoding works wstring greet = "Hello world"; assert(normalize(greet) is greet); // the same exact slice // An example of a character with all 4 forms being different: // Greek upsilon with acute and hook symbol (code point 0x03D3) writeln(normalize!NFC("ϓ")); // "\u03D3" writeln(normalize!NFD("ϓ")); // "\u03D2\u0301" writeln(normalize!NFKC("ϓ")); // "\u038E" writeln(normalize!NFKD("ϓ")); // "\u03A5\u0301" ``` bool **allowedIn**(NormalizationForm norm)(dchar ch); Tests if dchar `ch` is always allowed (Quick\_Check=YES) in normalization form `norm`. Examples: ``` // e.g. Cyrillic is always allowed, so is ASCII assert(allowedIn!NFC('я')); assert(allowedIn!NFD('я')); assert(allowedIn!NFKC('я')); assert(allowedIn!NFKD('я')); assert(allowedIn!NFC('Z')); ``` pure nothrow @nogc @safe bool **isWhite**(dchar c); Whether or not `c` is a Unicode whitespace [character](#Character). (general Unicode category: Part of C0(tab, vertical tab, form feed, carriage return, and linefeed characters), Zs, Zl, Zp, and NEL(U+0085)) pure nothrow @nogc @safe bool **isLower**(dchar c); Return whether `c` is a Unicode lowercase [character](#Character). pure nothrow @nogc @safe bool **isUpper**(dchar c); Return whether `c` is a Unicode uppercase [character](#Character). auto **asLowerCase**(Range)(Range str) Constraints: if (isInputRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range); auto **asUpperCase**(Range)(Range str) Constraints: if (isInputRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range); Convert an [input range](std_range_primitives#isInputRange) or a string to upper or lower case. Does not allocate memory. Characters in UTF-8 or UTF-16 format that cannot be decoded are treated as [`std.utf.replacementDchar`](std_utf#replacementDchar). Parameters: | | | | --- | --- | | Range `str` | string or range of characters | Returns: an input range of `dchar`s See Also: [`toUpper`](#toUpper), [`toLower`](#toLower) Examples: ``` import std.algorithm.comparison : equal; assert("hEllo".asUpperCase.equal("HELLO")); ``` auto **asCapitalized**(Range)(Range str) Constraints: if (isInputRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range); Capitalize an [input range](std_range_primitives#isInputRange) or string, meaning convert the first character to upper case and subsequent characters to lower case. Does not allocate memory. Characters in UTF-8 or UTF-16 format that cannot be decoded are treated as [`std.utf.replacementDchar`](std_utf#replacementDchar). Parameters: | | | | --- | --- | | Range `str` | string or range of characters | Returns: an InputRange of dchars See Also: [`toUpper`](#toUpper), [`toLower`](#toLower) [`asUpperCase`](#asUpperCase), [`asLowerCase`](#asLowerCase) Examples: ``` import std.algorithm.comparison : equal; assert("hEllo".asCapitalized.equal("Hello")); ``` pure @trusted void **toLowerInPlace**(C)(ref C[] s) Constraints: if (is(C == char) || is(C == wchar) || is(C == dchar)); Converts `s` to lowercase (by performing Unicode lowercase mapping) in place. For a few characters string length may increase after the transformation, in such a case the function reallocates exactly once. If `s` does not have any uppercase characters, then `s` is unaltered. pure @trusted void **toUpperInPlace**(C)(ref C[] s) Constraints: if (is(C == char) || is(C == wchar) || is(C == dchar)); Converts `s` to uppercase (by performing Unicode uppercase mapping) in place. For a few characters string length may increase after the transformation, in such a case the function reallocates exactly once. If `s` does not have any lowercase characters, then `s` is unaltered. pure nothrow @nogc @safe dchar **toLower**(dchar c); If `c` is a Unicode uppercase [character](#Character), then its lowercase equivalent is returned. Otherwise `c` is returned. Warning certain alphabets like German and Greek have no 1:1 upper-lower mapping. Use overload of toLower which takes full string instead. ElementEncodingType!S[] **toLower**(S)(S s) Constraints: if (isSomeString!S || isRandomAccessRange!S && hasLength!S && hasSlicing!S && isSomeChar!(ElementType!S)); Creates a new array which is identical to `s` except that all of its characters are converted to lowercase (by preforming Unicode lowercase mapping). If none of `s` characters were affected, then `s` itself is returned if `s` is a `string`-like type. Parameters: | | | | --- | --- | | S `s` | A [random access range](std_range_primitives#isRandomAccessRange) of characters | Returns: An array with the same element type as `s`. pure nothrow @nogc @safe dchar **toUpper**(dchar c); If `c` is a Unicode lowercase [character](#Character), then its uppercase equivalent is returned. Otherwise `c` is returned. Warning Certain alphabets like German and Greek have no 1:1 upper-lower mapping. Use overload of toUpper which takes full string instead. toUpper can be used as an argument to [`std.algorithm.iteration.map`](std_algorithm_iteration#map) to produce an algorithm that can convert a range of characters to upper case without allocating memory. A string can then be produced by using [`std.algorithm.mutation.copy`](std_algorithm_mutation#copy) to send it to an [`std.array.appender`](std_array#appender). Examples: ``` import std.algorithm.iteration : map; import std.algorithm.mutation : copy; import std.array : appender; auto abuf = appender!(char[])(); "hello".map!toUpper.copy(abuf); writeln(abuf.data); // "HELLO" ``` ElementEncodingType!S[] **toUpper**(S)(S s) Constraints: if (isSomeString!S || isRandomAccessRange!S && hasLength!S && hasSlicing!S && isSomeChar!(ElementType!S)); Allocates a new array which is identical to `s` except that all of its characters are converted to uppercase (by preforming Unicode uppercase mapping). If none of `s` characters were affected, then `s` itself is returned if `s` is a `string`-like type. Parameters: | | | | --- | --- | | S `s` | A [random access range](std_range_primitives#isRandomAccessRange) of characters | Returns: An new array with the same element type as `s`. pure nothrow @nogc @safe bool **isAlpha**(dchar c); Returns whether `c` is a Unicode alphabetic [character](#Character) (general Unicode category: Alphabetic). pure nothrow @nogc @safe bool **isMark**(dchar c); Returns whether `c` is a Unicode mark (general Unicode category: Mn, Me, Mc). pure nothrow @nogc @safe bool **isNumber**(dchar c); Returns whether `c` is a Unicode numerical [character](#Character) (general Unicode category: Nd, Nl, No). pure nothrow @nogc @safe bool **isAlphaNum**(dchar c); Returns whether `c` is a Unicode alphabetic [character](#Character) or number. (general Unicode category: Alphabetic, Nd, Nl, No). Parameters: | | | | --- | --- | | dchar `c` | any Unicode character | Returns: `true` if the character is in the Alphabetic, Nd, Nl, or No Unicode categories pure nothrow @nogc @safe bool **isPunctuation**(dchar c); Returns whether `c` is a Unicode punctuation [character](#Character) (general Unicode category: Pd, Ps, Pe, Pc, Po, Pi, Pf). pure nothrow @nogc @safe bool **isSymbol**(dchar c); Returns whether `c` is a Unicode symbol [character](#Character) (general Unicode category: Sm, Sc, Sk, So). pure nothrow @nogc @safe bool **isSpace**(dchar c); Returns whether `c` is a Unicode space [character](#Character) (general Unicode category: Zs) Note This doesn't include '\n', '\r', \t' and other non-space [character](#Character). For commonly used less strict semantics see [`isWhite`](#isWhite). pure nothrow @nogc @safe bool **isGraphical**(dchar c); Returns whether `c` is a Unicode graphical [character](#Character) (general Unicode category: L, M, N, P, S, Zs). pure nothrow @nogc @safe bool **isControl**(dchar c); Returns whether `c` is a Unicode control [character](#Character) (general Unicode category: Cc). pure nothrow @nogc @safe bool **isFormat**(dchar c); Returns whether `c` is a Unicode formatting [character](#Character) (general Unicode category: Cf). pure nothrow @nogc @safe bool **isPrivateUse**(dchar c); Returns whether `c` is a Unicode Private Use [code point](#Code%20point) (general Unicode category: Co). pure nothrow @nogc @safe bool **isSurrogate**(dchar c); Returns whether `c` is a Unicode surrogate [code point](#Code%20point) (general Unicode category: Cs). pure nothrow @nogc @safe bool **isSurrogateHi**(dchar c); Returns whether `c` is a Unicode high surrogate (lead surrogate). pure nothrow @nogc @safe bool **isSurrogateLo**(dchar c); Returns whether `c` is a Unicode low surrogate (trail surrogate). pure nothrow @nogc @safe bool **isNonCharacter**(dchar c); Returns whether `c` is a Unicode non-character i.e. a [code point](#Code%20point) with no assigned abstract character. (general Unicode category: Cn)
programming_docs
d std.datetime std.datetime ============ | Functionality | Symbols | | --- | --- | | Points in Time | [Date](std_datetime_date#Date) [TimeOfDay](std_datetime_date#TimeOfDay) [DateTime](std_datetime_date#DateTime) [SysTime](std_datetime_systime#SysTime) | | Timezones | [TimeZone](std_datetime_timezone#TimeZone) [UTC](std_datetime_timezone#UTC) [LocalTime](std_datetime_timezone#LocalTime) [PosixTimeZone](std_datetime_timezone#PosixTimeZone) [WindowsTimeZone](std_datetime_timezone#WindowsTimeZone) [SimpleTimeZone](std_datetime_timezone#SimpleTimeZone) | | Intervals and Ranges of Time | [Interval](std_datetime_interval#Interval) [PosInfInterval](std_datetime_interval#PosInfInterval) [NegInfInterval](std_datetime_interval#NegInfInterval) | | Durations of Time | [Duration](core_time#Duration) [weeks](core_time#weeks) [days](core_time#days) [hours](core_time#hours) [minutes](core_time#minutes) [seconds](core_time#seconds) [msecs](core_time#msecs) [usecs](core_time#usecs) [hnsecs](core_time#hnsecs) [nsecs](core_time#nsecs) | | Time Measurement and Benchmarking | [MonoTime](core_time#MonoTime) [StopWatch](std_datetime_stopwatch#StopWatch) [benchmark](std_datetime_stopwatch#benchmark) | Phobos provides the following functionality for time: This functionality is separated into the following modules * [`std.datetime.date`](std_datetime_date) for points in time without timezones. * [`std.datetime.timezone`](std_datetime_timezone) for classes which represent timezones. * [`std.datetime.systime`](std_datetime_systime) for a point in time with a timezone. * [`std.datetime.interval`](std_datetime_interval) for types which represent series of points in time. * [`std.datetime.stopwatch`](std_datetime_stopwatch) for measuring time. See Also: [Introduction to std.datetime](https://dlang.org/intro-to-datetime.html) [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601) [Wikipedia entry on TZ Database](http://en.wikipedia.org/wiki/Tz_database) [List of Time Zones](http://en.wikipedia.org/wiki/List_of_tz_database_time_zones) License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Jonathan M Davis](http://jmdavisprog.com) and Kato Shoichi Source [std/datetime/package.d](https://github.com/dlang/phobos/blob/master/std/datetime/package.d) Examples: Get the current time from the system clock ``` import std.datetime.systime : SysTime, Clock; SysTime currentTime = Clock.currTime(); ``` Examples: Construct a specific point in time without timezone information and get its ISO string. ``` import std.datetime.date : DateTime; auto dt = DateTime(2018, 1, 1, 12, 30, 10); writeln(dt.toISOString()); // "20180101T123010" writeln(dt.toISOExtString()); // "2018-01-01T12:30:10" ``` Examples: Construct a specific point in time in the UTC timezone and add two days. ``` import std.datetime.systime : SysTime; import std.datetime.timezone : UTC; import core.time : days; auto st = SysTime(DateTime(2018, 1, 1, 12, 30, 10), UTC()); writeln(st.toISOExtString()); // "2018-01-01T12:30:10Z" st += 2.days; writeln(st.toISOExtString()); // "2018-01-03T12:30:10Z" ``` d Enums Enums ===== **Contents** 1. [Named Enums](#named_enums) 1. [Enum Default Initializer](#enum_default_initializer) 2. [Enum Properties](#enum_properties) 2. [Anonymous Enums](#anonymous_enums) 3. [Manifest Constants](#manifest_constants) ``` EnumDeclaration: enum Identifier EnumBody enum Identifier : EnumBaseType EnumBody AnonymousEnumDeclaration EnumBaseType: Type EnumBody: { EnumMembers } ; EnumMembers: EnumMember EnumMember , EnumMember , EnumMembers EnumMemberAttributes: EnumMemberAttribute EnumMemberAttribute EnumMemberAttributes EnumMemberAttribute: DeprecatedAttribute UserDefinedAttribute @disable EnumMember: EnumMemberAttributesopt Identifier EnumMemberAttributesopt Identifier = AssignExpression AnonymousEnumDeclaration: enum : EnumBaseType { EnumMembers } enum { EnumMembers } enum { AnonymousEnumMembers } AnonymousEnumMembers: AnonymousEnumMember AnonymousEnumMember , AnonymousEnumMember , AnonymousEnumMembers AnonymousEnumMember: EnumMember Type Identifier = AssignExpression ``` Enum declarations are used to define a group of constants. Named Enums ----------- Named enums are used to declare related constants and group them by giving them a unique type. The [*EnumMembers*](#EnumMembers) are declared in the scope of the named enum. The named enum declares a new type, and all the *EnumMembers* have that type. This defines a new type `X` which has values `X.A=0`, `X.B=1`, `X.C=2`: ``` enum X { A, B, C } // named enum ``` If the *EnumBaseType* is not explicitly set, and the first *EnumMember* has an [*AssignExpression*](expression#AssignExpression), it is set to the type of that [*AssignExpression*](expression#AssignExpression). Otherwise, it defaults to type `int`. Named enum members may not have individual *Type*s. A named enum member can be implicitly cast to its [*EnumBaseType*](#EnumBaseType), but *EnumBaseType* types cannot be implicitly cast to an enum type. The value of an [*EnumMember*](#EnumMember) is given by its [*AssignExpression*](expression#AssignExpression). If there is no [*AssignExpression*](expression#AssignExpression) and it is the first *EnumMember*, its value is [*EnumBaseType*](#EnumBaseType)`.init`. If there is no [*AssignExpression*](expression#AssignExpression) and it is not the first *EnumMember*, it is given the value of the previous *EnumMember*`+1`. If the value of the previous *EnumMember* is [*EnumBaseType*](#EnumBaseType)`.max`, it is an error. If the value of the previous *EnumMember*`+1` is the same as the value of the previous *EnumMember*, it is an error. (This can happen with floating point types.) All *EnumMember*s are in scope for the [*AssignExpression*](expression#AssignExpression)s. ``` enum A = 3; enum B { A = A // error, circular reference } enum C { A = B, // A = 4 B = D, // B = 4 C = 3, // C = 3 D // D = 4 } enum E : C { E1 = C.D, E2 // error, C.D is C.max } ``` An empty enum body (For example `enum E;`) signifies an opaque enum - the enum members are unknown. ### Enum Default Initializer The `.init` property of an enum type is the value of the first member of that enum. This is also the default initializer for the enum type. ``` enum X { A=3, B, C } X x; // x is initialized to 3 ``` ### Enum Properties Enum properties only exist for named enums. Named Enum Properties| `.init` | First enum member value | | `.min` | Smallest enum member value | | `.max` | Largest enum member value | | `.sizeof` | Size of storage for an enumerated value | For example: ``` enum X { A=3, B=1, C=4, D, E=2 } X.init // is X.A X.min // is X.B X.max // is X.D X.sizeof // is same as int.sizeof ``` The [*EnumBaseType*](#EnumBaseType) of named enums must support comparison in order to compute the `.max` and `.min` properties. Anonymous Enums --------------- If the enum *Identifier* is not present, then the enum is an *anonymous enum*, and the [*EnumMembers*](#EnumMembers) are declared in the scope the [*EnumDeclaration*](#EnumDeclaration) appears in. No new type is created. The *EnumMembers* can have different types. Those types are given by the first of: 1. The *Type*, if present. Types are not permitted when an [*EnumBaseType*](#EnumBaseType) is present. 2. The *EnumBaseType*, if present. 3. The type of the *AssignExpression*, if present. 4. The type of the previous *EnumMember*, if present. 5. `int` ``` enum { A, B, C } // anonymous enum ``` Defines the constants A=0, B=1, C=2, all of type `int`. Enums must have at least one member. The value of an *EnumMember* is given by its [*AssignExpression*](expression#AssignExpression). If there is no [*AssignExpression*](expression#AssignExpression) and it is the first *EnumMember*, its value is the `.init` property of the *EnumMember*'s type. If there is no [*AssignExpression*](expression#AssignExpression) and it is not the first *EnumMember*, it is given the value of the previous *EnumMember*`+1`. If the value of the previous *EnumMember* is the `.max` property if the previous *EnumMember*'s type, it is an error. If the value of the previous *EnumMember*`+1` is the same as the value of the previous *EnumMember*, it is an error. (This can happen with floating point types.) All *EnumMember*s are in scope for the [*AssignExpression*](expression#AssignExpression)s. ``` enum { A, B = 5+7, C, D = 8+C, E } ``` Sets A=0, B=12, C=13, D=21, and E=22, all of type `int`. ``` enum : long { A = 3, B } ``` Sets A=3, B=4 all of type `long`. ``` enum : string { A = "hello", B = "betty", C // error, cannot add 1 to "betty" } ``` ``` enum { A = 1.2f, // A is 1.2f of type float B, // B is 2.2f of type float int C = 3, // C is 3 of type int D // D is 4 of type int } ``` Manifest Constants ------------------ If there is only one member of an anonymous enum, the `{ }` can be omitted. Gramatically speaking, this is an [*AutoDeclaration*](declaration#AutoDeclaration). ``` enum i = 4; // i is 4 of type int enum long l = 3; // l is 3 of type long ``` Manifest constants are not lvalues, meaning their address cannot be taken. They exist only in the memory of the compiler. ``` enum size = __traits(classInstanceSize, Foo); // evaluated at compile-time ``` The initializer for a manifest constant is evaluated using compile time function evaluation. ``` template Foo(T) { // Not bad, but the 'size' variable will be located in the executable. const size_t size = T.sizeof; // evaluated at compile-time // ... use of 'size' at compile time ... } template Bar(T) { // Better, the manifest constant has no runtime location in the executable. enum size_t size = T.sizeof; // evaluated at compile-time // ... use of 'size' at compile time ... // Taking the address of Foo!T.size also causes it to go into the exe file. auto p = &Foo!T.size; } ``` d std.algorithm.sorting std.algorithm.sorting ===================== This is a submodule of [`std.algorithm`](std_algorithm). It contains generic sorting algorithms. Cheat Sheet| Function Name | Description | | [`completeSort`](#completeSort) | If `a = [10, 20, 30]` and `b = [40, 6, 15]`, then `completeSort(a, b)` leaves `a = [6, 10, 15]` and `b = [20, 30, 40]`. The range `a` must be sorted prior to the call, and as a result the combination `[std.range.chain](std_range#chain)(a, b)` is sorted. | | [`isPartitioned`](#isPartitioned) | `isPartitioned!"a < 0"([-1, -2, 1, 0, 2])` returns `true` because the predicate is `true` for a portion of the range and `false` afterwards. | | [`isSorted`](#isSorted) | `isSorted([1, 1, 2, 3])` returns `true`. | | [`isStrictlyMonotonic`](#isStrictlyMonotonic) | `isStrictlyMonotonic([1, 1, 2, 3])` returns `false`. | | [`ordered`](#ordered) | `ordered(1, 1, 2, 3)` returns `true`. | | [`strictlyOrdered`](#strictlyOrdered) | `strictlyOrdered(1, 1, 2, 3)` returns `false`. | | [`makeIndex`](#makeIndex) | Creates a separate index for a range. | | [`merge`](#merge) | Lazily merges two or more sorted ranges. | | [`multiSort`](#multiSort) | Sorts by multiple keys. | | [`nextEvenPermutation`](#nextEvenPermutation) | Computes the next lexicographically greater even permutation of a range in-place. | | [`nextPermutation`](#nextPermutation) | Computes the next lexicographically greater permutation of a range in-place. | | [`nthPermutation`](#nthPermutation) | Computes the nth permutation of a range in-place. | | [`partialSort`](#partialSort) | If `a = [5, 4, 3, 2, 1]`, then `partialSort(a, 3)` leaves `a[0 .. 3] = [1, 2, 3]`. The other elements of `a` are left in an unspecified order. | | [`partition`](#partition) | Partitions a range according to a unary predicate. | | [`partition3`](#partition3) | Partitions a range according to a binary predicate in three parts (less than, equal, greater than the given pivot). Pivot is not given as an index, but instead as an element independent from the range's content. | | [`pivotPartition`](#pivotPartition) | Partitions a range according to a binary predicate in two parts: less than or equal, and greater than or equal to the given pivot, passed as an index in the range. | | [`schwartzSort`](#schwartzSort) | Sorts with the help of the [Schwartzian transform](https://en.wikipedia.org/wiki/Schwartzian_transform). | | [`sort`](#sort) | Sorts. | | [`topN`](#topN) | Separates the top elements in a range. | | [`topNCopy`](#topNCopy) | Copies out the top elements of a range. | | [`topNIndex`](#topNIndex) | Builds an index of the top elements of a range. | License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: [Andrei Alexandrescu](http://erdani.com) Source [std/algorithm/sorting.d](https://github.com/dlang/phobos/blob/master/std/algorithm/sorting.d) alias **SortOutput** = std.typecons.Flag!"sortOutput".Flag; Specifies whether the output of certain algorithm is desired in sorted format. If set to `SortOutput.no`, the output should not be sorted. Otherwise if set to `SortOutput.yes`, the output should be sorted. void **completeSort**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Lhs, Rhs)(SortedRange!(Lhs, less) lhs, Rhs rhs) Constraints: if (hasLength!Rhs && hasSlicing!Rhs && hasSwappableElements!Lhs && hasSwappableElements!Rhs); Sorts the random-access range `chain(lhs, rhs)` according to predicate `less`. The left-hand side of the range `lhs` is assumed to be already sorted; `rhs` is assumed to be unsorted. The exact strategy chosen depends on the relative sizes of `lhs` and `rhs`. Performs Ο(`lhs.length + rhs.length * log(rhs.length)`) (best case) to Ο(`(lhs.length + rhs.length) * log(lhs.length + rhs.length)`) (worst-case) evaluations of `swap`. Parameters: | | | | --- | --- | | less | The predicate to sort by. | | ss | The swapping strategy to use. | | SortedRange!(Lhs, less) `lhs` | The sorted, left-hand side of the random access range to be sorted. | | Rhs `rhs` | The unsorted, right-hand side of the random access range to be sorted. | Examples: ``` import std.range : assumeSorted; int[] a = [ 1, 2, 3 ]; int[] b = [ 4, 0, 6, 5 ]; completeSort(assumeSorted(a), b); writeln(a); // [0, 1, 2] writeln(b); // [3, 4, 5, 6] ``` bool **isSorted**(alias less = "a < b", Range)(Range r) Constraints: if (isForwardRange!Range); bool **isStrictlyMonotonic**(alias less = "a < b", Range)(Range r) Constraints: if (isForwardRange!Range); Checks whether a [forward range](std_range_primitives#isForwardRange) is sorted according to the comparison operation `less`. Performs Ο(`r.length`) evaluations of `less`. Unlike `isSorted`, `isStrictlyMonotonic` does not allow for equal values, i.e. values for which both `less(a, b)` and `less(b, a)` are false. With either function, the predicate must be a strict ordering just like with `isSorted`. For example, using `"a <= b"` instead of `"a < b"` is incorrect and will cause failed assertions. Parameters: | | | | --- | --- | | less | Predicate the range should be sorted by. | | Range `r` | Forward range to check for sortedness. | Returns: `true` if the range is sorted, false otherwise. `isSorted` allows duplicates, `isStrictlyMonotonic` not. Examples: ``` assert([1, 1, 2].isSorted); // strictly monotonic doesn't allow duplicates assert(![1, 1, 2].isStrictlyMonotonic); int[] arr = [4, 3, 2, 1]; assert(!isSorted(arr)); assert(!isStrictlyMonotonic(arr)); assert(isSorted!"a > b"(arr)); assert(isStrictlyMonotonic!"a > b"(arr)); sort(arr); assert(isSorted(arr)); assert(isStrictlyMonotonic(arr)); ``` bool **ordered**(alias less = "a < b", T...)(T values) Constraints: if (T.length == 2 && is(typeof(binaryFun!less(values[1], values[0])) : bool) || T.length > 2 && is(typeof(ordered!less(values[0..1 + $ / 2]))) && is(typeof(ordered!less(values[$ / 2..$])))); bool **strictlyOrdered**(alias less = "a < b", T...)(T values) Constraints: if (is(typeof(ordered!less(values)))); Like `isSorted`, returns `true` if the given `values` are ordered according to the comparison operation `less`. Unlike `isSorted`, takes values directly instead of structured in a range. `ordered` allows repeated values, e.g. `ordered(1, 1, 2)` is `true`. To verify that the values are ordered strictly monotonically, use `strictlyOrdered`; `strictlyOrdered(1, 1, 2)` is `false`. With either function, the predicate must be a strict ordering. For example, using `"a <= b"` instead of `"a < b"` is incorrect and will cause failed assertions. Parameters: | | | | --- | --- | | T `values` | The tested value | | less | The comparison predicate | Returns: `true` if the values are ordered; `ordered` allows for duplicates, `strictlyOrdered` does not. Examples: ``` assert(ordered(42, 42, 43)); assert(!strictlyOrdered(43, 42, 45)); assert(ordered(42, 42, 43)); assert(!strictlyOrdered(42, 42, 43)); assert(!ordered(43, 42, 45)); // Ordered lexicographically assert(ordered("Jane", "Jim", "Joe")); assert(strictlyOrdered("Jane", "Jim", "Joe")); // Incidentally also ordered by length decreasing assert(ordered!((a, b) => a.length > b.length)("Jane", "Jim", "Joe")); // ... but not strictly so: "Jim" and "Joe" have the same length assert(!strictlyOrdered!((a, b) => a.length > b.length)("Jane", "Jim", "Joe")); ``` Range **partition**(alias predicate, SwapStrategy ss, Range)(Range r) Constraints: if (ss == SwapStrategy.stable && isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && hasSwappableElements!Range); Range **partition**(alias predicate, SwapStrategy ss = SwapStrategy.unstable, Range)(Range r) Constraints: if (ss != SwapStrategy.stable && isInputRange!Range && hasSwappableElements!Range); Partitions a range in two using the given `predicate`. Specifically, reorders the range `r = [left, right)` using `swap` such that all elements `i` for which `predicate(i)` is `true` come before all elements `j` for which `predicate(j)` returns `false`. Performs Ο(`r.length`) (if unstable or semistable) or Ο(`r.length * log(r.length)`) (if stable) evaluations of `less` and `swap`. The unstable version computes the minimum possible evaluations of `swap` (roughly half of those performed by the semistable version). Parameters: | | | | --- | --- | | predicate | The predicate to partition by. | | ss | The swapping strategy to employ. | | Range `r` | The random-access range to partition. | Returns: The right part of `r` after partitioning. If `ss == SwapStrategy.stable`, `partition` preserves the relative ordering of all elements `a`, `b` in `r` for which `predicate(a) == predicate(b)`. If `ss == SwapStrategy.semistable`, `partition` preserves the relative ordering of all elements `a`, `b` in the left part of `r` for which `predicate(a) == predicate(b)`. Examples: ``` import std.algorithm.mutation : SwapStrategy; import std.algorithm.searching : count, find; import std.conv : text; import std.range.primitives : empty; auto Arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; auto arr = Arr.dup; static bool even(int a) { return (a & 1) == 0; } // Partition arr such that even numbers come first auto r = partition!(even)(arr); // Now arr is separated in evens and odds. // Numbers may have become shuffled due to instability writeln(r); // arr[5 .. &dollar;] writeln(count!(even)(arr[0 .. 5])); // 5 assert(find!(even)(r).empty); // Can also specify the predicate as a string. // Use 'a' as the predicate argument name arr[] = Arr[]; r = partition!(q{(a & 1) == 0})(arr); writeln(r); // arr[5 .. &dollar;] // Now for a stable partition: arr[] = Arr[]; r = partition!(q{(a & 1) == 0}, SwapStrategy.stable)(arr); // Now arr is [2 4 6 8 10 1 3 5 7 9], and r points to 1 assert(arr == [2, 4, 6, 8, 10, 1, 3, 5, 7, 9] && r == arr[5 .. $]); // In case the predicate needs to hold its own state, use a delegate: arr[] = Arr[]; int x = 3; // Put stuff greater than 3 on the left bool fun(int a) { return a > x; } r = partition!(fun, SwapStrategy.semistable)(arr); // Now arr is [4 5 6 7 8 9 10 2 3 1] and r points to 2 assert(arr == [4, 5, 6, 7, 8, 9, 10, 2, 3, 1] && r == arr[7 .. $]); ``` size\_t **pivotPartition**(alias less = "a < b", Range)(Range r, size\_t pivot) Constraints: if (isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && hasAssignableElements!Range); Partitions `r` around `pivot` using comparison function `less`, algorithm akin to [Hoare partition](https://en.wikipedia.org/wiki/Quicksort#Hoare_partition_scheme). Specifically, permutes elements of `r` and returns an index `k < r.length` such that: * `r[pivot]` is swapped to `r[k]` * All elements `e` in subrange `r[0 .. k]` satisfy `!less(r[k], e)` (i.e. `r[k]` is greater than or equal to each element to its left according to predicate `less`) * All elements `e` in subrange `r[k .. $]` satisfy `!less(e, r[k])` (i.e. `r[k]` is less than or equal to each element to its right according to predicate `less`) If `r` contains equivalent elements, multiple permutations of `r` satisfy these constraints. In such cases, `pivotPartition` attempts to distribute equivalent elements fairly to the left and right of `k` such that `k` stays close to `r.length / 2`. Parameters: | | | | --- | --- | | less | The predicate used for comparison, modeled as a [strict weak ordering](https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings) (irreflexive, antisymmetric, transitive, and implying a transitive equivalence) | | Range `r` | The range being partitioned | | size\_t `pivot` | The index of the pivot for partitioning, must be less than `r.length` or `0` if `r.length` is `0` | Returns: The new position of the pivot See Also: [Engineering of a Quicksort Partitioning Algorithm](http://jgrcs.info/index.php/jgrcs/article/view/142), D. Abhyankar, Journal of Global Research in Computer Science, February 2011. [ACCU 2016 Keynote](https://youtube.com/watch?v=AxnotgLql0k), Andrei Alexandrescu. Examples: ``` int[] a = [5, 3, 2, 6, 4, 1, 3, 7]; size_t pivot = pivotPartition(a, a.length / 2); import std.algorithm.searching : all; assert(a[0 .. pivot].all!(x => x <= a[pivot])); assert(a[pivot .. $].all!(x => x >= a[pivot])); ``` bool **isPartitioned**(alias pred, Range)(Range r) Constraints: if (isForwardRange!Range); Parameters: | | | | --- | --- | | pred | The predicate that the range should be partitioned by. | | Range `r` | The range to check. | Returns: `true` if `r` is partitioned according to predicate `pred`. Examples: ``` int[] r = [ 1, 3, 5, 7, 8, 2, 4, ]; assert(isPartitioned!"a & 1"(r)); ``` auto **partition3**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, E)(Range r, E pivot) Constraints: if (ss == SwapStrategy.unstable && isRandomAccessRange!Range && hasSwappableElements!Range && hasLength!Range && hasSlicing!Range && is(typeof(binaryFun!less(r.front, pivot)) == bool) && is(typeof(binaryFun!less(pivot, r.front)) == bool) && is(typeof(binaryFun!less(r.front, r.front)) == bool)); Rearranges elements in `r` in three adjacent ranges and returns them. The first and leftmost range only contains elements in `r` less than `pivot`. The second and middle range only contains elements in `r` that are equal to `pivot`. Finally, the third and rightmost range only contains elements in `r` that are greater than `pivot`. The less-than test is defined by the binary function `less`. Parameters: | | | | --- | --- | | less | The predicate to use for the rearrangement. | | ss | The swapping strategy to use. | | Range `r` | The random-access range to rearrange. | | E `pivot` | The pivot element. | Returns: A [`std.typecons.Tuple`](std_typecons#Tuple) of the three resulting ranges. These ranges are slices of the original range. Bugs: stable `partition3` has not been implemented yet. Examples: ``` auto a = [ 8, 3, 4, 1, 4, 7, 4 ]; auto pieces = partition3(a, 4); writeln(pieces[0]); // [1, 3] writeln(pieces[1]); // [4, 4, 4] writeln(pieces[2]); // [8, 7] ``` SortedRange!(RangeIndex, (a, b) => binaryFun!less(\*a, \*b)) **makeIndex**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, RangeIndex)(Range r, RangeIndex index) Constraints: if (isForwardRange!Range && isRandomAccessRange!RangeIndex && is(ElementType!RangeIndex : ElementType!Range\*) && hasAssignableElements!RangeIndex); void **makeIndex**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, RangeIndex)(Range r, RangeIndex index) Constraints: if (isRandomAccessRange!Range && !isInfinite!Range && isRandomAccessRange!RangeIndex && !isInfinite!RangeIndex && isIntegral!(ElementType!RangeIndex) && hasAssignableElements!RangeIndex); Computes an index for `r` based on the comparison `less`. The index is a sorted array of pointers or indices into the original range. This technique is similar to sorting, but it is more flexible because (1) it allows "sorting" of immutable collections, (2) allows binary search even if the original collection does not offer random access, (3) allows multiple indexes, each on a different predicate, and (4) may be faster when dealing with large objects. However, using an index may also be slower under certain circumstances due to the extra indirection, and is always larger than a sorting-based solution because it needs space for the index in addition to the original collection. The complexity is the same as `sort`'s. The first overload of `makeIndex` writes to a range containing pointers, and the second writes to a range containing offsets. The first overload requires `Range` to be a [forward range](std_range_primitives#isForwardRange), and the latter requires it to be a random-access range. `makeIndex` overwrites its second argument with the result, but never reallocates it. Parameters: | | | | --- | --- | | less | The comparison to use. | | ss | The swapping strategy. | | Range `r` | The range to index. | | RangeIndex `index` | The resulting index. | Returns: The pointer-based version returns a `SortedRange` wrapper over index, of type `SortedRange!(RangeIndex, (a, b) => binaryFun!less(*a, *b))` thus reflecting the ordering of the index. The index-based version returns `void` because the ordering relation involves not only `index` but also `r`. Throws: If the second argument's length is less than that of the range indexed, an exception is thrown. Examples: ``` immutable(int[]) arr = [ 2, 3, 1, 5, 0 ]; // index using pointers auto index1 = new immutable(int)*[arr.length]; makeIndex!("a < b")(arr, index1); assert(isSorted!("*a < *b")(index1)); // index using offsets auto index2 = new size_t[arr.length]; makeIndex!("a < b")(arr, index2); assert(isSorted! ((size_t a, size_t b){ return arr[a] < arr[b];}) (index2)); ``` Merge!(less, Rs) **merge**(alias less = "a < b", Rs...)(Rs rs) Constraints: if (Rs.length >= 2 && allSatisfy!(isInputRange, Rs) && !is(CommonType!(staticMap!(ElementType, Rs)) == void)); Merge multiple sorted ranges `rs` with less-than predicate function `pred` into one single sorted output range containing the sorted union of the elements of inputs. Duplicates are not eliminated, meaning that the total number of elements in the output is the sum of all elements in the ranges passed to it; the `length` member is offered if all inputs also have `length`. The element types of all the inputs must have a common type `CommonType`. Parameters: | | | | --- | --- | | less | Predicate the given ranges are sorted by. | | Rs `rs` | The ranges to compute the union for. | Returns: A range containing the union of the given ranges. Details All of its inputs are assumed to be sorted. This can mean that inputs are instances of [`std.range.SortedRange`](std_range#SortedRange). Use the result of [`std.algorithm.sorting.sort`](std_algorithm_sorting#sort), or [`std.range.assumeSorted`](std_range#assumeSorted) to merge ranges known to be sorted (show in the example below). Note that there is currently no way of ensuring that two or more instances of [`std.range.SortedRange`](std_range#SortedRange) are sorted using a specific comparison function `pred`. Therefore no checking is done here to assure that all inputs `rs` are instances of [`std.range.SortedRange`](std_range#SortedRange). This algorithm is lazy, doing work progressively as elements are pulled off the result. Time complexity is proportional to the sum of element counts over all inputs. If all inputs have the same element type and offer it by `ref`, output becomes a range with mutable `front` (and `back` where appropriate) that reflects in the original inputs. If any of the inputs `rs` is infinite so is the result (`empty` being always `false`). See Also: [`std.algorithm.setops.multiwayMerge`](std_algorithm_setops#multiwayMerge) for an analogous function that merges a dynamic number of ranges. Examples: ``` import std.algorithm.comparison : equal; import std.range : retro; int[] a = [1, 3, 5]; int[] b = [2, 3, 4]; assert(a.merge(b).equal([1, 2, 3, 3, 4, 5])); assert(a.merge(b).retro.equal([5, 4, 3, 3, 2, 1])); ``` Examples: test bi-directional access and common type ``` import std.algorithm.comparison : equal; import std.range : retro; import std.traits : CommonType; alias S = short; alias I = int; alias D = double; S[] a = [1, 2, 3]; I[] b = [50, 60]; D[] c = [10, 20, 30, 40]; auto m = merge(a, b, c); static assert(is(typeof(m.front) == CommonType!(S, I, D))); assert(equal(m, [1, 2, 3, 10, 20, 30, 40, 50, 60])); assert(equal(m.retro, [60, 50, 40, 30, 20, 10, 3, 2, 1])); m.popFront(); assert(equal(m, [2, 3, 10, 20, 30, 40, 50, 60])); m.popBack(); assert(equal(m, [2, 3, 10, 20, 30, 40, 50])); m.popFront(); assert(equal(m, [3, 10, 20, 30, 40, 50])); m.popBack(); assert(equal(m, [3, 10, 20, 30, 40])); m.popFront(); assert(equal(m, [10, 20, 30, 40])); m.popBack(); assert(equal(m, [10, 20, 30])); m.popFront(); assert(equal(m, [20, 30])); m.popBack(); assert(equal(m, [20])); m.popFront(); assert(m.empty); ``` template **multiSort**(less...) Sorts a range by multiple keys. The call `multiSort!("a.id < b.id", "a.date > b.date")(r)` sorts the range `r` by `id` ascending, and sorts elements that have the same `id` by `date` descending. Such a call is equivalent to `sort!"a.id != b.id ? a.id < b.id : a.date > b.date"(r)`, but `multiSort` is faster because it does fewer comparisons (in addition to being more convenient). Returns: The initial range wrapped as a `SortedRange` with its predicates converted to an equivalent single predicate. Examples: ``` import std.algorithm.mutation : SwapStrategy; static struct Point { int x, y; } auto pts1 = [ Point(0, 0), Point(5, 5), Point(0, 1), Point(0, 2) ]; auto pts2 = [ Point(0, 0), Point(0, 1), Point(0, 2), Point(5, 5) ]; multiSort!("a.x < b.x", "a.y < b.y", SwapStrategy.unstable)(pts1); writeln(pts1); // pts2 ``` SortedRange!(Range, less) **sort**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r) Constraints: if ((ss == SwapStrategy.unstable && (hasSwappableElements!Range || hasAssignableElements!Range) || ss != SwapStrategy.unstable && hasAssignableElements!Range) && isRandomAccessRange!Range && hasSlicing!Range && hasLength!Range); Sorts a random-access range according to the predicate `less`. Performs Ο(`r.length * log(r.length)`) evaluations of `less`. If `less` involves expensive computations on the sort key, it may be worthwhile to use [`schwartzSort`](#schwartzSort) instead. Stable sorting requires `hasAssignableElements!Range` to be true. `sort` returns a [`std.range.SortedRange`](std_range#SortedRange) over the original range, allowing functions that can take advantage of sorted data to know that the range is sorted and adjust accordingly. The [`std.range.SortedRange`](std_range#SortedRange) is a wrapper around the original range, so both it and the original range are sorted. Other functions can't know that the original range has been sorted, but they *can* know that [`std.range.SortedRange`](std_range#SortedRange) has been sorted. Preconditions The predicate is expected to satisfy certain rules in order for `sort` to behave as expected - otherwise, the program may fail on certain inputs (but not others) when not compiled in release mode, due to the cursory `assumeSorted` check. Specifically, `sort` expects `less(a,b) && less(b,c)` to imply `less(a,c)` (transitivity), and, conversely, `!less(a,b) && !less(b,c)` to imply `!less(a,c)`. Note that the default predicate (`"a < b"`) does not always satisfy these conditions for floating point types, because the expression will always be `false` when either `a` or `b` is NaN. Use [`std.math.cmp`](std_math#cmp) instead. Parameters: | | | | --- | --- | | less | The predicate to sort by. | | ss | The swapping strategy to use. | | Range `r` | The range to sort. | Returns: The initial range wrapped as a `SortedRange` with the predicate `binaryFun!less`. Algorithms [Introsort](http://en.wikipedia.org/wiki/Introsort) is used for unstable sorting and [Timsort](http://en.wikipedia.org/wiki/Timsort) is used for stable sorting. Each algorithm has benefits beyond stability. Introsort is generally faster but Timsort may achieve greater speeds on data with low entropy or if predicate calls are expensive. Introsort performs no allocations whereas Timsort will perform one or more allocations per call. Both algorithms have Ο(`n log n`) worst-case time complexity. See Also: [`std.range.assumeSorted`](std_range#assumeSorted) [`std.range.SortedRange`](std_range#SortedRange) [`std.algorithm.mutation.SwapStrategy`](std_algorithm_mutation#SwapStrategy) [`std.functional.binaryFun`](std_functional#binaryFun) Examples: ``` int[] array = [ 1, 2, 3, 4 ]; // sort in descending order array.sort!("a > b"); writeln(array); // [4, 3, 2, 1] // sort in ascending order array.sort(); writeln(array); // [1, 2, 3, 4] // sort with reusable comparator and chain alias myComp = (x, y) => x > y; writeln(array.sort!(myComp).release); // [4, 3, 2, 1] ``` Examples: ``` // Showcase stable sorting import std.algorithm.mutation : SwapStrategy; string[] words = [ "aBc", "a", "abc", "b", "ABC", "c" ]; sort!("toUpper(a) < toUpper(b)", SwapStrategy.stable)(words); writeln(words); // ["a", "aBc", "abc", "ABC", "b", "c"] ``` Examples: ``` // Sorting floating-point numbers in presence of NaN double[] numbers = [-0.0, 3.0, -2.0, double.nan, 0.0, -double.nan]; import std.algorithm.comparison : equal; import std.math : cmp, isIdentical; sort!((a, b) => cmp(a, b) < 0)(numbers); double[] sorted = [-double.nan, -2.0, -0.0, 0.0, 3.0, double.nan]; assert(numbers.equal!isIdentical(sorted)); ``` SortedRange!(R, (a, b) => binaryFun!less(unaryFun!transform(a), unaryFun!transform(b))) **schwartzSort**(alias transform, alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, R)(R r) Constraints: if (isRandomAccessRange!R && hasLength!R && hasSwappableElements!R && !is(typeof(binaryFun!less) == SwapStrategy)); auto **schwartzSort**(alias transform, SwapStrategy ss, R)(R r) Constraints: if (isRandomAccessRange!R && hasLength!R && hasSwappableElements!R); Alternative sorting method that should be used when comparing keys involves an expensive computation. Instead of using `less(a, b)` for comparing elements, `schwartzSort` uses `less(transform(a), transform(b))`. The values of the `transform` function are precomputed in a temporary array, thus saving on repeatedly computing it. Conversely, if the cost of `transform` is small compared to the cost of allocating and filling the precomputed array, `sort` may be faster and therefore preferable. This approach to sorting is akin to the [Schwartzian transform](http://wikipedia.org/wiki/Schwartzian_transform), also known as the decorate-sort-undecorate pattern in Python and Lisp. The complexity is the same as that of the corresponding `sort`, but `schwartzSort` evaluates `transform` only `r.length` times (less than half when compared to regular sorting). The usage can be best illustrated with an example. Example ``` uint hashFun(string) { ... expensive computation ... } string[] array = ...; // Sort strings by hash, slow sort!((a, b) => hashFun(a) < hashFun(b))(array); // Sort strings by hash, fast (only computes arr.length hashes): schwartzSort!(hashFun, "a < b")(array); ``` The `schwartzSort` function might require less temporary data and be faster than the Perl idiom or the decorate-sort-undecorate idiom present in Python and Lisp. This is because sorting is done in-place and only minimal extra data (one array of transformed elements) is created. To check whether an array was sorted and benefit of the speedup of Schwartz sorting, a function `schwartzIsSorted` is not provided because the effect can be achieved by calling `isSorted!less(map!transform(r))`. Parameters: | | | | --- | --- | | transform | The transformation to apply. Either a unary function (`unaryFun!transform(element)`), or a binary function (`binaryFun!transform(element, index)`). | | less | The predicate to sort the transformed elements by. | | ss | The swapping strategy to use. | | R `r` | The range to sort. | Returns: The initial range wrapped as a `SortedRange` with the predicate `(a, b) => binaryFun!less(transform(a), transform(b))`. Examples: ``` import std.algorithm.iteration : map; import std.numeric : entropy; auto lowEnt = [ 1.0, 0, 0 ], midEnt = [ 0.1, 0.1, 0.8 ], highEnt = [ 0.31, 0.29, 0.4 ]; auto arr = new double[][3]; arr[0] = midEnt; arr[1] = lowEnt; arr[2] = highEnt; schwartzSort!(entropy, "a > b")(arr); writeln(arr[0]); // highEnt writeln(arr[1]); // midEnt writeln(arr[2]); // lowEnt assert(isSorted!("a > b")(map!(entropy)(arr))); ``` void **partialSort**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r, size\_t n) Constraints: if (isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range); Reorders the random-access range `r` such that the range `r[0 .. mid]` is the same as if the entire `r` were sorted, and leaves the range `r[mid .. r.length]` in no particular order. Performs Ο(`r.length * log(mid)`) evaluations of `pred`. The implementation simply calls `topN!(less, ss)(r, n)` and then `sort!(less, ss)(r[0 .. n])`. Parameters: | | | | --- | --- | | less | The predicate to sort by. | | ss | The swapping strategy to use. | | Range `r` | The random-access range to reorder. | | size\_t `n` | The length of the initial segment of `r` to sort. | Examples: ``` int[] a = [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ]; partialSort(a, 5); writeln(a[0 .. 5]); // [0, 1, 2, 3, 4] ``` void **partialSort**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range1, Range2)(Range1 r1, Range2 r2) Constraints: if (isRandomAccessRange!Range1 && hasLength!Range1 && isInputRange!Range2 && is(ElementType!Range1 == ElementType!Range2) && hasLvalueElements!Range1 && hasLvalueElements!Range2); Stores the smallest elements of the two ranges in the left-hand range in sorted order. Parameters: | | | | --- | --- | | less | The predicate to sort by. | | ss | The swapping strategy to use. | | Range1 `r1` | The first range. | | Range2 `r2` | The second range. | Examples: ``` int[] a = [5, 7, 2, 6, 7]; int[] b = [2, 1, 5, 6, 7, 3, 0]; partialSort(a, b); writeln(a); // [0, 1, 2, 2, 3] ``` auto **topN**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r, size\_t nth) Constraints: if (isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && hasAssignableElements!Range); Reorders the range `r` using `swap` such that `r[nth]` refers to the element that would fall there if the range were fully sorted. In addition, it also partitions `r` such that all elements `e1` from `r[0]` to `r[nth]` satisfy `!less(r[nth], e1)`, and all elements `e2` from `r[nth]` to `r[r.length]` satisfy `!less(e2, r[nth])`. Effectively, it finds the nth smallest (according to `less`) elements in `r`. Performs an expected Ο(`r.length`) (if unstable) or Ο(`r.length * log(r.length)`) (if stable) evaluations of `less` and `swap`. If `n >= r.length`, the algorithm has no effect and returns `r[0 .. r.length]`. Parameters: | | | | --- | --- | | less | The predicate to sort by. | | ss | The swapping strategy to use. | | Range `r` | The random-access range to reorder. | | size\_t `nth` | The index of the element that should be in sorted position after the function is done. | See Also: [`topNIndex`](#topNIndex), Bugs: Stable topN has not been implemented yet. Examples: ``` int[] v = [ 25, 7, 9, 2, 0, 5, 21 ]; topN!"a < b"(v, 100); writeln(v); // [25, 7, 9, 2, 0, 5, 21] auto n = 4; topN!((a, b) => a < b)(v, n); writeln(v[n]); // 9 ``` auto **topN**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range1, Range2)(Range1 r1, Range2 r2) Constraints: if (isRandomAccessRange!Range1 && hasLength!Range1 && isInputRange!Range2 && is(ElementType!Range1 == ElementType!Range2) && hasLvalueElements!Range1 && hasLvalueElements!Range2); Stores the smallest elements of the two ranges in the left-hand range. Parameters: | | | | --- | --- | | less | The predicate to sort by. | | ss | The swapping strategy to use. | | Range1 `r1` | The first range. | | Range2 `r2` | The second range. | Examples: ``` int[] a = [ 5, 7, 2, 6, 7 ]; int[] b = [ 2, 1, 5, 6, 7, 3, 0 ]; topN(a, b); sort(a); writeln(a); // [0, 1, 2, 2, 3] ``` TRange **topNCopy**(alias less = "a < b", SRange, TRange)(SRange source, TRange target, SortOutput sorted = No.sortOutput) Constraints: if (isInputRange!SRange && isRandomAccessRange!TRange && hasLength!TRange && hasSlicing!TRange); Copies the top `n` elements of the [input range](std_range_primitives#isInputRange) `source` into the random-access range `target`, where `n = target.length`. Elements of `source` are not touched. If `sorted` is `true`, the target is sorted. Otherwise, the target respects the [heap property](http://en.wikipedia.org/wiki/Binary_heap). Parameters: | | | | --- | --- | | less | The predicate to sort by. | | SRange `source` | The source range. | | TRange `target` | The target range. | | SortOutput `sorted` | Whether to sort the elements copied into `target`. | Returns: The slice of `target` containing the copied elements. Examples: ``` import std.typecons : Yes; int[] a = [ 10, 16, 2, 3, 1, 5, 0 ]; int[] b = new int[3]; topNCopy(a, b, Yes.sortOutput); writeln(b); // [0, 1, 2] ``` void **topNIndex**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, RangeIndex)(Range r, RangeIndex index, SortOutput sorted = No.sortOutput) Constraints: if (isRandomAccessRange!Range && isRandomAccessRange!RangeIndex && hasAssignableElements!RangeIndex); Given a range of elements, constructs an index of its top *n* elements (i.e., the first *n* elements if the range were sorted). Similar to [`topN`](#topN), except that the range is not modified. Parameters: | | | | --- | --- | | less | A binary predicate that defines the ordering of range elements. Defaults to `a < b`. | | ss | (Not implemented yet.) Specify the swapping strategy. | | Range `r` | A [random-access range](std_range_primitives#isRandomAccessRange) of elements to make an index for. | | RangeIndex `index` | A [random-access range](std_range_primitives#isRandomAccessRange) with assignable elements to build the index in. The length of this range determines how many top elements to index in `r`. This index range can either have integral elements, in which case the constructed index will consist of zero-based numerical indices into `r`; or it can have pointers to the element type of `r`, in which case the constructed index will be pointers to the top elements in `r`. | | SortOutput `sorted` | Determines whether to sort the index by the elements they refer to. | See Also: [`topN`](#topN), [`topNCopy`](#topNCopy). Bugs: The swapping strategy parameter is not implemented yet; currently it is ignored. Examples: ``` import std.typecons : Yes; // Construct index to top 3 elements using numerical indices: int[] a = [ 10, 2, 7, 5, 8, 1 ]; int[] index = new int[3]; topNIndex(a, index, Yes.sortOutput); assert(index == [5, 1, 3]); // because a[5]==1, a[1]==2, a[3]==5 // Construct index to top 3 elements using pointer indices: int*[] ptrIndex = new int*[3]; topNIndex(a, ptrIndex, Yes.sortOutput); writeln(ptrIndex); // [&a[5], &a[1], &a[3]] ``` bool **nextPermutation**(alias less = "a < b", BidirectionalRange)(BidirectionalRange range) Constraints: if (isBidirectionalRange!BidirectionalRange && hasSwappableElements!BidirectionalRange); Permutes `range` in-place to the next lexicographically greater permutation. The predicate `less` defines the lexicographical ordering to be used on the range. If the range is currently the lexicographically greatest permutation, it is permuted back to the least permutation and false is returned. Otherwise, true is returned. One can thus generate all permutations of a range by sorting it according to `less`, which produces the lexicographically least permutation, and then calling nextPermutation until it returns false. This is guaranteed to generate all distinct permutations of the range exactly once. If there are *N* elements in the range and all of them are unique, then *N*! permutations will be generated. Otherwise, if there are some duplicated elements, fewer permutations will be produced. ``` // Enumerate all permutations int[] a = [1,2,3,4,5]; do { // use the current permutation and // proceed to the next permutation of the array. } while (nextPermutation(a)); ``` Parameters: | | | | --- | --- | | less | The ordering to be used to determine lexicographical ordering of the permutations. | | BidirectionalRange `range` | The range to permute. | Returns: false if the range was lexicographically the greatest, in which case the range is reversed back to the lexicographically smallest permutation; otherwise returns true. See Also: [`std.algorithm.iteration.permutations`](std_algorithm_iteration#permutations). Examples: ``` // Step through all permutations of a sorted array in lexicographic order int[] a = [1,2,3]; writeln(nextPermutation(a)); // true writeln(a); // [1, 3, 2] writeln(nextPermutation(a)); // true writeln(a); // [2, 1, 3] writeln(nextPermutation(a)); // true writeln(a); // [2, 3, 1] writeln(nextPermutation(a)); // true writeln(a); // [3, 1, 2] writeln(nextPermutation(a)); // true writeln(a); // [3, 2, 1] writeln(nextPermutation(a)); // false writeln(a); // [1, 2, 3] ``` Examples: ``` // Step through permutations of an array containing duplicate elements: int[] a = [1,1,2]; writeln(nextPermutation(a)); // true writeln(a); // [1, 2, 1] writeln(nextPermutation(a)); // true writeln(a); // [2, 1, 1] writeln(nextPermutation(a)); // false writeln(a); // [1, 1, 2] ``` bool **nextEvenPermutation**(alias less = "a < b", BidirectionalRange)(BidirectionalRange range) Constraints: if (isBidirectionalRange!BidirectionalRange && hasSwappableElements!BidirectionalRange); Permutes `range` in-place to the next lexicographically greater *even* permutation. The predicate `less` defines the lexicographical ordering to be used on the range. An even permutation is one which is produced by swapping an even number of pairs of elements in the original range. The set of *even* permutations is distinct from the set of *all* permutations only when there are no duplicate elements in the range. If the range has *N* unique elements, then there are exactly *N*!/2 even permutations. If the range is already the lexicographically greatest even permutation, it is permuted back to the least even permutation and false is returned. Otherwise, true is returned, and the range is modified in-place to be the lexicographically next even permutation. One can thus generate the even permutations of a range with unique elements by starting with the lexicographically smallest permutation, and repeatedly calling nextEvenPermutation until it returns false. ``` // Enumerate even permutations int[] a = [1,2,3,4,5]; do { // use the current permutation and // proceed to the next even permutation of the array. } while (nextEvenPermutation(a)); ``` One can also generate the *odd* permutations of a range by noting that permutations obey the rule that even + even = even, and odd + even = odd. Thus, by swapping the last two elements of a lexicographically least range, it is turned into the first odd permutation. Then calling nextEvenPermutation on this first odd permutation will generate the next even permutation relative to this odd permutation, which is actually the next odd permutation of the original range. Thus, by repeatedly calling nextEvenPermutation until it returns false, one enumerates the odd permutations of the original range. ``` // Enumerate odd permutations int[] a = [1,2,3,4,5]; swap(a[$-2], a[$-1]); // a is now the first odd permutation of [1,2,3,4,5] do { // use the current permutation and // proceed to the next odd permutation of the original array // (which is an even permutation of the first odd permutation). } while (nextEvenPermutation(a)); ``` Warning Since even permutations are only distinct from all permutations when the range elements are unique, this function assumes that there are no duplicate elements under the specified ordering. If this is not true, some permutations may fail to be generated. When the range has non-unique elements, you should use [*nextPermutation*](#nextPermutation) instead. Parameters: | | | | --- | --- | | less | The ordering to be used to determine lexicographical ordering of the permutations. | | BidirectionalRange `range` | The range to permute. | Returns: false if the range was lexicographically the greatest, in which case the range is reversed back to the lexicographically smallest permutation; otherwise returns true. Examples: ``` // Step through even permutations of a sorted array in lexicographic order int[] a = [1,2,3]; writeln(nextEvenPermutation(a)); // true writeln(a); // [2, 3, 1] writeln(nextEvenPermutation(a)); // true writeln(a); // [3, 1, 2] writeln(nextEvenPermutation(a)); // false writeln(a); // [1, 2, 3] ``` Examples: Even permutations are useful for generating coordinates of certain geometric shapes. Here's a non-trivial example: ``` import std.math : sqrt; // Print the 60 vertices of a uniform truncated icosahedron (soccer ball) enum real Phi = (1.0 + sqrt(5.0)) / 2.0; // Golden ratio real[][] seeds = [ [0.0, 1.0, 3.0*Phi], [1.0, 2.0+Phi, 2.0*Phi], [Phi, 2.0, Phi^^3] ]; size_t n; foreach (seed; seeds) { // Loop over even permutations of each seed do { // Loop over all sign changes of each permutation size_t i; do { // Generate all possible sign changes for (i=0; i < seed.length; i++) { if (seed[i] != 0.0) { seed[i] = -seed[i]; if (seed[i] < 0.0) break; } } n++; } while (i < seed.length); } while (nextEvenPermutation(seed)); } writeln(n); // 60 ``` ref Range **nthPermutation**(Range)(auto ref Range range, const ulong perm) Constraints: if (isRandomAccessRange!Range && hasLength!Range); Permutes `range` into the `perm` permutation. The algorithm has a constant runtime complexity with respect to the number of permutations created. Due to the number of unique values of `ulong` only the first 21 elements of `range` can be permuted. The rest of the range will therefore not be permuted. This algorithm uses the [Lehmer Code](http://en.wikipedia.org/wiki/Lehmer_code). The algorithm works as follows: ``` auto pem = [4,0,4,1,0,0,0]; // permutation 2982 in factorial auto src = [0,1,2,3,4,5,6]; // the range to permutate auto i = 0; // range index // range index iterates pem and src in sync // pem[i] + i is used as index into src // first src[pem[i] + i] is stored in t auto t = 4; // tmp value src = [0,1,2,3,n,5,6]; // then the values between i and pem[i] + i are moved one // to the right src = [n,0,1,2,3,5,6]; // at last t is inserted into position i src = [4,0,1,2,3,5,6]; // finally i is incremented ++i; // this process is repeated while i < pem.length t = 0; src = [4,n,1,2,3,5,6]; src = [4,0,1,2,3,5,6]; ++i; t = 6; src = [4,0,1,2,3,5,n]; src = [4,0,n,1,2,3,5]; src = [4,0,6,1,2,3,5]; ``` Returns: The permuted range. Parameters: | | | | --- | --- | | Range `range` | The Range to permute. The original ordering will be lost. | | ulong `perm` | The permutation to permutate `range` to. | Examples: ``` auto src = [0, 1, 2, 3, 4, 5, 6]; auto rslt = [4, 0, 6, 2, 1, 3, 5]; src = nthPermutation(src, 2982); writeln(src); // rslt ``` bool **nthPermutationImpl**(Range)(auto ref Range range, ulong perm) Constraints: if (isRandomAccessRange!Range && hasLength!Range); Returns: `true` in case the permutation worked, `false` in case `perm` had more digits in the factorial number system than range had elements. This case must not occur as this would lead to out of range accesses. Examples: ``` auto src = [0, 1, 2, 3, 4, 5, 6]; auto rslt = [4, 0, 6, 2, 1, 3, 5]; bool worked = nthPermutationImpl(src, 2982); assert(worked); writeln(src); // rslt ```
programming_docs
d std.variant std.variant =========== This module implements a [discriminated union](http://erdani.org/publications/cuj-04-2002.php.html) type (a.k.a. [tagged union](http://en.wikipedia.org/wiki/Tagged_union), [algebraic type](http://en.wikipedia.org/wiki/Algebraic_data_type)). Such types are useful for type-uniform binary interfaces, interfacing with scripting languages, and comfortable exploratory programming. A [`Variant`](#Variant) object can hold a value of any type, with very few restrictions (such as `shared` types and noncopyable types). Setting the value is as immediate as assigning to the `Variant` object. To read back the value of the appropriate type `T`, use the [`get`](#get) method. To query whether a `Variant` currently holds a value of type `T`, use [`peek`](#peek). To fetch the exact type currently held, call [`type`](#type), which returns the `TypeInfo` of the current value. In addition to [`Variant`](#Variant), this module also defines the [`Algebraic`](#Algebraic) type constructor. Unlike `Variant`, `Algebraic` only allows a finite set of types, which are specified in the instantiation (e.g. `Algebraic!(int, string)` may only hold an `int` or a `string`). Credits Reviewed by Brad Roberts. Daniel Keep provided a detailed code review prompting the following improvements: (1) better support for arrays; (2) support for associative arrays; (3) friendlier behavior towards the garbage collector. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Andrei Alexandrescu](http://erdani.org) Source [std/variant.d](https://github.com/dlang/phobos/blob/master/std/variant.d) Examples: ``` Variant a; // Must assign before use, otherwise exception ensues // Initialize with an integer; make the type int Variant b = 42; writeln(b.type); // typeid (int) // Peek at the value assert(b.peek!(int) !is null && *b.peek!(int) == 42); // Automatically convert per language rules auto x = b.get!(real); // Assign any other type, including other variants a = b; a = 3.14; writeln(a.type); // typeid (double) // Implicit conversions work just as with built-in types assert(a < b); // Check for convertibility assert(!a.convertsTo!(int)); // double not convertible to int // Strings and all other arrays are supported a = "now I'm a string"; writeln(a); // "now I'm a string" // can also assign arrays a = new int[42]; writeln(a.length); // 42 a[5] = 7; writeln(a[5]); // 7 // Can also assign class values class Foo {} auto foo = new Foo; a = foo; assert(*a.peek!(Foo) == foo); // and full type information is preserved ``` template **maxSize**(T...) Gives the `sizeof` the largest type given. Examples: ``` static assert(maxSize!(int, long) == 8); static assert(maxSize!(bool, byte) == 1); struct Cat { int a, b, c; } static assert(maxSize!(bool, Cat) == 12); ``` struct **VariantN**(size\_t maxDataSize, AllowedTypesParam...); Back-end type seldom used directly by user code. Two commonly-used types using `VariantN` are: 1. [`Algebraic`](#Algebraic): A closed discriminated union with a limited type universe (e.g., `Algebraic!(int, double, string)` only accepts these three types and rejects anything else). 2. [`Variant`](#Variant): An open discriminated union allowing an unbounded set of types. If any of the types in the `Variant` are larger than the largest built-in type, they will automatically be boxed. This means that even large types will only be the size of a pointer within the `Variant`, but this also implies some overhead. `Variant` can accommodate all primitive types and all user-defined types. Both `Algebraic` and `Variant` share `VariantN`'s interface. (See their respective documentations below.) `VariantN` is a discriminated union type parameterized with the largest size of the types stored (`maxDataSize`) and with the list of allowed types (`AllowedTypes`). If the list is empty, then any type up of size up to `maxDataSize` (rounded up for alignment) can be stored in a `VariantN` object without being boxed (types larger than this will be boxed). Examples: ``` alias Var = VariantN!(maxSize!(int, double, string)); Var a; // Must assign before use, otherwise exception ensues // Initialize with an integer; make the type int Var b = 42; writeln(b.type); // typeid (int) // Peek at the value assert(b.peek!(int) !is null && *b.peek!(int) == 42); // Automatically convert per language rules auto x = b.get!(real); // Assign any other type, including other variants a = b; a = 3.14; writeln(a.type); // typeid (double) // Implicit conversions work just as with built-in types assert(a < b); // Check for convertibility assert(!a.convertsTo!(int)); // double not convertible to int // Strings and all other arrays are supported a = "now I'm a string"; writeln(a); // "now I'm a string" ``` Examples: can also assign arrays ``` alias Var = VariantN!(maxSize!(int[])); Var a = new int[42]; writeln(a.length); // 42 a[5] = 7; writeln(a[5]); // 7 ``` Examples: Can also assign class values ``` alias Var = VariantN!(maxSize!(int*)); // classes are pointers Var a; class Foo {} auto foo = new Foo; a = foo; assert(*a.peek!(Foo) == foo); // and full type information is preserved ``` alias **AllowedTypes** = This2Variant!(VariantN, AllowedTypesParam); The list of allowed types. If empty, any type is allowed. enum bool **allowed**(T); Tells whether a type `T` is statically allowed for storage inside a `VariantN` object by looking `T` up in `AllowedTypes`. this(T)(T value); Constructs a `VariantN` value given an argument of a generic type. Statically rejects disallowed types. this(T : VariantN!(tsize, Types), size\_t tsize, Types...)(T value) Constraints: if (!is(T : VariantN) && (Types.length > 0) && allSatisfy!(allowed, Types)); Allows assignment from a subset algebraic type VariantN **opAssign**(T)(T rhs); Assigns a `VariantN` from a generic argument. Statically rejects disallowed types. const pure nothrow @property bool **hasValue**(); Returns true if and only if the `VariantN` object holds a valid value (has been initialized with, or assigned from, a valid value). Examples: ``` Variant a; assert(!a.hasValue); Variant b; a = b; assert(!a.hasValue); // still no value a = 5; assert(a.hasValue); ``` inout @property inout(T)\* **peek**(T)(); If the `VariantN` object holds a value of the *exact* type `T`, returns a pointer to that value. Otherwise, returns `null`. In cases where `T` is statically disallowed, `peek` will not compile. Examples: ``` Variant a = 5; auto b = a.peek!(int); assert(b !is null); *b = 6; writeln(a); // 6 ``` const nothrow @property @trusted TypeInfo **type**(); Returns the `typeid` of the currently held value. const @property bool **convertsTo**(T)(); Returns `true` if and only if the `VariantN` object holds an object implicitly convertible to type `T`. Implicit convertibility is defined as per [ImplicitConversionTargets](std_traits#ImplicitConversionTargets). inout @property inout(T) **get**(T)(); inout @property auto **get**(uint index)() Constraints: if (index < AllowedTypes.length); Returns the value stored in the `VariantN` object, either by specifying the needed type or the index in the list of allowed types. The latter overload only applies to bounded variants (e.g. [`Algebraic`](#Algebraic)). Parameters: | | | | --- | --- | | T | The requested type. The currently stored value must implicitly convert to the requested type, in fact `DecayStaticToDynamicArray!T`. If an implicit conversion is not possible, throws a `VariantException`. | | index | The index of the type among `AllowedTypesParam`, zero-based. | @property T **coerce**(T)(); Returns the value stored in the `VariantN` object, explicitly converted (coerced) to the requested type `T`. If `T` is a string type, the value is formatted as a string. If the `VariantN` object is a string, a parse of the string to type `T` is attempted. If a conversion is not possible, throws a `VariantException`. string **toString**(); Formats the stored value as a string. const bool **opEquals**(T)(auto ref T rhs) Constraints: if (allowed!T || is(immutable(T) == immutable(VariantN))); Comparison for equality used by the "==" and "!=" operators. int **opCmp**(T)(T rhs) Constraints: if (allowed!T); Ordering comparison used by the "<", "<=", ">", and ">=" operators. In case comparison is not sensible between the held value and `rhs`, an exception is thrown. const nothrow @safe size\_t **toHash**(); Computes the hash of the held value. VariantN **opBinary**(string op, T)(T rhs) Constraints: if ((op == "+" || op == "-" || op == "\*" || op == "/" || op == "^^" || op == "%") && is(typeof(opArithmetic!(T, op)(rhs)))); VariantN **opBinary**(string op, T)(T rhs) Constraints: if ((op == "&" || op == "|" || op == "^" || op == ">>" || op == "<<" || op == ">>>") && is(typeof(opLogic!(T, op)(rhs)))); VariantN **opBinaryRight**(string op, T)(T lhs) Constraints: if ((op == "+" || op == "\*") && is(typeof(opArithmetic!(T, op)(lhs)))); VariantN **opBinaryRight**(string op, T)(T lhs) Constraints: if ((op == "&" || op == "|" || op == "^") && is(typeof(opLogic!(T, op)(lhs)))); VariantN **opBinary**(string op, T)(T rhs) Constraints: if (op == "~"); VariantN **opOpAssign**(string op, T)(T rhs); Arithmetic between `VariantN` objects and numeric values. All arithmetic operations return a `VariantN` object typed depending on the types of both values involved. The conversion rules mimic D's built-in rules for arithmetic conversions. inout inout(Variant) **opIndex**(K)(K i); Variant **opIndexAssign**(T, N)(T value, N i); Variant **opIndexOpAssign**(string op, T, N)(T value, N i); Array and associative array operations. If a `VariantN` contains an (associative) array, it can be indexed into. Otherwise, an exception is thrown. Examples: ``` Variant a = new int[10]; a[5] = 42; writeln(a[5]); // 42 a[5] += 8; writeln(a[5]); // 50 int[int] hash = [ 42:24 ]; a = hash; writeln(a[42]); // 24 a[42] /= 2; writeln(a[42]); // 12 ``` @property size\_t **length**(); If the `VariantN` contains an (associative) array, returns the length of that array. Otherwise, throws an exception. int **opApply**(Delegate)(scope Delegate dg) Constraints: if (is(Delegate == delegate)); If the `VariantN` contains an array, applies `dg` to each element of the array in turn. Otherwise, throws an exception. template **Algebraic**(T...) Algebraic data type restricted to a closed set of possible types. It's an alias for [`VariantN`](#VariantN) with an appropriately-constructed maximum size. `Algebraic` is useful when it is desirable to restrict what a discriminated type could hold to the end of defining simpler and more efficient manipulation. Examples: ``` auto v = Algebraic!(int, double, string)(5); assert(v.peek!(int)); v = 3.14; assert(v.peek!(double)); // auto x = v.peek!(long); // won't compile, type long not allowed // v = '1'; // won't compile, type char not allowed ``` Examples: #### Self-Referential Types A useful and popular use of algebraic data structures is for defining [self-referential data structures](https://google.com/search?btnI=I%27m+Feeling+Lucky&ie=UTF-8&oe=UTF-8&q=self-referential%20data%20structures), i.e. structures that embed references to values of their own type within. This is achieved with `Algebraic` by using `This` as a placeholder whenever a reference to the type being defined is needed. The `Algebraic` instantiation will perform [alpha renaming](https://en.wikipedia.org/wiki/Name_resolution_(programming_languages)#Alpha_renaming_to_make_name_resolution_trivial) on its constituent types, replacing `This` with the self-referenced type. The structure of the type involving `This` may be arbitrarily complex. ``` import std.typecons : Tuple, tuple; // A tree is either a leaf or a branch of two other trees alias Tree(Leaf) = Algebraic!(Leaf, Tuple!(This*, This*)); Tree!int tree = tuple(new Tree!int(42), new Tree!int(43)); Tree!int* right = tree.get!1[1]; writeln(*right); // 43 // An object is a double, a string, or a hash of objects alias Obj = Algebraic!(double, string, This[string]); Obj obj = "hello"; writeln(obj.get!1); // "hello" obj = 42.0; writeln(obj.get!0); // 42 obj = ["customer": Obj("John"), "paid": Obj(23.95)]; writeln(obj.get!2["customer"]); // "John" ``` alias **Variant** = VariantN!32LU.VariantN; Alias for [`VariantN`](#VariantN) instantiated with the largest size of `creal`, `char[]`, and `void delegate()`. This ensures that `Variant` is large enough to hold all of D's predefined types unboxed, including all numeric types, pointers, delegates, and class references. You may want to use `VariantN` directly with a different maximum size either for storing larger types unboxed, or for saving memory. Examples: ``` Variant a; // Must assign before use, otherwise exception ensues // Initialize with an integer; make the type int Variant b = 42; writeln(b.type); // typeid (int) // Peek at the value assert(b.peek!(int) !is null && *b.peek!(int) == 42); // Automatically convert per language rules auto x = b.get!(real); // Assign any other type, including other variants a = b; a = 3.14; writeln(a.type); // typeid (double) // Implicit conversions work just as with built-in types assert(a < b); // Check for convertibility assert(!a.convertsTo!(int)); // double not convertible to int // Strings and all other arrays are supported a = "now I'm a string"; writeln(a); // "now I'm a string" ``` Examples: can also assign arrays ``` Variant a = new int[42]; writeln(a.length); // 42 a[5] = 7; writeln(a[5]); // 7 ``` Examples: Can also assign class values ``` Variant a; class Foo {} auto foo = new Foo; a = foo; assert(*a.peek!(Foo) == foo); // and full type information is preserved ``` Variant[] **variantArray**(T...)(T args); Returns an array of variants constructed from `args`. This is by design. During construction the `Variant` needs static type information about the type being held, so as to store a pointer to function for fast retrieval. Examples: ``` auto a = variantArray(1, 3.14, "Hi!"); writeln(a[1]); // 3.14 auto b = Variant(a); // variant array as variant writeln(b[1]); // 3.14 ``` class **VariantException**: object.Exception; Thrown in three cases: 1. An uninitialized `Variant` is used in any way except assignment and `hasValue`; 2. A `get` or `coerce` is attempted with an incompatible target type; 3. A comparison between `Variant` objects of incompatible types is attempted. Examples: ``` import std.exception : assertThrown; Variant v; // uninitialized use assertThrown!VariantException(v + 1); assertThrown!VariantException(v.length); // .get with an incompatible target type assertThrown!VariantException(Variant("a").get!int); // comparison between incompatible types assertThrown!VariantException(Variant(3) < Variant("a")); ``` TypeInfo **source**; The source type in the conversion or comparison TypeInfo **target**; The target type in the conversion or comparison template **visit**(Handlers...) if (Handlers.length > 0) Applies a delegate or function to the given [`Algebraic`](#Algebraic) depending on the held type, ensuring that all types are handled by the visiting functions. The delegate or function having the currently held value as parameter is called with `variant`'s current value. Visiting handlers are passed in the template parameter list. It is statically ensured that all held types of `variant` are handled across all handlers. `visit` allows delegates and static functions to be passed as parameters. If a function with an untyped parameter is specified, this function is called when the variant contains a type that does not match any other function. This can be used to apply the same function across multiple possible types. Exactly one generic function is allowed. If a function without parameters is specified, this function is called when `variant` doesn't hold a value. Exactly one parameter-less function is allowed. Duplicate overloads matching the same type in one of the visitors are disallowed. Returns: The return type of visit is deduced from the visiting functions and must be the same across all overloads. Throws: [`VariantException`](#VariantException) if `variant` doesn't hold a value and no parameter-less fallback function is specified. Examples: ``` Algebraic!(int, string) variant; variant = 10; assert(variant.visit!((string s) => cast(int) s.length, (int i) => i)() == 10); variant = "string"; assert(variant.visit!((int i) => i, (string s) => cast(int) s.length)() == 6); // Error function usage Algebraic!(int, string) emptyVar; auto rslt = emptyVar.visit!((string s) => cast(int) s.length, (int i) => i, () => -1)(); writeln(rslt); // -1 // Generic function usage Algebraic!(int, float, real) number = 2; writeln(number.visit!(x => x += 1)); // 3 // Generic function for int/float with separate behavior for string Algebraic!(int, float, string) something = 2; assert(something.visit!((string s) => s.length, x => x) == 2); // generic something = "asdf"; assert(something.visit!((string s) => s.length, x => x) == 4); // string // Generic handler and empty handler Algebraic!(int, float, real) empty2; writeln(empty2.visit!(x => x + 1, () => -1)); // -1 ``` auto **visit**(VariantType)(VariantType variant) Constraints: if (isAlgebraic!VariantType); template **tryVisit**(Handlers...) if (Handlers.length > 0) Behaves as [`visit`](#visit) but doesn't enforce that all types are handled by the visiting functions. If a parameter-less function is specified it is called when either `variant` doesn't hold a value or holds a type which isn't handled by the visiting functions. Returns: The return type of tryVisit is deduced from the visiting functions and must be the same across all overloads. Throws: [`VariantException`](#VariantException) if `variant` doesn't hold a value or `variant` holds a value which isn't handled by the visiting functions, when no parameter-less fallback function is specified. Examples: ``` Algebraic!(int, string) variant; variant = 10; auto which = -1; variant.tryVisit!((int i) { which = 0; })(); writeln(which); // 0 // Error function usage variant = "test"; variant.tryVisit!((int i) { which = 0; }, () { which = -100; })(); writeln(which); // -100 ``` auto **tryVisit**(VariantType)(VariantType variant) Constraints: if (isAlgebraic!VariantType); d std.base64 std.base64 ========== Support for Base64 encoding and decoding. This module provides two default implementations of Base64 encoding, [`Base64`](#Base64) with a standard encoding alphabet, and a variant [`Base64URL`](#Base64URL) that has a modified encoding alphabet designed to be safe for embedding in URLs and filenames. Both variants are implemented as instantiations of the template [`Base64Impl`](#Base64Impl). Most users will not need to use this template directly; however, it can be used to create customized Base64 encodings, such as one that omits padding characters, or one that is safe to embed inside a regular expression. Example ``` ubyte[] data = [0x14, 0xfb, 0x9c, 0x03, 0xd9, 0x7e]; const(char)[] encoded = Base64.encode(data); assert(encoded == "FPucA9l+"); ubyte[] decoded = Base64.decode("FPucA9l+"); assert(decoded == [0x14, 0xfb, 0x9c, 0x03, 0xd9, 0x7e]); ``` The range API is supported for both encoding and decoding: Example ``` // Create MIME Base64 with CRLF, per line 76. File f = File("./text.txt", "r"); scope(exit) f.close(); Appender!string mime64 = appender!string; foreach (encoded; Base64.encoder(f.byChunk(57))) { mime64.put(encoded); mime64.put("\r\n"); } writeln(mime64.data); ``` References [RFC 4648 - The Base16, Base32, and Base64 Data Encodings](https://tools.ietf.org/html/rfc4648) License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: Masahiro Nakagawa, Daniel Murphy (Single value Encoder and Decoder) Source [std/base64.d](https://github.com/dlang/phobos/blob/master/std/base64.d) alias **Base64** = Base64Impl!('+', '/', '='); Implementation of standard Base64 encoding. See [`Base64Impl`](#Base64Impl) for a description of available methods. Examples: ``` ubyte[] data = [0x83, 0xd7, 0x30, 0x7a, 0x01, 0x3f]; writeln(Base64.encode(data)); // "g9cwegE/" writeln(Base64.decode("g9cwegE/")); // data ``` alias **Base64URL** = Base64Impl!('-', '\_', '='); Variation of Base64 encoding that is safe for use in URLs and filenames. See [`Base64Impl`](#Base64Impl) for a description of available methods. Examples: ``` ubyte[] data = [0x83, 0xd7, 0x30, 0x7a, 0x01, 0x3f]; writeln(Base64URL.encode(data)); // "g9cwegE_" writeln(Base64URL.decode("g9cwegE_")); // data ``` alias **Base64URLNoPadding** = Base64Impl!('-', '\_', '\x00'); Unpadded variation of Base64 encoding that is safe for use in URLs and filenames, as used in RFCs 4648 and 7515 (JWS/JWT/JWE). See [`Base64Impl`](#Base64Impl) for a description of available methods. Examples: ``` ubyte[] data = [0x83, 0xd7, 0x30, 0x7b, 0xef]; writeln(Base64URLNoPadding.encode(data)); // "g9cwe-8" writeln(Base64URLNoPadding.decode("g9cwe-8")); // data ``` template **Base64Impl**(char Map62th, char Map63th, char Padding = '=') Template for implementing Base64 encoding and decoding. For most purposes, direct usage of this template is not necessary; instead, this module provides default implementations: [`Base64`](#Base64), implementing basic Base64 encoding, and [`Base64URL`](#Base64URL) and [`Base64URLNoPadding`](#Base64URLNoPadding), that implement the Base64 variant for use in URLs and filenames, with and without padding, respectively. Customized Base64 encoding schemes can be implemented by instantiating this template with the appropriate arguments. For example: ``` // Non-standard Base64 format for embedding in regular expressions. alias Base64Re = Base64Impl!('!', '=', Base64.NoPadding); ``` NOTE Encoded strings will not have any padding if the `Padding` parameter is set to `NoPadding`. Examples: ``` import std.string : representation; // pre-defined: alias Base64 = Base64Impl!('+', '/'); ubyte[] emptyArr; writeln(Base64.encode(emptyArr)); // "" writeln(Base64.encode("f".representation)); // "Zg==" writeln(Base64.encode("foo".representation)); // "Zm9v" alias Base64Re = Base64Impl!('!', '=', Base64.NoPadding); writeln(Base64Re.encode("f".representation)); // "Zg" writeln(Base64Re.encode("foo".representation)); // "Zm9v" ``` enum auto **NoPadding**; represents no-padding encoding pure nothrow @safe size\_t **encodeLength**(in size\_t sourceLength); Calculates the length needed to store the encoded string corresponding to an input of the given length. Parameters: | | | | --- | --- | | size\_t `sourceLength` | Length of the source array. | Returns: The length of a Base64 encoding of an array of the given length. Examples: ``` ubyte[] data = [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]; // Allocate a buffer large enough to hold the encoded string. auto buf = new char[Base64.encodeLength(data.length)]; Base64.encode(data, buf); writeln(buf); // "Gis8TV1u" ``` pure @trusted char[] **encode**(R1, R2)(in R1 source, R2 buffer) Constraints: if (isArray!R1 && is(ElementType!R1 : ubyte) && is(R2 == char[])); char[] **encode**(R1, R2)(R1 source, R2 buffer) Constraints: if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : ubyte) && hasLength!R1 && is(R2 == char[])); Encode source into a `char[]` buffer using Base64 encoding. Parameters: | | | | --- | --- | | R1 `source` | The [input range](std_range_primitives#isInputRange) to encode. | | R2 `buffer` | The `char[]` buffer to store the encoded result. | Returns: The slice of buffer that contains the encoded string. Examples: ``` ubyte[] data = [0x83, 0xd7, 0x30, 0x7a, 0x01, 0x3f]; char[32] buffer; // much bigger than necessary // Just to be sure... auto encodedLength = Base64.encodeLength(data.length); assert(buffer.length >= encodedLength); // encode() returns a slice to the provided buffer. auto encoded = Base64.encode(data, buffer[]); assert(encoded is buffer[0 .. encodedLength]); writeln(encoded); // "g9cwegE/" ``` size\_t **encode**(E, R)(scope const(E)[] source, auto ref R range) Constraints: if (is(E : ubyte) && isOutputRange!(R, char) && !is(R == char[])); size\_t **encode**(R1, R2)(R1 source, auto ref R2 range) Constraints: if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : ubyte) && hasLength!R1 && !is(R2 == char[]) && isOutputRange!(R2, char)); Encodes source into an [output range](std_range_primitives#isOutputRange) using Base64 encoding. Parameters: | | | | --- | --- | | const(E)[] `source` | The [input range](std_range_primitives#isInputRange) to encode. | | R `range` | The [output range](std_range_primitives#isOutputRange) to store the encoded result. | Returns: The number of times the output range's `put` method was invoked. Examples: ``` import std.array : appender; auto output = appender!string(); ubyte[] data = [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]; // This overload of encode() returns the number of calls to the output // range's put method. writeln(Base64.encode(data, output)); // 8 writeln(output.data); // "Gis8TV1u" ``` pure @safe char[] **encode**(Range)(Range source) Constraints: if (isArray!Range && is(ElementType!Range : ubyte)); char[] **encode**(Range)(Range source) Constraints: if (!isArray!Range && isInputRange!Range && is(ElementType!Range : ubyte) && hasLength!Range); Encodes source to newly-allocated buffer. This convenience method alleviates the need to manually manage output buffers. Parameters: | | | | --- | --- | | Range `source` | The [input range](std_range_primitives#isInputRange) to encode. | Returns: A newly-allocated `char[]` buffer containing the encoded string. Examples: ``` ubyte[] data = [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]; writeln(Base64.encode(data)); // "Gis8TV1u" ``` struct **Encoder**(Range) if (isInputRange!Range && (is(ElementType!Range : const(ubyte)[]) || is(ElementType!Range : const(char)[]))); An [input range](std_range_primitives#isInputRange) that iterates over the respective Base64 encodings of a range of data items. This range will be a [forward range](std_range_primitives#isForwardRange) if the underlying data source is at least a forward range. Note This struct is not intended to be created in user code directly; use the [`encoder`](#encoder) function instead. @property @trusted bool **empty**(); Returns: true if there is no more encoded data left. nothrow @property @safe char[] **front**(); Returns: The current chunk of encoded data. void **popFront**(); Advance the range to the next chunk of encoded data. Throws: `Base64Exception` If invoked when [`empty`](#Base64Impl.Encoder.empty) returns `true`. @property typeof(this) **save**(); Save the current iteration state of the range. This method is only available if the underlying range is a [forward range](std_range_primitives#isForwardRange). Returns: A copy of `this`. struct **Encoder**(Range) if (isInputRange!Range && is(ElementType!Range : ubyte)); An [input range](std_range_primitives#isInputRange) that iterates over the encoded bytes of the given source data. It will be a [forward range](std_range_primitives#isForwardRange) if the underlying data source is at least a forward range. Note This struct is not intended to be created in user code directly; use the [`encoder`](#encoder) function instead. const nothrow @property @safe bool **empty**(); Returns: true if there are no more encoded characters to be iterated. nothrow @property @safe ubyte **front**(); Returns: The current encoded character. void **popFront**(); Advance to the next encoded character. Throws: `Base64Exception` If invoked when [` empty`](#Base64Impl.Encoder.empty.2) returns `true`. @property typeof(this) **save**(); Save the current iteration state of the range. This method is only available if the underlying range is a [forward range](std_range_primitives#isForwardRange). Returns: A copy of `this`. Encoder!Range **encoder**(Range)(Range range) Constraints: if (isInputRange!Range); Construct an `Encoder` that iterates over the Base64 encoding of the given [input range](std_range_primitives#isInputRange). Parameters: | | | | --- | --- | | Range `range` | An [input range](std_range_primitives#isInputRange) over the data to be encoded. | Returns: If range is a range of bytes, an `Encoder` that iterates over the bytes of the corresponding Base64 encoding. If range is a range of ranges of bytes, an `Encoder` that iterates over the Base64 encoded strings of each element of the range. In both cases, the returned `Encoder` will be a [forward range](std_range_primitives#isForwardRange) if the given `range` is at least a forward range, otherwise it will be only an input range. Example This example encodes the input one line at a time. ``` File f = File("text.txt", "r"); scope(exit) f.close(); uint line = 0; foreach (encoded; Base64.encoder(f.byLine())) { writeln(++line, ". ", encoded); } ``` Example This example encodes the input data one byte at a time. ``` ubyte[] data = cast(ubyte[]) "0123456789"; // The ElementType of data is not aggregation type foreach (encoded; Base64.encoder(data)) { writeln(encoded); } ``` pure nothrow @safe size\_t **decodeLength**(in size\_t sourceLength); Given a Base64 encoded string, calculates the length of the decoded string. Parameters: | | | | --- | --- | | size\_t `sourceLength` | The length of the Base64 encoding. | Returns: The length of the decoded string corresponding to a Base64 encoding of length sourceLength. Examples: ``` auto encoded = "Gis8TV1u"; // Allocate a sufficiently large buffer to hold to decoded result. auto buffer = new ubyte[Base64.decodeLength(encoded.length)]; Base64.decode(encoded, buffer); writeln(buffer); // [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e] ``` pure @trusted ubyte[] **decode**(R1, R2)(in R1 source, R2 buffer) Constraints: if (isArray!R1 && is(ElementType!R1 : dchar) && is(R2 == ubyte[]) && isOutputRange!(R2, ubyte)); ubyte[] **decode**(R1, R2)(R1 source, R2 buffer) Constraints: if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : dchar) && hasLength!R1 && is(R2 == ubyte[]) && isOutputRange!(R2, ubyte)); Decodes source into the given buffer. Parameters: | | | | --- | --- | | R1 `source` | The [input range](std_range_primitives#isInputRange) to decode. | | R2 `buffer` | The buffer to store decoded result. | Returns: The slice of buffer containing the decoded result. Throws: `Base64Exception` if source contains characters outside the base alphabet of the current Base64 encoding scheme. Examples: ``` auto encoded = "Gis8TV1u"; ubyte[32] buffer; // much bigger than necessary // Just to be sure... auto decodedLength = Base64.decodeLength(encoded.length); assert(buffer.length >= decodedLength); // decode() returns a slice of the given buffer. auto decoded = Base64.decode(encoded, buffer[]); assert(decoded is buffer[0 .. decodedLength]); writeln(decoded); // [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e] ``` size\_t **decode**(R1, R2)(in R1 source, auto ref R2 range) Constraints: if (isArray!R1 && is(ElementType!R1 : dchar) && !is(R2 == ubyte[]) && isOutputRange!(R2, ubyte)); size\_t **decode**(R1, R2)(R1 source, auto ref R2 range) Constraints: if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : dchar) && hasLength!R1 && !is(R2 == ubyte[]) && isOutputRange!(R2, ubyte)); Decodes source into a given [output range](std_range_primitives#isOutputRange). Parameters: | | | | --- | --- | | R1 `source` | The [input range](std_range_primitives#isInputRange) to decode. | | R2 `range` | The [output range](std_range_primitives#isOutputRange) to store the decoded result. | Returns: The number of times the output range's `put` method was invoked. Throws: `Base64Exception` if source contains characters outside the base alphabet of the current Base64 encoding scheme. Examples: ``` struct OutputRange { ubyte[] result; void put(ubyte b) { result ~= b; } } OutputRange output; // This overload of decode() returns the number of calls to put(). writeln(Base64.decode("Gis8TV1u", output)); // 6 writeln(output.result); // [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e] ``` pure @safe ubyte[] **decode**(Range)(Range source) Constraints: if (isArray!Range && is(ElementType!Range : dchar)); ubyte[] **decode**(Range)(Range source) Constraints: if (!isArray!Range && isInputRange!Range && is(ElementType!Range : dchar) && hasLength!Range); Decodes source into newly-allocated buffer. This convenience method alleviates the need to manually manage decoding buffers. Parameters: | | | | --- | --- | | Range `source` | The [input range](std_range_primitives#isInputRange) to decode. | Returns: A newly-allocated `ubyte[]` buffer containing the decoded string. Examples: ``` auto data = "Gis8TV1u"; writeln(Base64.decode(data)); // [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e] ``` struct **Decoder**(Range) if (isInputRange!Range && (is(ElementType!Range : const(char)[]) || is(ElementType!Range : const(ubyte)[]))); An [input range](std_range_primitives#isInputRange) that iterates over the decoded data of a range of Base64 encodings. This range will be a [forward range](std_range_primitives#isForwardRange) if the underlying data source is at least a forward range. Note This struct is not intended to be created in user code directly; use the [`decoder`](#decoder) function instead. @property @trusted bool **empty**(); Returns: true if there are no more elements to be iterated. nothrow @property @safe ubyte[] **front**(); Returns: The decoding of the current element in the input. void **popFront**(); Advance to the next element in the input to be decoded. Throws: `Base64Exception` if invoked when [` empty`](#Base64Impl.Decoder.empty) returns `true`. @property typeof(this) **save**(); Saves the current iteration state. This method is only available if the underlying range is a [forward range](std_range_primitives#isForwardRange) Returns: A copy of `this`. struct **Decoder**(Range) if (isInputRange!Range && is(ElementType!Range : char)); An [input range](std_range_primitives#isInputRange) that iterates over the bytes of data decoded from a Base64 encoded string. This range will be a [forward range](std_range_primitives#isForwardRange) if the underlying data source is at least a forward range. Note This struct is not intended to be created in user code directly; use the [`decoder`](#decoder) function instead. const nothrow @property @safe bool **empty**(); Returns: true if there are no more elements to be iterated. nothrow @property @safe ubyte **front**(); Returns: The current decoded byte. void **popFront**(); Advance to the next decoded byte. Throws: `Base64Exception` if invoked when [` empty`](#Base64Impl.Decoder.empty) returns `true`. @property typeof(this) **save**(); Saves the current iteration state. This method is only available if the underlying range is a [forward range](std_range_primitives#isForwardRange) Returns: A copy of `this`. Decoder!Range **decoder**(Range)(Range range) Constraints: if (isInputRange!Range); Construct a `Decoder` that iterates over the decoding of the given Base64 encoded data. Parameters: | | | | --- | --- | | Range `range` | An [input range](std_range_primitives#isInputRange) over the data to be decoded. | Returns: If range is a range of characters, a `Decoder` that iterates over the bytes of the corresponding Base64 decoding. If range is a range of ranges of characters, a `Decoder` that iterates over the decoded strings corresponding to each element of the range. In this case, the length of each subrange must be a multiple of 4; the returned decoder does not keep track of Base64 decoding state across subrange boundaries. In both cases, the returned `Decoder` will be a [forward range](std_range_primitives#isForwardRange) if the given `range` is at least a forward range, otherwise it will be only an input range. If the input data contains characters not found in the base alphabet of the current Base64 encoding scheme, the returned range may throw a `Base64Exception`. Example This example shows decoding over a range of input data lines. ``` foreach (decoded; Base64.decoder(stdin.byLine())) { writeln(decoded); } ``` Example This example shows decoding one byte at a time. ``` auto encoded = Base64.encoder(cast(ubyte[])"0123456789"); foreach (n; map!q{a - '0'}(Base64.decoder(encoded))) { writeln(n); } ``` class **Base64Exception**: object.Exception; Exception thrown upon encountering Base64 encoding or decoding errors. Examples: ``` import std.exception : assertThrown; assertThrown!Base64Exception(Base64.decode("ab|c")); ```
programming_docs
d std.signals std.signals =========== Signals and Slots are an implementation of the Observer Pattern. Essentially, when a Signal is emitted, a list of connected Observers (called slots) are called. There have been several D implementations of Signals and Slots. This version makes use of several new features in D, which make using it simpler and less error prone. In particular, it is no longer necessary to instrument the slots. References [A Deeper Look at Signals and Slots](https://google.com/search?btnI=I%27m+Feeling+Lucky&ie=UTF-8&oe=UTF-8&q=A%20Deeper%20Look%20at%20Signals%20and%20Slots) [Observer pattern](http://en.wikipedia.org/wiki/Observer_pattern) [Wikipedia](http://en.wikipedia.org/wiki/Signals_and_slots) [Boost Signals](http://boost.org/doc/html/signals.html) [Qt](http://qt-project.org/doc/qt-5/signalsandslots.html) There has been a great deal of discussion in the D newsgroups over this, and several implementations: [signal slots library](http://www.digitalmars.com/d/archives/digitalmars/D/announce/signal_slots_library_4825.html) [Signals and Slots in D](http://www.digitalmars.com/d/archives/digitalmars/D/Signals_and_Slots_in_D_42387.html) [Dynamic binding -- Qt's Signals and Slots vs Objective-C](http://www.digitalmars.com/d/archives/digitalmars/D/Dynamic_binding_--_Qt_s_Signals_and_Slots_vs_Objective-C_42260.html) [Dissecting the SS](http://www.digitalmars.com/d/archives/digitalmars/D/Dissecting_the_SS_42377.html) [about harmonia](http://www.digitalmars.com/d/archives/digitalmars/D/dwt/about_harmonia_454.html) [Another event handling module](http://www.digitalmars.com/d/archives/digitalmars/D/announce/1502.html) [Suggestion: signal/slot mechanism](http://www.digitalmars.com/d/archives/digitalmars/D/41825.html) [Signals and slots?](http://www.digitalmars.com/d/archives/digitalmars/D/13251.html) [Signals and slots ready for evaluation](http://www.digitalmars.com/d/archives/digitalmars/D/10714.html) [Signals & Slots for Walter](http://www.digitalmars.com/d/archives/digitalmars/D/1393.html) [Signal/Slot mechanism?](http://www.digitalmars.com/d/archives/28456.html) [Modern Features?](http://www.digitalmars.com/d/archives/19470.html) [Delegates vs interfaces](http://www.digitalmars.com/d/archives/16592.html) [The importance of component programming (properties, signals and slots, etc)](http://www.digitalmars.com/d/archives/16583.html) [signals and slots](http://www.digitalmars.com/d/archives/16368.html) Bugs: Slots can only be delegates formed from class objects or interfaces to class objects. If a delegate to something else is passed to connect(), such as a struct member function, a nested function, a COM interface or a closure, undefined behavior will result. Not safe for multiple threads operating on the same signals or slots. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com) Source [std/signals.d](https://github.com/dlang/phobos/blob/master/std/signals.d) template **Signal**(T1...) Mixin to create a signal within a class object. Different signals can be added to a class by naming the mixins. Examples: ``` import std.signals; int observedMessageCounter = 0; class Observer { // our slot void watch(string msg, int value) { switch (observedMessageCounter++) { case 0: writeln(msg); // "setting new value" writeln(value); // 4 break; case 1: writeln(msg); // "setting new value" writeln(value); // 6 break; default: assert(0, "Unknown observation"); } } } class Observer2 { // our slot void watch(string msg, int value) { } } class Foo { int value() { return _value; } int value(int v) { if (v != _value) { _value = v; // call all the connected slots with the two parameters emit("setting new value", v); } return v; } // Mix in all the code we need to make Foo into a signal mixin Signal!(string, int); private : int _value; } Foo a = new Foo; Observer o = new Observer; auto o2 = new Observer2; auto o3 = new Observer2; auto o4 = new Observer2; auto o5 = new Observer2; a.value = 3; // should not call o.watch() a.connect(&o.watch); // o.watch is the slot a.connect(&o2.watch); a.connect(&o3.watch); a.connect(&o4.watch); a.connect(&o5.watch); a.value = 4; // should call o.watch() a.disconnect(&o.watch); // o.watch is no longer a slot a.disconnect(&o3.watch); a.disconnect(&o5.watch); a.disconnect(&o4.watch); a.disconnect(&o2.watch); a.value = 5; // so should not call o.watch() a.connect(&o2.watch); a.connect(&o.watch); // connect again a.value = 6; // should call o.watch() destroy(o); // destroying o should automatically disconnect it a.value = 7; // should not call o.watch() writeln(observedMessageCounter); // 2 ``` alias **slot\_t** = void delegate(T1); A slot is implemented as a delegate. The slot\_t is the type of the delegate. The delegate must be to an instance of a class or an interface to a class instance. Delegates to struct instances or nested functions must not be used as slots. final void **emit**(T1 i); Call each of the connected slots, passing the argument(s) i to them. Nested call will be ignored. final void **connect**(slot\_t slot); Add a slot to the list of slots to be called when emit() is called. final void **disconnect**(slot\_t slot); Remove a slot from the list of slots to be called when emit() is called. final void **disconnectAll**(); Disconnect all the slots. d rt.aApplyR rt.aApplyR ========== This code handles decoding UTF strings for foreach\_reverse loops. There are 6 combinations of conversions between char, wchar, and dchar, and 2 of each of those. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Walter Bright, Sean Kelly alias **dg\_t** = int delegate(void\*); int **\_aApplyRwd1**(in wchar[] aa, dg\_t dg); int **\_aApplyRcw1**(in char[] aa, dg\_t dg); int **\_aApplyRwc1**(in wchar[] aa, dg\_t dg); int **\_aApplyRdc1**(in dchar[] aa, dg\_t dg); int **\_aApplyRdw1**(in dchar[] aa, dg\_t dg); alias **dg2\_t** = int delegate(void\*, void\*); int **\_aApplyRwd2**(in wchar[] aa, dg2\_t dg); int **\_aApplyRcw2**(in char[] aa, dg2\_t dg); int **\_aApplyRwc2**(in wchar[] aa, dg2\_t dg); int **\_aApplyRdc2**(in dchar[] aa, dg2\_t dg); int **\_aApplyRdw2**(in dchar[] aa, dg2\_t dg); d core.stdc.stddef core.stdc.stddef ================ D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<stddef.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stddef.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly Source [core/stdc/stddef.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/stddef.d) Standards: ISO/IEC 9899:1999 (E) alias **nullptr\_t** = typeof(null); alias **wchar\_t** = dchar; d std.concurrency std.concurrency =============== 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 Tid, which allows messages to be sent to logical threads that are executing in both the current process and in external 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. A logical thread is an execution context that has its own stack and which runs asynchronously to other logical threads. These may be preemptively scheduled kernel threads, fibers (cooperative user-space threads), or some other concept with similar behavior. The type of concurrency used when logical threads are created is determined by the Scheduler selected at initialization time. The default behavior is currently to create a new kernel thread per call to spawn, but other schedulers are available that multiplex fibers across the main thread or use some combination of the two approaches. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Sean Kelly, Alex Rønne Petersen, Martin Nowak Source [std/concurrency.d](https://github.com/dlang/phobos/blob/master/std/concurrency.d) Examples: ``` __gshared string received; static void spawnedFunc(Tid ownerTid) { import std.conv : text; // Receive a message from the owner thread. receive((int i){ received = text("Received the number ", i); // Send a message back to the owner thread // indicating success. send(ownerTid, true); }); } // Start spawnedFunc in a new thread. auto childTid = spawn(&spawnedFunc, thisTid); // Send the number 42 to this new thread. send(childTid, 42); // Receive the result code. auto wasSuccessful = receiveOnly!(bool); assert(wasSuccessful); writeln(received); // "Received the number 42" ``` class **MessageMismatch**: object.Exception; Thrown on calls to `receiveOnly` if a message other than the type the receiving thread expected is sent. pure nothrow @nogc @safe this(string msg = "Unexpected message type"); class **OwnerTerminated**: object.Exception; Thrown on calls to `receive` if the thread that spawned the receiving thread has terminated and no more messages exist. pure nothrow @nogc @safe this(Tid t, string msg = "Owner terminated"); class **LinkTerminated**: object.Exception; Thrown if a linked thread has terminated. pure nothrow @nogc @safe this(Tid t, string msg = "Link terminated"); class **PriorityMessageException**: object.Exception; Thrown if a message was sent to a thread via [`std.concurrency.prioritySend`](std_concurrency#prioritySend) and the receiver does not have a handler for a message of this type. this(Variant vals); Variant **message**; The message that was sent. class **MailboxFull**: object.Exception; Thrown on mailbox crowding if the mailbox is configured with `OnCrowding.throwException`. pure nothrow @nogc @safe this(Tid t, string msg = "Mailbox full"); class **TidMissingException**: object.Exception; Thrown when a Tid is missing, e.g. when `ownerTid` doesn't find an owner thread. struct **Tid**; An opaque type used to represent a logical thread. void **toString**(scope void delegate(const(char)[]) sink); Generate a convenient string for identifying this Tid. This is only useful to see if Tid's that are currently executing are the same or different, e.g. for logging and debugging. It is potentially possible that a Tid executed in the future will have the same toString() output as another Tid that has already terminated. @property @safe Tid **thisTid**(); Returns: The [`Tid`](#Tid) of the caller's thread. @property Tid **ownerTid**(); Return the Tid of the thread which spawned the caller's thread. Throws: A `TidMissingException` exception if there is no owner thread. Tid **spawn**(F, T...)(F fn, T args) Constraints: if (isSpawnable!(F, T)); Starts fn(args) in a new logical thread. Executes the supplied function in a new logical thread represented by `Tid`. The calling thread is designated as the owner of the new thread. When the owner thread terminates an `OwnerTerminated` message will be sent to the new thread, causing an `OwnerTerminated` exception to be thrown on `receive()`. Parameters: | | | | --- | --- | | F `fn` | The function to execute. | | T `args` | Arguments to the function. | Returns: A Tid representing the new logical thread. Notes `args` must not have unshared aliasing. In other words, all arguments to `fn` must either be `shared` or `immutable` or have no pointer indirection. This is necessary for enforcing isolation among threads. Examples: ``` static void f(string msg) { writeln(msg); // "Hello World" } auto tid = spawn(&f, "Hello World"); ``` Examples: Fails: char[] has mutable aliasing. ``` string msg = "Hello, World!"; static void f1(string msg) {} static assert(!__traits(compiles, spawn(&f1, msg.dup))); static assert( __traits(compiles, spawn(&f1, msg.idup))); static void f2(char[] msg) {} static assert(!__traits(compiles, spawn(&f2, msg.dup))); static assert(!__traits(compiles, spawn(&f2, msg.idup))); ``` Examples: New thread with anonymous function ``` spawn({ ownerTid.send("This is so great!"); }); writeln(receiveOnly!string); // "This is so great!" ``` Tid **spawnLinked**(F, T...)(F fn, T args) Constraints: if (isSpawnable!(F, T)); Starts fn(args) in a logical thread and will receive a LinkTerminated message when the operation terminates. Executes the supplied function in a new logical thread represented by Tid. This new thread is linked to the calling thread so that if either it or the calling thread 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(). Parameters: | | | | --- | --- | | F `fn` | The function to execute. | | T `args` | Arguments to the function. | Returns: A Tid representing the new thread. void **send**(T...)(Tid tid, T vals); Places the values as a message at the back of tid's message queue. Sends the supplied value to the thread represented by tid. As with [`std.concurrency.spawn`](std_concurrency#spawn), `T` must not have unshared aliasing. void **prioritySend**(T...)(Tid tid, T vals); Places the values as a message on the front of tid's message queue. Send a message to `tid` but place it at the front of `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 **receive**(T...)(T ops); Receives a message from another thread. 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 [`std.variant.Variant`](std_variant#Variant) is included as the last argument to `receive`, it will match any message that was not matched by an earlier delegate. If more than one argument is sent, the `Variant` will contain a [`std.typecons.Tuple`](std_typecons#Tuple) of all values sent. Parameters: | | | | --- | --- | | T `ops` | Variadic list of function pointers and delegates. Entries in this list must not occlude later entries. | Throws: [`OwnerTerminated`](#OwnerTerminated) when the sending thread was terminated. Examples: ``` import std.variant : Variant; auto process = () { receive( (int i) { ownerTid.send(1); }, (double f) { ownerTid.send(2); }, (Variant v) { ownerTid.send(3); } ); }; { auto tid = spawn(process); send(tid, 42); writeln(receiveOnly!int); // 1 } { auto tid = spawn(process); send(tid, 3.14); writeln(receiveOnly!int); // 2 } { auto tid = spawn(process); send(tid, "something else"); writeln(receiveOnly!int); // 3 } ``` receiveOnlyRet!T **receiveOnly**(T...)(); Receives only messages with arguments of the specified types. Parameters: | | | | --- | --- | | T | Variadic list of types to be received. | Returns: The received message. If `T` has more than one entry, the message will be packed into a [`std.typecons.Tuple`](std_typecons#Tuple). Throws: [`MessageMismatch`](#MessageMismatch) if a message of types other than `T` is received, [`OwnerTerminated`](#OwnerTerminated) when the sending thread was terminated. Examples: ``` auto tid = spawn( { assert(receiveOnly!int == 42); }); send(tid, 42); ``` Examples: ``` auto tid = spawn( { assert(receiveOnly!string == "text"); }); send(tid, "text"); ``` Examples: ``` struct Record { string name; int age; } auto tid = spawn( { auto msg = receiveOnly!(double, Record); assert(msg[0] == 0.5); assert(msg[1].name == "Alice"); assert(msg[1].age == 31); }); send(tid, 0.5, Record("Alice", 31)); ``` bool **receiveTimeout**(T...)(Duration duration, T ops); Receives a message from another thread and gives up if no match arrives within a specified duration. Receive a message from another thread, or block until `duration` exceeds, 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 [`std.variant.Variant`](std_variant#Variant) is included as the last argument, it will match any message that was not matched by an earlier delegate. If more than one argument is sent, the `Variant` will contain a [`std.typecons.Tuple`](std_typecons#Tuple) of all values sent. Parameters: | | | | --- | --- | | Duration `duration` | Duration, how long to wait. If `duration` is negative, won't wait at all. | | T `ops` | Variadic list of function pointers and delegates. Entries in this list must not occlude later entries. | Returns: `true` if it received a message and `false` if it timed out waiting for one. Throws: [`OwnerTerminated`](#OwnerTerminated) when the sending thread was terminated. enum **OnCrowding**: int; These behaviors may be specified when a mailbox is full. **block** Wait until room is available. **throwException** Throw a MailboxFull exception. **ignore** Abort the send and return. pure @safe void **setMaxMailboxSize**(Tid tid, size\_t messages, OnCrowding doThis); Sets a maximum mailbox size. 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. Parameters: | | | | --- | --- | | Tid `tid` | The Tid of the thread for which this limit should be set. | | size\_t `messages` | The maximum number of messages or zero if no limit. | | OnCrowding `doThis` | The behavior executed when a message is sent to a full mailbox. | void **setMaxMailboxSize**(Tid tid, size\_t messages, bool function(Tid) onCrowdingDoThis); Sets a maximum mailbox size. 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. Parameters: | | | | --- | --- | | Tid `tid` | The Tid of the thread for which this limit should be set. | | size\_t `messages` | The maximum number of messages or zero if no limit. | | bool function(Tid) `onCrowdingDoThis` | The routine called when a message is sent to a full mailbox. | bool **register**(string name, Tid tid); Associates name with tid. Associates name with tid in a process-local map. When the thread represented by tid terminates, any names associated with it will be automatically unregistered. Parameters: | | | | --- | --- | | string `name` | The name to associate with tid. | | 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 **unregister**(string name); Removes the registered name associated with a tid. Parameters: | | | | --- | --- | | string `name` | The name to unregister. | Returns: true if the name is registered, false if not. Tid **locate**(string name); Gets the Tid associated with name. Parameters: | | | | --- | --- | | string `name` | The name to locate within the registry. | Returns: The associated Tid or Tid.init if name is not registered. struct **ThreadInfo**; Encapsulates all implementation-level data needed for scheduling. When defining a Scheduler, an instance of this struct must be associated with each logical thread. It contains all implementation-level information needed by the internal API. static nothrow @property ref auto **thisInfo**(); Gets a thread-local instance of ThreadInfo. Gets a thread-local instance of ThreadInfo, which should be used as the default instance when info is requested for a thread not created by the Scheduler. void **cleanup**(); Cleans up this ThreadInfo. This must be called when a scheduled thread terminates. It tears down the messaging system for the thread and notifies interested parties of the thread's termination. interface **Scheduler**; A Scheduler controls how threading is performed by spawn. Implementing a Scheduler allows the concurrency mechanism used by this module to be customized according to different needs. By default, a call to spawn will create a new kernel thread that executes the supplied routine and terminates when finished. But it is possible to create Schedulers that reuse threads, that multiplex Fibers (coroutines) across a single thread, or any number of other approaches. By making the choice of Scheduler a user-level option, std.concurrency may be used for far more types of application than if this behavior were predefined. Example ``` import std.concurrency; import std.stdio; void main() { scheduler = new FiberScheduler; scheduler.start( { writeln("the rest of main goes here"); }); } ``` Some schedulers have a dispatching loop that must run if they are to work properly, so for the sake of consistency, when using a scheduler, start() must be called within main(). This yields control to the scheduler and will ensure that any spawned threads are executed in an expected manner. abstract void **start**(void delegate() op); Spawns the supplied op and starts the Scheduler. This is intended to be called at the start of the program to yield all scheduling to the active Scheduler instance. This is necessary for schedulers that explicitly dispatch threads rather than simply relying on the operating system to do so, and so start should always be called within main() to begin normal program execution. Parameters: | | | | --- | --- | | void delegate() `op` | A wrapper for whatever the main thread would have done in the absence of a custom scheduler. It will be automatically executed via a call to spawn by the Scheduler. | abstract void **spawn**(void delegate() op); Assigns a logical thread to execute the supplied op. This routine is called by spawn. It is expected to instantiate a new logical thread and run the supplied operation. This thread must call thisInfo.cleanup() when the thread terminates if the scheduled thread is not a kernel thread--all kernel threads will have their ThreadInfo cleaned up automatically by a thread-local destructor. Parameters: | | | | --- | --- | | void delegate() `op` | The function to execute. This may be the actual function passed by the user to spawn itself, or may be a wrapper function. | abstract nothrow void **yield**(); Yields execution to another logical thread. This routine is called at various points within concurrency-aware APIs to provide a scheduler a chance to yield execution when using some sort of cooperative multithreading model. If this is not appropriate, such as when each logical thread is backed by a dedicated kernel thread, this routine may be a no-op. abstract nothrow @property ref ThreadInfo **thisInfo**(); Returns an appropriate ThreadInfo instance. Returns an instance of ThreadInfo specific to the logical thread that is calling this routine or, if the calling thread was not create by this scheduler, returns ThreadInfo.thisInfo instead. abstract nothrow Condition **newCondition**(Mutex m); Creates a Condition variable analog for signaling. Creates a new Condition variable analog which is used to check for and to signal the addition of messages to a thread's message queue. Like yield, some schedulers may need to define custom behavior so that calls to Condition.wait() yield to another thread when no new messages are available instead of blocking. Parameters: | | | | --- | --- | | Mutex `m` | The Mutex that will be associated with this condition. It will be locked prior to any operation on the condition, and so in some cases a Scheduler may need to hold this reference and unlock the mutex before yielding execution to another logical thread. | class **ThreadScheduler**: std.concurrency.Scheduler; An example Scheduler using kernel threads. This is an example Scheduler that mirrors the default scheduling behavior of creating one kernel thread per call to spawn. It is fully functional and may be instantiated and used, but is not a necessary part of the default functioning of this module. void **start**(void delegate() op); This simply runs op directly, since no real scheduling is needed by this approach. void **spawn**(void delegate() op); Creates a new kernel thread and assigns it to run the supplied op. nothrow void **yield**(); This scheduler does no explicit multiplexing, so this is a no-op. nothrow @property ref ThreadInfo **thisInfo**(); Returns ThreadInfo.thisInfo, since it is a thread-local instance of ThreadInfo, which is the correct behavior for this scheduler. nothrow Condition **newCondition**(Mutex m); Creates a new Condition variable. No custom behavior is needed here. class **FiberScheduler**: std.concurrency.Scheduler; An example Scheduler using Fibers. This is an example scheduler that creates a new Fiber per call to spawn and multiplexes the execution of all fibers within the main thread. void **start**(void delegate() op); This creates a new Fiber for the supplied op and then starts the dispatcher. nothrow void **spawn**(void delegate() op); This created a new Fiber for the supplied op and adds it to the dispatch list. nothrow void **yield**(); If the caller is a scheduled Fiber, this yields execution to another scheduled Fiber. nothrow @property ref ThreadInfo **thisInfo**(); Returns an appropriate ThreadInfo instance. Returns a ThreadInfo instance specific to the calling Fiber if the Fiber was created by this dispatcher, otherwise it returns ThreadInfo.thisInfo. nothrow Condition **newCondition**(Mutex m); Returns a Condition analog that yields when wait or notify is called. Bug For the default implementation, `notifyAll`will behave like `notify`. Parameters: | | | | --- | --- | | Mutex `m` | A `Mutex` to use for locking if the condition needs to be waited on or notified from multiple `Thread`s. If `null`, no `Mutex` will be used and it is assumed that the `Condition` is only waited on/notified from one `Thread`. | protected nothrow void **create**(void delegate() op); Creates a new Fiber which calls the given delegate. Parameters: | | | | --- | --- | | void delegate() `op` | The delegate the fiber should call | class **InfoFiber**: core.thread.fiber.Fiber; Fiber which embeds a ThreadInfo Scheduler **scheduler**; Sets the Scheduler behavior within the program. This variable sets the Scheduler behavior within this program. Typically, when setting a Scheduler, scheduler.start() should be called in main. This routine will not return until program execution is complete. nothrow void **yield**(); If the caller is a Fiber and is not a Generator, this function will call scheduler.yield() or Fiber.yield(), as appropriate. class **Generator**(T): Fiber, IsGenerator, InputRange!T; A Generator is a Fiber that periodically returns values of type T to the caller via yield. This is represented as an InputRange. Examples: ``` auto tid = spawn({ int i; while (i < 9) i = receiveOnly!int; ownerTid.send(i * 2); }); auto r = new Generator!int({ foreach (i; 1 .. 10) yield(i); }); foreach (e; r) tid.send(e); writeln(receiveOnly!int); // 18 ``` this(void function() fn); Initializes a generator object which is associated with a static D function. The function will be called once to prepare the range for iteration. Parameters: | | | | --- | --- | | void function() `fn` | The fiber function. | In fn must not be null. this(void function() fn, size\_t sz); Initializes a generator object which is associated with a static D function. The function will be called once to prepare the range for iteration. Parameters: | | | | --- | --- | | void function() `fn` | The fiber function. | | size\_t `sz` | The stack size for this fiber. | In fn must not be null. this(void function() fn, size\_t sz, size\_t guardPageSize); Initializes a generator object which is associated with a static D function. The function will be called once to prepare the range for iteration. Parameters: | | | | --- | --- | | void function() `fn` | The fiber function. | | size\_t `sz` | The stack size for this fiber. | | size\_t `guardPageSize` | size of the guard page to trap fiber's stack overflows. Refer to [`core.thread.Fiber`](core_thread#Fiber)'s documentation for more details. | In fn must not be null. this(void delegate() dg); Initializes a generator object which is associated with a dynamic D function. The function will be called once to prepare the range for iteration. Parameters: | | | | --- | --- | | void delegate() `dg` | The fiber function. | In dg must not be null. this(void delegate() dg, size\_t sz); Initializes a generator object which is associated with a dynamic D function. The function will be called once to prepare the range for iteration. Parameters: | | | | --- | --- | | void delegate() `dg` | The fiber function. | | size\_t `sz` | The stack size for this fiber. | In dg must not be null. this(void delegate() dg, size\_t sz, size\_t guardPageSize); Initializes a generator object which is associated with a dynamic D function. The function will be called once to prepare the range for iteration. Parameters: | | | | --- | --- | | void delegate() `dg` | The fiber function. | | size\_t `sz` | The stack size for this fiber. | | size\_t `guardPageSize` | size of the guard page to trap fiber's stack overflows. Refer to [`core.thread.Fiber`](core_thread#Fiber)'s documentation for more details. | In dg must not be null. final @property bool **empty**(); Returns true if the generator is empty. final void **popFront**(); Obtains the next value from the underlying function. final @property T **front**(); Returns the most recently generated value by shallow copy. final T **moveFront**(); Returns the most recently generated value without executing a copy contructor. Will not compile for element types defining a postblit, because Generator does not return by reference. void **yield**(T)(ref T value); void **yield**(T)(T value); Yields a value of type T to the caller of the currently executing generator. Parameters: | | | | --- | --- | | T `value` | The value to yield. | Examples: ``` import std.range; InputRange!int myIota = iota(10).inputRangeObject; myIota.popFront(); myIota.popFront(); writeln(myIota.moveFront); // 2 writeln(myIota.front); // 2 myIota.popFront(); writeln(myIota.front); // 3 //can be assigned to std.range.interfaces.InputRange directly myIota = new Generator!int( { foreach (i; 0 .. 10) yield(i); }); myIota.popFront(); myIota.popFront(); writeln(myIota.moveFront); // 2 writeln(myIota.front); // 2 myIota.popFront(); writeln(myIota.front); // 3 size_t[2] counter = [0, 0]; foreach (i, unused; myIota) counter[] += [1, i]; assert(myIota.empty); writeln(counter); // [7, 21] ``` ref auto **initOnce**(alias var)(lazy typeof(var) init); Initializes var with the lazy init value in a thread-safe manner. The implementation guarantees that all threads simultaneously calling initOnce with the same var argument block until var is fully initialized. All side-effects of init are globally visible afterwards. Parameters: | | | | --- | --- | | var | The variable to initialize | | typeof(var) `init` | The lazy initializer value | Returns: A reference to the initialized variable Examples: A typical use-case is to perform lazy but thread-safe initialization. ``` static class MySingleton { static MySingleton instance() { __gshared MySingleton inst; return initOnce!inst(new MySingleton); } } assert(MySingleton.instance !is null); ``` ref auto **initOnce**(alias var)(lazy typeof(var) init, shared Mutex mutex); ref auto **initOnce**(alias var)(lazy typeof(var) init, Mutex mutex); Same as above, but takes a separate mutex instead of sharing one among all initOnce instances. This should be used to avoid dead-locks when the init expression waits for the result of another thread that might also call initOnce. Use with care. Parameters: | | | | --- | --- | | var | The variable to initialize | | typeof(var) `init` | The lazy initializer value | | Mutex `mutex` | A mutex to prevent race conditions | Returns: A reference to the initialized variable Examples: Use a separate mutex when init blocks on another thread that might also call initOnce. ``` import core.sync.mutex : Mutex; static shared bool varA, varB; static shared Mutex m; m = new shared Mutex; spawn({ // use a different mutex for varB to avoid a dead-lock initOnce!varB(true, m); ownerTid.send(true); }); // init depends on the result of the spawned thread initOnce!varA(receiveOnly!bool); writeln(varA); // true writeln(varB); // true ```
programming_docs
d std.digest.sha std.digest.sha ============== Computes SHA1 and SHA2 hashes of arbitrary data. SHA hashes are 20 to 64 byte quantities (depending on the SHA algorithm) that are like a checksum or CRC, but are more robust. | Category | Functions | | --- | --- | | Template API | [*SHA1*](#SHA1) | | OOP API | [*SHA1Digest*](#SHA1Digest) | | Helpers | [*sha1Of*](#sha1Of) | SHA2 comes in several different versions, all supported by this module: SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224 and SHA-512/256. This module conforms to the APIs defined in [`std.digest`](std_digest). To understand the differences between the template and the OOP API, see [`std.digest`](std_digest). This module publicly imports `std.digest` and can be used as a stand-alone module. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). CTFE Digests do not work in CTFE Authors: The routines and algorithms are derived from the *Secure Hash Signature Standard (SHS) (FIPS PUB 180-2)*. Kai Nacke, Johannes Pfau, Nick Sabalausky References * [FIPS PUB180-2](http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf) * [Fast implementation of SHA1](http://software.intel.com/en-us/articles/improving-the-performance-of-the-secure-hash-algorithm-1/) * [Wikipedia article about SHA](http://en.wikipedia.org/wiki/Secure_Hash_Algorithm) Source [std/digest/sha.d](https://github.com/dlang/phobos/blob/master/std/digest/sha.d) Examples: ``` //Template API import std.digest.sha; ubyte[20] hash1 = sha1Of("abc"); writeln(toHexString(hash1)); // "A9993E364706816ABA3E25717850C26C9CD0D89D" ubyte[28] hash224 = sha224Of("abc"); writeln(toHexString(hash224)); // "23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7" //Feeding data ubyte[1024] data; SHA1 sha1; sha1.start(); sha1.put(data[]); sha1.start(); //Start again sha1.put(data[]); hash1 = sha1.finish(); ``` Examples: ``` //OOP API import std.digest.sha; auto sha1 = new SHA1Digest(); ubyte[] hash1 = sha1.digest("abc"); writeln(toHexString(hash1)); // "A9993E364706816ABA3E25717850C26C9CD0D89D" auto sha224 = new SHA224Digest(); ubyte[] hash224 = sha224.digest("abc"); writeln(toHexString(hash224)); // "23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7" //Feeding data ubyte[1024] data; sha1.put(data[]); sha1.reset(); //Start again sha1.put(data[]); hash1 = sha1.finish(); ``` struct **SHA**(uint hashBlockSize, uint digestSize); Template API SHA1/SHA2 implementation. Supports: SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224 and SHA-512/256. The hashBlockSize and digestSize are in bits. However, it's likely easier to simply use the convenience aliases: SHA1, SHA224, SHA256, SHA384, SHA512, SHA512\_224 and SHA512\_256. See `std.digest` for differences between template and OOP API. Examples: ``` //Simple example, hashing a string using sha1Of helper function ubyte[20] hash = sha1Of("abc"); //Let's get a hash string writeln(toHexString(hash)); // "A9993E364706816ABA3E25717850C26C9CD0D89D" //The same, but using SHA-224 ubyte[28] hash224 = sha224Of("abc"); writeln(toHexString(hash224)); // "23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7" ``` Examples: ``` //Using the basic API SHA1 hash; hash.start(); ubyte[1024] data; //Initialize data here... hash.put(data); ubyte[20] result = hash.finish(); ``` Examples: ``` //Let's use the template features: //Note: When passing a SHA1 to a function, it must be passed by reference! void doSomething(T)(ref T hash) if (isDigest!T) { hash.put(cast(ubyte) 0); } SHA1 sha; sha.start(); doSomething(sha); writeln(toHexString(sha.finish())); // "5BA93C9DB0CFF93F52B521D7420E43F6EDA2784F" ``` pure nothrow @nogc @safe void **start**(); SHA initialization. Begins an SHA1/SHA2 operation. Note For this SHA Digest implementation calling start after default construction is not necessary. Calling start is only necessary to reset the Digest. Generic code which deals with different Digest types should always call start though. Example ``` SHA1 digest; //digest.start(); //Not necessary digest.put(0); ``` pure nothrow @nogc @trusted void **put**(scope const(ubyte)[] input...); Use this to feed the digest with data. Also implements the [`std.range.primitives.isOutputRange`](std_range_primitives#isOutputRange) interface for `ubyte` and `const(ubyte)[]`. pure nothrow @nogc @trusted ubyte[digestSize / 8] **finish**(); Returns the finished SHA hash. This also calls [`start`](#start) to reset the internal state. Examples: ``` //Simple example SHA1 hash; hash.start(); hash.put(cast(ubyte) 0); ubyte[20] result = hash.finish(); ``` alias **SHA1** = SHA!(512u, 160u).SHA; SHA alias for SHA-1, hash is ubyte[20] alias **SHA224** = SHA!(512u, 224u).SHA; SHA alias for SHA-224, hash is ubyte[28] alias **SHA256** = SHA!(512u, 256u).SHA; SHA alias for SHA-256, hash is ubyte[32] alias **SHA384** = SHA!(1024u, 384u).SHA; SHA alias for SHA-384, hash is ubyte[48] alias **SHA512** = SHA!(1024u, 512u).SHA; SHA alias for SHA-512, hash is ubyte[64] alias **SHA512\_224** = SHA!(1024u, 224u).SHA; SHA alias for SHA-512/224, hash is ubyte[28] alias **SHA512\_256** = SHA!(1024u, 256u).SHA; SHA alias for SHA-512/256, hash is ubyte[32] auto **sha1Of**(T...)(T data); auto **sha224Of**(T...)(T data); auto **sha256Of**(T...)(T data); auto **sha384Of**(T...)(T data); auto **sha512Of**(T...)(T data); auto **sha512\_224Of**(T...)(T data); auto **sha512\_256Of**(T...)(T data); These are convenience aliases for [`std.digest.digest`](std_digest#digest) using the SHA implementation. Examples: ``` ubyte[20] hash = sha1Of("abc"); writeln(hash); // digest!SHA1("abc") ubyte[28] hash224 = sha224Of("abc"); writeln(hash224); // digest!SHA224("abc") ubyte[32] hash256 = sha256Of("abc"); writeln(hash256); // digest!SHA256("abc") ubyte[48] hash384 = sha384Of("abc"); writeln(hash384); // digest!SHA384("abc") ubyte[64] hash512 = sha512Of("abc"); writeln(hash512); // digest!SHA512("abc") ubyte[28] hash512_224 = sha512_224Of("abc"); writeln(hash512_224); // digest!SHA512_224("abc") ubyte[32] hash512_256 = sha512_256Of("abc"); writeln(hash512_256); // digest!SHA512_256("abc") ``` alias **SHA1Digest** = std.digest.WrapperDigest!(SHA!(512u, 160u)).WrapperDigest; alias **SHA224Digest** = std.digest.WrapperDigest!(SHA!(512u, 224u)).WrapperDigest; alias **SHA256Digest** = std.digest.WrapperDigest!(SHA!(512u, 256u)).WrapperDigest; alias **SHA384Digest** = std.digest.WrapperDigest!(SHA!(1024u, 384u)).WrapperDigest; alias **SHA512Digest** = std.digest.WrapperDigest!(SHA!(1024u, 512u)).WrapperDigest; alias **SHA512\_224Digest** = std.digest.WrapperDigest!(SHA!(1024u, 224u)).WrapperDigest; alias **SHA512\_256Digest** = std.digest.WrapperDigest!(SHA!(1024u, 256u)).WrapperDigest; OOP API SHA1 and SHA2 implementations. See `std.digest` for differences between template and OOP API. This is an alias for `[std.digest.WrapperDigest](std_digest#WrapperDigest)!SHA1`, see there for more information. Examples: ``` //Simple example, hashing a string using Digest.digest helper function auto sha = new SHA1Digest(); ubyte[] hash = sha.digest("abc"); //Let's get a hash string writeln(toHexString(hash)); // "A9993E364706816ABA3E25717850C26C9CD0D89D" //The same, but using SHA-224 auto sha224 = new SHA224Digest(); ubyte[] hash224 = sha224.digest("abc"); //Let's get a hash string writeln(toHexString(hash224)); // "23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7" ``` Examples: ``` //Let's use the OOP features: void test(Digest dig) { dig.put(cast(ubyte) 0); } auto sha = new SHA1Digest(); test(sha); //Let's use a custom buffer: ubyte[20] buf; ubyte[] result = sha.finish(buf[]); writeln(toHexString(result)); // "5BA93C9DB0CFF93F52B521D7420E43F6EDA2784F" ``` d core.stdc.math core.stdc.math ============== D header file for C99. This module contains bindings to selected types and functions from the standard C header [`<math.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/math.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Sean Kelly Source [core/stdc/math.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/math.d) alias **float\_t** = float; alias **double\_t** = double; enum double **HUGE\_VAL**; enum double **HUGE\_VALF**; enum double **HUGE\_VALL**; enum float **INFINITY**; enum float **NAN**; enum int **FP\_ILOGB0**; enum int **FP\_ILOGBNAN**; enum int **MATH\_ERRNO**; enum int **MATH\_ERREXCEPT**; enum int **math\_errhandling**; **FP\_NAN** **FP\_INFINITE** **FP\_ZERO** **FP\_SUBNORMAL** **FP\_NORMAL** **FP\_FAST\_FMA** **FP\_FAST\_FMAF** **FP\_FAST\_FMAL** pure nothrow @nogc @trusted int **fpclassify**(float x); pure nothrow @nogc @trusted int **fpclassify**(double x); pure nothrow @nogc @trusted int **fpclassify**(real x); pure nothrow @nogc @trusted int **isfinite**(float x); pure nothrow @nogc @trusted int **isfinite**(double x); pure nothrow @nogc @trusted int **isfinite**(real x); pure nothrow @nogc @trusted int **isinf**(float x); pure nothrow @nogc @trusted int **isinf**(double x); pure nothrow @nogc @trusted int **isinf**(real x); pure nothrow @nogc @trusted int **isnan**(float x); pure nothrow @nogc @trusted int **isnan**(double x); pure nothrow @nogc @trusted int **isnan**(real x); pure nothrow @nogc @trusted int **isnormal**(float x); pure nothrow @nogc @trusted int **isnormal**(double x); pure nothrow @nogc @trusted int **isnormal**(real x); pure nothrow @nogc @trusted int **signbit**(float x); pure nothrow @nogc @trusted int **signbit**(double x); pure nothrow @nogc @trusted int **signbit**(real x); pure nothrow @nogc @trusted int **isgreater**(float x, float y); pure nothrow @nogc @trusted int **isgreater**(double x, double y); pure nothrow @nogc @trusted int **isgreater**(real x, real y); pure nothrow @nogc @trusted int **isgreaterequal**(float x, float y); pure nothrow @nogc @trusted int **isgreaterequal**(double x, double y); pure nothrow @nogc @trusted int **isgreaterequal**(real x, real y); pure nothrow @nogc @trusted int **isless**(float x, float y); pure nothrow @nogc @trusted int **isless**(double x, double y); pure nothrow @nogc @trusted int **isless**(real x, real y); pure nothrow @nogc @trusted int **islessequal**(float x, float y); pure nothrow @nogc @trusted int **islessequal**(double x, double y); pure nothrow @nogc @trusted int **islessequal**(real x, real y); pure nothrow @nogc @trusted int **islessgreater**(float x, float y); pure nothrow @nogc @trusted int **islessgreater**(double x, double y); pure nothrow @nogc @trusted int **islessgreater**(real x, real y); pure nothrow @nogc @trusted int **isunordered**(float x, float y); pure nothrow @nogc @trusted int **isunordered**(double x, double y); pure nothrow @nogc @trusted int **isunordered**(real x, real y); nothrow @nogc @trusted double **acos**(double x); nothrow @nogc @trusted float **acosf**(float x); nothrow @nogc @trusted real **acosl**(real x); nothrow @nogc @trusted double **asin**(double x); nothrow @nogc @trusted float **asinf**(float x); nothrow @nogc @trusted real **asinl**(real x); pure nothrow @nogc @trusted double **atan**(double x); pure nothrow @nogc @trusted float **atanf**(float x); pure nothrow @nogc @trusted real **atanl**(real x); nothrow @nogc @trusted double **atan2**(double y, double x); nothrow @nogc @trusted float **atan2f**(float y, float x); nothrow @nogc @trusted real **atan2l**(real y, real x); pure nothrow @nogc @trusted double **cos**(double x); pure nothrow @nogc @trusted float **cosf**(float x); pure nothrow @nogc @trusted real **cosl**(real x); pure nothrow @nogc @trusted double **sin**(double x); pure nothrow @nogc @trusted float **sinf**(float x); pure nothrow @nogc @trusted real **sinl**(real x); pure nothrow @nogc @trusted double **tan**(double x); pure nothrow @nogc @trusted float **tanf**(float x); pure nothrow @nogc @trusted real **tanl**(real x); nothrow @nogc @trusted double **acosh**(double x); nothrow @nogc @trusted float **acoshf**(float x); nothrow @nogc @trusted real **acoshl**(real x); pure nothrow @nogc @trusted double **asinh**(double x); pure nothrow @nogc @trusted float **asinhf**(float x); pure nothrow @nogc @trusted real **asinhl**(real x); nothrow @nogc @trusted double **atanh**(double x); nothrow @nogc @trusted float **atanhf**(float x); nothrow @nogc @trusted real **atanhl**(real x); nothrow @nogc @trusted double **cosh**(double x); nothrow @nogc @trusted float **coshf**(float x); nothrow @nogc @trusted real **coshl**(real x); nothrow @nogc @trusted double **sinh**(double x); nothrow @nogc @trusted float **sinhf**(float x); nothrow @nogc @trusted real **sinhl**(real x); pure nothrow @nogc @trusted double **tanh**(double x); pure nothrow @nogc @trusted float **tanhf**(float x); pure nothrow @nogc @trusted real **tanhl**(real x); nothrow @nogc @trusted double **exp**(double x); nothrow @nogc @trusted float **expf**(float x); nothrow @nogc @trusted real **expl**(real x); nothrow @nogc @trusted double **exp2**(double x); nothrow @nogc @trusted float **exp2f**(float x); nothrow @nogc @trusted real **exp2l**(real x); nothrow @nogc @trusted double **expm1**(double x); nothrow @nogc @trusted float **expm1f**(float x); nothrow @nogc @trusted real **expm1l**(real x); pure nothrow @nogc @trusted double **frexp**(double value, int\* exp); pure nothrow @nogc @trusted float **frexpf**(float value, int\* exp); pure nothrow @nogc @trusted real **frexpl**(real value, int\* exp); nothrow @nogc @trusted int **ilogb**(double x); nothrow @nogc @trusted int **ilogbf**(float x); nothrow @nogc @trusted int **ilogbl**(real x); nothrow @nogc @trusted double **ldexp**(double x, int exp); nothrow @nogc @trusted float **ldexpf**(float x, int exp); nothrow @nogc @trusted real **ldexpl**(real x, int exp); nothrow @nogc @trusted double **log**(double x); nothrow @nogc @trusted float **logf**(float x); nothrow @nogc @trusted real **logl**(real x); nothrow @nogc @trusted double **log10**(double x); nothrow @nogc @trusted float **log10f**(float x); nothrow @nogc @trusted real **log10l**(real x); nothrow @nogc @trusted double **log1p**(double x); nothrow @nogc @trusted float **log1pf**(float x); nothrow @nogc @trusted real **log1pl**(real x); nothrow @nogc @trusted double **log2**(double x); nothrow @nogc @trusted float **log2f**(float x); nothrow @nogc @trusted real **log2l**(real x); nothrow @nogc @trusted double **logb**(double x); nothrow @nogc @trusted float **logbf**(float x); nothrow @nogc @trusted real **logbl**(real x); pure nothrow @nogc @trusted double **modf**(double value, double\* iptr); pure nothrow @nogc @trusted float **modff**(float value, float\* iptr); pure nothrow @nogc @trusted real **modfl**(real value, real\* iptr); nothrow @nogc @trusted double **scalbn**(double x, int n); nothrow @nogc @trusted float **scalbnf**(float x, int n); nothrow @nogc @trusted real **scalbnl**(real x, int n); nothrow @nogc @trusted double **scalbln**(double x, c\_long n); nothrow @nogc @trusted float **scalblnf**(float x, c\_long n); nothrow @nogc @trusted real **scalblnl**(real x, c\_long n); pure nothrow @nogc @trusted double **cbrt**(double x); pure nothrow @nogc @trusted float **cbrtf**(float x); pure nothrow @nogc @trusted real **cbrtl**(real x); pure nothrow @nogc @trusted double **fabs**(double x); pure nothrow @nogc @trusted float **fabsf**(float x); pure nothrow @nogc @trusted real **fabsl**(real x); nothrow @nogc @trusted double **hypot**(double x, double y); nothrow @nogc @trusted float **hypotf**(float x, float y); nothrow @nogc @trusted real **hypotl**(real x, real y); nothrow @nogc @trusted double **pow**(double x, double y); nothrow @nogc @trusted float **powf**(float x, float y); nothrow @nogc @trusted real **powl**(real x, real y); nothrow @nogc @trusted double **sqrt**(double x); nothrow @nogc @trusted float **sqrtf**(float x); nothrow @nogc @trusted real **sqrtl**(real x); pure nothrow @nogc @trusted double **erf**(double x); pure nothrow @nogc @trusted float **erff**(float x); pure nothrow @nogc @trusted real **erfl**(real x); nothrow @nogc @trusted double **erfc**(double x); nothrow @nogc @trusted float **erfcf**(float x); nothrow @nogc @trusted real **erfcl**(real x); nothrow @nogc @trusted double **lgamma**(double x); nothrow @nogc @trusted float **lgammaf**(float x); nothrow @nogc @trusted real **lgammal**(real x); nothrow @nogc @trusted double **tgamma**(double x); nothrow @nogc @trusted float **tgammaf**(float x); nothrow @nogc @trusted real **tgammal**(real x); pure nothrow @nogc @trusted double **ceil**(double x); pure nothrow @nogc @trusted float **ceilf**(float x); pure nothrow @nogc @trusted real **ceill**(real x); pure nothrow @nogc @trusted double **floor**(double x); pure nothrow @nogc @trusted float **floorf**(float x); pure nothrow @nogc @trusted real **floorl**(real x); pure nothrow @nogc @trusted double **nearbyint**(double x); pure nothrow @nogc @trusted float **nearbyintf**(float x); pure nothrow @nogc @trusted real **nearbyintl**(real x); pure nothrow @nogc @trusted double **rint**(double x); pure nothrow @nogc @trusted float **rintf**(float x); pure nothrow @nogc @trusted real **rintl**(real x); nothrow @nogc @trusted c\_long **lrint**(double x); nothrow @nogc @trusted c\_long **lrintf**(float x); nothrow @nogc @trusted c\_long **lrintl**(real x); nothrow @nogc @trusted long **llrint**(double x); nothrow @nogc @trusted long **llrintf**(float x); nothrow @nogc @trusted long **llrintl**(real x); pure nothrow @nogc @trusted double **round**(double x); pure nothrow @nogc @trusted float **roundf**(float x); pure nothrow @nogc @trusted real **roundl**(real x); nothrow @nogc @trusted c\_long **lround**(double x); nothrow @nogc @trusted c\_long **lroundf**(float x); nothrow @nogc @trusted c\_long **lroundl**(real x); nothrow @nogc @trusted long **llround**(double x); nothrow @nogc @trusted long **llroundf**(float x); nothrow @nogc @trusted long **llroundl**(real x); pure nothrow @nogc @trusted double **trunc**(double x); pure nothrow @nogc @trusted float **truncf**(float x); pure nothrow @nogc @trusted real **truncl**(real x); nothrow @nogc @trusted double **fmod**(double x, double y); nothrow @nogc @trusted float **fmodf**(float x, float y); nothrow @nogc @trusted real **fmodl**(real x, real y); nothrow @nogc @trusted double **remainder**(double x, double y); nothrow @nogc @trusted float **remainderf**(float x, float y); nothrow @nogc @trusted real **remainderl**(real x, real y); nothrow @nogc @trusted double **remquo**(double x, double y, int\* quo); nothrow @nogc @trusted float **remquof**(float x, float y, int\* quo); nothrow @nogc @trusted real **remquol**(real x, real y, int\* quo); pure nothrow @nogc @trusted double **copysign**(double x, double y); pure nothrow @nogc @trusted float **copysignf**(float x, float y); pure nothrow @nogc @trusted real **copysignl**(real x, real y); pure nothrow @nogc @trusted double **nan**(char\* tagp); pure nothrow @nogc @trusted float **nanf**(char\* tagp); pure nothrow @nogc @trusted real **nanl**(char\* tagp); nothrow @nogc @trusted double **nextafter**(double x, double y); nothrow @nogc @trusted float **nextafterf**(float x, float y); nothrow @nogc @trusted real **nextafterl**(real x, real y); nothrow @nogc @trusted double **nexttoward**(double x, real y); nothrow @nogc @trusted float **nexttowardf**(float x, real y); nothrow @nogc @trusted real **nexttowardl**(real x, real y); nothrow @nogc @trusted double **fdim**(double x, double y); nothrow @nogc @trusted float **fdimf**(float x, float y); nothrow @nogc @trusted real **fdiml**(real x, real y); pure nothrow @nogc @trusted double **fmax**(double x, double y); pure nothrow @nogc @trusted float **fmaxf**(float x, float y); pure nothrow @nogc @trusted real **fmaxl**(real x, real y); pure nothrow @nogc @trusted double **fmin**(double x, double y); pure nothrow @nogc @trusted float **fminf**(float x, float y); pure nothrow @nogc @trusted real **fminl**(real x, real y); pure nothrow @nogc @trusted double **fma**(double x, double y, double z); pure nothrow @nogc @trusted float **fmaf**(float x, float y, float z); pure nothrow @nogc @trusted real **fmal**(real x, real y, real z);
programming_docs
d std.encoding std.encoding ============ Classes and functions for handling and transcoding between various encodings. For cases where the encoding is known at compile-time, functions are provided for arbitrary encoding and decoding of characters, arbitrary transcoding between strings of different type, as well as validation and sanitization. Encodings currently supported are UTF-8, UTF-16, UTF-32, ASCII, ISO-8859-1 (also known as LATIN-1), ISO-8859-2 (LATIN-2), WINDOWS-1250, WINDOWS-1251 and WINDOWS-1252. | Category | Functions | | --- | --- | | Decode | [`codePoints`](#codePoints) [`decode`](#decode) [`decodeReverse`](#decodeReverse) [`safeDecode`](#safeDecode) | | Conversion | [`codeUnits`](#codeUnits) [`sanitize`](#sanitize) [`transcode`](#transcode) | | Classification | [`canEncode`](#canEncode) [`isValid`](#isValid) [`isValidCodePoint`](#isValidCodePoint) [`isValidCodeUnit`](#isValidCodeUnit) | | BOM | [`BOM`](#BOM) [`BOMSeq`](#BOMSeq) [`getBOM`](#getBOM) [`utfBOM`](#utfBOM) | | Length & Index | [`firstSequence`](#firstSequence) [`encodedLength`](#encodedLength) [`index`](#index) [`lastSequence`](#lastSequence) [`validLength`](#validLength) | | Encoding schemes | [`encodingName`](#encodingName) [`EncodingScheme`](#EncodingScheme) [`EncodingSchemeASCII`](#EncodingSchemeASCII) [`EncodingSchemeLatin1`](#EncodingSchemeLatin1) [`EncodingSchemeLatin2`](#EncodingSchemeLatin2) [`EncodingSchemeUtf16Native`](#EncodingSchemeUtf16Native) [`EncodingSchemeUtf32Native`](#EncodingSchemeUtf32Native) [`EncodingSchemeUtf8`](#EncodingSchemeUtf8) [`EncodingSchemeWindows1250`](#EncodingSchemeWindows1250) [`EncodingSchemeWindows1251`](#EncodingSchemeWindows1251) [`EncodingSchemeWindows1252`](#EncodingSchemeWindows1252) | | Representation | [`AsciiChar`](#AsciiChar) [`AsciiString`](#AsciiString) [`Latin1Char`](#Latin1Char) [`Latin1String`](#Latin1String) [`Latin2Char`](#Latin2Char) [`Latin2String`](#Latin2String) [`Windows1250Char`](#Windows1250Char) [`Windows1250String`](#Windows1250String) [`Windows1251Char`](#Windows1251Char) [`Windows1251String`](#Windows1251String) [`Windows1252Char`](#Windows1252Char) [`Windows1252String`](#Windows1252String) | | Exceptions | [`INVALID_SEQUENCE`](#INVALID_SEQUENCE) [`EncodingException`](#EncodingException) | For cases where the encoding is not known at compile-time, but is known at run-time, the abstract class [`EncodingScheme`](#EncodingScheme) and its subclasses is provided. To construct a run-time encoder/decoder, one does e.g. ``` auto e = EncodingScheme.create("utf-8"); ``` This library supplies [`EncodingScheme`](#EncodingScheme) subclasses for ASCII, ISO-8859-1 (also known as LATIN-1), ISO-8859-2 (LATIN-2), WINDOWS-1250, WINDOWS-1251, WINDOWS-1252, UTF-8, and (on little-endian architectures) UTF-16LE and UTF-32LE; or (on big-endian architectures) UTF-16BE and UTF-32BE. This library provides a mechanism whereby other modules may add [`EncodingScheme`](#EncodingScheme) subclasses for any other encoding. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Janice Caron Source [std/encoding.d](https://github.com/dlang/phobos/blob/master/std/encoding.d) enum dchar **INVALID\_SEQUENCE**; Special value returned by `safeDecode` enum **AsciiChar**: ubyte; alias **AsciiString** = immutable(AsciiChar)[]; Defines various character sets. enum **Latin1Char**: ubyte; Defines an Latin1-encoded character. alias **Latin1String** = immutable(Latin1Char)[]; Defines an Latin1-encoded string (as an array of `immutable(Latin1Char)`). enum **Latin2Char**: ubyte; Defines a Latin2-encoded character. alias **Latin2String** = immutable(Latin2Char)[]; Defines an Latin2-encoded string (as an array of `immutable(Latin2Char)`). enum **Windows1250Char**: ubyte; Defines a Windows1250-encoded character. alias **Windows1250String** = immutable(Windows1250Char)[]; Defines an Windows1250-encoded string (as an array of `immutable(Windows1250Char)`). enum **Windows1251Char**: ubyte; Defines a Windows1251-encoded character. alias **Windows1251String** = immutable(Windows1251Char)[]; Defines an Windows1251-encoded string (as an array of `immutable(Windows1251Char)`). enum **Windows1252Char**: ubyte; Defines a Windows1252-encoded character. alias **Windows1252String** = immutable(Windows1252Char)[]; Defines an Windows1252-encoded string (as an array of `immutable(Windows1252Char)`). pure nothrow @nogc @safe bool **isValidCodePoint**(dchar c); Returns true if c is a valid code point Note that this includes the non-character code points U+FFFE and U+FFFF, since these are valid code points (even though they are not valid characters). Supersedes This function supersedes `std.utf.startsValidDchar()`. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | dchar `c` | the code point to be tested | @property string **encodingName**(T)(); Returns the name of an encoding. The type of encoding cannot be deduced. Therefore, it is necessary to explicitly specify the encoding type. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Examples: ``` writeln(encodingName!(char)); // "UTF-8" writeln(encodingName!(wchar)); // "UTF-16" writeln(encodingName!(dchar)); // "UTF-32" writeln(encodingName!(AsciiChar)); // "ASCII" writeln(encodingName!(Latin1Char)); // "ISO-8859-1" writeln(encodingName!(Latin2Char)); // "ISO-8859-2" writeln(encodingName!(Windows1250Char)); // "windows-1250" writeln(encodingName!(Windows1251Char)); // "windows-1251" writeln(encodingName!(Windows1252Char)); // "windows-1252" ``` bool **canEncode**(E)(dchar c); Returns true iff it is possible to represent the specified codepoint in the encoding. The type of encoding cannot be deduced. Therefore, it is necessary to explicitly specify the encoding type. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Examples: ``` assert( canEncode!(Latin1Char)('A')); assert( canEncode!(Latin2Char)('A')); assert(!canEncode!(AsciiChar)('\u00A0')); assert( canEncode!(Latin1Char)('\u00A0')); assert( canEncode!(Latin2Char)('\u00A0')); assert( canEncode!(Windows1250Char)('\u20AC')); assert(!canEncode!(Windows1250Char)('\u20AD')); assert(!canEncode!(Windows1250Char)('\uFFFD')); assert( canEncode!(Windows1251Char)('\u0402')); assert(!canEncode!(Windows1251Char)('\u20AD')); assert(!canEncode!(Windows1251Char)('\uFFFD')); assert( canEncode!(Windows1252Char)('\u20AC')); assert(!canEncode!(Windows1252Char)('\u20AD')); assert(!canEncode!(Windows1252Char)('\uFFFD')); assert(!canEncode!(char)(cast(dchar) 0x110000)); ``` Examples: How to check an entire string ``` import std.algorithm.searching : find; import std.utf : byDchar; assert("The quick brown fox" .byDchar .find!(x => !canEncode!AsciiChar(x)) .empty); ``` bool **isValidCodeUnit**(E)(E c); Returns true if the code unit is legal. For example, the byte 0x80 would not be legal in ASCII, because ASCII code units must always be in the range 0x00 to 0x7F. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | E `c` | the code unit to be tested | Examples: ``` assert(!isValidCodeUnit(cast(char) 0xC0)); assert(!isValidCodeUnit(cast(char) 0xFF)); assert( isValidCodeUnit(cast(wchar) 0xD800)); assert(!isValidCodeUnit(cast(dchar) 0xD800)); assert(!isValidCodeUnit(cast(AsciiChar) 0xA0)); assert( isValidCodeUnit(cast(Windows1250Char) 0x80)); assert(!isValidCodeUnit(cast(Windows1250Char) 0x81)); assert( isValidCodeUnit(cast(Windows1251Char) 0x80)); assert(!isValidCodeUnit(cast(Windows1251Char) 0x98)); assert( isValidCodeUnit(cast(Windows1252Char) 0x80)); assert(!isValidCodeUnit(cast(Windows1252Char) 0x81)); ``` bool **isValid**(E)(const(E)[] s); Returns true if the string is encoded correctly Supersedes This function supersedes std.utf.validate(), however note that this function returns a bool indicating whether the input was valid or not, whereas the older function would throw an exception. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | const(E)[] `s` | the string to be tested | Examples: ``` assert( isValid("\u20AC100")); assert(!isValid(cast(char[3])[167, 133, 175])); ``` size\_t **validLength**(E)(const(E)[] s); Returns the length of the longest possible substring, starting from the first code unit, which is validly encoded. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | const(E)[] `s` | the string to be tested | immutable(E)[] **sanitize**(E)(immutable(E)[] s); Sanitizes a string by replacing malformed code unit sequences with valid code unit sequences. The result is guaranteed to be valid for this encoding. If the input string is already valid, this function returns the original, otherwise it constructs a new string by replacing all illegal code unit sequences with the encoding's replacement character, Invalid sequences will be replaced with the Unicode replacement character (U+FFFD) if the character repertoire contains it, otherwise invalid sequences will be replaced with '?'. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | immutable(E)[] `s` | the string to be sanitized | Examples: ``` writeln(sanitize("hello \xF0\x80world")); // "hello \xEF\xBF\xBDworld" ``` size\_t **firstSequence**(E)(const(E)[] s); Returns the length of the first encoded sequence. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | const(E)[] `s` | the string to be sliced | Examples: ``` writeln(firstSequence("\u20AC1000")); // "\u20AC".length writeln(firstSequence("hel")); // "h".length ``` size\_t **lastSequence**(E)(const(E)[] s); Returns the length of the last encoded sequence. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | const(E)[] `s` | the string to be sliced | Examples: ``` writeln(lastSequence("1000\u20AC")); // "\u20AC".length writeln(lastSequence("hellö")); // "ö".length ``` ptrdiff\_t **index**(E)(const(E)[] s, int n); Returns the array index at which the (n+1)th code point begins. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Supersedes This function supersedes std.utf.toUTFindex(). Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | const(E)[] `s` | the string to be counted | | int `n` | the current code point index | Examples: ``` writeln(index("\u20AC100", 1)); // 3 writeln(index("hällo", 2)); // 3 ``` dchar **decode**(S)(ref S s); Decodes a single code point. This function removes one or more code units from the start of a string, and returns the decoded code point which those code units represent. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Supersedes This function supersedes std.utf.decode(), however, note that the function codePoints() supersedes it more conveniently. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | S `s` | the string whose first code point is to be decoded | dchar **decodeReverse**(E)(ref const(E)[] s); Decodes a single code point from the end of a string. This function removes one or more code units from the end of a string, and returns the decoded code point which those code units represent. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | const(E)[] `s` | the string whose first code point is to be decoded | dchar **safeDecode**(S)(ref S s); Decodes a single code point. The input does not have to be valid. This function removes one or more code units from the start of a string, and returns the decoded code point which those code units represent. This function will accept an invalidly encoded string as input. If an invalid sequence is found at the start of the string, this function will remove it, and return the value INVALID\_SEQUENCE. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | S `s` | the string whose first code point is to be decoded | size\_t **encodedLength**(E)(dchar c); Returns the number of code units required to encode a single code point. The input to this function MUST be a valid code point. This is enforced by the function's in-contract. The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding as a template parameter. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | dchar `c` | the code point to be encoded | E[] **encode**(E)(dchar c); Encodes a single code point. This function encodes a single code point into one or more code units. It returns a string containing those code units. The input to this function MUST be a valid code point. This is enforced by the function's in-contract. The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding as a template parameter. Supersedes This function supersedes std.utf.encode(), however, note that the function codeUnits() supersedes it more conveniently. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | dchar `c` | the code point to be encoded | size\_t **encode**(E)(dchar c, E[] array); Encodes a single code point into an array. This function encodes a single code point into one or more code units The code units are stored in a user-supplied fixed-size array, which must be passed by reference. The input to this function MUST be a valid code point. This is enforced by the function's in-contract. The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding as a template parameter. Supersedes This function supersedes std.utf.encode(), however, note that the function codeUnits() supersedes it more conveniently. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | dchar `c` | the code point to be encoded | | E[] `array` | the destination array | Returns: the number of code units written to the array void **encode**(E)(dchar c, void delegate(E) dg); Encodes a single code point to a delegate. This function encodes a single code point into one or more code units. The code units are passed one at a time to the supplied delegate. The input to this function MUST be a valid code point. This is enforced by the function's in-contract. The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding as a template parameter. Supersedes This function supersedes std.utf.encode(), however, note that the function codeUnits() supersedes it more conveniently. Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | dchar `c` | the code point to be encoded | | void delegate(E) `dg` | the delegate to invoke for each code unit | size\_t **encode**(Tgt, Src, R)(in Src[] s, R range); Encodes the contents of `s` in units of type `Tgt`, writing the result to an output range. Returns: The number of `Tgt` elements written. Parameters: | | | | --- | --- | | Tgt | Element type of `range`. | | Src[] `s` | Input array. | | R `range` | Output range. | CodePoints!E **codePoints**(E)(immutable(E)[] s); Returns a foreachable struct which can bidirectionally iterate over all code points in a string. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. You can foreach either with or without an index. If an index is specified, it will be initialized at each iteration with the offset into the string at which the code point begins. Supersedes This function supersedes std.utf.decode(). Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | immutable(E)[] `s` | the string to be decoded | Example ``` string s = "hello world"; foreach (c;codePoints(s)) { // do something with c (which will always be a dchar) } ``` Note that, currently, foreach (c:codePoints(s)) is superior to foreach (c;s) in that the latter will fall over on encountering U+FFFF. Examples: ``` string s = "hello"; string t; foreach (c;codePoints(s)) { t ~= cast(char) c; } writeln(s); // t ``` CodeUnits!E **codeUnits**(E)(dchar c); Returns a foreachable struct which can bidirectionally iterate over all code units in a code point. The input to this function MUST be a valid code point. This is enforced by the function's in-contract. The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding type in the template parameter. Supersedes This function supersedes std.utf.encode(). Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | dchar `c` | the code point to be encoded | Examples: ``` char[] a; foreach (c;codeUnits!(char)(cast(dchar)'\u20AC')) { a ~= c; } writeln(a.length); // 3 writeln(a[0]); // 0xE2 writeln(a[1]); // 0x82 writeln(a[2]); // 0xAC ``` void **transcode**(Src, Dst)(Src[] s, out Dst[] r); Convert a string from one encoding to another. Supersedes This function supersedes std.utf.toUTF8(), std.utf.toUTF16() and std.utf.toUTF32() (but note that to!() supersedes it more conveniently). Standards: Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 Parameters: | | | | --- | --- | | Src[] `s` | Source string. Must be validly encoded. This is enforced by the function's in-contract. | | Dst[] `r` | Destination string | See Also: [`std.conv.to`](std_conv#to) Examples: ``` wstring ws; // transcode from UTF-8 to UTF-16 transcode("hello world",ws); writeln(ws); // "hello world"w Latin1String ls; // transcode from UTF-16 to ISO-8859-1 transcode(ws, ls); writeln(ls); // "hello world" ``` class **EncodingException**: object.Exception; The base class for exceptions thrown by this module abstract class **EncodingScheme**; Abstract base class of all encoding schemes void **register**(Klass : EncodingScheme)(); Registers a subclass of EncodingScheme. This function allows user-defined subclasses of EncodingScheme to be declared in other modules. Parameters: | | | | --- | --- | | Klass | The subclass of EncodingScheme to register. | Example ``` class Amiga1251 : EncodingScheme { shared static this() { EncodingScheme.register!Amiga1251; } } ``` static EncodingScheme **create**(string encodingName); Obtains a subclass of EncodingScheme which is capable of encoding and decoding the named encoding scheme. This function is only aware of EncodingSchemes which have been registered with the register() function. Example ``` auto scheme = EncodingScheme.create("Amiga-1251"); ``` abstract const string **toString**(); Returns the standard name of the encoding scheme abstract const string[] **names**(); Returns an array of all known names for this encoding scheme abstract const bool **canEncode**(dchar c); Returns true if the character c can be represented in this encoding scheme. abstract const size\_t **encodedLength**(dchar c); Returns the number of ubytes required to encode this code point. The input to this function MUST be a valid code point. Parameters: | | | | --- | --- | | dchar `c` | the code point to be encoded | Returns: the number of ubytes required. abstract const size\_t **encode**(dchar c, ubyte[] buffer); Encodes a single code point into a user-supplied, fixed-size buffer. This function encodes a single code point into one or more ubytes. The supplied buffer must be code unit aligned. (For example, UTF-16LE or UTF-16BE must be wchar-aligned, UTF-32LE or UTF-32BE must be dchar-aligned, etc.) The input to this function MUST be a valid code point. Parameters: | | | | --- | --- | | dchar `c` | the code point to be encoded | | ubyte[] `buffer` | the destination array | Returns: the number of ubytes written. abstract const dchar **decode**(ref const(ubyte)[] s); Decodes a single code point. This function removes one or more ubytes from the start of an array, and returns the decoded code point which those ubytes represent. The input to this function MUST be validly encoded. Parameters: | | | | --- | --- | | const(ubyte)[] `s` | the array whose first code point is to be decoded | abstract const dchar **safeDecode**(ref const(ubyte)[] s); Decodes a single code point. The input does not have to be valid. This function removes one or more ubytes from the start of an array, and returns the decoded code point which those ubytes represent. This function will accept an invalidly encoded array as input. If an invalid sequence is found at the start of the string, this function will remove it, and return the value INVALID\_SEQUENCE. Parameters: | | | | --- | --- | | const(ubyte)[] `s` | the array whose first code point is to be decoded | abstract const @property immutable(ubyte)[] **replacementSequence**(); Returns the sequence of ubytes to be used to represent any character which cannot be represented in the encoding scheme. Normally this will be a representation of some substitution character, such as U+FFFD or '?'. bool **isValid**(const(ubyte)[] s); Returns true if the array is encoded correctly Parameters: | | | | --- | --- | | const(ubyte)[] `s` | the array to be tested | size\_t **validLength**()(const(ubyte)[] s); Returns the length of the longest possible substring, starting from the first element, which is validly encoded. Parameters: | | | | --- | --- | | const(ubyte)[] `s` | the array to be tested | immutable(ubyte)[] **sanitize**()(immutable(ubyte)[] s); Sanitizes an array by replacing malformed ubyte sequences with valid ubyte sequences. The result is guaranteed to be valid for this encoding scheme. If the input array is already valid, this function returns the original, otherwise it constructs a new array by replacing all illegal sequences with the encoding scheme's replacement sequence. Parameters: | | | | --- | --- | | immutable(ubyte)[] `s` | the string to be sanitized | size\_t **firstSequence**()(const(ubyte)[] s); Returns the length of the first encoded sequence. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Parameters: | | | | --- | --- | | const(ubyte)[] `s` | the array to be sliced | size\_t **count**()(const(ubyte)[] s); Returns the total number of code points encoded in a ubyte array. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Parameters: | | | | --- | --- | | const(ubyte)[] `s` | the string to be counted | ptrdiff\_t **index**()(const(ubyte)[] s, size\_t n); Returns the array index at which the (n+1)th code point begins. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Parameters: | | | | --- | --- | | const(ubyte)[] `s` | the string to be counted | | size\_t `n` | the current code point index | class **EncodingSchemeASCII**: std.encoding.EncodingScheme; EncodingScheme to handle ASCII This scheme recognises the following names: "ANSI\_X3.4-1968", "ANSI\_X3.4-1986", "ASCII", "IBM367", "ISO646-US", "ISO\_646.irv:1991", "US-ASCII", "cp367", "csASCII" "iso-ir-6", "us" class **EncodingSchemeLatin1**: std.encoding.EncodingScheme; EncodingScheme to handle Latin-1 This scheme recognises the following names: "CP819", "IBM819", "ISO-8859-1", "ISO\_8859-1", "ISO\_8859-1:1987", "csISOLatin1", "iso-ir-100", "l1", "latin1" class **EncodingSchemeLatin2**: std.encoding.EncodingScheme; EncodingScheme to handle Latin-2 This scheme recognises the following names: "Latin 2", "ISO-8859-2", "ISO\_8859-2", "ISO\_8859-2:1999", "Windows-28592" class **EncodingSchemeWindows1250**: std.encoding.EncodingScheme; EncodingScheme to handle Windows-1250 This scheme recognises the following names: "windows-1250" class **EncodingSchemeWindows1251**: std.encoding.EncodingScheme; EncodingScheme to handle Windows-1251 This scheme recognises the following names: "windows-1251" class **EncodingSchemeWindows1252**: std.encoding.EncodingScheme; EncodingScheme to handle Windows-1252 This scheme recognises the following names: "windows-1252" class **EncodingSchemeUtf8**: std.encoding.EncodingScheme; EncodingScheme to handle UTF-8 This scheme recognises the following names: "UTF-8" class **EncodingSchemeUtf16Native**: std.encoding.EncodingScheme; EncodingScheme to handle UTF-16 in native byte order This scheme recognises the following names: "UTF-16LE" (little-endian architecture only) "UTF-16BE" (big-endian architecture only) class **EncodingSchemeUtf32Native**: std.encoding.EncodingScheme; EncodingScheme to handle UTF-32 in native byte order This scheme recognises the following names: "UTF-32LE" (little-endian architecture only) "UTF-32BE" (big-endian architecture only) enum **BOM**: int; Definitions of common Byte Order Marks. The elements of the `enum` can used as indices into `bomTable` to get matching `BOMSeq`. **none** no BOM was found **utf32be** [0x00, 0x00, 0xFE, 0xFF] **utf32le** [0xFF, 0xFE, 0x00, 0x00] **utf1** [0xF7, 0x64, 0x4C] **utfebcdic** [0xDD, 0x73, 0x66, 0x73] **scsu** [0x0E, 0xFE, 0xFF] **bocu1** [0xFB, 0xEE, 0x28] **gb18030** [0x84, 0x31, 0x95, 0x33] **utf8** [0xEF, 0xBB, 0xBF] **utf16be** [0xFE, 0xFF] **utf16le** [0xFF, 0xFE] alias **BOMSeq** = std.typecons.Tuple!(BOM, "schema", ubyte[], "sequence").Tuple; The type stored inside `bomTable`. immutable Tuple!(BOM, "schema", ubyte[], "sequence")[] **bomTable**; Mapping of a byte sequence to **Byte Order Mark (BOM)** immutable(BOMSeq) **getBOM**(Range)(Range input) Constraints: if (isForwardRange!Range && is(immutable(ElementType!Range) == immutable(ubyte))); Returns a `BOMSeq` for a given `input`. If no `BOM` is present the `BOMSeq` for `BOM.none` is returned. The `BOM` sequence at the beginning of the range will not be comsumed from the passed range. If you pass a reference type range make sure that `save` creates a deep copy. Parameters: | | | | --- | --- | | Range `input` | The sequence to check for the `BOM` | Returns: the found `BOMSeq` corresponding to the passed `input`. Examples: ``` import std.format : format; auto ts = dchar(0x0000FEFF) ~ "Hello World"d; auto entry = getBOM(cast(ubyte[]) ts); version (BigEndian) { writeln(entry.schema); // BOM.utf32be } else { writeln(entry.schema); // BOM.utf32le } ``` enum dchar **utfBOM**; Constant defining a fully decoded BOM
programming_docs
d rt.lifetime rt.lifetime =========== This module contains all functions related to an object's lifetime: allocation, resizing, deallocation, and finalization. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Walter Bright, Sean Kelly, Steven Schveighoffer Source [rt/lifetime.d](https://github.com/dlang/druntime/blob/master/src/rt/lifetime.d) void\* **\_d\_allocmemory**(size\_t sz); Object **\_d\_newclass**(const ClassInfo ci); void **\_d\_delinterface**(void\*\* p); void **\_d\_delclass**(Object\* p); void **\_d\_delstruct**(void\*\* p, TypeInfo\_Struct inf); This is called for a delete statement where the value being deleted is a pointer to a struct with a destructor but doesn't have an overloaded delete operator. pure nothrow bool **\_\_setArrayAllocLength**(ref BlkInfo info, size\_t newlength, bool isshared, const TypeInfo tinext, size\_t oldlength = ~0); Set the allocated length of the array block. This is called any time an array is appended to or its length is set. The allocated block looks like this for blocks < PAGESIZE: |elem0|elem1|elem2|...|elemN-1|emptyspace|N\*elemsize| The size of the allocated length at the end depends on the block size: a block of 16 to 256 bytes has an 8-bit length. a block with 512 to pagesize/2 bytes has a 16-bit length. For blocks >= pagesize, the length is a size\_t and is at the beginning of the block. The reason we have to do this is because the block can extend into more pages, so we cannot trust the block length if it sits at the end of the block, because it might have just been extended. If we can prove in the future that the block is unshared, we may be able to change this, but I'm not sure it's important. In order to do put the length at the front, we have to provide 16 bytes buffer space in case the block has to be aligned properly. In x86, certain SSE instructions will only work if the data is 16-byte aligned. In addition, we need the sentinel byte to prevent accidental pointers to the next block. Because of the extra overhead, we only do this for page size and above, where the overhead is minimal compared to the block size. So for those blocks, it looks like: |N\*elemsize|padding|elem0|elem1|...|elemN-1|emptyspace|sentinelbyte| where elem0 starts 16 bytes after the first byte. pure nothrow size\_t **\_\_arrayAllocLength**(ref BlkInfo info, const TypeInfo tinext); get the allocation size of the array for the given block (without padding or type info) pure nothrow void\* **\_\_arrayStart**(return BlkInfo info); get the start of the array for the given block pure nothrow @trusted size\_t **\_\_arrayPad**(size\_t size, const TypeInfo tinext); get the padding required to allocate size bytes. Note that the padding is NOT included in the passed in size. Therefore, do NOT call this function with the size of an allocated block. pure nothrow BlkInfo **\_\_arrayAlloc**(size\_t arrsize, const TypeInfo ti, const TypeInfo tinext); allocate an array memory block by applying the proper padding and assigning block attributes if not inherited from the existing block enum int **N\_CACHE\_BLOCKS**; cache for the lookup of the block info nothrow BlkInfo\* **\_\_getBlkInfo**(void\* interior); Get the cached block info of an interior pointer. Returns null if the interior pointer's block is not cached. NOTE The base ptr in this struct can be cleared asynchronously by the GC, so any use of the returned BlkInfo should copy it and then check the base ptr of the copy before actually using it. TODO Change this function so the caller doesn't have to be aware of this issue. Either return by value and expect the caller to always check the base ptr as an indication of whether the struct is valid, or set the BlkInfo as a side-effect and return a bool to indicate success. void **\_d\_arrayshrinkfit**(const TypeInfo ti, void[] arr); Shrink the "allocated" length of an array to be the exact size of the array. It doesn't matter what the current allocated length of the array is, the user is telling the runtime that he knows what he is doing. size\_t **\_d\_arraysetcapacity**(const TypeInfo ti, size\_t newcapacity, void[]\* p); set the array capacity. If the array capacity isn't currently large enough to hold the requested capacity (in number of elements), then the array is resized/reallocated to the appropriate size. Pass in a requested capacity of 0 to get the current capacity. Returns the number of elements that can actually be stored once the resizing is done. pure nothrow void[] **\_d\_newarrayU**(const TypeInfo ti, size\_t length); Allocate a new uninitialized array of length elements. ti is the type of the resulting array, or pointer to element. pure nothrow void[] **\_d\_newarrayT**(const TypeInfo ti, size\_t length); Allocate a new array of length elements. ti is the type of the resulting array, or pointer to element. (For when the array is initialized to 0) pure nothrow void[] **\_d\_newarrayiT**(const TypeInfo ti, size\_t length); For when the array has a non-zero initializer. void[] **\_d\_newarrayOpT**(alias op)(const TypeInfo ti, size\_t[] dims); void[] **\_d\_newarraymTX**(const TypeInfo ti, size\_t[] dims); void[] **\_d\_newarraymiTX**(const TypeInfo ti, size\_t[] dims); void\* **\_d\_newitemU**(in TypeInfo \_ti); Allocate an uninitialized non-array item. This is an optimization to avoid things needed for arrays like the \_arrayPad(size). void\* **\_d\_newitemT**(in TypeInfo \_ti); Same as above, zero initializes the item. void\* **\_d\_newitemiT**(in TypeInfo \_ti); Same as above, for item with non-zero initializer. struct **Array**; void **\_d\_delarray\_t**(void[]\* p, const TypeInfo\_Struct ti); void **\_d\_delmemory**(void\*\* p); void **\_d\_callinterfacefinalizer**(void\* p); void **\_d\_callfinalizer**(void\* p); void **rt\_setCollectHandler**(CollectHandler h); CollectHandler **rt\_getCollectHandler**(); nothrow int **rt\_hasFinalizerInSegment**(void\* p, size\_t size, uint attr, in void[] segment); nothrow void **rt\_finalize2**(void\* p, bool det = true, bool resetMemory = true); void[] **\_d\_arraysetlengthT**(const TypeInfo ti, size\_t newlength, void[]\* p); Resize dynamic arrays with 0 initializers. void[] **\_d\_arraysetlengthiT**(const TypeInfo ti, size\_t newlength, void[]\* p); Resize arrays for non-zero initializers. p pointer to array lvalue to be updated newlength new .length property of array sizeelem size of each element of array initsize size of initializer ... initializer void[] **\_d\_arrayappendT**(const TypeInfo ti, ref byte[] x, byte[] y); Append y[] to array x[] size\_t **newCapacity**(size\_t newlength, size\_t size); byte[] **\_d\_arrayappendcTX**(const TypeInfo ti, ref byte[] px, size\_t n); Extend an array by n elements. Caller must initialize those elements. void[] **\_d\_arrayappendcd**(ref byte[] x, dchar c); Append dchar to char[] void[] **\_d\_arrayappendwd**(ref byte[] x, dchar c); Append dchar to wchar[] byte[] **\_d\_arraycatT**(const TypeInfo ti, byte[] x, byte[] y); void[] **\_d\_arraycatnTX**(const TypeInfo ti, byte[][] arrs); void\* **\_d\_arrayliteralTX**(const TypeInfo ti, size\_t length); Allocate the array, rely on the caller to do the initialization of the array. d std.outbuffer std.outbuffer ============= Serialize data to `ubyte` arrays. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com) Source [std/outbuffer.d](https://github.com/dlang/phobos/blob/master/std/outbuffer.d) class **OutBuffer**; OutBuffer provides a way to build up an array of bytes out of raw data. It is useful for things like preparing an array of bytes to write out to a file. OutBuffer's byte order is the format native to the computer. To control the byte order (endianness), use a class derived from OutBuffer. OutBuffer's internal buffer is allocated with the GC. Pointers stored into the buffer are scanned by the GC, but you have to ensure proper alignment, e.g. by using alignSize((void\*).sizeof). Examples: ``` import std.string : cmp; OutBuffer buf = new OutBuffer(); writeln(buf.offset); // 0 buf.write("hello"); buf.write(cast(byte) 0x20); buf.write("world"); buf.printf(" %d", 62665); writeln(cmp(buf.toString(), "hello world 62665")); // 0 buf.clear(); writeln(cmp(buf.toString(), "")); // 0 buf.write("New data"); writeln(cmp(buf.toString(), "New data")); // 0 ``` inout pure nothrow scope @safe inout(ubyte)[] **toBytes**(); Convert to array of bytes. pure nothrow @trusted void **reserve**(size\_t nbytes); Preallocate nbytes more to the size of the internal buffer. This is a speed optimization, a good guess at the maximum size of the resulting buffer will improve performance by eliminating reallocations and copying. alias **put** = write; put enables OutBuffer to be used as an OutputRange. pure nothrow @safe void **write**(scope const(ubyte)[] bytes); pure nothrow @safe void **write**(byte b); pure nothrow @safe void **write**(char c); pure nothrow @safe void **write**(dchar c); pure nothrow @safe void **write**(short s); pure nothrow @safe void **write**(int i); pure nothrow @safe void **write**(long l); Append data to the internal buffer. pure nothrow @safe void **fill0**(size\_t nbytes); Append nbytes of 0 to the internal buffer. pure nothrow @safe void **alignSize**(size\_t alignsize); 0-fill to align on power of 2 boundary. pure nothrow @safe void **clear**(); Clear the data in the buffer pure nothrow @safe void **align2**(); Optimize common special case alignSize(2) pure nothrow @safe void **align4**(); Optimize common special case alignSize(4) const pure nothrow @safe string **toString**(); Convert internal buffer to array of chars. nothrow @trusted void **vprintf**(scope string format, va\_list args); Append output of C's vprintf() to internal buffer. @trusted void **printf**(scope string format, ...); Append output of C's printf() to internal buffer. void **writef**(Char, A...)(scope const(Char)[] fmt, A args); Formats and writes its arguments in text format to the OutBuffer. Parameters: | | | | --- | --- | | const(Char)[] `fmt` | format string as described in [`std.format.formattedWrite`](std_format#formattedWrite) | | A `args` | arguments to be formatted | See Also: [`std.stdio.writef`](std_stdio#writef); [`std.format.formattedWrite`](std_format#formattedWrite); Examples: ``` OutBuffer b = new OutBuffer(); b.writef("a%sb", 16); writeln(b.toString()); // "a16b" ``` void **writefln**(Char, A...)(scope const(Char)[] fmt, A args); Formats and writes its arguments in text format to the OutBuffer, followed by a newline. Parameters: | | | | --- | --- | | const(Char)[] `fmt` | format string as described in [`std.format.formattedWrite`](std_format#formattedWrite) | | A `args` | arguments to be formatted | See Also: [`std.stdio.writefln`](std_stdio#writefln); [`std.format.formattedWrite`](std_format#formattedWrite); Examples: ``` OutBuffer b = new OutBuffer(); b.writefln("a%sb", 16); writeln(b.toString()); // "a16b\n" ``` pure nothrow @safe void **spread**(size\_t index, size\_t nbytes); At offset index into buffer, create nbytes of space by shifting upwards all data past index. d core.math core.math ========= Builtin mathematical intrinsics Source [core/math.d](https://github.com/dlang/druntime/blob/master/src/core/math.d) License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com), Don Clugston nothrow @nogc @safe real **rndtonl**(real x); Returns x rounded to a long value using the FE\_TONEAREST rounding mode. If the integer value of x is greater than long.max, the result is indeterminate. pure nothrow @nogc @safe float **cos**(float x); pure nothrow @nogc @safe double **cos**(double x); pure nothrow @nogc @safe real **cos**(real x); Returns cosine of x. x is in radians. Special Values| x | cos(x) | invalid? | | NAN | NAN | yes | | ±∞ | NAN | yes | Bugs: Results are undefined if |x| >= 264. pure nothrow @nogc @safe float **sin**(float x); pure nothrow @nogc @safe double **sin**(double x); pure nothrow @nogc @safe real **sin**(real x); Returns sine of x. x is in radians. Special Values| x | sin(x) | invalid? | | NAN | NAN | yes | | ±0.0 | ±0.0 | no | | ±∞ | NAN | yes | Bugs: Results are undefined if |x| >= 264. pure nothrow @nogc @safe long **rndtol**(float x); pure nothrow @nogc @safe long **rndtol**(double x); pure nothrow @nogc @safe long **rndtol**(real x); Returns x rounded to a long value using the current rounding mode. If the integer value of x is greater than long.max, the result is indeterminate. pure nothrow @nogc @safe float **sqrt**(float x); pure nothrow @nogc @safe double **sqrt**(double x); pure nothrow @nogc @safe real **sqrt**(real x); Compute square root of x. Special Values| x | sqrt(x) | invalid? | | -0.0 | -0.0 | no | | <0.0 | NAN | yes | | +∞ | +∞ | no | pure nothrow @nogc @safe float **ldexp**(float n, int exp); pure nothrow @nogc @safe double **ldexp**(double n, int exp); pure nothrow @nogc @safe real **ldexp**(real n, int exp); Compute n \* 2exp References frexp pure nothrow @nogc @safe float **fabs**(float x); Compute the absolute value. Special Values| x | fabs(x) | | ±0.0 | +0.0 | | ±∞ | +∞ | It is implemented as a compiler intrinsic. Parameters: | | | | --- | --- | | float `x` | floating point value | Returns: |x| References equivalent to `std.math.fabs` pure nothrow @nogc @safe double **fabs**(double x); ditto Compute the absolute value. Special Values| x | fabs(x) | | ±0.0 | +0.0 | | ±∞ | +∞ | It is implemented as a compiler intrinsic. Parameters: | | | | --- | --- | | double `x` | floating point value | Returns: |x| References equivalent to `std.math.fabs` pure nothrow @nogc @safe real **fabs**(real x); ditto Compute the absolute value. Special Values| x | fabs(x) | | ±0.0 | +0.0 | | ±∞ | +∞ | It is implemented as a compiler intrinsic. Parameters: | | | | --- | --- | | real `x` | floating point value | Returns: |x| References equivalent to `std.math.fabs` pure nothrow @nogc @safe float **rint**(float x); pure nothrow @nogc @safe double **rint**(double x); pure nothrow @nogc @safe real **rint**(real x); Rounds x to the nearest integer value, using the current rounding mode. If the return value is not equal to x, the FE\_INEXACT exception is raised. **nearbyint** performs the same operation, but does not set the FE\_INEXACT exception. pure nothrow @nogc @safe float **yl2x**(float x, float y); pure nothrow @nogc @safe double **yl2x**(double x, double y); pure nothrow @nogc @safe real **yl2x**(real x, real y); pure nothrow @nogc @safe double **yl2xp1**(double x, double y); pure nothrow @nogc @safe real **yl2xp1**(real x, real y); Building block functions, they translate to a single x87 instruction. T **toPrec**(T : float)(float f); T **toPrec**(T : float)(double f); T **toPrec**(T : float)(real f); T **toPrec**(T : double)(float f); T **toPrec**(T : double)(double f); T **toPrec**(T : double)(real f); T **toPrec**(T : real)(float f); T **toPrec**(T : real)(double f); T **toPrec**(T : real)(real f); Round argument to a specific precision. D language types specify only a minimum precision, not a maximum. The `toPrec()` function forces rounding of the argument `f` to the precision of the specified floating point type `T`. The rounding mode used is inevitably target-dependent, but will be done in a way to maximize accuracy. In most cases, the default is round-to-nearest. Parameters: | | | | --- | --- | | T | precision type to round to | | float `f` | value to convert | Returns: f in precision of type `T` d invariant invariant ========= void **\_d\_invariant**(Object o); Implementation of invariant support routines. Copyright: Copyright Digital Mars 2007 - 2010. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Walter Bright d std.stdio std.stdio ========= Standard I/O functions that extend **core.stdc.stdio**. **core.stdc.stdio** is publically imported when importing **std.stdio**. Source [std/stdio.d](https://github.com/dlang/phobos/blob/master/std/stdio.d) License: [Boost License 1.0](http://boost.org/LICENSE_1_0.txt). Authors: [Walter Bright](http://digitalmars.com), [Andrei Alexandrescu](http://erdani.org), Alex Rønne Petersen alias **KeepTerminator** = std.typecons.Flag!"keepTerminator".Flag; If flag `KeepTerminator` is set to `KeepTerminator.yes`, then the delimiter is included in the strings returned. struct **File**; Encapsulates a `FILE*`. Generally D does not attempt to provide thin wrappers over equivalent functions in the C standard library, but manipulating `FILE*` values directly is unsafe and error-prone in many ways. The `File` type ensures safe manipulation, automatic file closing, and a lot of convenience. The underlying `FILE*` handle is maintained in a reference-counted manner, such that as soon as the last `File` variable bound to a given `FILE*` goes out of scope, the underlying `FILE*` is automatically closed. Example ``` // test.d import std.stdio; void main(string[] args) { auto f = File("test.txt", "w"); // open for writing f.write("Hello"); if (args.length > 1) { auto g = f; // now g and f write to the same file // internal reference count is 2 g.write(", ", args[1]); // g exits scope, reference count decreases to 1 } f.writeln("!"); // f exits scope, reference count falls to zero, // underlying `FILE*` is closed. } ``` ``` % rdmd test.d Jimmy % cat test.txt Hello, Jimmy! % _ ``` @safe this(string name, scope const(char)[] stdioOpenmode = "rb"); this(R1, R2)(R1 name) Constraints: if (isInputRange!R1 && isSomeChar!(ElementEncodingType!R1)); this(R1, R2)(R1 name, R2 mode) Constraints: if (isInputRange!R1 && isSomeChar!(ElementEncodingType!R1) && isInputRange!R2 && isSomeChar!(ElementEncodingType!R2)); Constructor taking the name of the file to open and the open mode. Copying one `File` object to another results in the two `File` objects referring to the same underlying file. The destructor automatically closes the file as soon as no `File` object refers to it anymore. Parameters: | | | | --- | --- | | string `name` | range or string representing the file name | | const(char)[] `stdioOpenmode` | range or string represting the open mode (with the same semantics as in the C standard library [fopen](http://cplusplus.com/reference/clibrary/cstdio/fopen.html) function) | Throws: `ErrnoException` if the file could not be opened. ref @safe File **opAssign**(File rhs) return; Assigns a file to another. The target of the assignment gets detached from whatever file it was attached to, and attaches itself to the new file. @trusted void **open**(string name, scope const(char)[] stdioOpenmode = "rb"); Detaches from the current file (throwing on failure), and then attempts to open file `name` with mode `stdioOpenmode`. The mode has the same semantics as in the C standard library [fopen](http://cplusplus.com/reference/clibrary/cstdio/fopen.html) function. Throws: `ErrnoException` in case of error. @trusted void **reopen**(string name, scope const(char)[] stdioOpenmode = "rb"); Reuses the `File` object to either open a different file, or change the file mode. If `name` is `null`, the mode of the currently open file is changed; otherwise, a new file is opened, reusing the C `FILE*`. The function has the same semantics as in the C standard library [freopen](http://cplusplus.com/reference/cstdio/freopen/) function. Note Calling `reopen` with a `null` `name` is not implemented in all C runtimes. Throws: `ErrnoException` in case of error. @safe void **popen**(string command, scope const(char)[] stdioOpenmode = "r"); Detaches from the current file (throwing on failure), and then runs a command by calling the C standard library function [popen](http://opengroup.org/onlinepubs/007908799/xsh/popen.html). Throws: `ErrnoException` in case of error. @safe void **fdopen**(int fd, scope const(char)[] stdioOpenmode = "rb"); First calls `detach` (throwing on failure), then attempts to associate the given file descriptor with the `File`, and sets the file's name to `null`. The mode must be compatible with the mode of the file descriptor. Throws: `ErrnoException` in case of error. Parameters: | | | | --- | --- | | int `fd` | File descriptor to associate with this `File`. | | const(char)[] `stdioOpenmode` | Mode to associate with this File. The mode has the same semantics semantics as in the C standard library [fdopen](http://cplusplus.com/reference/cstdio/fopen/) function, and must be compatible with `fd`. | void **windowsHandleOpen**(HANDLE handle, scope const(char)[] stdioOpenmode); First calls `detach` (throwing on failure), and then attempts to associate the given Windows `HANDLE` with the `File`. The mode must be compatible with the access attributes of the handle. Windows only. Throws: `ErrnoException` in case of error. const pure nothrow @property @safe bool **isOpen**(); Returns `true` if the file is opened. const pure @property @trusted bool **eof**(); Returns `true` if the file is at end (see [feof](http://cplusplus.com/reference/clibrary/cstdio/feof.html)). Throws: `Exception` if the file is not opened. const pure nothrow @property @safe string **name**(); Returns the name last used to initialize this `File`, if any. Some functions that create or initialize the `File` set the name field to `null`. Examples include [`tmpfile`](#tmpfile), [`wrapFile`](#wrapFile), and [`fdopen`](#fdopen). See the documentation of those functions for details. Returns: The name last used to initialize this this file, or `null` otherwise. const pure nothrow @property @trusted bool **error**(); If the file is not opened, returns `true`. Otherwise, returns [ferror](http://cplusplus.com/reference/clibrary/cstdio/ferror.html) for the file handle. @trusted void **detach**(); Detaches from the underlying file. If the sole owner, calls `close`. Throws: `ErrnoException` on failure if closing the file. @trusted void **close**(); If the file was unopened, succeeds vacuously. Otherwise closes the file (by calling [fclose](http://cplusplus.com/reference/clibrary/cstdio/fclose.html)), throwing on error. Even if an exception is thrown, afterwards the `File` object is empty. This is different from `detach` in that it always closes the file; consequently, all other `File` objects referring to the same handle will see a closed file henceforth. Throws: `ErrnoException` on error. pure nothrow @safe void **clearerr**(); If the file is not opened, succeeds vacuously. Otherwise, returns [clearerr](http://cplusplus.com/reference/clibrary/cstdio/clearerr.html) for the file handle. @trusted void **flush**(); Flushes the C `FILE` buffers. Calls [fflush](http://cplusplus.com/reference/clibrary/cstdio/fflush.html) for the file handle. Throws: `Exception` if the file is not opened or if the call to `fflush` fails. @trusted void **sync**(); Forces any data buffered by the OS to be written to disk. Call [`flush`](#flush) before calling this function to flush the C `FILE` buffers first. This function calls [`FlushFileBuffers`](http://msdn.microsoft.com/en-us/library/windows/desktop/aa364439%28v=vs.85%29.aspx) on Windows and [`fsync`](http://pubs.opengroup.org/onlinepubs/7908799/xsh/fsync.html) on POSIX for the file handle. Throws: `Exception` if the file is not opened or if the OS call fails. T[] **rawRead**(T)(T[] buffer); Calls [fread](http://cplusplus.com/reference/clibrary/cstdio/fread.html) for the file handle. The number of items to read and the size of each item is inferred from the size and type of the input array, respectively. Returns: The slice of `buffer` containing the data that was actually read. This will be shorter than `buffer` if EOF was reached before the buffer could be filled. Throws: `Exception` if `buffer` is empty. `ErrnoException` if the file is not opened or the call to `fread` fails. `rawRead` always reads in binary mode on Windows. Examples: ``` static import std.file; auto testFile = std.file.deleteme(); std.file.write(testFile, "\r\n\n\r\n"); scope(exit) std.file.remove(testFile); auto f = File(testFile, "r"); auto buf = f.rawRead(new char[5]); f.close(); writeln(buf); // "\r\n\n\r\n" ``` void **rawWrite**(T)(in T[] buffer); Calls [fwrite](http://cplusplus.com/reference/clibrary/cstdio/fwrite.html) for the file handle. The number of items to write and the size of each item is inferred from the size and type of the input array, respectively. An error is thrown if the buffer could not be written in its entirety. `rawWrite` always writes in binary mode on Windows. Throws: `ErrnoException` if the file is not opened or if the call to `fwrite` fails. Examples: ``` static import std.file; auto testFile = std.file.deleteme(); auto f = File(testFile, "w"); scope(exit) std.file.remove(testFile); f.rawWrite("\r\n\n\r\n"); f.close(); writeln(std.file.read(testFile)); // "\r\n\n\r\n" ``` @trusted void **seek**(long offset, int origin = SEEK\_SET); Calls [fseek](http://cplusplus.com/reference/clibrary/cstdio/fseek.html) for the file handle to move its position indicator. Parameters: | | | | --- | --- | | long `offset` | Binary files: Number of bytes to offset from origin. Text files: Either zero, or a value returned by [`tell`](#tell). | | int `origin` | Binary files: Position used as reference for the offset, must be one of [SEEK\_SET](core_stdc_stdio#SEEK_SET), [SEEK\_CUR](core_stdc_stdio#SEEK_CUR) or [SEEK\_END](core_stdc_stdio#SEEK_END). Text files: Shall necessarily be [SEEK\_SET](core_stdc_stdio#SEEK_SET). | Throws: `Exception` if the file is not opened. `ErrnoException` if the call to `fseek` fails. const @property @trusted ulong **tell**(); Calls [ftell](http://cplusplus.com/reference/clibrary/cstdio/ftell.html) for the managed file handle. Throws: `Exception` if the file is not opened. `ErrnoException` if the call to `ftell` fails. Examples: ``` import std.conv : text; static import std.file; auto testFile = std.file.deleteme(); std.file.write(testFile, "abcdefghijklmnopqrstuvwqxyz"); scope(exit) { std.file.remove(testFile); } auto f = File(testFile); auto a = new ubyte[4]; f.rawRead(a); writeln(f.tell); // 4 ``` @safe void **rewind**(); Calls [rewind](http://cplusplus.com/reference/clibrary/cstdio/rewind.html) for the file handle. Throws: `Exception` if the file is not opened. @trusted void **setvbuf**(size\_t size, int mode = \_IOFBF); Calls [setvbuf](http://cplusplus.com/reference/clibrary/cstdio/setvbuf.html) for the file handle. Throws: `Exception` if the file is not opened. `ErrnoException` if the call to `setvbuf` fails. @trusted void **setvbuf**(void[] buf, int mode = \_IOFBF); Calls [setvbuf](http://cplusplus.com/reference/clibrary/cstdio/setvbuf.html) for the file handle. Throws: `Exception` if the file is not opened. `ErrnoException` if the call to `setvbuf` fails. void **lock**(LockType lockType = LockType.readWrite, ulong start = 0, ulong length = 0); Locks the specified file segment. If the file segment is already locked by another process, waits until the existing lock is released. If both `start` and `length` are zero, the entire file is locked. Locks created using `lock` and `tryLock` have the following properties: * All locks are automatically released when the process terminates. * Locks are not inherited by child processes. * Closing a file will release all locks associated with the file. On POSIX, even locks acquired via a different `File` will be released as well. * Not all NFS implementations correctly implement file locking. bool **tryLock**(LockType lockType = LockType.readWrite, ulong start = 0, ulong length = 0); Attempts to lock the specified file segment. If both `start` and `length` are zero, the entire file is locked. Returns: `true` if the lock was successful, and `false` if the specified file segment was already locked. void **unlock**(ulong start = 0, ulong length = 0); Removes the lock over the specified file segment. void **write**(S...)(S args); Writes its arguments in text format to the file. Throws: `Exception` if the file is not opened. `ErrnoException` on an error writing to the file. void **writeln**(S...)(S args); Writes its arguments in text format to the file, followed by a newline. Throws: `Exception` if the file is not opened. `ErrnoException` on an error writing to the file. void **writef**(alias fmt, A...)(A args) Constraints: if (isSomeString!(typeof(fmt))); void **writef**(Char, A...)(in Char[] fmt, A args); Writes its arguments in text format to the file, according to the format string fmt. Parameters: | | | | --- | --- | | Char[] `fmt` | The [format string](std_format#formattedWrite). When passed as a compile-time argument, the string will be statically checked against the argument types passed. | | A `args` | Items to write. | Throws: `Exception` if the file is not opened. `ErrnoException` on an error writing to the file. void **writefln**(alias fmt, A...)(A args) Constraints: if (isSomeString!(typeof(fmt))); void **writefln**(Char, A...)(in Char[] fmt, A args); Equivalent to `file.writef(fmt, args, '\n')`. S **readln**(S = string)(dchar terminator = '\x0a') Constraints: if (isSomeString!S); Read line from the file handle and return it as a specified type. This version manages its own read buffer, which means one memory allocation per call. If you are not retaining a reference to the read data, consider the `File.readln(buf)` version, which may offer better performance as it can reuse its read buffer. Parameters: | | | | --- | --- | | S | Template parameter; the type of the allocated buffer, and the type returned. Defaults to `string`. | | dchar `terminator` | Line terminator (by default, `'\n'`). | Note String terminators are not supported due to ambiguity with readln(buf) below. Returns: The line that was read, including the line terminator character. Throws: `StdioException` on I/O error, or `UnicodeException` on Unicode conversion error. Example ``` // Reads `stdin` and writes it to `stdout`. import std.stdio; void main() { string line; while ((line = stdin.readln()) !is null) write(line); } ``` size\_t **readln**(C)(ref C[] buf, dchar terminator = '\x0a') Constraints: if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum)); size\_t **readln**(C, R)(ref C[] buf, R terminator) Constraints: if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum) && isBidirectionalRange!R && is(typeof(terminator.front == (dchar).init))); Read line from the file handle and write it to `buf[]`, including terminating character. This can be faster than `line = File.readln()` because you can reuse the buffer for each call. Note that reusing the buffer means that you must copy the previous contents if you wish to retain them. Parameters: | | | | --- | --- | | C[] `buf` | Buffer used to store the resulting line data. buf is enlarged if necessary, then set to the slice exactly containing the line. | | dchar `terminator` | Line terminator (by default, `'\n'`). Use [`std.ascii.newline`](std_ascii#newline) for portability (unless the file was opened in text mode). | Returns: 0 for end of file, otherwise number of characters read. The return value will always be equal to `buf.length`. Throws: `StdioException` on I/O error, or `UnicodeException` on Unicode conversion error. Example ``` // Read lines from `stdin` into a string // Ignore lines starting with '#' // Write the string to `stdout` import std.stdio; void main() { string output; char[] buf; while (stdin.readln(buf)) { if (buf[0] == '#') continue; output ~= buf; } write(output); } ``` This method can be more efficient than the one in the previous example because `stdin.readln(buf)` reuses (if possible) memory allocated for `buf`, whereas `line = stdin.readln()` makes a new memory allocation for every line. For even better performance you can help `readln` by passing in a large buffer to avoid memory reallocations. This can be done by reusing the largest buffer returned by `readln`: Example ``` // Read lines from `stdin` and count words import std.array, std.stdio; void main() { char[] buf; size_t words = 0; while (!stdin.eof) { char[] line = buf; stdin.readln(line); if (line.length > buf.length) buf = line; words += line.split.length; } writeln(words); } ``` This is actually what [`byLine`](#byLine) does internally, so its usage is recommended if you want to process a complete file. uint **readf**(alias format, Data...)(auto ref Data data) Constraints: if (isSomeString!(typeof(format))); uint **readf**(Data...)(scope const(char)[] format, auto ref Data data); Reads formatted data from the file using [`std.format.formattedRead`](std_format#formattedRead). Parameters: | | | | --- | --- | | const(char)[] `format` | The [format string](std%20format_#formattedWrite). When passed as a compile-time argument, the string will be statically checked against the argument types passed. | | Data `data` | Items to be read. | Example ``` // test.d void main() { import std.stdio; auto f = File("input"); foreach (_; 0 .. 3) { int a; f.readf!" %d"(a); writeln(++a); } } ``` ``` % echo "1 2 3" > input % rdmd test.d 2 3 4 ``` Examples: ``` static import std.file; auto deleteme = std.file.deleteme(); std.file.write(deleteme, "hello\nworld\ntrue\nfalse\n"); scope(exit) std.file.remove(deleteme); string s; auto f = File(deleteme); f.readf!"%s\n"(s); writeln(s); // "hello" f.readf("%s\n", s); writeln(s); // "world" bool b1, b2; f.readf("%s\n%s\n", b1, b2); assert(b1 == true && b2 == false); ``` static @safe File **tmpfile**(); Returns a temporary file by calling [tmpfile](http://cplusplus.com/reference/clibrary/cstdio/tmpfile.html). Note that the created file has no [`name`](#name). static @safe File **wrapFile**(FILE\* f); Unsafe function that wraps an existing `FILE*`. The resulting `File` never takes the initiative in closing the file. Note that the created file has no [`name`](#name) pure @safe FILE\* **getFP**(); Returns the `FILE*` corresponding to this object. const @property @trusted int **fileno**(); Returns the file number corresponding to this object. @property HANDLE **windowsHandle**(); Returns the underlying operating system `HANDLE` (Windows only). auto **byLine**(Terminator = char, Char = char)(KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\x0a') Constraints: if (isScalarType!Terminator); auto **byLine**(Terminator, Char = char)(KeepTerminator keepTerminator, Terminator terminator) Constraints: if (is(immutable(ElementEncodingType!Terminator) == immutable(Char))); Returns an [input range](std_range_primitives#isInputRange) set up to read from the file handle one line at a time. The element type for the range will be `Char[]`. Range primitives may throw `StdioException` on I/O error. Note Each `front` will not persist after `popFront` is called, so the caller must copy its contents (e.g. by calling `to!string`) when retention is needed. If the caller needs to retain a copy of every line, use the [`byLineCopy`](#byLineCopy) function instead. Parameters: | | | | --- | --- | | Char | Character type for each line, defaulting to `char`. | | KeepTerminator `keepTerminator` | Use `Yes.keepTerminator` to include the terminator at the end of each line. | | Terminator `terminator` | Line separator (`'\n'` by default). Use [`std.ascii.newline`](std_ascii#newline) for portability (unless the file was opened in text mode). | Example ``` import std.algorithm, std.stdio, std.string; // Count words in a file using ranges. void main() { auto file = File("file.txt"); // Open for reading const wordCount = file.byLine() // Read lines .map!split // Split into words .map!(a => a.length) // Count words per line .sum(); // Total word count writeln(wordCount); } ``` Example ``` import std.range, std.stdio; // Read lines using foreach. void main() { auto file = File("file.txt"); // Open for reading auto range = file.byLine(); // Print first three lines foreach (line; range.take(3)) writeln(line); // Print remaining lines beginning with '#' foreach (line; range) { if (!line.empty && line[0] == '#') writeln(line); } } ``` Notice that neither example accesses the line data returned by `front` after the corresponding `popFront` call is made (because the contents may well have changed). auto **byLineCopy**(Terminator = char, Char = immutable(char))(KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\x0a') Constraints: if (isScalarType!Terminator); auto **byLineCopy**(Terminator, Char = immutable(char))(KeepTerminator keepTerminator, Terminator terminator) Constraints: if (is(immutable(ElementEncodingType!Terminator) == immutable(Char))); Returns an [input range](std_range_primitives#isInputRange) set up to read from the file handle one line at a time. Each line will be newly allocated. `front` will cache its value to allow repeated calls without unnecessary allocations. Note Due to caching byLineCopy can be more memory-efficient than `File.byLine.map!idup`. The element type for the range will be `Char[]`. Range primitives may throw `StdioException` on I/O error. Parameters: | | | | --- | --- | | Char | Character type for each line, defaulting to `immutable char`. | | KeepTerminator `keepTerminator` | Use `Yes.keepTerminator` to include the terminator at the end of each line. | | Terminator `terminator` | Line separator (`'\n'` by default). Use [`std.ascii.newline`](std_ascii#newline) for portability (unless the file was opened in text mode). | Example ``` import std.algorithm, std.array, std.stdio; // Print sorted lines of a file. void main() { auto sortedLines = File("file.txt") // Open for reading .byLineCopy() // Read persistent lines .array() // into an array .sort(); // then sort them foreach (line; sortedLines) writeln(line); } ``` See Also: [`std.file.readText`](std_file#readText) auto **byRecord**(Fields...)(string format); Creates an [input range](std_range_primitives#isInputRange) set up to parse one line at a time from the file into a tuple. Range primitives may throw `StdioException` on I/O error. Parameters: | | | | --- | --- | | string `format` | tuple record [format](std_format#formattedRead) | Returns: The input range set up to parse one line at a time into a record tuple. See Also: It is similar to [`byLine`](#byLine) and uses [format](std_format#formattedRead) under the hood. Examples: ``` static import std.file; import std.typecons : tuple; // prepare test file auto testFile = std.file.deleteme(); scope(failure) printf("Failed test at line %d\n", __LINE__); std.file.write(testFile, "1 2\n4 1\n5 100"); scope(exit) std.file.remove(testFile); File f = File(testFile); scope(exit) f.close(); auto expected = [tuple(1, 2), tuple(4, 1), tuple(5, 100)]; uint i; foreach (e; f.byRecord!(int, int)("%s %s")) { writeln(e); // expected[i++] } ``` auto **byChunk**(size\_t chunkSize); auto **byChunk**(ubyte[] buffer); Returns an [input range](std_range_primitives#isInputRange) set up to read from the file handle a chunk at a time. The element type for the range will be `ubyte[]`. Range primitives may throw `StdioException` on I/O error. Example ``` void main() { // Read standard input 4KB at a time foreach (ubyte[] buffer; stdin.byChunk(4096)) { ... use buffer ... } } ``` The parameter may be a number (as shown in the example above) dictating the size of each chunk. Alternatively, `byChunk` accepts a user-provided buffer that it uses directly. Example ``` void main() { // Read standard input 4KB at a time foreach (ubyte[] buffer; stdin.byChunk(new ubyte[4096])) { ... use buffer ... } } ``` In either case, the content of the buffer is reused across calls. That means `front` will not persist after `popFront` is called, so if retention is needed, the caller must copy its contents (e.g. by calling `buffer.dup`). In the example above, `buffer.length` is 4096 for all iterations, except for the last one, in which case `buffer.length` may be less than 4096 (but always greater than zero). With the mentioned limitations, `byChunk` works with any algorithm compatible with input ranges. Example ``` // Efficient file copy, 1MB at a time. import std.algorithm, std.stdio; void main() { stdin.byChunk(1024 * 1024).copy(stdout.lockingTextWriter()); } ``` [`std.algorithm.iteration.joiner`](std_algorithm_iteration#joiner) can be used to join chunks together into a single range lazily. Example ``` import std.algorithm, std.stdio; void main() { //Range of ranges static assert(is(typeof(stdin.byChunk(4096).front) == ubyte[])); //Range of elements static assert(is(typeof(stdin.byChunk(4096).joiner.front) == ubyte)); } ``` Returns: A call to `byChunk` returns a range initialized with the `File` object and the appropriate buffer. Throws: If the user-provided size is zero or the user-provided buffer is empty, throws an `Exception`. In case of an I/O error throws `StdioException`. @safe auto **lockingTextWriter**(); Output range which locks the file when created, and unlocks the file when it goes out of scope. Returns: An [output range](std_range_primitives#isOutputRange) which accepts string types, `ubyte[]`, individual character types, and individual `ubyte`s. Note Writing either arrays of `char`s or `ubyte`s is faster than writing each character individually from a range. For large amounts of data, writing the contents in chunks using an intermediary array can result in a speed increase. Throws: [`std.utf.UTFException`](std_utf#UTFException) if the data given is a `char` range and it contains malformed UTF data. See Also: [`byChunk`](#byChunk) for an example. auto **lockingBinaryWriter**(); Returns an output range that locks the file and allows fast writing to it. Example Produce a grayscale image of the [Mandelbrot set](https://en.wikipedia.org/wiki/Mandelbrot_set) in binary [Netpbm format](https://en.wikipedia.org/wiki/Netpbm_format) to standard output. ``` import std.algorithm, std.complex, std.range, std.stdio; void main() { enum size = 500; writef("P5\n%d %d %d\n", size, size, ubyte.max); iota(-1, 3, 2.0/size).map!(y => iota(-1.5, 0.5, 2.0/size).map!(x => cast(ubyte)(1+ recurrence!((a, n) => x + y * complex(0, 1) + a[n-1]^^2)(complex(0)) .take(ubyte.max) .countUntil!(z => z.re^^2 + z.im^^2 > 4)) ) ) .copy(stdout.lockingBinaryWriter); } ``` @property @safe ulong **size**(); Returns the size of the file in bytes, ulong.max if file is not searchable or throws if the operation fails. Example ``` import std.stdio, std.file; void main() { string deleteme = "delete.me"; auto file_handle = File(deleteme, "w"); file_handle.write("abc"); //create temporary file scope(exit) deleteme.remove; //remove temporary file at scope exit assert(file_handle.size() == 3); //check if file size is 3 bytes } ``` enum **LockType**: int; Used to specify the lock type for `File.lock` and `File.tryLock`. **read** Specifies a read (shared) lock. A read lock denies all processes write access to the specified region of the file, including the process that first locks the region. All processes can read the locked region. Multiple simultaneous read locks are allowed, as long as there are no exclusive locks. **readWrite** Specifies a read/write (exclusive) lock. A read/write lock denies all other processes both read and write access to the locked file region. If a segment has an exclusive lock, it may not have any shared locks or other exclusive locks. enum auto **isFileHandle**(T); Indicates whether `T` is a file handle, i.e. the type is implicitly convertable to [`File`](#File) or a pointer to a [`core.stdc.stdio.FILE`](core_stdc_stdio#FILE). Returns: `true` if `T` is a file handle, `false` otherwise. Examples: ``` static assert(isFileHandle!(FILE*)); static assert(isFileHandle!(File)); ``` void **write**(T...)(T args) Constraints: if (!is(T[0] : File)); Writes its arguments in text format to standard output (without a trailing newline). Parameters: | | | | --- | --- | | T `args` | the items to write to `stdout` | Throws: In case of an I/O error, throws an `StdioException`. Example Reads `stdin` and writes it to `stdout` with an argument counter. ``` import std.stdio; void main() { string line; for (size_t count = 0; (line = readln) !is null; count++) { write("Input ", count, ": ", line, "\n"); } } ``` void **writeln**(T...)(T args); Equivalent to `write(args, '\n')`. Calling `writeln` without arguments is valid and just prints a newline to the standard output. Parameters: | | | | --- | --- | | T `args` | the items to write to `stdout` | Throws: In case of an I/O error, throws an [`StdioException`](#StdioException). Example Reads `stdin` and writes it to `stdout` with an argument counter. ``` import std.stdio; void main() { string line; for (size_t count = 0; (line = readln) !is null; count++) { writeln("Input ", count, ": ", line); } } ``` void **writef**(alias fmt, A...)(A args) Constraints: if (isSomeString!(typeof(fmt))); void **writef**(Char, A...)(in Char[] fmt, A args); Writes formatted data to standard output (without a trailing newline). Parameters: | | | | --- | --- | | Char[] `fmt` | The [format string](std_format#formattedWrite). When passed as a compile-time argument, the string will be statically checked against the argument types passed. | | A `args` | Items to write. | Note In older versions of Phobos, it used to be possible to write: ``` writef(stderr, "%s", "message"); ``` to print a message to `stderr`. This syntax is no longer supported, and has been superceded by: ``` stderr.writef("%s", "message"); ``` void **writefln**(alias fmt, A...)(A args) Constraints: if (isSomeString!(typeof(fmt))); void **writefln**(Char, A...)(in Char[] fmt, A args); Equivalent to `writef(fmt, args, '\n')`. uint **readf**(alias format, A...)(auto ref A args) Constraints: if (isSomeString!(typeof(format))); uint **readf**(A...)(scope const(char)[] format, auto ref A args); Reads formatted data from `stdin` using [`std.format.formattedRead`](std_format#formattedRead). Parameters: | | | | --- | --- | | const(char)[] `format` | The [format string](std_format#formattedWrite). When passed as a compile-time argument, the string will be statically checked against the argument types passed. | | A `args` | Items to be read. | Example ``` // test.d void main() { import std.stdio; foreach (_; 0 .. 3) { int a; readf!" %d"(a); writeln(++a); } } ``` ``` % echo "1 2 3" | rdmd test.d 2 3 4 ``` S **readln**(S = string)(dchar terminator = '\x0a') Constraints: if (isSomeString!S); Read line from `stdin`. This version manages its own read buffer, which means one memory allocation per call. If you are not retaining a reference to the read data, consider the `readln(buf)` version, which may offer better performance as it can reuse its read buffer. Returns: The line that was read, including the line terminator character. Parameters: | | | | --- | --- | | S | Template parameter; the type of the allocated buffer, and the type returned. Defaults to `string`. | | dchar `terminator` | Line terminator (by default, `'\n'`). | Note String terminators are not supported due to ambiguity with readln(buf) below. Throws: `StdioException` on I/O error, or `UnicodeException` on Unicode conversion error. Example Reads `stdin` and writes it to `stdout`. ``` import std.stdio; void main() { string line; while ((line = readln()) !is null) write(line); } ``` size\_t **readln**(C)(ref C[] buf, dchar terminator = '\x0a') Constraints: if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum)); size\_t **readln**(C, R)(ref C[] buf, R terminator) Constraints: if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum) && isBidirectionalRange!R && is(typeof(terminator.front == (dchar).init))); Read line from `stdin` and write it to buf[], including terminating character. This can be faster than `line = readln()` because you can reuse the buffer for each call. Note that reusing the buffer means that you must copy the previous contents if you wish to retain them. Returns: `size_t` 0 for end of file, otherwise number of characters read Parameters: | | | | --- | --- | | C[] `buf` | Buffer used to store the resulting line data. buf is resized as necessary. | | dchar `terminator` | Line terminator (by default, `'\n'`). Use [`std.ascii.newline`](std_ascii#newline) for portability (unless the file was opened in text mode). | Throws: `StdioException` on I/O error, or `UnicodeException` on Unicode conversion error. Example Reads `stdin` and writes it to `stdout`. ``` import std.stdio; void main() { char[] buf; while (readln(buf)) write(buf); } ``` nothrow @nogc @trusted FILE\* **\_popen**(R1, R2)(R1 name, R2 mode = "r") Constraints: if ((isInputRange!R1 && isSomeChar!(ElementEncodingType!R1) || isSomeString!R1) && (isInputRange!R2 && isSomeChar!(ElementEncodingType!R2) || isSomeString!R2)); Convenience function that forwards to `core.sys.posix.stdio.popen` with appropriately-constructed C-style strings. struct **lines**; Iterates through the lines of a file by using `foreach`. Example ``` void main() { foreach (string line; lines(stdin)) { ... use line ... } } ``` The line terminator (`'\n'` by default) is part of the string read (it could be missing in the last line of the file). Several types are supported for `line`, and the behavior of `lines` changes accordingly: 1. If `line` has type `string`, `wstring`, or `dstring`, a new string of the respective type is allocated every read. 2. If `line` has type `char[]`, `wchar[]`, `dchar[]`, the line's content will be reused (overwritten) across reads. 3. If `line` has type `immutable(ubyte)[]`, the behavior is similar to case (1), except that no UTF checking is attempted upon input. 4. If `line` has type `ubyte[]`, the behavior is similar to case (2), except that no UTF checking is attempted upon input. In all cases, a two-symbols versions is also accepted, in which case the first symbol (of integral type, e.g. `ulong` or `uint`) tracks the zero-based number of the current line. Example ``` foreach (ulong i, string line; lines(stdin)) { ... use line ... } ``` In case of an I/O error, an `StdioException` is thrown. See Also: [`byLine`](#byLine) this(File f, dchar terminator = '\x0a'); Constructor. Parameters: | | | | --- | --- | | File `f` | File to read lines from. | | dchar `terminator` | Line separator (`'\n'` by default). | auto **chunks**(File f, size\_t size); Iterates through a file a chunk at a time by using `foreach`. Example ``` void main() { foreach (ubyte[] buffer; chunks(stdin, 4096)) { ... use buffer ... } } ``` The content of `buffer` is reused across calls. In the example above, `buffer.length` is 4096 for all iterations, except for the last one, in which case `buffer.length` may be less than 4096 (but always greater than zero). In case of an I/O error, an `StdioException` is thrown. void **toFile**(T)(T data, string fileName) Constraints: if (is(typeof(copy(data, stdout.lockingBinaryWriter)))); Writes an array or range to a file. Shorthand for `data.copy(File(fileName, "wb").lockingBinaryWriter)`. Similar to [`std.file.write`](std_file#write), strings are written as-is, rather than encoded according to the `File`'s [orientation](http://en.cppreference.com/w/c/io#Narrow_and_wide_orientation). class **StdioException**: object.Exception; Thrown if I/O errors happen. uint **errno**; Operating system error code. @trusted this(string message, uint e = core.stdc.errno.errno); Initialize with a message and an error code. static void **opCall**(string msg); static void **opCall**(); Convenience functions that throw an `StdioException`. alias **stdin** = makeGlobal!"core.stdc.stdio.**stdin**".makeGlobal; The standard input stream. Returns: stdin as a [`File`](#File). Note The returned [`File`](#File) wraps [`core.stdc.stdio.stdin`](core_stdc_stdio#stdin), and is therefore thread global. Reassigning `stdin` to a different `File` must be done in a single-threaded or locked context in order to avoid race conditions. All reading from `stdin` automatically locks the file globally, and will cause all other threads calling `read` to wait until the lock is released. Examples: ``` // Read stdin, sort lines, write to stdout import std.algorithm.mutation : copy; import std.algorithm.sorting : sort; import std.array : array; import std.typecons : Yes; void main() { stdin // read from stdin .byLineCopy(Yes.keepTerminator) // copying each line .array() // convert to array of lines .sort() // sort the lines .copy( // copy output of .sort to an OutputRange stdout.lockingTextWriter()); // the OutputRange } ``` alias **stdout** = makeGlobal!"core.stdc.stdio.**stdout**".makeGlobal; The standard output stream. Returns: stdout as a [`File`](#File). Note The returned [`File`](#File) wraps [`core.stdc.stdio.stdout`](core_stdc_stdio#stdout), and is therefore thread global. Reassigning `stdout` to a different `File` must be done in a single-threaded or locked context in order to avoid race conditions. All writing to `stdout` automatically locks the file globally, and will cause all other threads calling `write` to wait until the lock is released. Examples: ``` void main() { stdout.writeln("Write a message to stdout."); } ``` Examples: ``` void main() { import std.algorithm.iteration : filter, map, sum; import std.format : format; import std.range : iota, tee; int len; const r = 6.iota .filter!(a => a % 2) // 1 3 5 .map!(a => a * 2) // 2 6 10 .tee!(_ => stdout.writefln("len: %d", len++)) .sum; writeln(r); // 18 } ``` Examples: ``` void main() { import std.algorithm.mutation : copy; import std.algorithm.iteration : map; import std.format : format; import std.range : iota; 10.iota .map!(e => "N: %d".format(e)) .copy(stdout.lockingTextWriter()); // the OutputRange } ``` alias **stderr** = makeGlobal!"core.stdc.stdio.**stderr**".makeGlobal; The standard error stream. Returns: stderr as a [`File`](#File). Note The returned [`File`](#File) wraps [`core.stdc.stdio.stderr`](core_stdc_stdio#stderr), and is therefore thread global. Reassigning `stderr` to a different `File` must be done in a single-threaded or locked context in order to avoid race conditions. All writing to `stderr` automatically locks the file globally, and will cause all other threads calling `write` to wait until the lock is released. Examples: ``` void main() { stderr.writeln("Write a message to stderr."); } ``` File **openNetwork**(string host, ushort port); Experimental network access via the File interface Opens a TCP connection to the given host and port, then returns a File struct with read and write access through the same interface as any other file (meaning writef and the byLine ranges work!). Authors: Adam D. Ruppe Bugs: Only works on Linux
programming_docs
d std.datetime.timezone std.datetime.timezone ===================== | Category | Functions | | --- | --- | | Time zones | [`TimeZone`](#TimeZone) [`UTC`](#UTC) [`LocalTime`](#LocalTime) [`PosixTimeZone`](#PosixTimeZone) [`WindowsTimeZone`](#WindowsTimeZone) [`SimpleTimeZone`](#SimpleTimeZone) | | Utilities | [`clearTZEnvVar`](#clearTZEnvVar) [`parseTZConversions`](#parseTZConversions) [`setTZEnvVar`](#setTZEnvVar) [`TZConversions`](#TZConversions) | License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: [Jonathan M Davis](http://jmdavisprog.com) Source [std/datetime/timezone.d](https://github.com/dlang/phobos/blob/master/std/datetime/timezone.d) abstract class **TimeZone**; Represents a time zone. It is used with [`std.datetime.systime.SysTime`](std_datetime_systime#SysTime) to indicate the time zone of a [`std.datetime.systime.SysTime`](std_datetime_systime#SysTime). const nothrow @property @safe string **name**(); The name of the time zone. Exactly how the time zone name is formatted depends on the derived class. In the case of [`PosixTimeZone`](#PosixTimeZone), it's the TZ Database name, whereas with [`WindowsTimeZone`](#WindowsTimeZone), it's the name that Windows chose to give the registry key for that time zone (typically the name that they give [`stdTime`](#stdTime) if the OS is in English). For other time zone types, what it is depends on how they're implemented. See Also: [Wikipedia entry on TZ Database](http://en.wikipedia.org/wiki/Tz_database) [List of Time Zones](http://en.wikipedia.org/wiki/List_of_tz_database_time_zones) const nothrow @property @safe string **stdName**(); Typically, the abbreviation (generally 3 or 4 letters) for the time zone when DST is *not* in effect (e.g. PST). It is not necessarily unique. However, on Windows, it may be the unabbreviated name (e.g. Pacific Standard Time). Regardless, it is not the same as name. const nothrow @property @safe string **dstName**(); Typically, the abbreviation (generally 3 or 4 letters) for the time zone when DST *is* in effect (e.g. PDT). It is not necessarily unique. However, on Windows, it may be the unabbreviated name (e.g. Pacific Daylight Time). Regardless, it is not the same as name. abstract const nothrow @property @safe bool **hasDST**(); Whether this time zone has Daylight Savings Time at any point in time. Note that for some time zone types it may not have DST for current dates but will still return true for `hasDST` because the time zone did at some point have DST. abstract const nothrow @safe bool **dstInEffect**(long stdTime); Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and returns whether DST is effect in this time zone at the given point in time. Parameters: | | | | --- | --- | | long `stdTime` | The UTC time that needs to be checked for DST in this time zone. | abstract const nothrow @safe long **utcToTZ**(long stdTime); Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and converts it to this time zone's time. Parameters: | | | | --- | --- | | long `stdTime` | The UTC time that needs to be adjusted to this time zone's time. | abstract const nothrow @safe long **tzToUTC**(long adjTime); Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in this time zone's time and converts it to UTC (i.e. std time). Parameters: | | | | --- | --- | | long `adjTime` | The time in this time zone that needs to be adjusted to UTC time. | const nothrow @safe Duration **utcOffsetAt**(long stdTime); Returns what the offset from UTC is at the given std time. It includes the DST offset in effect at that time (if any). Parameters: | | | | --- | --- | | long `stdTime` | The UTC time for which to get the offset from UTC for this time zone. | protected immutable pure @safe this(string name, string stdName, string dstName); Parameters: | | | | --- | --- | | string `name` | The name of the time zone. | | string `stdName` | The abbreviation for the time zone during std time. | | string `dstName` | The abbreviation for the time zone during DST. | class **LocalTime**: std.datetime.timezone.TimeZone; A TimeZone which represents the current local time zone on the system running your program. This uses the underlying C calls to adjust the time rather than using specific D code based off of system settings to calculate the time such as [`PosixTimeZone`](#PosixTimeZone) and [`WindowsTimeZone`](#WindowsTimeZone) do. That also means that it will use whatever the current time zone is on the system, even if the system's time zone changes while the program is running. static pure nothrow @trusted immutable(LocalTime) **opCall**(); [`LocalTime`](#LocalTime) is a singleton class. [`LocalTime`](#LocalTime) returns its only instance. const nothrow @property @safe string **name**(); In principle, this is the name of the local time zone. However, this always returns the empty string. This is because time zones cannot be uniquely identified by the attributes given by the OS (such as the `stdName` and `dstName`), and neither Posix systems nor Windows systems provide an easy way to get the TZ Database name of the local time zone. See Also: [Wikipedia entry on TZ Database](http://en.wikipedia.org/wiki/Tz_database) [List of Time Zones](http://en.wikipedia.org/wiki/List_of_tz_database_time_zones) const nothrow @property @trusted string **stdName**(); Typically, the abbreviation (generally 3 or 4 letters) for the time zone when DST is *not* in effect (e.g. PST). It is not necessarily unique. However, on Windows, it may be the unabbreviated name (e.g. Pacific Standard Time). Regardless, it is not the same as name. This property is overridden because the local time of the system could change while the program is running and we need to determine it dynamically rather than it being fixed like it would be with most time zones. const nothrow @property @trusted string **dstName**(); Typically, the abbreviation (generally 3 or 4 letters) for the time zone when DST *is* in effect (e.g. PDT). It is not necessarily unique. However, on Windows, it may be the unabbreviated name (e.g. Pacific Daylight Time). Regardless, it is not the same as name. This property is overridden because the local time of the system could change while the program is running and we need to determine it dynamically rather than it being fixed like it would be with most time zones. const nothrow @property @trusted bool **hasDST**(); Whether this time zone has Daylight Savings Time at any point in time. Note that for some time zone types it may not have DST for current dates but will still return true for `hasDST` because the time zone did at some point have DST. const nothrow @trusted bool **dstInEffect**(long stdTime); Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and returns whether DST is in effect in this time zone at the given point in time. Parameters: | | | | --- | --- | | long `stdTime` | The UTC time that needs to be checked for DST in this time zone. | const nothrow @trusted long **utcToTZ**(long stdTime); Returns hnsecs in the local time zone using the standard C function calls on Posix systems and the standard Windows system calls on Windows systems to adjust the time to the appropriate time zone from std time. Parameters: | | | | --- | --- | | long `stdTime` | The UTC time that needs to be adjusted to this time zone's time. | See Also: `TimeZone.utcToTZ` const nothrow @trusted long **tzToUTC**(long adjTime); Returns std time using the standard C function calls on Posix systems and the standard Windows system calls on Windows systems to adjust the time to UTC from the appropriate time zone. See Also: `TimeZone.tzToUTC` Parameters: | | | | --- | --- | | long `adjTime` | The time in this time zone that needs to be adjusted to UTC time. | class **UTC**: std.datetime.timezone.TimeZone; A [`TimeZone`](#TimeZone) which represents UTC. static pure nothrow @safe immutable(UTC) **opCall**(); `UTC` is a singleton class. `UTC` returns its only instance. const nothrow @property @safe bool **hasDST**(); Always returns false. const nothrow @safe bool **dstInEffect**(long stdTime); Always returns false. const nothrow @safe long **utcToTZ**(long stdTime); Returns the given hnsecs without changing them at all. Parameters: | | | | --- | --- | | long `stdTime` | The UTC time that needs to be adjusted to this time zone's time. | See Also: `TimeZone.utcToTZ` const nothrow @safe long **tzToUTC**(long adjTime); Returns the given hnsecs without changing them at all. See Also: `TimeZone.tzToUTC` Parameters: | | | | --- | --- | | long `adjTime` | The time in this time zone that needs to be adjusted to UTC time. | const nothrow @safe Duration **utcOffsetAt**(long stdTime); Returns a [`core.time.Duration`](core_time#Duration) of 0. Parameters: | | | | --- | --- | | long `stdTime` | The UTC time for which to get the offset from UTC for this time zone. | class **SimpleTimeZone**: std.datetime.timezone.TimeZone; Represents a time zone with an offset (in minutes, west is negative) from UTC but no DST. It's primarily used as the time zone in the result of [`std.datetime.systime.SysTime`](std_datetime_systime#SysTime)'s `fromISOString`, `fromISOExtString`, and `fromSimpleString`. `name` and `dstName` are always the empty string since this time zone has no DST, and while it may be meant to represent a time zone which is in the TZ Database, obviously it's not likely to be following the exact rules of any of the time zones in the TZ Database, so it makes no sense to set it. const nothrow @property @safe bool **hasDST**(); Always returns false. const nothrow @safe bool **dstInEffect**(long stdTime); Always returns false. const nothrow @safe long **utcToTZ**(long stdTime); Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and converts it to this time zone's time. Parameters: | | | | --- | --- | | long `stdTime` | The UTC time that needs to be adjusted to this time zone's time. | const nothrow @safe long **tzToUTC**(long adjTime); Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in this time zone's time and converts it to UTC (i.e. std time). Parameters: | | | | --- | --- | | long `adjTime` | The time in this time zone that needs to be adjusted to UTC time. | const nothrow @safe Duration **utcOffsetAt**(long stdTime); Returns utcOffset as a [`core.time.Duration`](core_time#Duration). Parameters: | | | | --- | --- | | long `stdTime` | The UTC time for which to get the offset from UTC for this time zone. | immutable pure @safe this(Duration utcOffset, string stdName = ""); Parameters: | | | | --- | --- | | Duration `utcOffset` | This time zone's offset from UTC with west of UTC being negative (it is added to UTC to get the adjusted time). | | string `stdName` | The `stdName` for this time zone. | const pure nothrow @property @safe Duration **utcOffset**(); The amount of time the offset from UTC is (negative is west of UTC, positive is east). class **PosixTimeZone**: std.datetime.timezone.TimeZone; Represents a time zone from a TZ Database time zone file. Files from the TZ Database are how Posix systems hold their time zone information. Unfortunately, Windows does not use the TZ Database. To use the TZ Database, use `PosixTimeZone` (which reads its information from the TZ Database files on disk) on Windows by providing the TZ Database files and telling `PosixTimeZone.getTimeZone` where the directory holding them is. To get a `PosixTimeZone`, call `PosixTimeZone.getTimeZone` (which allows specifying the location the time zone files). Note Unless your system's local time zone deals with leap seconds (which is highly unlikely), then the only way to get a time zone which takes leap seconds into account is to use `PosixTimeZone` with a time zone whose name starts with "right/". Those time zone files do include leap seconds, and `PosixTimeZone` will take them into account (though posix systems which use a "right/" time zone as their local time zone will *not* take leap seconds into account even though they're in the file). See Also: [Home of the TZ Database files](http://www.iana.org/time-zones) [Wikipedia entry on TZ Database](http://en.wikipedia.org/wiki/Tz_database) [List of Time Zones](http://en.wikipedia.org/wiki/List_of_tz_database_time_zones) const nothrow @property @safe bool **hasDST**(); Whether this time zone has Daylight Savings Time at any point in time. Note that for some time zone types it may not have DST for current dates but will still return true for `hasDST` because the time zone did at some point have DST. const nothrow @safe bool **dstInEffect**(long stdTime); Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and returns whether DST is in effect in this time zone at the given point in time. Parameters: | | | | --- | --- | | long `stdTime` | The UTC time that needs to be checked for DST in this time zone. | const nothrow @safe long **utcToTZ**(long stdTime); Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and converts it to this time zone's time. Parameters: | | | | --- | --- | | long `stdTime` | The UTC time that needs to be adjusted to this time zone's time. | const nothrow @safe long **tzToUTC**(long adjTime); Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in this time zone's time and converts it to UTC (i.e. std time). Parameters: | | | | --- | --- | | long `adjTime` | The time in this time zone that needs to be adjusted to UTC time. | enum string **defaultTZDatabaseDir**; The default directory where the TZ Database files are stored. It's empty for Windows, since Windows doesn't have them. You can also use the TZDatabaseDir version to pass an arbitrary path at compile-time, rather than hard-coding it here. Android concatenates all time zone data into a single file called tzdata and stores it in the directory below. static @trusted immutable(PosixTimeZone) **getTimeZone**(string name, string tzDatabaseDir = defaultTZDatabaseDir); Returns a [`TimeZone`](#TimeZone) with the give name per the TZ Database. The time zone information is fetched from the TZ Database time zone files in the given directory. See Also: [Wikipedia entry on TZ Database](http://en.wikipedia.org/wiki/Tz_database) [List of Time Zones](http://en.wikipedia.org/wiki/List_of_tz_database_time_zones) Parameters: | | | | --- | --- | | string `name` | The TZ Database name of the desired time zone | | string `tzDatabaseDir` | The directory where the TZ Database files are located. Because these files are not located on Windows systems, provide them and give their location here to use [`PosixTimeZone`](#PosixTimeZone)s. | Throws: [`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given time zone could not be found or `FileException` if the TZ Database file could not be opened. Examples: ``` version (Posix) { auto tz = PosixTimeZone.getTimeZone("America/Los_Angeles"); writeln(tz.name); // "America/Los_Angeles" writeln(tz.stdName); // "PST" writeln(tz.dstName); // "PDT" } ``` static @safe string[] **getInstalledTZNames**(string subName = "", string tzDatabaseDir = defaultTZDatabaseDir); Returns a list of the names of the time zones installed on the system. Providing a sub-name narrows down the list of time zones (which can number in the thousands). For example, passing in "America" as the sub-name returns only the time zones which begin with "America". Parameters: | | | | --- | --- | | string `subName` | The first part of the desired time zones. | | string `tzDatabaseDir` | The directory where the TZ Database files are located. | Throws: `FileException` if it fails to read from disk. class **WindowsTimeZone**: std.datetime.timezone.TimeZone; This class is Windows-Only. Represents a time zone from the Windows registry. Unfortunately, Windows does not use the TZ Database. To use the TZ Database, use [`PosixTimeZone`](#PosixTimeZone) (which reads its information from the TZ Database files on disk) on Windows by providing the TZ Database files and telling `PosixTimeZone.getTimeZone` where the directory holding them is. The TZ Database files and Windows' time zone information frequently do not match. Windows has many errors with regards to when DST switches occur (especially for historical dates). Also, the TZ Database files include far more time zones than Windows does. So, for accurate time zone information, use the TZ Database files with [`PosixTimeZone`](#PosixTimeZone) rather than `WindowsTimeZone`. However, because `WindowsTimeZone` uses Windows system calls to deal with the time, it's far more likely to match the behavior of other Windows programs. Be aware of the differences when selecting a method. `WindowsTimeZone` does not exist on Posix systems. To get a `WindowsTimeZone`, call `WindowsTimeZone.getTimeZone`. See Also: [Home of the TZ Database files](http://www.iana.org/time-zones) const nothrow @property @safe bool **hasDST**(); Whether this time zone has Daylight Savings Time at any point in time. Note that for some time zone types it may not have DST for current dates but will still return true for `hasDST` because the time zone did at some point have DST. const nothrow @safe bool **dstInEffect**(long stdTime); Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and returns whether DST is in effect in this time zone at the given point in time. Parameters: | | | | --- | --- | | long `stdTime` | The UTC time that needs to be checked for DST in this time zone. | const nothrow @safe long **utcToTZ**(long stdTime); Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and converts it to this time zone's time. Parameters: | | | | --- | --- | | long `stdTime` | The UTC time that needs to be adjusted to this time zone's time. | const nothrow @safe long **tzToUTC**(long adjTime); Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in this time zone's time and converts it to UTC (i.e. std time). Parameters: | | | | --- | --- | | long `adjTime` | The time in this time zone that needs to be adjusted to UTC time. | static @safe immutable(WindowsTimeZone) **getTimeZone**(string name); Returns a [`TimeZone`](#TimeZone) with the given name per the Windows time zone names. The time zone information is fetched from the Windows registry. See Also: [Wikipedia entry on TZ Database](http://en.wikipedia.org/wiki/Tz_database) [List of Time Zones](http://en.wikipedia.org/wiki/List_of_tz_database_time_zones) Parameters: | | | | --- | --- | | string `name` | The TZ Database name of the desired time zone. | Throws: [`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given time zone could not be found. Example ``` auto tz = WindowsTimeZone.getTimeZone("Pacific Standard Time"); ``` static @safe string[] **getInstalledTZNames**(); Returns a list of the names of the time zones installed on the system. The list returned by WindowsTimeZone contains the Windows TZ names, not the TZ Database names. However, `TimeZone.getinstalledTZNames` will return the TZ Database names which are equivalent to the Windows TZ names. nothrow @safe void **setTZEnvVar**(string tzDatabaseName); This function is Posix-Only. Sets the local time zone on Posix systems with the TZ Database name by setting the TZ environment variable. Unfortunately, there is no way to do it on Windows using the TZ Database name, so this function only exists on Posix systems. nothrow @safe void **clearTZEnvVar**(); This function is Posix-Only. Clears the TZ environment variable. struct **TZConversions**; pure @safe TZConversions **parseTZConversions**(string windowsZonesXMLText); Provides the conversions between the IANA time zone database time zone names (which POSIX systems use) and the time zone names that Windows uses. Windows uses a different set of time zone names than the IANA time zone database does, and how they correspond to one another changes over time (particularly when Microsoft updates Windows). [windowsZones.xml](http://unicode.org/cldr/data/common/supplemental/windowsZones.xml) provides the current conversions (which may or may not match up with what's on a particular Windows box depending on how up-to-date it is), and parseTZConversions reads in those conversions from windowsZones.xml so that a D program can use those conversions. However, it should be noted that the time zone information on Windows is frequently less accurate than that in the IANA time zone database, and if someone really wants accurate time zone information, they should use the IANA time zone database files with [`PosixTimeZone`](#PosixTimeZone) on Windows rather than [`WindowsTimeZone`](#WindowsTimeZone), whereas [`WindowsTimeZone`](#WindowsTimeZone) makes more sense when trying to match what Windows will think the time is in a specific time zone. Also, the IANA time zone database has a lot more time zones than Windows does. Parameters: | | | | --- | --- | | string `windowsZonesXMLText` | The text from [windowsZones.xml](http://unicode.org/cldr/data/common/supplemental/windowsZones.xml) | Throws: Exception if there is an error while parsing the given XML. ``` // Parse the conversions from a local file. auto text = std.file.readText("path/to/windowsZones.xml"); auto conversions = parseTZConversions(text); // Alternatively, grab the XML file from the web at runtime // and parse it so that it's guaranteed to be up-to-date, though // that has the downside that the code needs to worry about the // site being down or unicode.org changing the URL. auto url = "http://unicode.org/cldr/data/common/supplemental/windowsZones.xml"; auto conversions2 = parseTZConversions(std.net.curl.get(url)); ``` string[][string] **toWindows**; The key is the Windows time zone name, and the value is a list of IANA TZ database names which are close (currently only ever one, but it allows for multiple in case it's ever necessary). string[][string] **fromWindows**; The key is the IANA time zone database name, and the value is a list of Windows time zone names which are close (usually only one, but it could be multiple).
programming_docs
d core.gc.registry core.gc.registry ================ Contains a registry for GC factories. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Martin Nowak alias **GCFactory** = GC function(); A factory function that instantiates an implementation of the GC interface. In case the instance was allocated on the C heap, it is supposed to free itself upon calling it's destructor. The factory should print an error and abort the program if it cannot successfully initialize the GC instance. nothrow @nogc void **registerGCFactory**(string name, GCFactory factory); Register a GC factory under the given `name`. This function must be called from a C constructor before druntime is initialized. To use the registered GC, it's name must be specified gcopt runtime option, e.g. by passing *, --DRT-gcopt=gc:my\_gc\_name* as application argument. Parameters: | | | | --- | --- | | string `name` | name of the GC implementation; should be unique | | GCFactory `factory` | function to instantiate the implementation | Note The registry does not perform synchronization, as registration is assumed to be executed serially, as is the case for C constructors. See Also: [Configuring the Garbage Collector](https://dlang.org/spec/garbage.html#gc_config) GC **createGCInstance**(string name); Called during runtime initialization to initialize a GC instance of given `name`. Parameters: | | | | --- | --- | | string `name` | name of the GC to instantiate | Returns: The created GC instance or `null` if no factory for that name was registered d etc.c.sqlite3 etc.c.sqlite3 ============= enum string **SQLITE\_VERSION**; enum int **SQLITE\_VERSION\_NUMBER**; enum string **SQLITE\_SOURCE\_ID**; CAPI3REF Compile-Time Library Version Numbers immutable(char)\* **sqlite3\_version**; nothrow immutable(char)\* **sqlite3\_libversion**(); nothrow immutable(char)\* **sqlite3\_sourceid**(); nothrow int **sqlite3\_libversion\_number**(); CAPI3REF Run-Time Library Version Numbers nothrow int **sqlite3\_compileoption\_used**(const char\* zOptName); nothrow immutable(char)\* **sqlite3\_compileoption\_get**(int N); CAPI3REF Run-Time Library Compilation Options Diagnostics nothrow int **sqlite3\_threadsafe**(); CAPI3REF Test To See If The Library Is Threadsafe struct **sqlite3**; CAPI3REF Database Connection Handle alias **sqlite3\_int64** = long; alias **sqlite3\_uint64** = ulong; nothrow int **sqlite3\_close**(sqlite3\*); CAPI3REF Closing A Database Connection alias **sqlite3\_callback** = extern (C) int function(void\*, int, char\*\*, char\*\*) nothrow; The type for a callback function. This is legacy and deprecated. It is included for historical compatibility and is not documented. nothrow int **sqlite3\_exec**(sqlite3\*, const(char)\* sql, int function(void\*, int, char\*\*, char\*\*) callback, void\*, char\*\* errmsg); CAPI3REF One-Step Query Execution Interface **SQLITE\_OK** Successful result **SQLITE\_ERROR** Ditto Generic error **SQLITE\_INTERNAL** Internal logic error in SQLite **SQLITE\_PERM** Access permission denied **SQLITE\_ABORT** Callback routine requested an abort **SQLITE\_BUSY** The database file is locked **SQLITE\_LOCKED** A table in the database is locked **SQLITE\_NOMEM** A malloc() failed **SQLITE\_READONLY** Attempt to write a readonly database **SQLITE\_INTERRUPT** Operation terminated by sqlite3\_interrupt() **SQLITE\_IOERR** Some kind of disk I/O error occurred **SQLITE\_CORRUPT** The database disk image is malformed **SQLITE\_NOTFOUND** Unknown opcode in sqlite3\_file\_control() **SQLITE\_FULL** Insertion failed because database is full **SQLITE\_CANTOPEN** Unable to open the database file **SQLITE\_PROTOCOL** Database lock protocol error **SQLITE\_EMPTY** Internal use only **SQLITE\_SCHEMA** The database schema changed **SQLITE\_TOOBIG** String or BLOB exceeds size limit **SQLITE\_CONSTRAINT** Abort due to constraint violation **SQLITE\_MISMATCH** Data type mismatch **SQLITE\_MISUSE** Library used incorrectly **SQLITE\_NOLFS** Uses OS features not supported on host **SQLITE\_AUTH** Authorization denied **SQLITE\_FORMAT** Not used **SQLITE\_RANGE** 2nd parameter to sqlite3\_bind out of range **SQLITE\_NOTADB** File opened that is not a database file **SQLITE\_ROW** sqlite3\_step() has another row ready **SQLITE\_DONE** sqlite3\_step() has finished executing **SQLITE\_OPEN\_READONLY** Ok for sqlite3\_open\_v2() **SQLITE\_OPEN\_READWRITE** Ok for sqlite3\_open\_v2() **SQLITE\_OPEN\_CREATE** Ok for sqlite3\_open\_v2() **SQLITE\_OPEN\_DELETEONCLOSE** VFS only **SQLITE\_OPEN\_EXCLUSIVE** VFS only **SQLITE\_OPEN\_AUTOPROXY** VFS only **SQLITE\_OPEN\_URI** Ok for sqlite3\_open\_v2() **SQLITE\_OPEN\_MEMORY** Ok for sqlite3\_open\_v2() **SQLITE\_OPEN\_MAIN\_DB** VFS only **SQLITE\_OPEN\_TEMP\_DB** VFS only **SQLITE\_OPEN\_TRANSIENT\_DB** VFS only **SQLITE\_OPEN\_MAIN\_JOURNAL** VFS only **SQLITE\_OPEN\_TEMP\_JOURNAL** VFS only **SQLITE\_OPEN\_SUBJOURNAL** VFS only **SQLITE\_OPEN\_SUPER\_JOURNAL** VFS only **SQLITE\_OPEN\_NOMUTEX** Ok for sqlite3\_open\_v2() **SQLITE\_OPEN\_FULLMUTEX** Ok for sqlite3\_open\_v2() **SQLITE\_OPEN\_SHAREDCACHE** Ok for sqlite3\_open\_v2() **SQLITE\_OPEN\_PRIVATECACHE** Ok for sqlite3\_open\_v2() **SQLITE\_OPEN\_WAL** VFS only **SQLITE\_OPEN\_NOFOLLOW** Ok for sqlite3\_open\_v2() deprecated alias **SQLITE\_OPEN\_MASTER\_JOURNAL** = SQLITE\_OPEN\_SUPER\_JOURNAL; VFS only struct **sqlite3\_file**; CAPI3REF OS Interface Open File Handle struct **sqlite3\_io\_methods**; CAPI3REF OS Interface File Virtual Methods Object struct **sqlite3\_mutex**; CAPI3REF Mutex Handle struct **sqlite3\_api\_routines**; CAPI3REF Loadable Extension Thunk alias **xDlSymReturn** = extern (C) void\* function() nothrow; alias **sqlite3\_syscall\_ptr** = extern (C) void function() nothrow; CAPI3REF OS Interface Object **SQLITE\_ACCESS\_READWRITE** Used by PRAGMA temp\_store\_directory **SQLITE\_ACCESS\_READ** Unused enum int **SQLITE\_SHM\_NLOCK**; CAPI3REF Maximum xShmLock index nothrow int **sqlite3\_initialize**(); nothrow int **sqlite3\_shutdown**(); nothrow int **sqlite3\_os\_init**(); nothrow int **sqlite3\_os\_end**(); CAPI3REF Initialize The SQLite Library nothrow int **sqlite3\_config**(int, ...); CAPI3REF Configuring The SQLite Library nothrow int **sqlite3\_db\_config**(sqlite3\*, int op, ...); CAPI3REF Configure database connections struct **sqlite3\_mem\_methods**; CAPI3REF Memory Allocation Routines void\* function(int) **xMalloc**; Memory allocation function void function(void\*) **xFree**; Free a prior allocation void\* function(void\*, int) **xRealloc**; Resize an allocation int function(void\*) **xSize**; Return the size of an allocation int function(int) **xRoundup**; Round up request size to allocation size int function(void\*) **xInit**; Initialize the memory allocator void function(void\*) **xShutdown**; Deinitialize the memory allocator void\* **pAppData**; Argument to xInit() and xShutdown() **SQLITE\_CONFIG\_SINGLETHREAD** nil **SQLITE\_CONFIG\_MULTITHREAD** nil **SQLITE\_CONFIG\_SERIALIZED** nil **SQLITE\_CONFIG\_MALLOC** sqlite3\_mem\_methods\* **SQLITE\_CONFIG\_GETMALLOC** sqlite3\_mem\_methods\* **SQLITE\_CONFIG\_SCRATCH** No longer used **SQLITE\_CONFIG\_PAGECACHE** void\*, int sz, int N **SQLITE\_CONFIG\_HEAP** void\*, int nByte, int min **SQLITE\_CONFIG\_MEMSTATUS** boolean **SQLITE\_CONFIG\_MUTEX** sqlite3\_mutex\_methods\* **SQLITE\_CONFIG\_GETMUTEX** sqlite3\_mutex\_methods\* **SQLITE\_CONFIG\_LOOKASIDE** int int **SQLITE\_CONFIG\_PCACHE** no-op **SQLITE\_CONFIG\_GETPCACHE** no-op **SQLITE\_CONFIG\_LOG** xFunc, void\* **SQLITE\_CONFIG\_URI** int **SQLITE\_CONFIG\_PCACHE2** sqlite3\_pcache\_methods2\* **SQLITE\_CONFIG\_GETPCACHE2** sqlite3\_pcache\_methods2\* **SQLITE\_CONFIG\_COVERING\_INDEX\_SCAN** int **SQLITE\_CONFIG\_SQLLOG** xSqllog, void\* **SQLITE\_CONFIG\_MMAP\_SIZE** sqlite3\_int64, sqlite3\_int64 **SQLITE\_CONFIG\_WIN32\_HEAPSIZE** int nByte **SQLITE\_CONFIG\_PCACHE\_HDRSZ** int \*psz **SQLITE\_CONFIG\_PMASZ** unsigned int szPma **SQLITE\_CONFIG\_STMTJRNL\_SPILL** int nByte **SQLITE\_CONFIG\_SMALL\_MALLOC** boolean **SQLITE\_CONFIG\_SORTERREF\_SIZE** int nByte **SQLITE\_CONFIG\_MEMDB\_MAXSIZE** sqlite3\_int64 **SQLITE\_DBCONFIG\_MAINDBNAME** const char\* **SQLITE\_DBCONFIG\_LOOKASIDE** void\* int int **SQLITE\_DBCONFIG\_ENABLE\_FKEY** int int\* **SQLITE\_DBCONFIG\_ENABLE\_TRIGGER** int int\* **SQLITE\_DBCONFIG\_ENABLE\_FTS3\_TOKENIZER** int int\* **SQLITE\_DBCONFIG\_ENABLE\_LOAD\_EXTENSION** int int\* **SQLITE\_DBCONFIG\_NO\_CKPT\_ON\_CLOSE** int int\* **SQLITE\_DBCONFIG\_ENABLE\_QPSG** int int\* **SQLITE\_DBCONFIG\_TRIGGER\_EQP** int int\* **SQLITE\_DBCONFIG\_RESET\_DATABASE** int int\* **SQLITE\_DBCONFIG\_DEFENSIVE** int int\* **SQLITE\_DBCONFIG\_WRITABLE\_SCHEMA** int int\* **SQLITE\_DBCONFIG\_LEGACY\_ALTER\_TABLE** int int\* **SQLITE\_DBCONFIG\_DQS\_DML** int int\* **SQLITE\_DBCONFIG\_DQS\_DDL** int int\* **SQLITE\_DBCONFIG\_ENABLE\_VIEW** int int\* **SQLITE\_DBCONFIG\_LEGACY\_FILE\_FORMAT** int int\* **SQLITE\_DBCONFIG\_TRUSTED\_SCHEMA** int int\* **SQLITE\_DBCONFIG\_MAX** Largest DBCONFIG nothrow int **sqlite3\_extended\_result\_codes**(sqlite3\*, int onoff); CAPI3REF Enable Or Disable Extended Result Codes nothrow sqlite3\_int64 **sqlite3\_last\_insert\_rowid**(sqlite3\*); CAPI3REF Last Insert Rowid nothrow void **sqlite3\_set\_last\_insert\_rowid**(sqlite3\*, sqlite3\_int64); CAPI3REF Set the Last Insert Rowid value nothrow int **sqlite3\_changes**(sqlite3\*); CAPI3REF Count The Number Of Rows Modified nothrow int **sqlite3\_total\_changes**(sqlite3\*); CAPI3REF Total Number Of Rows Modified nothrow void **sqlite3\_interrupt**(sqlite3\*); CAPI3REF Interrupt A Long-Running Query nothrow int **sqlite3\_complete**(const char\* sql); nothrow int **sqlite3\_complete16**(const void\* sql); CAPI3REF Determine If An SQL Statement Is Complete nothrow int **sqlite3\_busy\_handler**(sqlite3\*, int function(void\*, int), void\*); CAPI3REF Register A Callback To Handle SQLITE\_BUSY Errors nothrow int **sqlite3\_busy\_timeout**(sqlite3\*, int ms); CAPI3REF Set A Busy Timeout nothrow int **sqlite3\_get\_table**(sqlite3\* db, const(char)\* zSql, char\*\*\* pazResult, int\* pnRow, int\* pnColumn, char\*\* pzErrmsg); CAPI3REF Convenience Routines For Running Queries nothrow void **sqlite3\_free\_table**(char\*\* result); nothrow char\* **sqlite3\_mprintf**(const char\*, ...); CAPI3REF Formatted String Printing Functions nothrow void\* **sqlite3\_malloc**(int); nothrow void\* **sqlite3\_malloc64**(sqlite3\_uint64); nothrow void\* **sqlite3\_realloc**(void\*, int); nothrow void\* **sqlite3\_realloc64**(void\*, sqlite3\_uint64); nothrow void **sqlite3\_free**(void\*); nothrow sqlite3\_uint64 **sqlite3\_msize**(void\*); CAPI3REF Memory Allocation Subsystem nothrow sqlite3\_int64 **sqlite3\_memory\_used**(); CAPI3REF Memory Allocator Statistics nothrow void **sqlite3\_randomness**(int N, void\* P); CAPI3REF Pseudo-Random Number Generator nothrow int **sqlite3\_set\_authorizer**(sqlite3\*, int function(void\*, int, const char\*, const char\*, const char\*, const char\*) xAuth, void\* pUserData); CAPI3REF Compile-Time Authorization Callbacks **SQLITE\_DENY** Abort the SQL statement with an error **SQLITE\_IGNORE** Don't allow access, but don't generate an error **SQLITE\_CREATE\_INDEX** Index Name Table Name **SQLITE\_CREATE\_TABLE** Table Name NULL **SQLITE\_CREATE\_TEMP\_INDEX** Index Name Table Name **SQLITE\_CREATE\_TEMP\_TABLE** Table Name NULL **SQLITE\_CREATE\_TEMP\_TRIGGER** Trigger Name Table Name **SQLITE\_CREATE\_TEMP\_VIEW** View Name NULL **SQLITE\_CREATE\_TRIGGER** Trigger Name Table Name **SQLITE\_CREATE\_VIEW** View Name NULL **SQLITE\_DELETE** Table Name NULL **SQLITE\_DROP\_INDEX** Index Name Table Name **SQLITE\_DROP\_TABLE** Table Name NULL **SQLITE\_DROP\_TEMP\_INDEX** Index Name Table Name **SQLITE\_DROP\_TEMP\_TABLE** Table Name NULL **SQLITE\_DROP\_TEMP\_TRIGGER** Trigger Name Table Name **SQLITE\_DROP\_TEMP\_VIEW** View Name NULL **SQLITE\_DROP\_TRIGGER** Trigger Name Table Name **SQLITE\_DROP\_VIEW** View Name NULL **SQLITE\_INSERT** Table Name NULL **SQLITE\_PRAGMA** Pragma Name 1st arg or NULL **SQLITE\_READ** Table Name Column Name **SQLITE\_SELECT** NULL NULL **SQLITE\_TRANSACTION** Operation NULL **SQLITE\_UPDATE** Table Name Column Name **SQLITE\_ATTACH** Filename NULL **SQLITE\_DETACH** Database Name NULL **SQLITE\_ALTER\_TABLE** Database Name Table Name **SQLITE\_REINDEX** Index Name NULL **SQLITE\_ANALYZE** Table Name NULL **SQLITE\_CREATE\_VTABLE** Table Name Module Name **SQLITE\_DROP\_VTABLE** Table Name Module Name **SQLITE\_FUNCTION** NULL Function Name **SQLITE\_SAVEPOINT** Operation Savepoint Name **SQLITE\_COPY** No longer used **SQLITE\_RECURSIVE** NULL NULL deprecated nothrow void\* **sqlite3\_trace**(sqlite3\*, void function(void\*, const char\*) xTrace, void\*); deprecated nothrow void\* **sqlite3\_profile**(sqlite3\*, void function(void\*, const char\*, sqlite3\_uint64) xProfile, void\*); CAPI3REF Tracing And Profiling Functions nothrow int **sqlite3\_trace\_v2**(sqlite3\*, uint uMask, int function(uint, void\*, void\*, void\*) xCallback, void\* pCtx); CAPI3REF SQL Trace Hook nothrow void **sqlite3\_progress\_handler**(sqlite3\*, int, int function(void\*), void\*); CAPI3REF Query Progress Callbacks nothrow int **sqlite3\_open**(const(char)\* filename, sqlite3\*\* ppDb); nothrow int **sqlite3\_open16**(const(void)\* filename, sqlite3\*\* ppDb); nothrow int **sqlite3\_open\_v2**(const(char)\* filename, sqlite3\*\* ppDb, int flags, const(char)\* zVfs); nothrow int **sqlite3\_uri\_boolean**(const(char)\* zFile, const(char)\* zParam, int bDefault); nothrow sqlite3\_int64 **sqlite3\_uri\_int64**(const char\*, const char\*, sqlite3\_int64); nothrow const(char)\* **sqlite3\_uri\_key**(const(char)\* zFilename, int N); nothrow const(char)\* **sqlite3\_filename\_journal**(const(char)\*); nothrow const(char)\* **sqlite3\_filename\_wal**(const(char)\*); nothrow void **sqlite3\_free\_filename**(char\*); CAPI3REF Opening A New Database Connection nothrow int **sqlite3\_errcode**(sqlite3\* db); nothrow int **sqlite3\_extended\_errcode**(sqlite3\* db); nothrow const(char)\* **sqlite3\_errmsg**(sqlite3\*); nothrow const(void)\* **sqlite3\_errmsg16**(sqlite3\*); nothrow const(char)\* **sqlite3\_errstr**(int); CAPI3REF Error Codes And Messages struct **sqlite3\_stmt**; CAPI3REF SQL Statement Object nothrow int **sqlite3\_limit**(sqlite3\*, int id, int newVal); CAPI3REF Run-time Limits nothrow int **sqlite3\_prepare**(sqlite3\* db, const(char)\* zSql, int nByte, sqlite3\_stmt\*\* ppStmt, const(char\*)\* pzTail); nothrow int **sqlite3\_prepare\_v2**(sqlite3\* db, const(char)\* zSql, int nByte, sqlite3\_stmt\*\* ppStmt, const(char\*)\* pzTail); nothrow int **sqlite3\_prepare\_v3**(sqlite3\* db, const(char)\* zSql, int nByte, uint prepFlags, sqlite3\_stmt\*\* ppStmt, const(char\*)\* pzTail); nothrow int **sqlite3\_prepare16**(sqlite3\* db, const(void)\* zSql, int nByte, sqlite3\_stmt\*\* ppStmt, const(void\*)\* pzTail); nothrow int **sqlite3\_prepare16\_v2**(sqlite3\* db, const(void)\* zSql, int nByte, sqlite3\_stmt\*\* ppStmt, const(void\*)\* pzTail); nothrow int **sqlite3\_prepare16\_v3**(sqlite3\* db, const(void)\* zSql, int nByte, uint prepFlags, sqlite3\_stmt\*\* ppStmt, const(void\*)\* pzTail); CAPI3REF Compiling An SQL Statement nothrow const(char)\* **sqlite3\_sql**(sqlite3\_stmt\* pStmt); nothrow char\* **sqlite3\_expanded\_sql**(sqlite3\_stmt\* pStmt); CAPI3REF Retrieving Statement SQL nothrow int **sqlite3\_stmt\_busy**(sqlite3\_stmt\*); CAPI3REF Determine If A Prepared Statement Has Been Reset struct **sqlite3\_value**; CAPI3REF Dynamically Typed Value Object struct **sqlite3\_context**; CAPI3REF SQL Function Context Object nothrow int **sqlite3\_bind\_blob**(sqlite3\_stmt\*, int, const void\*, int n, void function(void\*)); nothrow int **sqlite3\_bind\_blob64**(sqlite3\_stmt\*, int, const void\*, sqlite3\_uint64, void function(void\*)); nothrow int **sqlite3\_bind\_double**(sqlite3\_stmt\*, int, double); nothrow int **sqlite3\_bind\_int**(sqlite3\_stmt\*, int, int); nothrow int **sqlite3\_bind\_int64**(sqlite3\_stmt\*, int, sqlite3\_int64); nothrow int **sqlite3\_bind\_null**(sqlite3\_stmt\*, int); nothrow int **sqlite3\_bind\_text**(sqlite3\_stmt\*, int, const char\*, int n, void function(void\*)); nothrow int **sqlite3\_bind\_text16**(sqlite3\_stmt\*, int, const void\*, int, void function(void\*)); nothrow int **sqlite3\_bind\_text64**(sqlite3\_stmt\*, int, const char\*, sqlite3\_uint64, void function(void\*), ubyte encoding); nothrow int **sqlite3\_bind\_value**(sqlite3\_stmt\*, int, const sqlite3\_value\*); nothrow int **sqlite3\_bind\_zeroblob**(sqlite3\_stmt\*, int, int n); nothrow int **sqlite3\_bind\_zeroblob64**(sqlite3\_stmt\*, int, sqlite3\_uint64 n); CAPI3REF Binding Values To Prepared Statements nothrow int **sqlite3\_bind\_parameter\_count**(sqlite3\_stmt\*); CAPI3REF Number Of SQL Parameters nothrow const(char)\* **sqlite3\_bind\_parameter\_name**(sqlite3\_stmt\*, int); CAPI3REF Name Of A Host Parameter nothrow int **sqlite3\_bind\_parameter\_index**(sqlite3\_stmt\*, const char\* zName); CAPI3REF Index Of A Parameter With A Given Name nothrow int **sqlite3\_clear\_bindings**(sqlite3\_stmt\*); CAPI3REF Reset All Bindings On A Prepared Statement nothrow int **sqlite3\_column\_count**(sqlite3\_stmt\* pStmt); CAPI3REF Number Of Columns In A Result Set nothrow const(char)\* **sqlite3\_column\_name**(sqlite3\_stmt\*, int N); nothrow const(void)\* **sqlite3\_column\_name16**(sqlite3\_stmt\*, int N); CAPI3REF Column Names In A Result Set nothrow const(char)\* **sqlite3\_column\_database\_name**(sqlite3\_stmt\*, int); nothrow const(void)\* **sqlite3\_column\_database\_name16**(sqlite3\_stmt\*, int); nothrow const(char)\* **sqlite3\_column\_table\_name**(sqlite3\_stmt\*, int); nothrow const(void)\* **sqlite3\_column\_table\_name16**(sqlite3\_stmt\*, int); nothrow const(char)\* **sqlite3\_column\_origin\_name**(sqlite3\_stmt\*, int); nothrow const(void)\* **sqlite3\_column\_origin\_name16**(sqlite3\_stmt\*, int); CAPI3REF Source Of Data In A Query Result nothrow const(char)\* **sqlite3\_column\_decltype**(sqlite3\_stmt\*, int); nothrow const(void)\* **sqlite3\_column\_decltype16**(sqlite3\_stmt\*, int); CAPI3REF Declared Datatype Of A Query Result nothrow int **sqlite3\_step**(sqlite3\_stmt\*); CAPI3REF Evaluate An SQL Statement nothrow int **sqlite3\_data\_count**(sqlite3\_stmt\* pStmt); CAPI3REF Number of columns in a result set nothrow const(void)\* **sqlite3\_column\_blob**(sqlite3\_stmt\*, int iCol); nothrow double **sqlite3\_column\_double**(sqlite3\_stmt\*, int iCol); nothrow int **sqlite3\_column\_int**(sqlite3\_stmt\*, int iCol); nothrow sqlite3\_int64 **sqlite3\_column\_int64**(sqlite3\_stmt\*, int iCol); nothrow const(char)\* **sqlite3\_column\_text**(sqlite3\_stmt\*, int iCol); nothrow const(void)\* **sqlite3\_column\_text16**(sqlite3\_stmt\*, int iCol); nothrow sqlite3\_value\* **sqlite3\_column\_value**(sqlite3\_stmt\*, int iCol); nothrow int **sqlite3\_column\_bytes**(sqlite3\_stmt\*, int iCol); nothrow int **sqlite3\_column\_bytes16**(sqlite3\_stmt\*, int iCol); nothrow int **sqlite3\_column\_type**(sqlite3\_stmt\*, int iCol); CAPI3REF Result Values From A Query nothrow int **sqlite3\_finalize**(sqlite3\_stmt\* pStmt); CAPI3REF Destroy A Prepared Statement Object nothrow int **sqlite3\_reset**(sqlite3\_stmt\* pStmt); CAPI3REF Reset A Prepared Statement Object nothrow int **sqlite3\_create\_function**(sqlite3\* db, const(char)\* zFunctionName, int nArg, int eTextRep, void\* pApp, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xFunc, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xStep, void function(sqlite3\_context\*) xFinal); nothrow int **sqlite3\_create\_function16**(sqlite3\* db, const(void)\* zFunctionName, int nArg, int eTextRep, void\* pApp, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xFunc, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xStep, void function(sqlite3\_context\*) xFinal); nothrow int **sqlite3\_create\_function\_v2**(sqlite3\* db, const(char)\* zFunctionName, int nArg, int eTextRep, void\* pApp, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xFunc, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xStep, void function(sqlite3\_context\*) xFinal, void function(void\*) xDestroy); nothrow int **sqlite3\_create\_window\_function**(sqlite3\* db, const(char)\* zFunctionName, int nArg, int eTextRep, void\* pApp, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xStep, void function(sqlite3\_context\*) xFinal, void function(sqlite3\_context\*) xValue, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xInverse, void function(void\*) xDestroy); CAPI3REF Create Or Redefine SQL Functions **SQLITE\_UTF8** IMP R-37514-35566 **SQLITE\_UTF16LE** IMP R-03371-37637 **SQLITE\_UTF16BE** IMP R-51971-34154 **SQLITE\_UTF16** Use native byte order **SQLITE\_ANY** sqlite3\_create\_function only **SQLITE\_UTF16\_ALIGNED** sqlite3\_create\_collation only enum int **SQLITE\_DETERMINISTIC**; CAPI3REF Function Flags deprecated nothrow int **sqlite3\_aggregate\_count**(sqlite3\_context\*); CAPI3REF Deprecated Functions nothrow const(void)\* **sqlite3\_value\_blob**(sqlite3\_value\*); nothrow int **sqlite3\_value\_bytes**(sqlite3\_value\*); nothrow int **sqlite3\_value\_bytes16**(sqlite3\_value\*); nothrow double **sqlite3\_value\_double**(sqlite3\_value\*); nothrow int **sqlite3\_value\_int**(sqlite3\_value\*); nothrow sqlite3\_int64 **sqlite3\_value\_int64**(sqlite3\_value\*); nothrow const(char)\* **sqlite3\_value\_text**(sqlite3\_value\*); nothrow const(void)\* **sqlite3\_value\_text16**(sqlite3\_value\*); nothrow const(void)\* **sqlite3\_value\_text16le**(sqlite3\_value\*); nothrow const(void)\* **sqlite3\_value\_text16be**(sqlite3\_value\*); nothrow int **sqlite3\_value\_type**(sqlite3\_value\*); nothrow int **sqlite3\_value\_numeric\_type**(sqlite3\_value\*); nothrow int **sqlite3\_value\_nochange**(sqlite3\_value\*); nothrow int **sqlite3\_value\_frombind**(sqlite3\_value\*); CAPI3REF Obtaining SQL Function Parameter Values nothrow void\* **sqlite3\_aggregate\_context**(sqlite3\_context\*, int nBytes); CAPI3REF Obtain Aggregate Function Context nothrow void\* **sqlite3\_user\_data**(sqlite3\_context\*); CAPI3REF User Data For Functions nothrow sqlite3\* **sqlite3\_context\_db\_handle**(sqlite3\_context\*); CAPI3REF Database Connection For Functions nothrow void\* **sqlite3\_get\_auxdata**(sqlite3\_context\*, int N); nothrow void **sqlite3\_set\_auxdata**(sqlite3\_context\*, int N, void\*, void function(void\*)); CAPI3REF Function Auxiliary Data alias **sqlite3\_destructor\_type** = extern (C) void function(void\*) nothrow; CAPI3REF Constants Defining Special Destructor Behavior nothrow void **sqlite3\_result\_blob**(sqlite3\_context\*, const void\*, int, void function(void\*)); nothrow void **sqlite3\_result\_blob64**(sqlite3\_context\*, const void\*, sqlite3\_uint64, void function(void\*)); nothrow void **sqlite3\_result\_double**(sqlite3\_context\*, double); nothrow void **sqlite3\_result\_error**(sqlite3\_context\*, const char\*, int); nothrow void **sqlite3\_result\_error16**(sqlite3\_context\*, const void\*, int); nothrow void **sqlite3\_result\_error\_toobig**(sqlite3\_context\*); nothrow void **sqlite3\_result\_error\_nomem**(sqlite3\_context\*); nothrow void **sqlite3\_result\_error\_code**(sqlite3\_context\*, int); nothrow void **sqlite3\_result\_int**(sqlite3\_context\*, int); nothrow void **sqlite3\_result\_int64**(sqlite3\_context\*, sqlite3\_int64); nothrow void **sqlite3\_result\_null**(sqlite3\_context\*); nothrow void **sqlite3\_result\_text**(sqlite3\_context\*, const char\*, int, void function(void\*)); nothrow void **sqlite3\_result\_text64**(sqlite3\_context\*, const char\*, sqlite3\_uint64, void function(void\*), ubyte encoding); nothrow void **sqlite3\_result\_text16**(sqlite3\_context\*, const void\*, int, void function(void\*)); nothrow void **sqlite3\_result\_text16le**(sqlite3\_context\*, const void\*, int, void function(void\*)); nothrow void **sqlite3\_result\_text16be**(sqlite3\_context\*, const void\*, int, void function(void\*)); nothrow void **sqlite3\_result\_value**(sqlite3\_context\*, sqlite3\_value\*); nothrow void **sqlite3\_result\_zeroblob**(sqlite3\_context\*, int n); nothrow int **sqlite3\_result\_zeroblob64**(sqlite3\_context\*, sqlite3\_uint64 n); CAPI3REF Setting The Result Of An SQL Function nothrow int **sqlite3\_create\_collation**(sqlite3\*, const(char)\* zName, int eTextRep, void\* pArg, int function(void\*, int, const void\*, int, const void\*) xCompare); nothrow int **sqlite3\_create\_collation\_v2**(sqlite3\*, const(char)\* zName, int eTextRep, void\* pArg, int function(void\*, int, const void\*, int, const void\*) xCompare, void function(void\*) xDestroy); nothrow int **sqlite3\_create\_collation16**(sqlite3\*, const(void)\* zName, int eTextRep, void\* pArg, int function(void\*, int, const void\*, int, const void\*) xCompare); CAPI3REF Define New Collating Sequences nothrow int **sqlite3\_collation\_needed**(sqlite3\*, void\*, void function(void\*, sqlite3\*, int eTextRep, const char\*)); nothrow int **sqlite3\_collation\_needed16**(sqlite3\*, void\*, void function(void\*, sqlite3\*, int eTextRep, const void\*)); CAPI3REF Collation Needed Callbacks nothrow void **sqlite3\_activate\_cerod**(const(char)\* zPassPhrase); Specify the activation key for a CEROD database. Unless activated, none of the CEROD routines will work. nothrow int **sqlite3\_sleep**(int); CAPI3REF Suspend Execution For A Short Time char\* **sqlite3\_temp\_directory**; CAPI3REF Name Of The Folder Holding Temporary Files char\* **sqlite3\_data\_directory**; CAPI3REF Name Of The Folder Holding Database Files nothrow int **sqlite3\_win32\_set\_directory**(c\_ulong type, void\* zValue); nothrow int **sqlite3\_win32\_set\_directory8**(c\_ulong type, void\* zValue); nothrow int **sqlite3\_win32\_set\_directory16**(c\_ulong type, void\* zValue); CAPI3REF Win32 Specific Interface nothrow int **sqlite3\_get\_autocommit**(sqlite3\*); CAPI3REF Test For Auto-Commit Mode nothrow sqlite3\* **sqlite3\_db\_handle**(sqlite3\_stmt\*); CAPI3REF Find The Database Handle Of A Prepared Statement nothrow const(char)\* **sqlite3\_db\_filename**(sqlite3\* db, const char\* zDbName); CAPI3REF Return The Filename For A Database Connection nothrow int **sqlite3\_db\_readonly**(sqlite3\* db, const char\* zDbName); CAPI3REF Determine if a database is read-only nothrow void\* **sqlite3\_commit\_hook**(sqlite3\*, int function(void\*), void\*); nothrow void\* **sqlite3\_rollback\_hook**(sqlite3\*, void function(void\*), void\*); CAPI3REF Commit And Rollback Notification Callbacks nothrow void\* **sqlite3\_update\_hook**(sqlite3\*, void function(void\*, int, char\*, char\*, sqlite3\_int64), void\*); CAPI3REF Data Change Notification Callbacks nothrow int **sqlite3\_enable\_shared\_cache**(int); CAPI3REF Enable Or Disable Shared Pager Cache nothrow int **sqlite3\_release\_memory**(int); CAPI3REF Attempt To Free Heap Memory nothrow int **sqlite3\_db\_release\_memory**(sqlite3\*); CAPI3REF Free Memory Used By A Database Connection deprecated nothrow void **sqlite3\_soft\_heap\_limit**(int N); CAPI3REF Deprecated Soft Heap Limit Interface nothrow int **sqlite3\_table\_column\_metadata**(sqlite3\* db, const(char)\* zDbName, const(char)\* zTableName, const(char)\* zColumnName, char\*\* pzDataType, char\*\* pzCollSeq, int\* pNotNull, int\* pPrimaryKey, int\* pAutoinc); CAPI3REF Extract Metadata About A Column Of A Table nothrow int **sqlite3\_load\_extension**(sqlite3\* db, const(char)\* zFile, const(char)\* zProc, char\*\* pzErrMsg); CAPI3REF Load An Extension nothrow int **sqlite3\_enable\_load\_extension**(sqlite3\* db, int onoff); CAPI3REF Enable Or Disable Extension Loading nothrow int **sqlite3\_auto\_extension**(void function() xEntryPoint); CAPI3REF Automatically Load Statically Linked Extensions nothrow int **sqlite3\_cancel\_auto\_extension**(void function() xEntryPoint); CAPI3REF Cancel Automatic Extension Loading nothrow void **sqlite3\_reset\_auto\_extension**(); CAPI3REF Reset Automatic Extension Loading alias **mapFunction** = extern (C) void function(sqlite3\_context\*, int, sqlite3\_value\*\*) nothrow; struct **sqlite3\_module**; The interface to the virtual-table mechanism is currently considered to be experimental. The interface might change in incompatible ways. If this is a problem for you, do not use the interface at this time. When the virtual-table mechanism stabilizes, we will declare the interface fixed, support it indefinitely, and remove this comment. CAPI3REF Virtual Table Object struct **sqlite3\_index\_info**; CAPI3REF Virtual Table Indexing Information int **nConstraint**; Number of entries in aConstraint sqlite3\_index\_constraint\* **aConstraint**; Table of WHERE clause constraints int **nOrderBy**; Number of terms in the ORDER BY clause sqlite3\_index\_orderby\* **aOrderBy**; The ORDER BY clause int **idxNum**; Number used to identify the index char\* **idxStr**; String, possibly obtained from sqlite3\_malloc int **needToFreeIdxStr**; Free idxStr using sqlite3\_free() if true int **orderByConsumed**; True if output is already ordered double **estimatedCost**; Estimated cost of using this index nothrow int **sqlite3\_create\_module**(sqlite3\* db, const(char)\* zName, const(sqlite3\_module)\* p, void\* pClientData); nothrow int **sqlite3\_create\_module\_v2**(sqlite3\* db, const(char)\* zName, const(sqlite3\_module)\* p, void\* pClientData, void function(void\*) xDestroy); CAPI3REF Register A Virtual Table Implementation nothrow int **sqlite3\_drop\_modules**(sqlite3\* db, const(char\*)\* azKeep); CAPI3REF Remove Unnecessary Virtual Table Implementations struct **sqlite3\_vtab**; CAPI3REF Virtual Table Instance Object const(sqlite3\_module)\* **pModule**; The module for this virtual table int **nRef**; NO LONGER USED char\* **zErrMsg**; Error message from sqlite3\_mprintf() struct **sqlite3\_vtab\_cursor**; CAPI3REF Virtual Table Cursor Object sqlite3\_vtab\* **pVtab**; Virtual table of this cursor nothrow int **sqlite3\_declare\_vtab**(sqlite3\*, const char\* zSQL); CAPI3REF Declare The Schema Of A Virtual Table nothrow int **sqlite3\_overload\_function**(sqlite3\*, const char\* zFuncName, int nArg); CAPI3REF Overload A Function For A Virtual Table struct **sqlite3\_blob**; The interface to the virtual-table mechanism defined above (back up to a comment remarkably similar to this one) is currently considered to be experimental. The interface might change in incompatible ways. If this is a problem for you, do not use the interface at this time. When the virtual-table mechanism stabilizes, we will declare the interface fixed, support it indefinitely, and remove this comment. nothrow int **sqlite3\_blob\_open**(sqlite3\*, const(char)\* zDb, const(char)\* zTable, const(char)\* zColumn, sqlite3\_int64 iRow, int flags, sqlite3\_blob\*\* ppBlob); CAPI3REF Open A BLOB For Incremental I/O nothrow int **sqlite3\_blob\_reopen**(sqlite3\_blob\*, sqlite3\_int64); CAPI3REF Move a BLOB Handle to a New Row nothrow int **sqlite3\_blob\_close**(sqlite3\_blob\*); CAPI3REF Close A BLOB Handle nothrow int **sqlite3\_blob\_bytes**(sqlite3\_blob\*); CAPI3REF Return The Size Of An Open BLOB nothrow int **sqlite3\_blob\_read**(sqlite3\_blob\*, void\* Z, int N, int iOffset); CAPI3REF Read Data From A BLOB Incrementally nothrow int **sqlite3\_blob\_write**(sqlite3\_blob\*, const void\* z, int n, int iOffset); CAPI3REF Write Data Into A BLOB Incrementally nothrow sqlite3\_vfs\* **sqlite3\_vfs\_find**(const char\* zVfsName); nothrow int **sqlite3\_vfs\_register**(sqlite3\_vfs\*, int makeDflt); nothrow int **sqlite3\_vfs\_unregister**(sqlite3\_vfs\*); CAPI3REF Virtual File System Objects nothrow sqlite3\_mutex\* **sqlite3\_mutex\_alloc**(int); nothrow void **sqlite3\_mutex\_free**(sqlite3\_mutex\*); nothrow void **sqlite3\_mutex\_enter**(sqlite3\_mutex\*); nothrow int **sqlite3\_mutex\_try**(sqlite3\_mutex\*); nothrow void **sqlite3\_mutex\_leave**(sqlite3\_mutex\*); CAPI3REF Mutexes struct **sqlite3\_mutex\_methods**; CAPI3REF Mutex Methods Object nothrow int **sqlite3\_mutex\_held**(sqlite3\_mutex\*); nothrow int **sqlite3\_mutex\_notheld**(sqlite3\_mutex\*); CAPI3REF Mutex Verification Routines **SQLITE\_MUTEX\_STATIC\_MEM** sqlite3\_malloc() **SQLITE\_MUTEX\_STATIC\_MEM2** NOT USED **SQLITE\_MUTEX\_STATIC\_OPEN** sqlite3BtreeOpen() **SQLITE\_MUTEX\_STATIC\_PRNG** sqlite3\_randomness() **SQLITE\_MUTEX\_STATIC\_LRU** lru page list **SQLITE\_MUTEX\_STATIC\_LRU2** NOT USED **SQLITE\_MUTEX\_STATIC\_PMEM** sqlite3PageMalloc() **SQLITE\_MUTEX\_STATIC\_APP1** For use by application **SQLITE\_MUTEX\_STATIC\_APP2** For use by application **SQLITE\_MUTEX\_STATIC\_APP3** For use by application **SQLITE\_MUTEX\_STATIC\_VFS1** For use by built-in VFS **SQLITE\_MUTEX\_STATIC\_VFS2** For use by extension VFS **SQLITE\_MUTEX\_STATIC\_VFS3** For use by application VFS nothrow sqlite3\_mutex\* **sqlite3\_db\_mutex**(sqlite3\*); CAPI3REF Retrieve the mutex for a database connection nothrow int **sqlite3\_file\_control**(sqlite3\*, const char\* zDbName, int op, void\*); CAPI3REF Low-Level Control Of Database Files nothrow int **sqlite3\_test\_control**(int op, ...); CAPI3REF Testing Interface **SQLITE\_TESTCTRL\_PRNG\_RESET** NOT USED **SQLITE\_TESTCTRL\_RESERVE** NOT USED **SQLITE\_TESTCTRL\_ISKEYWORD** NOT USED **SQLITE\_TESTCTRL\_SCRATCHMALLOC** NOT USED **SQLITE\_TESTCTRL\_EXPLAIN\_STMT** NOT USED **SQLITE\_TESTCTRL\_LAST** Largest TESTCTRL nothrow int **sqlite3\_keyword\_count**(); nothrow int **sqlite3\_keyword\_name**(int, const(char\*)\*, int\*); nothrow int **sqlite3\_keyword\_check**(const(char)\*, int); CAPI3REF SQL Keyword Checking struct **sqlite3\_str**; CAPI3REF Dynamic String Object nothrow sqlite3\_str\* **sqlite3\_str\_new**(sqlite3\*); CAPI3REF Create A New Dynamic String Object nothrow char\* **sqlite3\_str\_finish**(sqlite3\_str\*); CAPI3REF Finalize A Dynamic String nothrow void **sqlite3\_str\_appendf**(sqlite3\_str\*, const(char)\* zFormat, ...); nothrow void **sqlite3\_str\_vappendf**(sqlite3\_str\*, const(char)\* zFormat, va\_list); nothrow void **sqlite3\_str\_append**(sqlite3\_str\*, const(char)\* zIn, int N); nothrow void **sqlite3\_str\_appendall**(sqlite3\_str\*, const(char)\* zIn); nothrow void **sqlite3\_str\_appendchar**(sqlite3\_str\*, int N, char C); nothrow void **sqlite3\_str\_reset**(sqlite3\_str\*); CAPI3REF Add Content To A Dynamic String nothrow int **sqlite3\_str\_errcode**(sqlite3\_str\*); CAPI3REF Status Of A Dynamic String nothrow int **sqlite3\_status**(int op, int\* pCurrent, int\* pHighwater, int resetFlag); nothrow int **sqlite3\_status64**(int op, long\* pCurrent, long\* pHighwater, int resetFlag); CAPI3REF SQLite Runtime Status **SQLITE\_STATUS\_SCRATCH\_USED** NOT USED **SQLITE\_STATUS\_SCRATCH\_OVERFLOW** NOT USED **SQLITE\_STATUS\_SCRATCH\_SIZE** NOT USED nothrow int **sqlite3\_db\_status**(sqlite3\*, int op, int\* pCur, int\* pHiwtr, int resetFlg); CAPI3REF Database Connection Status **SQLITE\_DBSTATUS\_MAX** Largest defined DBSTATUS nothrow int **sqlite3\_stmt\_status**(sqlite3\_stmt\*, int op, int resetFlg); CAPI3REF Prepared Statement Status struct **sqlite3\_pcache**; CAPI3REF Custom Page Cache Object struct **sqlite3\_pcache\_page**; CAPI3REF Custom Page Cache Object struct **sqlite3\_pcache\_methods2**; CAPI3REF Application Defined Page Cache. struct **sqlite3\_backup**; CAPI3REF Online Backup Object nothrow sqlite3\_backup\* **sqlite3\_backup\_init**(sqlite3\* pDest, const(char)\* zDestName, sqlite3\* pSource, const(char)\* zSourceName); nothrow int **sqlite3\_backup\_step**(sqlite3\_backup\* p, int nPage); nothrow int **sqlite3\_backup\_finish**(sqlite3\_backup\* p); nothrow int **sqlite3\_backup\_remaining**(sqlite3\_backup\* p); nothrow int **sqlite3\_backup\_pagecount**(sqlite3\_backup\* p); CAPI3REF Online Backup API. nothrow int **sqlite3\_unlock\_notify**(sqlite3\* pBlocked, void function(void\*\* apArg, int nArg) xNotify, void\* pNotifyArg); CAPI3REF Unlock Notification nothrow int **sqlite3\_stricmp**(const char\*, const char\*); CAPI3REF String Comparison nothrow void **sqlite3\_log**(int iErrCode, const char\* zFormat, ...); CAPI3REF Error Logging Interface nothrow void\* **sqlite3\_wal\_hook**(sqlite3\*, int function(void\*, sqlite3\*, const char\*, int), void\*); CAPI3REF Write-Ahead Log Commit Hook nothrow int **sqlite3\_wal\_autocheckpoint**(sqlite3\* db, int N); CAPI3REF Configure an auto-checkpoint nothrow int **sqlite3\_wal\_checkpoint**(sqlite3\* db, const char\* zDb); CAPI3REF Checkpoint a database nothrow int **sqlite3\_wal\_checkpoint\_v2**(sqlite3\* db, const(char)\* zDb, int eMode, int\* pnLog, int\* pnCkpt); CAPI3REF Checkpoint a database enum int **SQLITE\_VTAB\_CONSTRAINT\_SUPPORT**; nothrow int **sqlite3\_preupdate\_old**(sqlite3\*, int, sqlite3\_value\*\*); nothrow int **sqlite3\_preupdate\_count**(sqlite3\*); nothrow int **sqlite3\_preupdate\_depth**(sqlite3\*); nothrow int **sqlite3\_preupdate\_new**(sqlite3\*, int, sqlite3\_value\*\*); CAPI3REF Virtual Table Configuration Options nothrow int **sqlite3\_rtree\_geometry\_callback**(sqlite3\* db, const(char)\* zGeom, int function(sqlite3\_rtree\_geometry\*, int nCoord, double\* aCoord, int\* pRes) xGeom, void\* pContext); Register a geometry callback named zGeom that can be used as part of an R-Tree geometry query as follows: SELECT ... FROM <rtree> WHERE <rtree col> MATCH zGeom(... params ...) struct **sqlite3\_rtree\_geometry**; A pointer to a structure of the following type is passed as the first argument to callbacks registered using rtree\_geometry\_callback(). void\* **pContext**; Copy of pContext passed to s\_r\_g\_c() int **nParam**; Size of array aParam[] double\* **aParam**; Parameters passed to SQL geom function void\* **pUser**; Callback implementation user data void function(void\*) **xDelUser**; Called by SQLite to clean up pUser **NOT\_WITHIN** Object completely outside of query region **PARTLY\_WITHIN** Object partially overlaps query region **FULLY\_WITHIN** nothrow int **sqlite3changeset\_start\_v2**(sqlite3\_changeset\_iter\*\* pp, int nChangeset, void\* pChangeset, int flags); nothrow int **sqlite3changeset\_apply\_v2**(sqlite3\* db, int nChangeset, void\* pChangeset, int function(void\* pCtx, const(char)\* zTab) xFilter, int function(void\* pCtx, int eConflict, sqlite3\_changeset\_iter\* p) xConflict, void\* pCtx, void\*\* ppRebase, int\* pnRebase, int flags); nothrow int **sqlite3changeset\_apply\_v2\_strm**(sqlite3\* db, int function(void\* pIn, void\* pData, int\* pnData) xInput, void\* pIn, int function(void\* pCtx, const(char)\* zTab) xFilter, int function(void\* pCtx, int eConflict, sqlite3\_changeset\_iter\* p) xConflict, void\* pCtx, void\*\* ppRebase, int\* pnRebase, int flags); nothrow int **sqlite3changeset\_concat\_strm**(int function(void\* pIn, void\* pData, int\* pnData) xInputA, void\* pInA, int function(void\* pIn, void\* pData, int\* pnData) xInputB, void\* pInB, int function(void\* pOut, const(void)\* pData, int nData) xOutput, void\* pOut); nothrow int **sqlite3changeset\_invert\_strm**(int function(void\* pIn, void\* pData, int\* pnData) xInput, void\* pIn, int function(void\* pOut, const(void)\* pData, int nData) xOutput, void\* pOut); nothrow int **sqlite3changeset\_start\_strm**(sqlite3\_changeset\_iter\*\* pp, int function(void\* pIn, void\* pData, int\* pnData) xInput, void\* pIn); nothrow int **sqlite3changeset\_start\_v2\_strm**(sqlite3\_changeset\_iter\*\* pp, int function(void\* pIn, void\* pData, int\* pnData) xInput, void\* pIn, int flags); nothrow int **sqlite3session\_changeset\_strm**(sqlite3\_session\* pSession, int function(void\* pOut, const(void)\* pData, int nData) xOutput, void\* pOut); nothrow int **sqlite3session\_patchset\_strm**(sqlite3\_session\* pSession, int function(void\* pOut, const(void)\* pData, int nData) xOutput, void\* pOut); nothrow int **sqlite3changegroup\_add\_strm**(sqlite3\_changegroup\*, int function(void\* pIn, void\* pData, int\* pnData) xInput, void\* pIn); nothrow int **sqlite3changegroup\_output\_strm**(sqlite3\_changegroup\*, int function(void\* pOut, const(void)\* pData, int nData) xOutput, void\* pOut); nothrow int **sqlite3rebaser\_rebase\_strm**(sqlite3\_rebaser\* pRebaser, int function(void\* pIn, void\* pData, int\* pnData) xInput, void\* pIn, int function(void\* pOut, const(void)\* pData, int nData) xOutput, void\* pOut); Object fully contained within query region struct **Fts5Context**; alias **fts5\_extension\_function** = extern (C) void function(const(Fts5ExtensionApi\*) pApi, Fts5Context\* pFts, sqlite3\_context\* pCtx, int nVal, sqlite3\_value\*\* apVal) nothrow; struct **Fts5PhraseIter**; struct **Fts5ExtensionApi**; struct **Fts5Tokenizer**; enum int **FTS5\_TOKENIZE\_QUERY**; enum int **FTS5\_TOKENIZE\_PREFIX**; enum int **FTS5\_TOKENIZE\_DOCUMENT**; enum int **FTS5\_TOKENIZE\_AUX**; enum int **FTS5\_TOKEN\_COLOCATED**; struct **fts5\_api**; Interfaces to extend FTS5.
programming_docs
d std.experimental.allocator.building_blocks.aligned_block_list std.experimental.allocator.building\_blocks.aligned\_block\_list ================================================================ `AlignedBlockList` represents a wrapper around a chain of allocators, allowing for fast deallocations and preserving a low degree of fragmentation by means of aligned allocations. Source [std/experimental/allocator/building\_blocks/aligned\_block\_list.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/aligned_block_list.d) struct **AlignedBlockList**(Allocator, ParentAllocator, ulong theAlignment = 1 << 21); `AlignedBlockList` represents a wrapper around a chain of allocators, allowing for fast deallocations and preserving a low degree of fragmentation. The allocator holds internally a doubly linked list of `Allocator` objects, which will serve allocations in a most-recently-used fashion. Most recent allocators used for `allocate` calls, will be moved to the front of the list. Although allocations are in theory served in linear searching time, `deallocate` calls take Ο(`1`) time, by using aligned allocations. `ParentAllocator` must implement `alignedAllocate` and it must be able to allocate `theAlignment` bytes at the same alignment. Each aligned allocation done by `ParentAllocator` will contain metadata for an `Allocator`, followed by its payload. Parameters: | | | | --- | --- | | Allocator | the allocator which is used to manage each node; it must have a constructor which receives `ubyte[]` and it must not have any parent allocators, except for the `NullAllocator` | | ParentAllocator | each node draws memory from the parent allocator; it must support `alignedAllocate` | | theAlignment | alignment of each block and at the same time length of each node | Examples: ``` import std.experimental.allocator.building_blocks.ascending_page_allocator : AscendingPageAllocator; import std.experimental.allocator.building_blocks.segregator : Segregator; import std.experimental.allocator.building_blocks.bitmapped_block : BitmappedBlock; import std.typecons : Ternary; /* In this example we use 'AlignedBlockList' in conjunction with other allocators in order to create a more complex allocator. The 'SuperAllocator' uses a 'Segregator' to distribute allocations to sub-allocators, based on the requested size. Each sub-allocator is represented by an 'AlignedBlockList' of 'BitmappedBlocks'. Each 'AlignedBlockList' draws memory from a root allocator which in this case is an 'AscendingPageAllocator' Such an allocator not only provides good performance, but also a low degree of memory fragmentation. */ alias SuperAllocator = Segregator!( 32, AlignedBlockList!(BitmappedBlock!32, AscendingPageAllocator*, 1 << 12), Segregator!( 64, AlignedBlockList!(BitmappedBlock!64, AscendingPageAllocator*, 1 << 12), Segregator!( 128, AlignedBlockList!(BitmappedBlock!128, AscendingPageAllocator*, 1 << 12), AscendingPageAllocator* ))); SuperAllocator a; auto pageAlloc = AscendingPageAllocator(128 * 4096); // Set the parent allocator for all the sub allocators a.allocatorForSize!256 = &pageAlloc; a.allocatorForSize!128.parent = &pageAlloc; a.allocatorForSize!64.parent = &pageAlloc; a.allocatorForSize!32.parent = &pageAlloc; enum testNum = 10; void[][testNum] buf; // Allocations of size 32 will go to the first 'AlignedBlockList' foreach (j; 0 .. testNum) { buf[j] = a.allocate(32); writeln(buf[j].length); // 32 // This is owned by the first 'AlignedBlockList' writeln(a.allocatorForSize!32.owns(buf[j])); // Ternary.yes } // Free the memory foreach (j; 0 .. testNum) assert(a.deallocate(buf[j])); // Allocations of size 64 will go to the second 'AlignedBlockList' foreach (j; 0 .. testNum) { buf[j] = a.allocate(64); writeln(buf[j].length); // 64 // This is owned by the second 'AlignedBlockList' writeln(a.allocatorForSize!64.owns(buf[j])); // Ternary.yes } // Free the memory foreach (j; 0 .. testNum) assert(a.deallocate(buf[j])); // Allocations of size 128 will go to the third 'AlignedBlockList' foreach (j; 0 .. testNum) { buf[j] = a.allocate(128); writeln(buf[j].length); // 128 // This is owned by the third 'AlignedBlockList' writeln(a.allocatorForSize!128.owns(buf[j])); // Ternary.yes } // Free the memory foreach (j; 0 .. testNum) assert(a.deallocate(buf[j])); // Allocations which exceed 128, will go to the 'AscendingPageAllocator*' void[] b = a.allocate(256); writeln(b.length); // 256 a.deallocate(b); ``` void[] **allocate**(size\_t n); Returns a chunk of memory of size `n` It finds the first node in the `AlignedBlockNode` list which has available memory, and moves it to the front of the list. All empty nodes which cannot return new memory, are removed from the list. Parameters: | | | | --- | --- | | size\_t `n` | bytes to allocate | Returns: A chunk of memory of the required length or `null` on failure or bool **deallocate**(void[] b); Deallocates the buffer `b` given as parameter. Deallocations take place in constant time, regardless of the number of nodes in the list. `b.ptr` is rounded down to the nearest multiple of the `alignment` to quickly find the corresponding `AlignedBlockNode`. Parameters: | | | | --- | --- | | void[] `b` | buffer candidate for deallocation | Returns: `true` on success and `false` on failure Ternary **owns**(void[] b); Returns `Ternary.yes` if the buffer belongs to the parent allocator and `Ternary.no` otherwise. Parameters: | | | | --- | --- | | void[] `b` | buffer tested if owned by this allocator | Returns: `Ternary.yes` if owned by this allocator and `Ternary.no` otherwise struct **SharedAlignedBlockList**(Allocator, ParentAllocator, ulong theAlignment = 1 << 21); `SharedAlignedBlockList` is the threadsafe version of `AlignedBlockList`. The `Allocator` template parameter must refer a shared allocator. Also, `ParentAllocator` must be a shared allocator, supporting `alignedAllocate`. Parameters: | | | | --- | --- | | Allocator | the shared allocator which is used to manage each node; it must have a constructor which receives `ubyte[]` and it must not have any parent allocators, except for the `NullAllocator` | | ParentAllocator | each node draws memory from the parent allocator; it must be shared and support `alignedAllocate` | | theAlignment | alignment of each block and at the same time length of each node | Examples: ``` import std.experimental.allocator.building_blocks.region : SharedRegion; import std.experimental.allocator.building_blocks.ascending_page_allocator : SharedAscendingPageAllocator; import std.experimental.allocator.building_blocks.null_allocator : NullAllocator; import core.thread : ThreadGroup; enum numThreads = 8; enum size = 2048; enum maxIter = 10; /* In this example we use 'SharedAlignedBlockList' together with 'SharedRegion', in order to create a fast, thread-safe allocator. */ alias SuperAllocator = SharedAlignedBlockList!( SharedRegion!(NullAllocator, 1), SharedAscendingPageAllocator, 4096); SuperAllocator a; // The 'SuperAllocator' will draw memory from a 'SharedAscendingPageAllocator' a.parent = SharedAscendingPageAllocator(4096 * 1024); // Launch 'numThreads', each performing allocations void fun() { foreach (i; 0 .. maxIter) { void[] b = a.allocate(size); writeln(b.length); // size } } auto tg = new ThreadGroup; foreach (i; 0 .. numThreads) { tg.create(&fun); } tg.joinAll(); ``` void[] **allocate**(size\_t n); Returns a chunk of memory of size `n` It finds the first node in the `AlignedBlockNode` list which has available memory, and moves it to the front of the list. All empty nodes which cannot return new memory, are removed from the list. Parameters: | | | | --- | --- | | size\_t `n` | bytes to allocate | Returns: A chunk of memory of the required length or `null` on failure or bool **deallocate**(void[] b); Deallocates the buffer `b` given as parameter. Deallocations take place in constant time, regardless of the number of nodes in the list. `b.ptr` is rounded down to the nearest multiple of the `alignment` to quickly find the corresponding `AlignedBlockNode`. Parameters: | | | | --- | --- | | void[] `b` | buffer candidate for deallocation | Returns: `true` on success and `false` on failure Ternary **owns**(void[] b); Returns `Ternary.yes` if the buffer belongs to the parent allocator and `Ternary.no` otherwise. Parameters: | | | | --- | --- | | void[] `b` | buffer tested if owned by this allocator | Returns: `Ternary.yes` if owned by this allocator and `Ternary.no` otherwise d std.container.dlist std.container.dlist =================== This module implements a generic doubly-linked list container. It can be used as a queue, dequeue or stack. This module is a submodule of [`std.container`](std_container). Source [std/container/dlist.d](https://github.com/dlang/phobos/blob/master/std/container/dlist.d) License: Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE\_1\_0.txt or copy at [boost.org/LICENSE\_1\_0.txt](http://boost.org/LICENSE_1_0.txt)). Authors: [Andrei Alexandrescu](http://erdani.com) Examples: ``` import std.algorithm.comparison : equal; import std.container : DList; auto s = DList!int(1, 2, 3); assert(equal(s[], [1, 2, 3])); s.removeFront(); assert(equal(s[], [2, 3])); s.removeBack(); assert(equal(s[], [2])); s.insertFront([4, 5]); assert(equal(s[], [4, 5, 2])); s.insertBack([6, 7]); assert(equal(s[], [4, 5, 2, 6, 7])); // If you want to apply range operations, simply slice it. import std.algorithm.searching : countUntil; import std.range : popFrontN, popBackN, walkLength; auto sl = DList!int([1, 2, 3, 4, 5]); writeln(countUntil(sl[], 2)); // 1 auto r = sl[]; popFrontN(r, 2); popBackN(r, 2); assert(r.equal([3])); writeln(walkLength(r)); // 1 // DList.Range can be used to remove elements from the list it spans auto nl = DList!int([1, 2, 3, 4, 5]); for (auto rn = nl[]; !rn.empty;) if (rn.front % 2 == 0) nl.popFirstOf(rn); else rn.popFront(); assert(equal(nl[], [1, 3, 5])); auto rs = nl[]; rs.popFront(); nl.remove(rs); assert(equal(nl[], [1])); ``` struct **DList**(T); Implements a doubly-linked list. `DList` uses reference semantics. this(U)(U[] values...) Constraints: if (isImplicitlyConvertible!(U, T)); Constructor taking a number of nodes this(Stuff)(Stuff stuff) Constraints: if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T)); Constructor taking an [input range](std_range_primitives#isInputRange) const bool **opEquals**()(ref const DList rhs) Constraints: if (is(typeof(front == front))); Comparison for equality. Complexity Ο(`min(n, n1)`) where `n1` is the number of elements in `rhs`. struct **Range**; Defines the container's primary range, which embodies a bidirectional range. const nothrow @property bool **empty**(); Property returning `true` if and only if the container has no elements. Complexity Ο(`1`) void **clear**(); Removes all contents from the `DList`. Postcondition `empty` Complexity Ο(`1`) @property DList **dup**(); Duplicates the container. The elements themselves are not transitively duplicated. Complexity Ο(`n`). Range **opSlice**(); Returns a range that iterates over all elements of the container, in forward order. Complexity Ο(`1`) inout @property ref inout(T) **front**(); Forward to `opSlice().front`. Complexity Ο(`1`) inout @property ref inout(T) **back**(); Forward to `opSlice().back`. Complexity Ο(`1`) DList **opBinary**(string op, Stuff)(Stuff rhs) Constraints: if (op == "~" && is(typeof(insertBack(rhs)))); Returns a new `DList` that's the concatenation of `this` and its argument `rhs`. DList **opBinaryRight**(string op, Stuff)(Stuff lhs) Constraints: if (op == "~" && is(typeof(insertFront(lhs)))); Returns a new `DList` that's the concatenation of the argument `lhs` and `this`. DList **opOpAssign**(string op, Stuff)(Stuff rhs) Constraints: if (op == "~" && is(typeof(insertBack(rhs)))); Appends the contents of the argument `rhs` into `this`. size\_t **insertFront**(Stuff)(Stuff stuff); size\_t **insertBack**(Stuff)(Stuff stuff); alias **insert** = insertBack; alias **stableInsert** = insert; alias **stableInsertFront** = insertFront; alias **stableInsertBack** = insertBack; Inserts `stuff` to the front/back of the container. `stuff` can be a value convertible to `T` or a range of objects convertible to `T`. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. Returns: The number of elements inserted Complexity Ο(`log(n)`) size\_t **insertBefore**(Stuff)(Range r, Stuff stuff); alias **stableInsertBefore** = insertBefore; size\_t **insertAfter**(Stuff)(Range r, Stuff stuff); alias **stableInsertAfter** = insertAfter; Inserts `stuff` after range `r`, which must be a non-empty range previously extracted from this container. `stuff` can be a value convertible to `T` or a range of objects convertible to `T`. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. Returns: The number of values inserted. Complexity Ο(`k + m`), where `k` is the number of elements in `r` and `m` is the length of `stuff`. T **removeAny**(); alias **stableRemoveAny** = removeAny; Picks one value in an unspecified position in the container, removes it from the container, and returns it. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. Precondition `!empty` Returns: The element removed. Complexity Ο(`1`). void **removeFront**(); alias **stableRemoveFront** = removeFront; void **removeBack**(); alias **stableRemoveBack** = removeBack; Removes the value at the front/back of the container. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. Precondition `!empty` Complexity Ο(`1`). size\_t **removeFront**(size\_t howMany); alias **stableRemoveFront** = removeFront; size\_t **removeBack**(size\_t howMany); alias **stableRemoveBack** = removeBack; Removes `howMany` values at the front or back of the container. Unlike the unparameterized versions above, these functions do not throw if they could not remove `howMany` elements. Instead, if `howMany > n`, all elements are removed. The returned value is the effective number of elements removed. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. Returns: The number of elements removed Complexity Ο(`howMany`). Range **remove**(Range r); Range **linearRemove**(Range r); alias **stableRemove** = remove; Removes all elements belonging to `r`, which must be a range obtained originally from this container. Returns: A range spanning the remaining elements in the container that initially were right after `r`. Complexity Ο(`1`) void **popFirstOf**(ref Range r); Removes first element of `r`, wich must be a range obtained originally from this container, from both DList instance and range `r`. Compexity Ο(`1`) void **popLastOf**(ref Range r); Removes last element of `r`, wich must be a range obtained originally from this container, from both DList instance and range `r`. Compexity Ο(`1`) Range **linearRemove**(Take!Range r); alias **stableLinearRemove** = linearRemove; `linearRemove` functions as `remove`, but also accepts ranges that are result the of a `take` operation. This is a convenient way to remove a fixed amount of elements from the range. Complexity Ο(`r.walkLength`) bool **linearRemoveElement**(T value); Removes the first occurence of an element from the list in linear time. Returns: True if the element existed and was successfully removed, false otherwise. Parameters: | | | | --- | --- | | T `value` | value of the node to be removed | Complexity Ο(`n`) d core.stdcpp.string core.stdcpp.string ================== D header file for interaction with C++ std::string. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Guillaume Chatelet Manu Evans Source [core/stdcpp/string.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/string.d) enum DefaultConstruct **Default**; Constructor argument for default construction struct **char\_traits**(CharT); Character traits classes specify character properties and provide specific semantics for certain operations on characters and sequences of characters. struct **basic\_string**(T, Traits = char\_traits!T, Alloc = allocator!T); D language counterpart to C++ std::basic\_string. C++ reference: enum size\_type **npos**; alias **size\_type** = size\_t; alias **difference\_type** = ptrdiff\_t; alias **value\_type** = T; alias **traits\_type** = Traits; alias **allocator\_type** = Alloc; alias **pointer** = value\_type\*; alias **const\_pointer** = const(value\_type)\*; alias **toString** = as\_array; this(); MSVC allocates on default initialisation in debug, which can't be modelled by D `struct` alias **length** = size; alias **opDollar** = length; const nothrow @safe bool **empty**(); const pure nothrow @nogc @safe size\_t[2] **opSlice**(size\_t dim : 0)(size\_t start, size\_t end); inout pure nothrow @nogc ref @safe inout(T) **opIndex**(size\_t index); inout pure nothrow @nogc @safe inout(T)[] **opIndex**(size\_t[2] slice); inout pure nothrow @nogc @safe inout(T)[] **opIndex**(); const pure nothrow @safe bool **opEquals**(ref scope const basic\_string s); const pure nothrow @safe bool **opEquals**(scope const T[] s); Two `basic_string`s are equal if they represent the same sequence of code units. const pure nothrow @safe int **opCmp**(ref scope const basic\_string rhs); const pure nothrow @safe int **opCmp**(scope const T[] rhs); Performs lexicographical comparison. const pure nothrow @nogc @safe size\_t **toHash**(); Hash to allow `basic_string`s to be used as keys for built-in associative arrays. **The result will generally not be the same as C++ `std::hash<std::basic_string<T>>`.** void **clear**(); @trusted void **resize**(size\_type n, T c = T(0)); inout nothrow ref @safe inout(T) **front**(); inout nothrow ref @safe inout(T) **back**(); const nothrow @safe const(T)\* **c\_str**(); ref basic\_string **opAssign**()(auto ref basic\_string str); ref basic\_string **opAssign**(const(T)[] str); ref basic\_string **opAssign**(T c); ref basic\_string **opIndexAssign**(T c, size\_t index); ref basic\_string **opIndexAssign**(T c, size\_t[2] slice); ref basic\_string **opIndexAssign**(const(T)[] str, size\_t[2] slice); ref basic\_string **opIndexAssign**(T c); ref basic\_string **opIndexAssign**(const(T)[] str); ref basic\_string **opIndexOpAssign**(string op)(T c, size\_t index); ref basic\_string **opIndexOpAssign**(string op)(T c, size\_t[2] slice); ref basic\_string **opIndexOpAssign**(string op)(const(T)[] str, size\_t[2] slice); ref basic\_string **opIndexOpAssign**(string op)(T c); ref basic\_string **opIndexOpAssign**(string op)(const(T)[] str); ref basic\_string **append**(T c); ref basic\_string **opOpAssign**(string op : "~")(const(T)[] str); ref basic\_string **opOpAssign**(string op : "~")(T c); ref basic\_string **insert**(size\_type pos, ref const(basic\_string) str); ref @trusted basic\_string **insert**(size\_type pos, ref const(basic\_string) str, size\_type subpos, size\_type sublen); ref basic\_string **insert**(S : size\_type)(S pos, const(T)\* s); ref basic\_string **insert**(size\_type pos, const(T)[] s); ref basic\_string **erase**(size\_type pos = 0); ref basic\_string **erase**(size\_type pos, size\_type len); ref basic\_string **replace**()(size\_type pos, size\_type len, auto ref basic\_string str); ref basic\_string **replace**()(size\_type pos, size\_type len, auto ref basic\_string str, size\_type subpos, size\_type sublen = npos); ref basic\_string **replace**(size\_type pos, size\_type len, const(value\_type)[] s); ref basic\_string **replace**(S : size\_type)(S pos, size\_type len, const(value\_type)\* s); @trusted void **push\_back**(T c); void **pop\_back**(); this(DefaultConstruct); this(const(T)[] str); this(const(T)[] str, ref const(allocator\_type) al); inout ref inout(Alloc) **get\_allocator**(); const nothrow @safe size\_type **max\_size**(); const nothrow @safe size\_type **size**(); const nothrow @safe size\_type **capacity**(); inout @safe inout(T)\* **data**(); inout nothrow @trusted inout(T)[] **as\_array**(); inout nothrow ref @trusted inout(T) **at**(size\_type i); ref basic\_string **assign**(const(T)[] str); ref basic\_string **assign**(ref const basic\_string str); ref basic\_string **append**(const(T)[] str); ref basic\_string **append**(size\_type n, T c); void **reserve**(size\_type \_Newcap = 0); void **shrink\_to\_fit**(); ref basic\_string **insert**(size\_type pos, const(T)\* s, size\_type n); ref basic\_string **insert**(size\_type pos, size\_type n, T c); ref basic\_string **replace**(size\_type pos, size\_type len, const(T)\* s, size\_type slen); ref basic\_string **replace**(size\_type \_Off, size\_type \_N0, size\_type \_Count, T \_Ch); void **swap**(ref basic\_string \_Right);
programming_docs
d std.experimental.allocator.building_blocks.bitmapped_block std.experimental.allocator.building\_blocks.bitmapped\_block ============================================================ Source [std/experimental/allocator/building\_blocks/bitmapped\_block.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/bitmapped_block.d) struct **BitmappedBlock**(size\_t theBlockSize, uint theAlignment = platformAlignment, ParentAllocator = NullAllocator, Flag!"multiblock" f = Yes.multiblock); `BitmappedBlock` implements a simple heap consisting of one contiguous area of memory organized in blocks, each of size `theBlockSize`. A block is a unit of allocation. A bitmap serves as bookkeeping data, more precisely one bit per block indicating whether that block is currently allocated or not. Passing `NullAllocator` as `ParentAllocator` (the default) means user code manages allocation of the memory block from the outside; in that case `BitmappedBlock` must be constructed with a `ubyte[]` preallocated block and has no responsibility regarding the lifetime of its support underlying storage. If another allocator type is passed, `BitmappedBlock` defines a destructor that uses the parent allocator to release the memory block. That makes the combination of `AllocatorList`, `BitmappedBlock`, and a back-end allocator such as `MmapAllocator` a simple and scalable solution for memory allocation. There are advantages to storing bookkeeping data separated from the payload (as opposed to e.g. using `AffixAllocator` to store metadata together with each allocation). The layout is more compact (overhead is one bit per block), searching for a free block during allocation enjoys better cache locality, and deallocation does not touch memory around the payload being deallocated (which is often cold). Allocation requests are handled on a first-fit basis. Although linear in complexity, allocation is in practice fast because of the compact bookkeeping representation, use of simple and fast bitwise routines, and caching of the first available block position. A known issue with this general approach is fragmentation, partially mitigated by coalescing. Since `BitmappedBlock` does not need to maintain the allocated size, freeing memory implicitly coalesces free blocks together. Also, tuning `blockSize` has a considerable impact on both internal and external fragmentation. If the last template parameter is set to `No.multiblock`, the allocator will only serve allocations which require at most `theBlockSize`. The `BitmappedBlock` has a specialized implementation for single-block allocations which allows for greater performance, at the cost of not being able to allocate more than one block at a time. The size of each block can be selected either during compilation or at run time. Statically-known block sizes are frequent in practice and yield slightly better performance. To choose a block size statically, pass it as the `blockSize` parameter as in `BitmappedBlock!(4096)`. To choose a block size parameter, use `BitmappedBlock!(chooseAtRuntime)` and pass the block size to the constructor. Parameters: | | | | --- | --- | | theBlockSize | the length of a block, which must be a multiple of `theAlignment` | | theAlignment | alignment of each block | | ParentAllocator | allocator from which the `BitmappedBlock` will draw memory. If set to `NullAllocator`, the storage must be passed via the constructor | | f | `Yes.multiblock` to support allocations spanning across multiple blocks and `No.multiblock` to support single block allocations. Although limited by single block allocations, `No.multiblock` will generally provide higher performance. | Examples: ``` // Create a block allocator on top of a 10KB stack region. import std.experimental.allocator.building_blocks.region : InSituRegion; import std.traits : hasMember; InSituRegion!(10_240, 64) r; auto a = BitmappedBlock!(64, 64)(cast(ubyte[])(r.allocateAll())); static assert(hasMember!(InSituRegion!(10_240, 64), "allocateAll")); const b = a.allocate(100); writeln(b.length); // 100 ``` Examples: ``` import std.experimental.allocator.mallocator : Mallocator; import std.typecons : Flag, Yes; enum blockSize = 64; enum numBlocks = 10; // The 'BitmappedBlock' is implicitly instantiated with Yes.multiblock auto a = BitmappedBlock!(blockSize, 8, Mallocator, Yes.multiblock)(numBlocks * blockSize); // Instantiated with Yes.multiblock, can allocate more than one block at a time void[] buf = a.allocate(2 * blockSize); writeln(buf.length); // 2 * blockSize assert(a.deallocate(buf)); // Can also allocate less than one block buf = a.allocate(blockSize / 2); writeln(buf.length); // blockSize / 2 // Expands inside the same block assert(a.expand(buf, blockSize / 2)); writeln(buf.length); // blockSize // If Yes.multiblock, can expand past the size of a single block assert(a.expand(buf, 3 * blockSize)); writeln(buf.length); // 4 * blockSize assert(a.deallocate(buf)); ``` Examples: ``` import std.experimental.allocator.mallocator : Mallocator; import std.typecons : Flag, No; enum blockSize = 64; auto a = BitmappedBlock!(blockSize, 8, Mallocator, No.multiblock)(1024 * blockSize); // Since instantiated with No.multiblock, can only allocate at most the block size void[] buf = a.allocate(blockSize + 1); assert(buf is null); buf = a.allocate(blockSize); writeln(buf.length); // blockSize assert(a.deallocate(buf)); // This is also fine, because it's less than the block size buf = a.allocate(blockSize / 2); writeln(buf.length); // blockSize / 2 // Can expand the buffer until its length is at most 64 assert(a.expand(buf, blockSize / 2)); writeln(buf.length); // blockSize // Cannot expand anymore assert(!a.expand(buf, 1)); assert(a.deallocate(buf)); ``` this(ubyte[] data); this(ubyte[] data, uint blockSize); this(size\_t capacity); this(ParentAllocator parent, size\_t capacity); this(size\_t capacity, uint blockSize); this(ParentAllocator parent, size\_t capacity, uint blockSize); Constructs a block allocator given a hunk of memory, or a desired capacity in bytes. * If `ParentAllocator` is [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator), only the constructor taking `data` is defined and the user is responsible for freeing `data` if desired. * Otherwise, both constructors are defined. The `data`-based constructor assumes memory has been allocated with the parent allocator. The `capacity`-based constructor uses `ParentAllocator` to allocate an appropriate contiguous hunk of memory. Regardless of the constructor used, the destructor releases the memory by using `ParentAllocator.deallocate`. alias **blockSize** = theBlockSize; If `blockSize == chooseAtRuntime`, `BitmappedBlock` offers a read/write property `blockSize`. It must be set before any use of the allocator. Otherwise (i.e. `theBlockSize` is a legit constant), `blockSize` is an alias for `theBlockSize`. Whether constant or variable, must also be a multiple of `alignment`. This constraint is `assert`ed statically and dynamically. alias **alignment** = theAlignment; The alignment offered is user-configurable statically through parameter `theAlignment`, defaulted to `platformAlignment`. ParentAllocator **parent**; The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`. pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n); Returns the actual bytes allocated when `n` bytes are requested, i.e. `n.roundUpToMultipleOf(blockSize)`. const pure nothrow @nogc @trusted Ternary **owns**(const void[] b); Returns `Ternary.yes` if `b` belongs to the `BitmappedBlock` object, `Ternary.no` otherwise. Never returns `Ternary.unkown`. (This method is somewhat tolerant in that accepts an interior slice.) pure nothrow @nogc @trusted bool **expand**(ref void[] b, immutable size\_t delta); Expands in place a buffer previously allocated by `BitmappedBlock`. If instantiated with `No.multiblock`, the expansion fails if the new length exceeds `theBlockSize`. nothrow @nogc bool **deallocate**(void[] b); Deallocates a block previously allocated with this allocator. pure nothrow @nogc @trusted void[] **allocate**(const size\_t s); Allocates `s` bytes of memory and returns it, or `null` if memory could not be allocated. The following information might be of help with choosing the appropriate block size. Actual allocation occurs in sizes multiple of the block size. Allocating one block is the fastest because only one 0 bit needs to be found in the metadata. Allocating 2 through 64 blocks is the next cheapest because it affects a maximum of two `ulong` in the metadata. Allocations greater than 64 blocks require a multiword search through the metadata. If instantiated with `No.multiblock`, it performs a search for the first zero bit in the bitmap and sets it. @trusted void[] **allocateFresh**(const size\_t s); Allocates s bytes of memory and returns it, or `null` if memory could not be allocated. `allocateFresh` behaves just like allocate, the only difference being that this always returns unused(fresh) memory. Although there may still be available space in the `BitmappedBlock`, `allocateFresh` could still return null, because all the available blocks have been previously deallocated. void[] **allocateAll**(); If the `BitmappedBlock` object is empty (has no active allocation), allocates all memory within and returns a slice to it. Otherwise, returns `null` (i.e. no attempt is made to allocate the largest available block). pure nothrow @nogc @safe Ternary **empty**(); Returns `Ternary.yes` if no memory is currently allocated with this allocator, otherwise `Ternary.no`. This method never returns `Ternary.unknown`. pure nothrow @nogc bool **deallocateAll**(); Forcibly deallocates all memory allocated by this allocator, making it available for further allocations. Does not return memory to `ParentAllocator`. @system bool **alignedReallocate**(ref void[] b, size\_t newSize, uint a); Reallocates a block previously allocated with `alignedAllocate`. Contractions do not occur in place. @system bool **reallocate**(ref void[] b, size\_t newSize); Reallocates a previously-allocated block. Contractions occur in place. void[] **alignedAllocate**(size\_t n, uint a); Allocates a block with specified alignment `a`. The alignment must be a power of 2. If `a <= alignment`, function forwards to `allocate`. Otherwise, it attempts to overallocate and then adjust the result for proper alignment. In the worst case the slack memory is around two blocks. struct **SharedBitmappedBlock**(size\_t theBlockSize, uint theAlignment = platformAlignment, ParentAllocator = NullAllocator, Flag!"multiblock" f = Yes.multiblock); The threadsafe version of the [`BitmappedBlock`](#BitmappedBlock). The semantics of the `SharedBitmappedBlock` are identical to the regular [`BitmappedBlock`](#BitmappedBlock). Parameters: | | | | --- | --- | | theBlockSize | the length of a block, which must be a multiple of `theAlignment` | | theAlignment | alignment of each block | | ParentAllocator | allocator from which the `BitmappedBlock` will draw memory. If set to `NullAllocator`, the storage must be passed via the constructor | | f | `Yes.multiblock` to support allocations spanning across multiple blocks and `No.multiblock` to support single block allocations. Although limited by single block allocations, `No.multiblock` will generally provide higher performance. | Examples: ``` import std.experimental.allocator.mallocator : Mallocator; import std.experimental.allocator.common : platformAlignment; import std.typecons : Flag, Yes, No; // Create 'numThreads' threads, each allocating in parallel a chunk of memory static void testAlloc(Allocator)(ref Allocator a, size_t allocSize) { import core.thread : ThreadGroup; import std.algorithm.sorting : sort; import core.internal.spinlock : SpinLock; SpinLock lock = SpinLock(SpinLock.Contention.brief); enum numThreads = 10; void[][numThreads] buf; size_t count = 0; // Each threads allocates 'allocSize' void fun() { void[] b = a.allocate(allocSize); writeln(b.length); // allocSize lock.lock(); scope(exit) lock.unlock(); buf[count] = b; count++; } auto tg = new ThreadGroup; foreach (i; 0 .. numThreads) { tg.create(&fun); } tg.joinAll(); // Sorting the allocations made by each thread, we expect the buffers to be // adjacent inside the SharedBitmappedBlock sort!((a, b) => a.ptr < b.ptr)(buf[0 .. numThreads]); foreach (i; 0 .. numThreads - 1) { assert(buf[i].ptr + a.goodAllocSize(buf[i].length) <= buf[i + 1].ptr); } // Deallocate everything foreach (i; 0 .. numThreads) { assert(a.deallocate(buf[i])); } } enum blockSize = 64; auto alloc1 = SharedBitmappedBlock!(blockSize, platformAlignment, Mallocator, Yes.multiblock)(1024 * 1024); auto alloc2 = SharedBitmappedBlock!(blockSize, platformAlignment, Mallocator, No.multiblock)(1024 * 1024); testAlloc(alloc1, 2 * blockSize); testAlloc(alloc2, blockSize); ``` this(ubyte[] data); this(ubyte[] data, uint blockSize); this(size\_t capacity); this(ParentAllocator parent, size\_t capacity); this(size\_t capacity, uint blockSize); this(ParentAllocator parent, size\_t capacity, uint blockSize); Constructs a block allocator given a hunk of memory, or a desired capacity in bytes. * If `ParentAllocator` is [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator), only the constructor taking `data` is defined and the user is responsible for freeing `data` if desired. * Otherwise, both constructors are defined. The `data`-based constructor assumes memory has been allocated with the parent allocator. The `capacity`-based constructor uses `ParentAllocator` to allocate an appropriate contiguous hunk of memory. Regardless of the constructor used, the destructor releases the memory by using `ParentAllocator.deallocate`. alias **blockSize** = theBlockSize; If `blockSize == chooseAtRuntime`, `SharedBitmappedBlock` offers a read/write property `blockSize`. It must be set before any use of the allocator. Otherwise (i.e. `theBlockSize` is a legit constant), `blockSize` is an alias for `theBlockSize`. Whether constant or variable, must also be a multiple of `alignment`. This constraint is `assert`ed statically and dynamically. alias **alignment** = theAlignment; The alignment offered is user-configurable statically through parameter `theAlignment`, defaulted to `platformAlignment`. ParentAllocator **parent**; The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`. pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n); Returns the actual bytes allocated when `n` bytes are requested, i.e. `n.roundUpToMultipleOf(blockSize)`. const pure nothrow @nogc @trusted Ternary **owns**(const void[] b); Returns `Ternary.yes` if `b` belongs to the `SharedBitmappedBlock` object, `Ternary.no` otherwise. Never returns `Ternary.unkown`. (This method is somewhat tolerant in that accepts an interior slice.) bool **expand**(ref void[] b, immutable size\_t delta); Expands in place a buffer previously allocated by `SharedBitmappedBlock`. Expansion fails if the new length exceeds the block size. nothrow @nogc bool **deallocate**(void[] b); Deallocates the given buffer `b`, by atomically setting the corresponding bit to `0`. `b` must be valid, and cannot contain multiple adjacent `blocks`. nothrow @nogc @trusted void[] **allocate**(const size\_t s); Allocates `s` bytes of memory and returns it, or `null` if memory could not be allocated. The `SharedBitmappedBlock` cannot allocate more than the given block size. Allocations are satisfied by searching the first unset bit in the bitmap, and atomically setting it. In rare memory pressure scenarios, the allocation could fail. @trusted void[] **allocateFresh**(const size\_t s); Allocates s bytes of memory and returns it, or `null` if memory could not be allocated. `allocateFresh` behaves just like allocate, the only difference being that this always returns unused(fresh) memory. Although there may still be available space in the `SharedBitmappedBlock`, `allocateFresh` could still return null, because all the available blocks have been previously deallocated. void[] **allocateAll**(); If the `SharedBitmappedBlock` object is empty (has no active allocation), allocates all memory within and returns a slice to it. Otherwise, returns `null` (i.e. no attempt is made to allocate the largest available block). nothrow @nogc @safe Ternary **empty**(); Returns `Ternary.yes` if no memory is currently allocated with this allocator, otherwise `Ternary.no`. This method never returns `Ternary.unknown`. nothrow @nogc bool **deallocateAll**(); Forcibly deallocates all memory allocated by this allocator, making it available for further allocations. Does not return memory to `ParentAllocator`. @system bool **alignedReallocate**(ref void[] b, size\_t newSize, uint a); Reallocates a block previously allocated with `alignedAllocate`. Contractions do not occur in place. @system bool **reallocate**(ref void[] b, size\_t newSize); Reallocates a previously-allocated block. Contractions occur in place. void[] **alignedAllocate**(size\_t n, uint a); Allocates a block with specified alignment `a`. The alignment must be a power of 2. If `a <= alignment`, function forwards to `allocate`. Otherwise, it attempts to overallocate and then adjust the result for proper alignment. In the worst case the slack memory is around two blocks. struct **BitmappedBlockWithInternalPointers**(size\_t theBlockSize, uint theAlignment = platformAlignment, ParentAllocator = NullAllocator); A `BitmappedBlock` with additional structure for supporting `resolveInternalPointer`. To that end, `BitmappedBlockWithInternalPointers` adds a bitmap (one bit per block) that marks object starts. The bitmap itself has variable size and is allocated together with regular allocations. The time complexity of `resolveInternalPointer` is Ο(`k`), where `k` is the size of the object within which the internal pointer is looked up. this(ubyte[] data); this(size\_t capacity); this(ParentAllocator parent, size\_t capacity); Constructors accepting desired capacity or a preallocated buffer, similar in semantics to those of `BitmappedBlock`. alias **alignment** = theAlignment; pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n); void[] **allocate**(size\_t bytes); void[] **allocateAll**(); bool **expand**(ref void[] b, size\_t bytes); bool **deallocate**(void[] b); nothrow @nogc @safe Ternary **resolveInternalPointer**(const void\* p, ref void[] result); Ternary **empty**(); Allocator primitives. d std.experimental.allocator.building_blocks.bucketizer std.experimental.allocator.building\_blocks.bucketizer ====================================================== Source [std/experimental/allocator/building\_blocks/bucketizer.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/bucketizer.d) struct **Bucketizer**(Allocator, size\_t min, size\_t max, size\_t step); A `Bucketizer` uses distinct allocators for handling allocations of sizes in the intervals `[min, min + step - 1]`, `[min + step, min + 2 * step - 1]`, `[min + 2 * step, min + 3 * step - 1]`, `...`, `[max - step + 1, max]`. `Bucketizer` holds a fixed-size array of allocators and dispatches calls to them appropriately. The size of the array is `(max + 1 - min) / step`, which must be an exact division. Allocations for sizes smaller than `min` or larger than `max` are illegal for `Bucketizer`. To handle them separately, `Segregator` may be of use. Examples: ``` import std.algorithm.comparison : max; import std.experimental.allocator.building_blocks.allocator_list : AllocatorList; import std.experimental.allocator.building_blocks.free_list : FreeList; import std.experimental.allocator.building_blocks.region : Region; import std.experimental.allocator.common : unbounded; import std.experimental.allocator.mallocator : Mallocator; import std.typecons : Ternary; Bucketizer!( FreeList!( AllocatorList!( (size_t n) => Region!Mallocator(max(n, 1024 * 1024))), 0, unbounded), 65, 512, 64) a; auto b = a.allocate(400); writeln(b.length); // 400 writeln(a.owns(b)); // Ternary.yes a.deallocate(b); ``` Allocator[(max + 1 - min) / step] **buckets**; The array of allocators is publicly available for e.g. initialization and inspection. enum uint **alignment**; The alignment offered is the same as `Allocator.alignment`. const pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t bytes); Rounds up to the maximum size of the bucket in which `bytes` falls. void[] **allocate**(size\_t bytes); Directs the call to either one of the `buckets` allocators. void[] **alignedAllocate**(size\_t bytes, uint alignment); Allocates the requested `bytes` of memory with specified `alignment`. Directs the call to either one of the `buckets` allocators. Defined only if `Allocator` defines `alignedAllocate`. bool **expand**(ref void[] b, size\_t delta); This method allows expansion within the respective bucket range. It succeeds if both `b.length` and `b.length + delta` fall in a range of the form `[min + k * step, min + (k + 1) * step - 1]`. bool **reallocate**(ref void[] b, size\_t size); This method allows reallocation within the respective bucket range. If both `b.length` and `size` fall in a range of the form `[min + k * step, min + (k + 1) * step - 1]`, then reallocation is in place. Otherwise, reallocation with moving is attempted. bool **alignedReallocate**(ref void[] b, size\_t size, uint a); Similar to `reallocate`, with alignment. Defined only if `Allocator` defines `alignedReallocate`. Ternary **owns**(void[] b); Defined only if `Allocator` defines `owns`. Finds the owner of `b` and forwards the call to it. bool **deallocate**(void[] b); This method is only defined if `Allocator` defines `deallocate`. bool **deallocateAll**(); This method is only defined if all allocators involved define `deallocateAll`, and calls it for each bucket in turn. Returns `true` if all allocators could deallocate all. Ternary **resolveInternalPointer**(const void\* p, ref void[] result); This method is only defined if all allocators involved define `resolveInternalPointer`, and tries it for each bucket in turn.
programming_docs
d rt.memset rt.memset ========= Contains a memset implementation used by compiler-generated code. License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Authors: Walter Bright d rt.util.utility rt.util.utility =============== Contains various utility functions used by the runtime implementation. License: Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) Authors: Jacob Carlborg Source [rt/util/utility.d](https://github.com/dlang/druntime/blob/master/src/rt/util/utility.d) package(rt) nothrow @nogc @safe void **safeAssert**(bool condition, scope string msg, scope string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_); Asserts that the given condition is `true`. The assertion is independent from -release, by abort()ing. Regular assertions throw an AssertError and thus require an initialized GC, which might not be the case (yet or anymore) for the startup/shutdown code in this package (called by CRT ctors/dtors etc.). d std.process std.process =========== Functions for starting and interacting with other processes, and for working with the current process' execution environment. Process handling * [`spawnProcess`](#spawnProcess) spawns a new process, optionally assigning it an arbitrary set of standard input, output, and error streams. The function returns immediately, leaving the child process to execute in parallel with its parent. All other functions in this module that spawn processes are built around `spawnProcess`. * [`wait`](#wait) makes the parent process wait for a child process to terminate. In general one should always do this, to avoid child processes becoming "zombies" when the parent process exits. Scope guards are perfect for this – see the [`spawnProcess`](#spawnProcess) documentation for examples. [`tryWait`](#tryWait) is similar to `wait`, but does not block if the process has not yet terminated. * [`pipeProcess`](#pipeProcess) also spawns a child process which runs in parallel with its parent. However, instead of taking arbitrary streams, it automatically creates a set of pipes that allow the parent to communicate with the child through the child's standard input, output, and/or error streams. This function corresponds roughly to C's `popen` function. * [`execute`](#execute) starts a new process and waits for it to complete before returning. Additionally, it captures the process' standard output and error streams and returns the output of these as a string. * [`spawnShell`](#spawnShell), [`pipeShell`](#pipeShell) and [`executeShell`](#executeShell) work like `spawnProcess`, `pipeProcess` and `execute`, respectively, except that they take a single command string and run it through the current user's default command interpreter. `executeShell` corresponds roughly to C's `system` function. * [`kill`](#kill) attempts to terminate a running process. The following table compactly summarises the different process creation functions and how they relate to each other: | | Runs program directly | Runs shell command | | --- | --- | --- | | Low-level process creation | [`spawnProcess`](#spawnProcess) | [`spawnShell`](#spawnShell) | | Automatic input/output redirection using pipes | [`pipeProcess`](#pipeProcess) | [`pipeShell`](#pipeShell) | | Execute and wait for completion, collect output | [`execute`](#execute) | [`executeShell`](#executeShell) | Other functionality * [`pipe`](#pipe) is used to create unidirectional pipes. * [`environment`](#environment) is an interface through which the current process' environment variables can be read and manipulated. * [`escapeShellCommand`](#escapeShellCommand) and [`escapeShellFileName`](#escapeShellFileName) are useful for constructing shell command lines in a portable way. Authors: [Lars Tandle Kyllingstad](https://github.com/kyllingstad), [Steven Schveighoffer](https://github.com/schveiguy), [Vladimir Panteleev](http://thecybershadow.net) License: [Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). Source [std/process.d](https://github.com/dlang/phobos/blob/master/std/process.d) Note Most of the functionality in this module is not available on iOS, tvOS and watchOS. The only functions available on those platforms are: [`environment`](#environment), [`thisProcessID`](#thisProcessID) and [`thisThreadID`](#thisThreadID). abstract class **environment**; Manipulates environment variables using an associative-array-like interface. This class contains only static methods, and cannot be instantiated. See below for examples of use. static @safe string **opIndex**(scope const(char)[] name); Retrieves the value of the environment variable with the given `name`. ``` auto path = environment["PATH"]; ``` Throws: [`Exception`](object#Exception) if the environment variable does not exist, or [`std.utf.UTFException`](std_utf#UTFException) if the variable contains invalid UTF-16 characters (Windows only). See Also: [`environment.get`](#environment.get), which doesn't throw on failure. static @safe string **get**(scope const(char)[] name, string defaultValue = null); Retrieves the value of the environment variable with the given `name`, or a default value if the variable doesn't exist. Unlike [`environment.opIndex`](#environment.opIndex), this function never throws on Posix. ``` auto sh = environment.get("SHELL", "/bin/sh"); ``` This function is also useful in checking for the existence of an environment variable. ``` auto myVar = environment.get("MYVAR"); if (myVar is null) { // Environment variable doesn't exist. // Note that we have to use 'is' for the comparison, since // myVar == null is also true if the variable exists but is // empty. } ``` Parameters: | | | | --- | --- | | const(char)[] `name` | name of the environment variable to retrieve | | string `defaultValue` | default value to return if the environment variable doesn't exist. | Returns: the value of the environment variable if found, otherwise `null` if the environment doesn't exist. Throws: [`std.utf.UTFException`](std_utf#UTFException) if the variable contains invalid UTF-16 characters (Windows only). static @trusted inout(char)[] **opIndexAssign**(inout char[] value, scope const(char)[] name); Assigns the given `value` to the environment variable with the given `name`. If `value` is null the variable is removed from environment. If the variable does not exist, it will be created. If it already exists, it will be overwritten. ``` environment["foo"] = "bar"; ``` Throws: [`Exception`](object#Exception) if the environment variable could not be added (e.g. if the name is invalid). Note On some platforms, modifying environment variables may not be allowed in multi-threaded programs. See e.g. [glibc](https://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access). static nothrow @nogc @trusted void **remove**(scope const(char)[] name); Removes the environment variable with the given `name`. If the variable isn't in the environment, this function returns successfully without doing anything. Note On some platforms, modifying environment variables may not be allowed in multi-threaded programs. See e.g. [glibc](https://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access). @trusted bool **opBinaryRight**(string op : "in")(scope const(char)[] name); Identify whether a variable is defined in the environment. Because it doesn't return the value, this function is cheaper than `get`. However, if you do need the value as well, you should just check the return of `get` for `null` instead of using this function first. Example ``` // good usage if ("MY_ENV_FLAG" in environment) doSomething(); // bad usage if ("MY_ENV_VAR" in environment) doSomething(environment["MY_ENV_VAR"]); // do this instead if (auto var = environment.get("MY_ENV_VAR")) doSomething(var); ``` static @trusted string[string] **toAA**(); Copies all environment variables into an associative array. Windows specific While Windows environment variable names are case insensitive, D's built-in associative arrays are not. This function will store all variable names in uppercase (e.g. `PATH`). Throws: [`Exception`](object#Exception) if the environment variables could not be retrieved (Windows only). nothrow @property @trusted int **thisProcessID**(); Returns the process ID of the current process, which is guaranteed to be unique on the system. Example ``` writefln("Current process ID: %d", thisProcessID); ``` nothrow @property @trusted ThreadID **thisThreadID**(); Returns the process ID of the current thread, which is guaranteed to be unique within the current process. Returns: A [`core.thread.ThreadID`](core_thread#ThreadID) value for the calling thread. Example ``` writefln("Current thread ID: %s", thisThreadID); ``` @safe Pid **spawnProcess**(scope const(char[])[] args, File stdin = std.stdio.stdin, File stdout = std.stdio.stdout, File stderr = std.stdio.stderr, const string[string] env = null, Config config = Config.none, scope const char[] workDir = null); @trusted Pid **spawnProcess**(scope const(char[])[] args, const string[string] env, Config config = Config.none, scope const(char)[] workDir = null); @trusted Pid **spawnProcess**(scope const(char)[] program, File stdin = std.stdio.stdin, File stdout = std.stdio.stdout, File stderr = std.stdio.stderr, const string[string] env = null, Config config = Config.none, scope const(char)[] workDir = null); @trusted Pid **spawnProcess**(scope const(char)[] program, const string[string] env, Config config = Config.none, scope const(char)[] workDir = null); Spawns a new process, optionally assigning it an arbitrary set of standard input, output, and error streams. The function returns immediately, leaving the child process to execute in parallel with its parent. It is recommended to always call [`wait`](#wait) on the returned [`Pid`](#Pid) unless the process was spawned with `Config.detached` flag, as detailed in the documentation for `wait`. Command line There are four overloads of this function. The first two take an array of strings, `args`, which should contain the program name as the zeroth element and any command-line arguments in subsequent elements. The third and fourth versions are included for convenience, and may be used when there are no command-line arguments. They take a single string, `program`, which specifies the program name. Unless a directory is specified in `args[0]` or `program`, `spawnProcess` will search for the program in a platform-dependent manner. On POSIX systems, it will look for the executable in the directories listed in the PATH environment variable, in the order they are listed. On Windows, it will search for the executable in the following sequence: 1. The directory from which the application loaded. 2. The current directory for the parent process. 3. The 32-bit Windows system directory. 4. The 16-bit Windows system directory. 5. The Windows directory. 6. The directories listed in the PATH environment variable. ``` // Run an executable called "prog" located in the current working // directory: auto pid = spawnProcess("./prog"); scope(exit) wait(pid); // We can do something else while the program runs. The scope guard // ensures that the process is waited for at the end of the scope. ... // Run DMD on the file "myprog.d", specifying a few compiler switches: auto dmdPid = spawnProcess(["dmd", "-O", "-release", "-inline", "myprog.d" ]); if (wait(dmdPid) != 0) writeln("Compilation failed!"); ``` Environment variables By default, the child process inherits the environment of the parent process, along with any additional variables specified in the `env` parameter. If the same variable exists in both the parent's environment and in `env`, the latter takes precedence. If the [`Config.newEnv`](#Config.newEnv) flag is set in `config`, the child process will *not* inherit the parent's environment. Its entire environment will then be determined by `env`. ``` wait(spawnProcess("myapp", ["foo" : "bar"], Config.newEnv)); ``` Standard streams The optional arguments `stdin`, `stdout` and `stderr` may be used to assign arbitrary [`std.stdio.File`](std_stdio#File) objects as the standard input, output and error streams, respectively, of the child process. The former must be opened for reading, while the latter two must be opened for writing. The default is for the child process to inherit the standard streams of its parent. ``` // Run DMD on the file myprog.d, logging any error messages to a // file named errors.log. auto logFile = File("errors.log", "w"); auto pid = spawnProcess(["dmd", "myprog.d"], std.stdio.stdin, std.stdio.stdout, logFile); if (wait(pid) != 0) writeln("Compilation failed. See errors.log for details."); ``` Note that if you pass a `File` object that is *not* one of the standard input/output/error streams of the parent process, that stream will by default be *closed* in the parent process when this function returns. See the [`Config`](#Config) documentation below for information about how to disable this behaviour. Beware of buffering issues when passing `File` objects to `spawnProcess`. The child process will inherit the low-level raw read/write offset associated with the underlying file descriptor, but it will not be aware of any buffered data. In cases where this matters (e.g. when a file should be aligned before being passed on to the child process), it may be a good idea to use unbuffered streams, or at least ensure all relevant buffers are flushed. Parameters: | | | | --- | --- | | const(char[])[] `args` | An array which contains the program name as the zeroth element and any command-line arguments in the following elements. | | File `stdin` | The standard input stream of the child process. This can be any [`std.stdio.File`](std_stdio#File) that is opened for reading. By default the child process inherits the parent's input stream. | | File `stdout` | The standard output stream of the child process. This can be any [`std.stdio.File`](std_stdio#File) that is opened for writing. By default the child process inherits the parent's output stream. | | File `stderr` | The standard error stream of the child process. This can be any [`std.stdio.File`](std_stdio#File) that is opened for writing. By default the child process inherits the parent's error stream. | | string[string] `env` | Additional environment variables for the child process. | | Config `config` | Flags that control process creation. See [`Config`](#Config) for an overview of available flags. | | char[] `workDir` | The working directory for the new process. By default the child process inherits the parent's working directory. | Returns: A [`Pid`](#Pid) object that corresponds to the spawned process. Throws: [`ProcessException`](#ProcessException) on failure to start the process. [`std.stdio.StdioException`](std_stdio#StdioException) on failure to pass one of the streams to the child process (Windows only). [`core.exception.RangeError`](core_exception#RangeError) if `args` is empty. @safe Pid **spawnShell**(scope const(char)[] command, File stdin = std.stdio.stdin, File stdout = std.stdio.stdout, File stderr = std.stdio.stderr, scope const string[string] env = null, Config config = Config.none, scope const(char)[] workDir = null, scope string shellPath = nativeShell); @trusted Pid **spawnShell**(scope const(char)[] command, scope const string[string] env, Config config = Config.none, scope const(char)[] workDir = null, scope string shellPath = nativeShell); A variation on [`spawnProcess`](#spawnProcess) that runs the given command through the current user's preferred command interpreter (aka. shell). The string `command` is passed verbatim to the shell, and is therefore subject to its rules about command structure, argument/filename quoting and escaping of special characters. The path to the shell executable defaults to [`nativeShell`](#nativeShell). In all other respects this function works just like `spawnProcess`. Please refer to the [`spawnProcess`](#spawnProcess) documentation for descriptions of the other function parameters, the return value and any exceptions that may be thrown. ``` // Run the command/program "foo" on the file named "my file.txt", and // redirect its output into foo.log. auto pid = spawnShell(`foo "my file.txt" > foo.log`); wait(pid); ``` See Also: [`escapeShellCommand`](#escapeShellCommand), which may be helpful in constructing a properly quoted and escaped shell command line for the current platform. enum **Config**: int; Flags that control the behaviour of process creation functions in this module. Most flags only apply to [`spawnProcess`](#spawnProcess) and [`spawnShell`](#spawnShell). Use bitwise OR to combine flags. Example ``` auto logFile = File("myapp_error.log", "w"); // Start program, suppressing the console window (Windows only), // redirect its error stream to logFile, and leave logFile open // in the parent process as well. auto pid = spawnProcess("myapp", stdin, stdout, logFile, Config.retainStderr | Config.suppressConsole); scope(exit) { auto exitCode = wait(pid); logFile.writeln("myapp exited with code ", exitCode); logFile.close(); } ``` **newEnv** By default, the child process inherits the parent's environment, and any environment variables passed to [`spawnProcess`](#spawnProcess) will be added to it. If this flag is set, the only variables in the child process' environment will be those given to spawnProcess. **retainStdin** **retainStdout** **retainStderr** Unless the child process inherits the standard input/output/error streams of its parent, one almost always wants the streams closed in the parent when [`spawnProcess`](#spawnProcess) returns. Therefore, by default, this is done. If this is not desirable, pass any of these options to spawnProcess. **suppressConsole** On Windows, if the child process is a console application, this flag will prevent the creation of a console window. Otherwise, it will be ignored. On POSIX, `suppressConsole` has no effect. **inheritFDs** On POSIX, open [file descriptors](http://en.wikipedia.org/wiki/File_descriptor) are by default inherited by the child process. As this may lead to subtle bugs when pipes or multiple threads are involved, [`spawnProcess`](#spawnProcess) ensures that all file descriptors except the ones that correspond to standard input/output/error are closed in the child process when it starts. Use `inheritFDs` to prevent this. On Windows, this option has no effect, and any handles which have been explicitly marked as inheritable will always be inherited by the child process. **detached** Spawn process in detached state. This removes the need in calling [`wait`](#wait) to clean up the process resources. Note Calling [`wait`](#wait) or [`kill`](#kill) with the resulting `Pid` is invalid. **stderrPassThrough** By default, the [`execute`](#execute) and [`executeShell`](#executeShell) functions will capture child processes' both stdout and stderr. This can be undesirable if the standard output is to be processed or otherwise used by the invoking program, as `execute`'s result would then contain a mix of output and warning/error messages. Specify this flag when calling `execute` or `executeShell` to cause invoked processes' stderr stream to be sent to [`std.stdio.stderr`](std_stdio#stderr), and only capture and return standard output. This flag has no effect on [`spawnProcess`](#spawnProcess) or [`spawnShell`](#spawnShell). class **Pid**; A handle that corresponds to a spawned process. const pure nothrow @property @safe int **processID**(); The process ID number. This is a number that uniquely identifies the process on the operating system, for at least as long as the process is running. Once [`wait`](#wait) has been called on the [`Pid`](#Pid), this method will return an invalid (negative) process ID. pure nothrow @nogc @property @safe pid\_t **osHandle**(); An operating system handle to the process. This handle is used to specify the process in OS-specific APIs. On POSIX, this function returns a `core.sys.posix.sys.types.pid_t` with the same value as [`Pid.processID`](#Pid.processID), while on Windows it returns a `core.sys.windows.windows.HANDLE`. Once [`wait`](#wait) has been called on the [`Pid`](#Pid), this method will return an invalid handle. @safe int **wait**(Pid pid); Waits for the process associated with `pid` to terminate, and returns its exit status. In general one should always wait for child processes to terminate before exiting the parent process unless the process was spawned as detached (that was spawned with `Config.detached` flag). Otherwise, they may become "[zombies](http://en.wikipedia.org/wiki/Zombie_process)" – processes that are defunct, yet still occupy a slot in the OS process table. You should not and must not wait for detached processes, since you don't own them. If the process has already terminated, this function returns directly. The exit code is cached, so that if wait() is called multiple times on the same [`Pid`](#Pid) it will always return the same value. POSIX specific If the process is terminated by a signal, this function returns a negative number whose absolute value is the signal number. Since POSIX restricts normal exit codes to the range 0-255, a negative return value will always indicate termination by signal. Signal codes are defined in the `core.sys.posix.signal` module (which corresponds to the `signal.h` POSIX header). Throws: [`ProcessException`](#ProcessException) on failure or on attempt to wait for detached process. Example See the [`spawnProcess`](#spawnProcess) documentation. See Also: [`tryWait`](#tryWait), for a non-blocking function. @safe auto **tryWait**(Pid pid); A non-blocking version of [`wait`](#wait). If the process associated with `pid` has already terminated, `tryWait` has the exact same effect as `wait`. In this case, it returns a tuple where the `terminated` field is set to `true` and the `status` field has the same interpretation as the return value of `wait`. If the process has *not* yet terminated, this function differs from `wait` in that does not wait for this to happen, but instead returns immediately. The `terminated` field of the returned tuple will then be set to `false`, while the `status` field will always be 0 (zero). `wait` or `tryWait` should then be called again on the same `Pid` at some later time; not only to get the exit code, but also to avoid the process becoming a "zombie" when it finally terminates. (See [`wait`](#wait) for details). Returns: An `std.typecons.Tuple!(bool, "terminated", int, "status")`. Throws: [`ProcessException`](#ProcessException) on failure or on attempt to wait for detached process. Example ``` auto pid = spawnProcess("dmd myapp.d"); scope(exit) wait(pid); ... auto dmd = tryWait(pid); if (dmd.terminated) { if (dmd.status == 0) writeln("Compilation succeeded!"); else writeln("Compilation failed"); } else writeln("Still compiling..."); ... ``` Note that in this example, the first `wait` call will have no effect if the process has already terminated by the time `tryWait` is called. In the opposite case, however, the `scope` statement ensures that we always wait for the process if it hasn't terminated by the time we reach the end of the scope. void **kill**(Pid pid); void **kill**(Pid pid, int codeOrSignal); Attempts to terminate the process associated with `pid`. The effect of this function, as well as the meaning of `codeOrSignal`, is highly platform dependent. Details are given below. Common to all platforms is that this function only *initiates* termination of the process, and returns immediately. It does not wait for the process to end, nor does it guarantee that the process does in fact get terminated. Always call [`wait`](#wait) to wait for a process to complete, even if `kill` has been called on it. Windows specific The process will be [forcefully and abruptly terminated](http://msdn.microsoft.com/en-us/library/windows/desktop/ms686714%28v=vs.100%29.aspx). If `codeOrSignal` is specified, it must be a nonnegative number which will be used as the exit code of the process. If not, the process wil exit with code 1. Do not use `codeOrSignal = 259`, as this is a special value (aka. [STILL\_ACTIVE](http://msdn.microsoft.com/en-us/library/windows/desktop/ms683189.aspx)) used by Windows to signal that a process has in fact *not* terminated yet. ``` auto pid = spawnProcess("some_app"); kill(pid, 10); assert(wait(pid) == 10); ``` POSIX specific A [signal](http://en.wikipedia.org/wiki/Unix_signal) will be sent to the process, whose value is given by `codeOrSignal`. Depending on the signal sent, this may or may not terminate the process. Symbolic constants for various [POSIX signals](http://en.wikipedia.org/wiki/Unix_signal#POSIX_signals) are defined in `core.sys.posix.signal`, which corresponds to the [`signal.h` POSIX header](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html). If `codeOrSignal` is omitted, the `SIGTERM` signal will be sent. (This matches the behaviour of the [`_kill`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/kill.html) shell command.) ``` import core.sys.posix.signal : SIGKILL; auto pid = spawnProcess("some_app"); kill(pid, SIGKILL); assert(wait(pid) == -SIGKILL); // Negative return value on POSIX! ``` Throws: [`ProcessException`](#ProcessException) on error (e.g. if codeOrSignal is invalid). or on attempt to kill detached process. Note that failure to terminate the process is considered a "normal" outcome, not an error. @trusted Pipe **pipe**(); Creates a unidirectional pipe. Data is written to one end of the pipe and read from the other. ``` auto p = pipe(); p.writeEnd.writeln("Hello World"); p.writeEnd.flush(); assert(p.readEnd.readln().chomp() == "Hello World"); ``` Pipes can, for example, be used for interprocess communication by spawning a new process and passing one end of the pipe to the child, while the parent uses the other end. (See also [`pipeProcess`](#pipeProcess) and [`pipeShell`](#pipeShell) for an easier way of doing this.) ``` // Use cURL to download the dlang.org front page, pipe its // output to grep to extract a list of links to ZIP files, // and write the list to the file "D downloads.txt": auto p = pipe(); auto outFile = File("D downloads.txt", "w"); auto cpid = spawnProcess(["curl", "http://dlang.org/download.html"], std.stdio.stdin, p.writeEnd); scope(exit) wait(cpid); auto gpid = spawnProcess(["grep", "-o", `http://\S*\.zip`], p.readEnd, outFile); scope(exit) wait(gpid); ``` Returns: A [`Pipe`](#Pipe) object that corresponds to the created pipe. Throws: [`std.stdio.StdioException`](std_stdio#StdioException) on failure. struct **Pipe**; An interface to a pipe created by the [`pipe`](#pipe) function. nothrow @property @safe File **readEnd**(); The read end of the pipe. nothrow @property @safe File **writeEnd**(); The write end of the pipe. @safe void **close**(); Closes both ends of the pipe. Normally it is not necessary to do this manually, as [`std.stdio.File`](std_stdio#File) objects are automatically closed when there are no more references to them. Note that if either end of the pipe has been passed to a child process, it will only be closed in the parent process. (What happens in the child process is platform dependent.) Throws: [`std.exception.ErrnoException`](std_exception#ErrnoException) if an error occurs. @safe ProcessPipes **pipeProcess**(scope const(char[])[] args, Redirect redirect = Redirect.all, const string[string] env = null, Config config = Config.none, scope const(char)[] workDir = null); @safe ProcessPipes **pipeProcess**(scope const(char)[] program, Redirect redirect = Redirect.all, const string[string] env = null, Config config = Config.none, scope const(char)[] workDir = null); @safe ProcessPipes **pipeShell**(scope const(char)[] command, Redirect redirect = Redirect.all, const string[string] env = null, Config config = Config.none, scope const(char)[] workDir = null, string shellPath = nativeShell); Starts a new process, creating pipes to redirect its standard input, output and/or error streams. `pipeProcess` and `pipeShell` are convenient wrappers around [`spawnProcess`](#spawnProcess) and [`spawnShell`](#spawnShell), respectively, and automate the task of redirecting one or more of the child process' standard streams through pipes. Like the functions they wrap, these functions return immediately, leaving the child process to execute in parallel with the invoking process. It is recommended to always call [`wait`](#wait) on the returned [`ProcessPipes.pid`](#ProcessPipes.pid), as detailed in the documentation for `wait`. The `args`/`program`/`command`, `env` and `config` parameters are forwarded straight to the underlying spawn functions, and we refer to their documentation for details. Parameters: | | | | --- | --- | | const(char[])[] `args` | An array which contains the program name as the zeroth element and any command-line arguments in the following elements. (See [`spawnProcess`](#spawnProcess) for details.) | | const(char)[] `program` | The program name, *without* command-line arguments. (See [`spawnProcess`](#spawnProcess) for details.) | | const(char)[] `command` | A shell command which is passed verbatim to the command interpreter. (See [`spawnShell`](#spawnShell) for details.) | | Redirect `redirect` | Flags that determine which streams are redirected, and how. See [`Redirect`](#Redirect) for an overview of available flags. | | string[string] `env` | Additional environment variables for the child process. (See [`spawnProcess`](#spawnProcess) for details.) | | Config `config` | Flags that control process creation. See [`Config`](#Config) for an overview of available flags, and note that the `retainStd...` flags have no effect in this function. | | const(char)[] `workDir` | The working directory for the new process. By default the child process inherits the parent's working directory. | | string `shellPath` | The path to the shell to use to run the specified program. By default this is [`nativeShell`](#nativeShell). | Returns: A [`ProcessPipes`](#ProcessPipes) object which contains [`std.stdio.File`](std_stdio#File) handles that communicate with the redirected streams of the child process, along with a [`Pid`](#Pid) object that corresponds to the spawned process. Throws: [`ProcessException`](#ProcessException) on failure to start the process. [`std.stdio.StdioException`](std_stdio#StdioException) on failure to redirect any of the streams. Example ``` // my_application writes to stdout and might write to stderr auto pipes = pipeProcess("my_application", Redirect.stdout | Redirect.stderr); scope(exit) wait(pipes.pid); // Store lines of output. string[] output; foreach (line; pipes.stdout.byLine) output ~= line.idup; // Store lines of errors. string[] errors; foreach (line; pipes.stderr.byLine) errors ~= line.idup; // sendmail expects to read from stdin pipes = pipeProcess(["/usr/bin/sendmail", "-t"], Redirect.stdin); pipes.stdin.writeln("To: you"); pipes.stdin.writeln("From: me"); pipes.stdin.writeln("Subject: dlang"); pipes.stdin.writeln(""); pipes.stdin.writeln(message); // a single period tells sendmail we are finished pipes.stdin.writeln("."); // but at this point sendmail might not see it, we need to flush pipes.stdin.flush(); // sendmail happens to exit on ".", but some you have to close the file: pipes.stdin.close(); // otherwise this wait will wait forever wait(pipes.pid); ``` enum **Redirect**: int; Flags that can be passed to [`pipeProcess`](#pipeProcess) and [`pipeShell`](#pipeShell) to specify which of the child process' standard streams are redirected. Use bitwise OR to combine flags. **stdin** **stdout** **stderr** Redirect the standard input, output or error streams, respectively. **all** Redirect all three streams. This is equivalent to `Redirect.stdin | Redirect.stdout | Redirect.stderr`. **stderrToStdout** Redirect the standard error stream into the standard output stream. This can not be combined with `Redirect.stderr`. **stdoutToStderr** Redirect the standard output stream into the standard error stream. This can not be combined with `Redirect.stdout`. struct **ProcessPipes**; Object which contains [`std.stdio.File`](std_stdio#File) handles that allow communication with a child process through its standard streams. nothrow @property @safe Pid **pid**(); The [`Pid`](#Pid) of the child process. nothrow @property @safe File **stdin**(); An [`std.stdio.File`](std_stdio#File) that allows writing to the child process' standard input stream. Throws: [`Error`](object#Error) if the child process' standard input stream hasn't been redirected. nothrow @property @safe File **stdout**(); An [`std.stdio.File`](std_stdio#File) that allows reading from the child process' standard output stream. Throws: [`Error`](object#Error) if the child process' standard output stream hasn't been redirected. nothrow @property @safe File **stderr**(); An [`std.stdio.File`](std_stdio#File) that allows reading from the child process' standard error stream. Throws: [`Error`](object#Error) if the child process' standard error stream hasn't been redirected. @safe auto **execute**(scope const(char[])[] args, const string[string] env = null, Config config = Config.none, size\_t maxOutput = size\_t.max, scope const(char)[] workDir = null); @safe auto **execute**(scope const(char)[] program, const string[string] env = null, Config config = Config.none, size\_t maxOutput = size\_t.max, scope const(char)[] workDir = null); @safe auto **executeShell**(scope const(char)[] command, const string[string] env = null, Config config = Config.none, size\_t maxOutput = size\_t.max, scope const(char)[] workDir = null, string shellPath = nativeShell); Executes the given program or shell command and returns its exit code and output. `execute` and `executeShell` start a new process using [`spawnProcess`](#spawnProcess) and [`spawnShell`](#spawnShell), respectively, and wait for the process to complete before returning. The functions capture what the child process prints to both its standard output and standard error streams, and return this together with its exit code. ``` auto dmd = execute(["dmd", "myapp.d"]); if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output); auto ls = executeShell("ls -l"); if (ls.status != 0) writeln("Failed to retrieve file listing"); else writeln(ls.output); ``` The `args`/`program`/`command`, `env` and `config` parameters are forwarded straight to the underlying spawn functions, and we refer to their documentation for details. Parameters: | | | | --- | --- | | const(char[])[] `args` | An array which contains the program name as the zeroth element and any command-line arguments in the following elements. (See [`spawnProcess`](#spawnProcess) for details.) | | const(char)[] `program` | The program name, *without* command-line arguments. (See [`spawnProcess`](#spawnProcess) for details.) | | const(char)[] `command` | A shell command which is passed verbatim to the command interpreter. (See [`spawnShell`](#spawnShell) for details.) | | string[string] `env` | Additional environment variables for the child process. (See [`spawnProcess`](#spawnProcess) for details.) | | Config `config` | Flags that control process creation. See [`Config`](#Config) for an overview of available flags, and note that the `retainStd...` flags have no effect in this function. | | size\_t `maxOutput` | The maximum number of bytes of output that should be captured. | | const(char)[] `workDir` | The working directory for the new process. By default the child process inherits the parent's working directory. | | string `shellPath` | The path to the shell to use to run the specified program. By default this is [`nativeShell`](#nativeShell). | Returns: An `std.typecons.Tuple!(int, "status", string, "output")`. POSIX specific If the process is terminated by a signal, the `status` field of the return value will contain a negative number whose absolute value is the signal number. (See [`wait`](#wait) for details.) Throws: [`ProcessException`](#ProcessException) on failure to start the process. [`std.stdio.StdioException`](std_stdio#StdioException) on failure to capture output. class **ProcessException**: object.Exception; An exception that signals a problem with starting or waiting for a process. @property @safe string **userShell**(); Determines the path to the current user's preferred command interpreter. On Windows, this function returns the contents of the COMSPEC environment variable, if it exists. Otherwise, it returns the result of [`nativeShell`](#nativeShell). On POSIX, `userShell` returns the contents of the SHELL environment variable, if it exists and is non-empty. Otherwise, it returns the result of [`nativeShell`](#nativeShell). pure nothrow @nogc @property @safe string **nativeShell**(); The platform-specific native shell path. This function returns `"cmd.exe"` on Windows, `"/bin/sh"` on POSIX, and `"/system/bin/sh"` on Android. pure @safe string **escapeShellCommand**(scope const(char[])[] args...); Escapes an argv-style argument array to be used with [`spawnShell`](#spawnShell), [`pipeShell`](#pipeShell) or [`executeShell`](#executeShell). ``` string url = "http://dlang.org/"; executeShell(escapeShellCommand("wget", url, "-O", "dlang-index.html")); ``` Concatenate multiple `escapeShellCommand` and [`escapeShellFileName`](#escapeShellFileName) results to use shell redirection or piping operators. ``` executeShell( escapeShellCommand("curl", "http://dlang.org/download.html") ~ "|" ~ escapeShellCommand("grep", "-o", `http://\S*\.zip`) ~ ">" ~ escapeShellFileName("D download links.txt")); ``` Throws: [`Exception`](object#Exception) if any part of the command line contains unescapable characters (NUL on all platforms, as well as CR and LF on Windows). pure nothrow @trusted string **escapeWindowsArgument**(scope const(char)[] arg); Quotes a command-line argument in a manner conforming to the behavior of [CommandLineToArgvW](http://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx). pure nothrow @trusted string **escapeShellFileName**(scope const(char)[] fileName); Escapes a filename to be used for shell redirection with [`spawnShell`](#spawnShell), [`pipeShell`](#pipeShell) or [`executeShell`](#executeShell). int **execv**(in string pathname, in string[] argv); int **execve**(in string pathname, in string[] argv, in string[] envp); int **execvp**(in string pathname, in string[] argv); int **execvpe**(in string pathname, in string[] argv, in string[] envp); Replaces the current process by executing a command, `pathname`, with the arguments in `argv`. This function is Posix-Only. Typically, the first element of `argv` is the command being executed, i.e. `argv[0] == pathname`. The 'p' versions of `exec` search the PATH environment variable for `pathname`. The 'e' versions additionally take the new process' environment variables as an array of strings of the form key=value. Does not return on success (the current process will have been replaced). Returns -1 on failure with no indication of the underlying error. Windows specific These functions are only supported on POSIX platforms, as the Windows operating systems do not provide the ability to overwrite the current process image with another. In single-threaded programs it is possible to approximate the effect of `execv*` by using [`spawnProcess`](#spawnProcess) and terminating the current process once the child process has returned. For example: ``` auto commandLine = [ "program", "arg1", "arg2" ]; version (Posix) { execv(commandLine[0], commandLine); throw new Exception("Failed to execute program"); } else version (Windows) { import core.stdc.stdlib : _Exit; _Exit(wait(spawnProcess(commandLine))); } ``` This is, however, NOT equivalent to POSIX' `execv*`. For one thing, the executed program is started as a separate process, with all this entails. Secondly, in a multithreaded program, other threads will continue to do work while the current thread is waiting for the child process to complete. A better option may sometimes be to terminate the current program immediately after spawning the child process. This is the behaviour exhibited by the [`__exec`](http://msdn.microsoft.com/en-us/library/431x4c1w.aspx) functions in Microsoft's C runtime library, and it is how D's now-deprecated Windows `execv*` functions work. Example: ``` auto commandLine = [ "program", "arg1", "arg2" ]; version (Posix) { execv(commandLine[0], commandLine); throw new Exception("Failed to execute program"); } else version (Windows) { spawnProcess(commandLine); import core.stdc.stdlib : _exit; _exit(0); } ``` void **browse**(scope const(char)[] url); Start up the browser and set it to viewing the page at url.
programming_docs
d Interfacing to C Interfacing to C ================ **Contents** 1. [Calling C Functions](#calling_c_functions) 2. [Storage Allocation](#storage_allocation) 3. [Data Type Compatibility](#data_type_compat) 4. [Passing D Array Arguments to C Functions](#passing_d_array) 5. [Calling `printf()`](#calling_printf) 6. [Structs and Unions](#structs_and_unions) 7. [Callbacks](#callbacks) 8. [Using Existing C Libraries](#using-c-libraries) 9. [Accessing C Globals](#c-globals) D is designed to fit comfortably with a C compiler for the target system. D makes up for not having its own VM by relying on the target environment's C runtime library. It would be senseless to attempt to port to D or write D wrappers for the vast array of C APIs available. How much easier it is to just call them directly. This is done by matching the C compiler's data types, layouts, and function call/return sequences. Calling C Functions ------------------- C functions can be called directly from D. There is no need for wrapper functions, argument swizzling, and the C functions do not need to be put into a separate DLL. The C function must be declared and given a calling convention, most likely the "C" calling convention, for example: ``` extern (C) int strcmp(const char* string1, const char* string2); ``` and then it can be called within D code in the obvious way: ``` import std.string; int myDfunction(char[] s) { return strcmp(std.string.toStringz(s), "foo"); } ``` There are several things going on here: * D understands how C function names are "mangled" and the correct C function call/return sequence. * C functions cannot be overloaded with another C function with the same name. * There are no `__cdecl`, `__far`, `__stdcall`, [`__declspec`](http://www.digitalmars.com/ctg/ctgLanguageImplementation.html#declspec), or other such C [extended type modifiers](http://www.digitalmars.com/ctg/ctgLanguageImplementation.html#extended) in D. These are handled by [linkage attributes](attribute#linkage), such as `extern (C)`. * There is no volatile type modifier in D. To declare a C function that uses volatile, just drop the keyword from the declaration. * Strings are not 0 terminated in D. See "Data Type Compatibility" for more information about this. However, string literals in D are 0 terminated. C code can correspondingly call D functions, if the D functions use an attribute that is compatible with the C compiler, most likely the extern (C): ``` // myfunc() can be called from any C function extern (C) { void myfunc(int a, int b) { ... } } ``` Storage Allocation ------------------ C code explicitly manages memory with calls to [malloc()](http://www.digitalmars.com/rtl/stdlib.html#malloc) and [free()](http://www.digitalmars.com/rtl/stdlib.html#free). D allocates memory using the D garbage collector, so no explicit frees are necessary. D can still explicitly allocate memory using core.stdc.stdlib.malloc() and core.stdc.stdlib.free(), these are useful for connecting to C functions that expect malloc'd buffers, etc. If pointers to D garbage collector allocated memory are passed to C functions, it's critical to ensure that that memory will not be collected by the garbage collector before the C function is done with it. This is accomplished by: * Making a copy of the data using core.stdc.stdlib.malloc() and passing the copy instead. * Leaving a pointer to it on the stack (as a parameter or automatic variable), as the garbage collector will scan the stack. * Leaving a pointer to it in the static data segment, as the garbage collector will scan the static data segment. * Registering the pointer with the garbage collector with the [std.gc.addRoot()](https://dlang.org/phobos/core_memory.html#addRoot) or [std.gc.addRange()](https://dlang.org/phobos/core_memory.html#addRange) calls. An interior pointer to the allocated memory block is sufficient to let the GC know the object is in use; i.e. it is not necessary to maintain a pointer to the beginning of the allocated memory. The garbage collector does not scan the stacks of threads not created by the D Thread interface. Nor does it scan the data segments of other DLLs, etc. Data Type Compatibility ----------------------- D And C Type Equivalence| D | C | | 32 bit | 64 bit | | `void` | `void` | | `byte` | `signed char` | | `ubyte` | `unsigned char` | | `char` | `char` (chars are unsigned in D) | | `wchar` | `wchar_t` (when `sizeof(wchar_t)` is 2) | | `dchar` | `wchar_t` (when `sizeof(wchar_t)` is 4) | | `short` | `short` | | `ushort` | `unsigned short` | | `int` | `int` | | `uint` | `unsigned` | | `ulong` | `unsigned long long` | `unsigned long` | | `core.stdc.config.c_long` | `long` | `long` | | `core.stdc.config.c_ulong` | `unsigned long` | `unsigned long` | | `long` | `long long` | `long` (or `long long`) | | `ulong` | `unsigned long long` | `unsigned long` (or `unsigned long long`) | | `float` | `float` | | `double` | `double` | | `real` | `long double` | | `cdouble` | `double _Complex` | | `creal` | `long double _Complex` | | `struct` | `struct` | | `union` | `union` | | `enum` | `enum` | | `class` | no equivalent | | `type *` | `type *` | | `type[dim]` | `type[dim]` | | `type[dim]*, type()*[dim]` | `type[dim]*, type()*[dim]` | | `type[]` | no equivalent | | `type1[type2]` | no equivalent | | `type function(params)` | `type(*)(params)` | | `type delegate(params)` | no equivalent | | `size_t` | `size_t` | | `ptrdiff_t` | `ptrdiff_t` | These equivalents hold for most C compilers. The C standard does not pin down the sizes of the types, so some care is needed. Passing D Array Arguments to C Functions ---------------------------------------- In C, arrays are passed to functions as pointers even if the function prototype says its an array. In D, static arrays are passed by value, not by reference. Thus, the function prototype must be adjusted to match what C expects. D And C Function Prototype Equivalence| **D type** | **C type** | | *T*\* | *T*[] | | ref *T*[*dim*] | *T*[*dim*] | For example: ``` void foo(int a[3]) { ... } // C code ``` ``` extern (C) { void foo(ref int[3] a); // D prototype } ``` Calling `printf()` ------------------ `printf` can be directly called from D code: ``` import core.stdc.stdio; int main { printf("hello world\n"); return 0; } ``` Printing values works as it does in C: ``` int apples; printf("there are %d apples\n", apples); ``` Correctly matching the format specifier to the D type is necessary. The D compiler recognizes the printf formats and diagnoses mismatches with the supplied arguments. The specification for the formats used by D is the C99 specification 7.19.6.1. A generous interpretation of what is a match between the argument and format specifier is taken, for example, an unsigned type can be printed with a signed format specifier. Diagnosed incompatibilites are: * incompatible sizes which may cause argument misalignment * dereferencing arguments that are not pointers * insufficient number of arguments * struct, array and slice arguments are not allowed * non-pointer arguments to `s` specifier * non-Standard formats * undefined behavior per C99 ### Strings A string cannot be printed directly. But `%.*s` can be used: ``` string s = "betty"; printf("hello %.*s\n", cast(int) s.length, s.ptr); ``` The cast to `int` is required. ### `size_t` and `ptrdiff_t` These use the `zd` and `dt` format specifiers respectively: ``` int* p, q; printf("size of an int is %zt, pointer difference is %td\n", int.sizeof, p - q); ``` ### Non-Standard Format Specifiers Non-Standard format specifiers will be rejected by the compiler. Since the checking is only done for formats as string literals, non-Standard ones can be used: ``` const char* format = "value: %K\n"; printf(format, value); ``` ### Modern Formatted Writing An improved D function for formatted output is `std.stdio.writef()`. Structs and Unions ------------------ D structs and unions are analogous to C's. C code often adjusts the alignment and packing of struct members with a command line switch or with various implementation specific #pragmas. D supports explicit alignment attributes that correspond to the C compiler's rules. Check what alignment the C code is using, and explicitly set it for the D struct declaration. D does not support bit fields. If needed, they can be emulated with shift and mask operations, or use the [std.bitmanip.bitfields](https://dlang.org/phobos/std_bitmanip.html#bitfields) library type. [htod](https://dlang.org/htod.html) will convert bit fields to inline functions that do the right shift and masks. D does not support declaring variables of anonymous struct types. In such a case, define a named struct in D and make it private: ``` union Info // C code { struct { char *name; } file; }; ``` ``` union Info // D code { private struct File { char* name; } File file; } ``` Callbacks --------- D can easily call C callbacks (function pointers), and C can call callbacks provided by D code if the callback is an `extern(C)` function, or some other linkage that both sides have agreed to (e.g. `extern(Windows)`). Here's an example of C code providing a callback to D code: ``` void someFunc(void *arg) { printf("Called someFunc!\n"); } // C code typedef void (*Callback)(void *); extern "C" Callback getCallback(void) { return someFunc; } ``` ``` extern(C) alias Callback = int function(int, int); // D code extern(C) Callback getCallback(); void main() { Callback cb = getCallback(); cb(); // invokes the callback } ``` And an example of D code providing a callback to C code: ``` extern "C" void printer(int (*callback)(int, int)) // C code { printf("calling callback with 2 and 4 returns: %d\n", callback(2, 4)); } ``` ``` extern(C) alias Callback = int function(int, int); // D code extern(C) void printer(Callback callback); extern(C) int sum(int x, int y) { return x + y; } void main() { printer(&sum); } ``` For more info about callbacks read the [closures](function#closures) section. Using Existing C Libraries -------------------------- Since D can call C code directly, it can also call any C library functions, giving D access to the smorgasbord of existing C libraries. To do so, however, one needs to write a D interface (.di) file, which is a translation of the C .h header file for the C library into D. For popular C libraries, the first place to look for the corresponding D interface file is the [Deimos Project](https://github.com/D-Programming-Deimos/). If it isn't there already, please write and contribute one to the Deimos Project. Accessing C Globals ------------------- C globals can be accessed directly from D. C globals have the C naming convention, and so must be in an `extern (C)` block. Use the `extern` storage class to indicate that the global is allocated in the C code, not the D code. C globals default to being in global, not thread local, storage. To reference global storage from D, use the `__gshared` storage class. ``` extern (C) extern __gshared int x; ``` d Traits Traits ====== **Contents** 1. [isArithmetic](#isArithmetic) 2. [isFloating](#isFloating) 3. [isIntegral](#isIntegral) 4. [isScalar](#isScalar) 5. [isUnsigned](#isUnsigned) 6. [isStaticArray](#isStaticArray) 7. [isAssociativeArray](#isAssociativeArray) 8. [isAbstractClass](#isAbstractClass) 9. [isFinalClass](#isFinalClass) 10. [isPOD](#isPOD) 11. [isNested](#isNested) 12. [isFuture](#isFuture) 13. [isDeprecated](#isDeprecated) 14. [isDisabled](#isDisabled) 15. [isVirtualFunction](#isVirtualFunction) 16. [isVirtualMethod](#isVirtualMethod) 17. [isAbstractFunction](#isAbstractFunction) 18. [isFinalFunction](#isFinalFunction) 19. [isOverrideFunction](#isOverrideFunction) 20. [isStaticFunction](#isStaticFunction) 21. [isRef](#isRef) 22. [isTemplate](#isTemplate) 23. [isZeroInit](#isZeroInit) 24. [isReturnOnStack](#isReturnOnStack) 25. [isModule](#isModule) 26. [isPackage](#isPackage) 27. [hasMember](#hasMember) 28. [hasCopyConstructor](#hasCopyConstructor) 29. [hasPostblit](#hasPostblit) 30. [identifier](#identifier) 31. [getAliasThis](#getAliasThis) 32. [getAttributes](#getAttributes) 33. [getFunctionVariadicStyle](#getFunctionVariadicStyle) 34. [getFunctionAttributes](#getFunctionAttributes) 35. [getLinkage](#getLinkage) 36. [getLocation](#getLocation) 37. [getMember](#getMember) 38. [getOverloads](#getOverloads) 39. [getParameterStorageClasses](#getParameterStorageClasses) 40. [getPointerBitmap](#getPointerBitmap) 41. [getCppNamespaces](#getCppNamespaces) 42. [getVisibility](#getVisibility) 43. [getProtection](#getProtection) 44. [getTargetInfo](#getTargetInfo) 45. [getVirtualFunctions](#getVirtualFunctions) 46. [getVirtualMethods](#getVirtualMethods) 47. [getUnitTests](#getUnitTests) 48. [parent](#parent) 49. [child](#child) 50. [classInstanceSize](#classInstanceSize) 51. [getVirtualIndex](#getVirtualIndex) 52. [allMembers](#allMembers) 53. [derivedMembers](#derivedMembers) 54. [isSame](#isSame) 55. [compiles](#compiles) Traits are extensions to the language to enable programs, at compile time, to get at information internal to the compiler. This is also known as compile time reflection. It is done as a special, easily extended syntax (similar to Pragmas) so that new capabilities can be added as required. ``` TraitsExpression: __traits ( TraitsKeyword , TraitsArguments ) TraitsKeyword: isAbstractClass isArithmetic isAssociativeArray isFinalClass isPOD isNested isFuture isDeprecated isFloating isIntegral isScalar isStaticArray isUnsigned isDisabled isVirtualFunction isVirtualMethod isAbstractFunction isFinalFunction isStaticFunction isOverrideFunction isTemplate isRef isOut isLazy isReturnOnStack isZeroInit isModule isPackage hasMember hasCopyConstructor hasPostblit identifier getAliasThis getAttributes getFunctionAttributes getFunctionVariadicStyle getLinkage getLocation getMember getOverloads getParameterStorageClasses getPointerBitmap getCppNamespaces getVisibility getProtection getTargetInfo getVirtualFunctions getVirtualMethods getUnitTests parent child classInstanceSize getVirtualIndex allMembers derivedMembers isSame compiles TraitsArguments: TraitsArgument TraitsArgument , TraitsArguments TraitsArgument: AssignExpression Type ``` isArithmetic ------------ If the arguments are all either types that are arithmetic types, or expressions that are typed as arithmetic types, then `true` is returned. Otherwise, `false` is returned. If there are no arguments, `false` is returned. ``` import std.stdio; void main() { int i; writeln(__traits(isArithmetic, int)); writeln(__traits(isArithmetic, i, i+1, int)); writeln(__traits(isArithmetic)); writeln(__traits(isArithmetic, int*)); } ``` Prints: ``` true true false false ``` isFloating ---------- Works like `isArithmetic`, except it's for floating point types (including imaginary and complex types). ``` import core.simd : float4; enum E : float { a, b } static assert(__traits(isFloating, float)); static assert(__traits(isFloating, idouble)); static assert(__traits(isFloating, creal)); static assert(__traits(isFloating, E)); static assert(__traits(isFloating, float4)); static assert(!__traits(isFloating, float[4])); ``` isIntegral ---------- Works like `isArithmetic`, except it's for integral types (including character types). ``` import core.simd : int4; enum E { a, b } static assert(__traits(isIntegral, bool)); static assert(__traits(isIntegral, char)); static assert(__traits(isIntegral, int)); static assert(__traits(isIntegral, E)); static assert(__traits(isIntegral, int4)); static assert(!__traits(isIntegral, float)); static assert(!__traits(isIntegral, int[4])); static assert(!__traits(isIntegral, void*)); ``` isScalar -------- Works like `isArithmetic`, except it's for scalar types. ``` import core.simd : int4, void16; enum E { a, b } static assert(__traits(isScalar, bool)); static assert(__traits(isScalar, char)); static assert(__traits(isScalar, int)); static assert(__traits(isScalar, float)); static assert(__traits(isScalar, E)); static assert(__traits(isScalar, int4)); static assert(__traits(isScalar, void*)); // Includes pointers! static assert(!__traits(isScalar, int[4])); static assert(!__traits(isScalar, void16)); static assert(!__traits(isScalar, void)); static assert(!__traits(isScalar, typeof(null))); static assert(!__traits(isScalar, Object)); ``` isUnsigned ---------- Works like `isArithmetic`, except it's for unsigned types. ``` import core.simd : uint4; enum SignedEnum { a, b } enum UnsignedEnum : uint { a, b } static assert(__traits(isUnsigned, bool)); static assert(__traits(isUnsigned, char)); static assert(__traits(isUnsigned, uint)); static assert(__traits(isUnsigned, UnsignedEnum)); static assert(__traits(isUnsigned, uint4)); static assert(!__traits(isUnsigned, int)); static assert(!__traits(isUnsigned, float)); static assert(!__traits(isUnsigned, SignedEnum)); static assert(!__traits(isUnsigned, uint[4])); static assert(!__traits(isUnsigned, void*)); ``` isStaticArray ------------- Works like `isArithmetic`, except it's for static array types. ``` import core.simd : int4; enum E : int[4] { a = [1, 2, 3, 4] } static array = [1, 2, 3]; // Not a static array: the type is inferred as int[] not int[3]. static assert(__traits(isStaticArray, void[0])); static assert(__traits(isStaticArray, E)); static assert(!__traits(isStaticArray, int4)); static assert(!__traits(isStaticArray, array)); ``` isAssociativeArray ------------------ Works like `isArithmetic`, except it's for associative array types. isAbstractClass --------------- If the arguments are all either types that are abstract classes, or expressions that are typed as abstract classes, then `true` is returned. Otherwise, `false` is returned. If there are no arguments, `false` is returned. ``` import std.stdio; abstract class C { int foo(); } void main() { C c; writeln(__traits(isAbstractClass, C)); writeln(__traits(isAbstractClass, c, C)); writeln(__traits(isAbstractClass)); writeln(__traits(isAbstractClass, int*)); } ``` Prints: ``` true true false false ``` isFinalClass ------------ Works like `isAbstractClass`, except it's for final classes. isPOD ----- Takes one argument, which must be a type. It returns `true` if the type is a [POD](https://dlang.org/glossary.html#pod) type, otherwise `false`. isNested -------- Takes one argument. It returns `true` if the argument is a nested type which internally stores a context pointer, otherwise it returns `false`. Nested types can be [classes](class#nested), [structs](struct#nested), and [functions](function#variadicnested). isFuture -------- Takes one argument. It returns `true` if the argument is a symbol marked with the `@future` keyword, otherwise `false`. Currently, only functions and variable declarations have support for the `@future` keyword. isDeprecated ------------ Takes one argument. It returns `true` if the argument is a symbol marked with the `deprecated` keyword, otherwise `false`. isDisabled ---------- Takes one argument and returns `true` if it's a function declaration marked with `@disable`. ``` struct Foo { @disable void foo(); void bar(){} } static assert(__traits(isDisabled, Foo.foo)); static assert(!__traits(isDisabled, Foo.bar)); ``` For any other declaration even if `@disable` is a syntactically valid attribute `false` is returned because the annotation has no effect. ``` @disable struct Bar{} static assert(!__traits(isDisabled, Bar)); ``` isVirtualFunction ----------------- The same as [*isVirtualMethod*](#isVirtualMethod), except that final functions that don't override anything return true. isVirtualMethod --------------- Takes one argument. If that argument is a virtual function, `true` is returned, otherwise `false`. Final functions that don't override anything return false. ``` import std.stdio; struct S { void bar() { } } class C { void bar() { } } void main() { writeln(__traits(isVirtualMethod, C.bar)); // true writeln(__traits(isVirtualMethod, S.bar)); // false } ``` isAbstractFunction ------------------ Takes one argument. If that argument is an abstract function, `true` is returned, otherwise `false`. ``` import std.stdio; struct S { void bar() { } } class C { void bar() { } } class AC { abstract void foo(); } void main() { writeln(__traits(isAbstractFunction, C.bar)); // false writeln(__traits(isAbstractFunction, S.bar)); // false writeln(__traits(isAbstractFunction, AC.foo)); // true } ``` isFinalFunction --------------- Takes one argument. If that argument is a final function, `true` is returned, otherwise `false`. ``` import std.stdio; struct S { void bar() { } } class C { void bar() { } final void foo(); } final class FC { void foo(); } void main() { writeln(__traits(isFinalFunction, C.bar)); // false writeln(__traits(isFinalFunction, S.bar)); // false writeln(__traits(isFinalFunction, C.foo)); // true writeln(__traits(isFinalFunction, FC.foo)); // true } ``` isOverrideFunction ------------------ Takes one argument. If that argument is a function marked with override, `true` is returned, otherwise `false`. ``` import std.stdio; class Base { void foo() { } } class Foo : Base { override void foo() { } void bar() { } } void main() { writeln(__traits(isOverrideFunction, Base.foo)); // false writeln(__traits(isOverrideFunction, Foo.foo)); // true writeln(__traits(isOverrideFunction, Foo.bar)); // false } ``` isStaticFunction ---------------- Takes one argument. If that argument is a static function, meaning it has no context pointer, `true` is returned, otherwise `false`. ``` struct A { int foo() { return 3; } static int boo(int a) { return a; } } void main() { assert(__traits(isStaticFunction, A.boo)); assert(!__traits(isStaticFunction, A.foo)); assert(__traits(isStaticFunction, main)); } ``` isRef, isOut, isLazy --------------------- Takes one argument. If that argument is a declaration, `true` is returned if it is ref, out, or lazy, otherwise `false`. ``` void fooref(ref int x) { static assert(__traits(isRef, x)); static assert(!__traits(isOut, x)); static assert(!__traits(isLazy, x)); } void fooout(out int x) { static assert(!__traits(isRef, x)); static assert(__traits(isOut, x)); static assert(!__traits(isLazy, x)); } void foolazy(lazy int x) { static assert(!__traits(isRef, x)); static assert(!__traits(isOut, x)); static assert(__traits(isLazy, x)); } ``` isTemplate ---------- Takes one argument. If that argument is a template then `true` is returned, otherwise `false`. ``` void foo(T)(){} static assert(__traits(isTemplate,foo)); static assert(!__traits(isTemplate,foo!int())); static assert(!__traits(isTemplate,"string")); ``` isZeroInit ---------- Takes one argument which must be a type. If the type's [default initializer](property#init) is all zero bits then `true` is returned, otherwise `false`. ``` struct S1 { int x; } struct S2 { int x = -1; } static assert(__traits(isZeroInit, S1)); static assert(!__traits(isZeroInit, S2)); void test() { int x = 3; static assert(__traits(isZeroInit, typeof(x))); } // `isZeroInit` will always return true for a class C // because `C.init` is null reference. class C { int x = -1; } static assert(__traits(isZeroInit, C)); // For initializing arrays of element type `void`. static assert(__traits(isZeroInit, void)); ``` isReturnOnStack --------------- Takes one argument which must either be a function symbol, function literal, a delegate, or a function pointer. It returns a `bool` which is `true` if the return value of the function is returned on the stack via a pointer to it passed as a hidden extra parameter to the function. ``` struct S { int[20] a; } int test1(); S test2(); static assert(__traits(isReturnOnStack, test1) == false); static assert(__traits(isReturnOnStack, test2) == true); ``` **Implementation Defined:** This is determined by the function ABI calling convention in use, which is often complex. **Best Practices:** This has applications in: 1. Returning values in registers is often faster, so this can be used as a check on a hot function to ensure it is using the fastest method. 2. When using inline assembly to correctly call a function. 3. Testing that the compiler does this correctly is normally hackish and awkward, this enables efficient, direct, and simple testing. isModule -------- Takes one argument. If that argument is a symbol that refers to a [spec/module, module](module) then `true` is returned, otherwise `false`. [Package modules](module#package-module) are considered to be modules even if they have not been directly imported as modules. ``` import std.algorithm.sorting; // A regular package (no package.d) static assert(!__traits(isModule, std)); // A package module (has a package.d file) // Note that we haven't imported std.algorithm directly. // (In other words, we don't have an "import std.algorithm;" directive.) static assert(__traits(isModule, std.algorithm)); // A regular module static assert(__traits(isModule, std.algorithm.sorting)); ``` isPackage --------- Takes one argument. If that argument is a symbol that refers to a [spec/module, package](module) then `true` is returned, otherwise `false`. ``` import std.algorithm.sorting; static assert(__traits(isPackage, std)); static assert(__traits(isPackage, std.algorithm)); static assert(!__traits(isPackage, std.algorithm.sorting)); ``` hasMember --------- The first argument is a type that has members, or is an expression of a type that has members. The second argument is a string. If the string is a valid property of the type, `true` is returned, otherwise `false`. ``` import std.stdio; struct S { int m; import std.stdio; // imports write } void main() { S s; writeln(__traits(hasMember, S, "m")); // true writeln(__traits(hasMember, s, "m")); // true writeln(__traits(hasMember, S, "y")); // false writeln(__traits(hasMember, S, "write")); // true writeln(__traits(hasMember, int, "sizeof")); // true } ``` hasCopyConstructor ------------------ The argument is a type. If it is a struct with a copy constructor, returns `true`. Otherwise, return `false`. Note that a copy constructor is distinct from a postblit. ``` import std.stdio; struct S { } class C { } struct P { this(ref P rhs) {} } struct B { this(this) {} } void main() { writeln(__traits(hasCopyConstructor, S)); // false writeln(__traits(hasCopyConstructor, C)); // false writeln(__traits(hasCopyConstructor, P)); // true writeln(__traits(hasCopyConstructor, B)); // false, this is a postblit } ``` hasPostblit ----------- The argument is a type. If it is a struct with a postblit, returns `true`. Otherwise, return `false`. Note a postblit is distinct from a copy constructor. ``` import std.stdio; struct S { } class C { } struct P { this(ref P rhs) {} } struct B { this(this) {} } void main() { writeln(__traits(hasPostblit, S)); // false writeln(__traits(hasPostblit, C)); // false writeln(__traits(hasPostblit, P)); // false, this is a copy ctor writeln(__traits(hasPostblit, B)); // true } ``` identifier ---------- Takes one argument, a symbol. Returns the identifier for that symbol as a string literal. ``` import std.stdio; int var = 123; pragma(msg, typeof(var)); // int pragma(msg, typeof(__traits(identifier, var))); // string writeln(var); // 123 writeln(__traits(identifier, var)); // "var" ``` getAliasThis ------------ Takes one argument, a type. If the type has `alias this` declarations, returns a sequence of the names (as `string`s) of the members used in those declarations. Otherwise returns an empty sequence. ``` alias AliasSeq(T...) = T; struct S1 { string var; alias var this; } static assert(__traits(getAliasThis, S1) == AliasSeq!("var")); static assert(__traits(getAliasThis, int).length == 0); pragma(msg, __traits(getAliasThis, S1)); pragma(msg, __traits(getAliasThis, int)); ``` Prints: ``` tuple("var") tuple() ``` getAttributes ------------- Takes one argument, a symbol. Returns a tuple of all attached user-defined attributes. If no UDAs exist it will return an empty tuple. For more information, see: [User-Defined Attributes](attribute#uda) ``` @(3) int a; @("string", 7) int b; enum Foo; @Foo int c; pragma(msg, __traits(getAttributes, a)); pragma(msg, __traits(getAttributes, b)); pragma(msg, __traits(getAttributes, c)); ``` Prints: ``` tuple(3) tuple("string", 7) tuple((Foo)) ``` getFunctionVariadicStyle ------------------------ Takes one argument which must either be a function symbol, or a type that is a function, delegate or a function pointer. It returns a string identifying the kind of [variadic arguments](function#variadic) that are supported. getFunctionVariadicStyle| **result** | **kind** | **access** | **example** | | `"none"` | not a variadic function | | `void foo();` | | `"argptr"` | D style variadic function | `_argptr` and `_arguments` | `void bar(...)` | | `"stdarg"` | C style variadic function | [`core.stdc.stdarg`](https://dlang.org/phobos/core_stdc_stdarg.html) | `extern (C) void abc(int, ...)` | | `"typesafe"` | typesafe variadic function | array on stack | `void def(int[] ...)` | ``` import core.stdc.stdarg; void novar() {} extern(C) void cstyle(int, ...) {} extern(C++) void cppstyle(int, ...) {} void dstyle(...) {} void typesafe(int[]...) {} static assert(__traits(getFunctionVariadicStyle, novar) == "none"); static assert(__traits(getFunctionVariadicStyle, cstyle) == "stdarg"); static assert(__traits(getFunctionVariadicStyle, cppstyle) == "stdarg"); static assert(__traits(getFunctionVariadicStyle, dstyle) == "argptr"); static assert(__traits(getFunctionVariadicStyle, typesafe) == "typesafe"); static assert(__traits(getFunctionVariadicStyle, (int[] a...) {}) == "typesafe"); static assert(__traits(getFunctionVariadicStyle, typeof(cstyle)) == "stdarg"); ``` getFunctionAttributes --------------------- Takes one argument which must either be a function symbol, function literal, or a function pointer. It returns a string tuple of all the attributes of that function **excluding** any user-defined attributes (UDAs can be retrieved with the [getAttributes](#get-attributes) trait). If no attributes exist it will return an empty tuple. **Note:** The order of the attributes in the returned tuple is implementation-defined and should not be relied upon. A list of currently supported attributes are: * `pure`, `nothrow`, `@nogc`, `@property`, `@system`, `@trusted`, `@safe`, `ref` and `@live` **Note:** `ref` is a function attribute even though it applies to the return type. Additionally the following attributes are only valid for non-static member functions: * `const`, `immutable`, `inout`, `shared` For example: ``` int sum(int x, int y) pure nothrow { return x + y; } pragma(msg, __traits(getFunctionAttributes, sum)); struct S { void test() const @system { } } pragma(msg, __traits(getFunctionAttributes, S.test)); void main(){} ``` Prints: ``` tuple("pure", "nothrow", "@system") tuple("const", "@system") ``` Note that some attributes can be inferred. For example: ``` pragma(msg, __traits(getFunctionAttributes, (int x) @trusted { return x * 2; })); void main(){} ``` Prints: ``` tuple("pure", "nothrow", "@nogc", "@trusted") ``` getLinkage ---------- Takes one argument, which is a declaration symbol, or the type of a function, delegate, pointer to function, struct, class, or interface. Returns a string representing the [LinkageAttribute](attribute#LinkageAttribute) of the declaration. The string is one of: * `"D"` * `"C"` * `"C++"` * `"Windows"` * `"Objective-C"` * `"System"` ``` extern (C) int fooc(); alias aliasc = fooc; static assert(__traits(getLinkage, fooc) == "C"); static assert(__traits(getLinkage, aliasc) == "C"); extern (C++) struct FooCPPStruct {} extern (C++) class FooCPPClass {} extern (C++) interface FooCPPInterface {} static assert(__traits(getLinkage, FooCPPStruct) == "C++"); static assert(__traits(getLinkage, FooCPPClass) == "C++"); static assert(__traits(getLinkage, FooCPPInterface) == "C++"); ``` getLocation ----------- Takes one argument which is a symbol. To disambiguate between overloads, pass the result of [*getOverloads*](#getOverloads) with the desired index, to `getLocation`. Returns a `tuple(string, int, int)` whose entries correspond to the filename, line number and column number where the argument was declared. getMember --------- Takes two arguments, the second must be a string. The result is an expression formed from the first argument, followed by a ‘.’, followed by the second argument as an identifier. ``` import std.stdio; struct S { int mx; static int my; } void main() { S s; __traits(getMember, s, "mx") = 1; // same as s.mx=1; writeln(__traits(getMember, s, "m" ~ "x")); // 1 // __traits(getMember, S, "mx") = 1; // error, no this for S.mx __traits(getMember, S, "my") = 2; // ok } ``` getOverloads ------------ The first argument is an aggregate (e.g. struct/class/module). The second argument is a `string` that matches the name of the member(s) to return. The third argument is a `bool`, and is optional. If `true`, the result will also include template overloads. The result is a tuple of all the overloads of the supplied name. ``` import std.stdio; class D { this() { } ~this() { } void foo() { } int foo(int) { return 2; } void bar(T)() { return T.init; } class bar(int n) {} } void main() { D d = new D(); foreach (t; __traits(getOverloads, D, "foo")) writeln(typeid(typeof(t))); alias b = typeof(__traits(getOverloads, D, "foo")); foreach (t; b) writeln(typeid(t)); auto i = __traits(getOverloads, d, "foo")[1](1); writeln(i); foreach (t; __traits(getOverloads, D, "bar", true)) writeln(t.stringof); } ``` Prints: ``` void() int() void() int() 2 bar(T)() bar(int n) ``` getParameterStorageClasses -------------------------- Takes two arguments. The first must either be a function symbol, or a type that is a function, delegate or a function pointer. The second is an integer identifying which parameter, where the first parameter is 0. It returns a tuple of strings representing the storage classes of that parameter. ``` ref int foo(return ref const int* p, scope int* a, out int b, lazy int c); static assert(__traits(getParameterStorageClasses, foo, 0)[0] == "return"); static assert(__traits(getParameterStorageClasses, foo, 0)[1] == "ref"); static assert(__traits(getParameterStorageClasses, foo, 1)[0] == "scope"); static assert(__traits(getParameterStorageClasses, foo, 2)[0] == "out"); static assert(__traits(getParameterStorageClasses, typeof(&foo), 3)[0] == "lazy"); ``` getPointerBitmap ---------------- The argument is a type. The result is an array of `size_t` describing the memory used by an instance of the given type. The first element of the array is the size of the type (for classes it is the [*classInstanceSize*](#classInstanceSize)). The following elements describe the locations of GC managed pointers within the memory occupied by an instance of the type. For type T, there are `T.sizeof / size_t.sizeof` possible pointers represented by the bits of the array values. This array can be used by a precise GC to avoid false pointers. ``` void main() { static class C { // implicit virtual function table pointer not marked // implicit monitor field not marked, usually managed manually C next; size_t sz; void* p; void function () fn; // not a GC managed pointer } static struct S { size_t val1; void* p; C c; byte[] arr; // { length, ptr } void delegate () dg; // { context, func } } static assert (__traits(getPointerBitmap, C) == [6*size_t.sizeof, 0b010100]); static assert (__traits(getPointerBitmap, S) == [7*size_t.sizeof, 0b0110110]); } ``` getCppNamespaces ---------------- The argument is a symbol. The result is a tuple of strings, possibly empty, that correspond to the namespaces the symbol resides in. ``` extern(C++, "ns") struct Foo {} struct Bar {} extern(C++, __traits(getCppNamespaces, Foo)) struct Baz {} static assert(__traits(getCppNamespaces, Foo) == __traits(getCppNamespaces, Baz)); void main() { static assert(__traits(getCppNamespaces, Foo)[0] == "ns"); static assert(!__traits(getCppNamespaces, Bar).length); static assert(__traits(getCppNamespaces, Foo) == __traits(getCppNamespaces, Baz)); } ``` getVisibility ------------- The argument is a symbol. The result is a string giving its visibility level: "public", "private", "protected", "export", or "package". ``` import std.stdio; class D { export void foo() { } public int bar; } void main() { D d = new D(); auto i = __traits(getVisibility, d.foo); writeln(i); auto j = __traits(getVisibility, d.bar); writeln(j); } ``` Prints: ``` export public ``` getProtection ------------- A backward-compatible alias for [*getVisibility*](#getVisibility). getTargetInfo ------------- Receives a string key as argument. The result is an expression describing the requested target information. ``` version (CppRuntime_Microsoft) static assert(__traits(getTargetInfo, "cppRuntimeLibrary") == "libcmt"); ``` Keys are implementation defined, allowing relevant data for exotic targets. A reliable subset exists which are always available: * `"cppRuntimeLibrary"` - The C++ runtime library affinity for this toolchain * `"cppStd"` - The version of the C++ standard supported by `extern(C++)` code, equivalent to the `__cplusplus` macro in a C++ compiler * `"floatAbi"` - Floating point ABI; may be `"hard"`, `"soft"`, or `"softfp"` * `"objectFormat"` - Target object format getVirtualFunctions ------------------- The same as [*getVirtualMethods*](#getVirtualMethods), except that final functions that do not override anything are included. getVirtualMethods ----------------- The first argument is a class type or an expression of class type. The second argument is a string that matches the name of one of the functions of that class. The result is a tuple of the virtual overloads of that function. It does not include final functions that do not override anything. ``` import std.stdio; class D { this() { } ~this() { } void foo() { } int foo(int) { return 2; } } void main() { D d = new D(); foreach (t; __traits(getVirtualMethods, D, "foo")) writeln(typeid(typeof(t))); alias b = typeof(__traits(getVirtualMethods, D, "foo")); foreach (t; b) writeln(typeid(t)); auto i = __traits(getVirtualMethods, d, "foo")[1](1); writeln(i); } ``` Prints: ``` void() int() void() int() 2 ``` getUnitTests ------------ Takes one argument, a symbol of an aggregate (e.g. struct/class/module). The result is a tuple of all the unit test functions of that aggregate. The functions returned are like normal nested static functions, [CTFE](https://dlang.org/glossary.html#ctfe) will work and [UDAs](attribute#uda) will be accessible. ### Note: The -unittest flag needs to be passed to the compiler. If the flag is not passed `__traits(getUnitTests)` will always return an empty tuple. ``` module foo; import core.runtime; import std.stdio; struct name { string name; } class Foo { unittest { writeln("foo.Foo.unittest"); } } @name("foo") unittest { writeln("foo.unittest"); } template Tuple (T...) { alias Tuple = T; } shared static this() { // Override the default unit test runner to do nothing. After that, "main" will // be called. Runtime.moduleUnitTester = { return true; }; } void main() { writeln("start main"); alias tests = Tuple!(__traits(getUnitTests, foo)); static assert(tests.length == 1); alias attributes = Tuple!(__traits(getAttributes, tests[0])); static assert(attributes.length == 1); foreach (test; tests) test(); foreach (test; __traits(getUnitTests, Foo)) test(); } ``` By default, the above will print: ``` start main foo.unittest foo.Foo.unittest ``` parent ------ Takes a single argument which must evaluate to a symbol. The result is the symbol that is the parent of it. child ----- Takes two arguments. The first must be a symbol or expression. The second is a symbol, such as an alias to a member of the first argument. The result is the second argument interpreted with its `this` context set to the value of the first argument. ``` import std.stdio; struct A { int i; int foo(int j) { return i * j; } T bar(T)(T t) { return i + t; } } alias Ai = A.i; alias Abar = A.bar!int; void main() { A a; __traits(child, a, Ai) = 3; writeln(a.i); writeln(__traits(child, a, A.foo)(2)); writeln(__traits(child, a, Abar)(5)); } ``` Prints: ``` 3 6 7 ``` classInstanceSize ----------------- Takes a single argument, which must evaluate to either a class type or an expression of class type. The result is of type `size_t`, and the value is the number of bytes in the runtime instance of the class type. It is based on the static type of a class, not the polymorphic type. getVirtualIndex --------------- Takes a single argument which must evaluate to a function. The result is a `ptrdiff_t` containing the index of that function within the vtable of the parent type. If the function passed in is final and does not override a virtual function, `-1` is returned instead. allMembers ---------- Takes a single argument, which must evaluate to either a type or an expression of type. A tuple of string literals is returned, each of which is the name of a member of that type combined with all of the members of the base classes (if the type is a class). No name is repeated. Builtin properties are not included. ``` import std.stdio; class D { this() { } ~this() { } void foo() { } int foo(int) { return 0; } } void main() { auto b = [ __traits(allMembers, D) ]; writeln(b); // ["__ctor", "__dtor", "foo", "toString", "toHash", "opCmp", "opEquals", // "Monitor", "factory"] } ``` The order in which the strings appear in the result is not defined. derivedMembers -------------- Takes a single argument, which must evaluate to either a type or an expression of type. A tuple of string literals is returned, each of which is the name of a member of that type. No name is repeated. Base class member names are not included. Builtin properties are not included. ``` import std.stdio; class D { this() { } ~this() { } void foo() { } int foo(int) { return 0; } } void main() { auto a = [__traits(derivedMembers, D)]; writeln(a); // ["__ctor", "__dtor", "foo"] } ``` The order in which the strings appear in the result is not defined. isSame ------ Takes two arguments and returns bool `true` if they are the same symbol, `false` if not. ``` import std.stdio; struct S { } int foo(); int bar(); void main() { writeln(__traits(isSame, foo, foo)); // true writeln(__traits(isSame, foo, bar)); // false writeln(__traits(isSame, foo, S)); // false writeln(__traits(isSame, S, S)); // true writeln(__traits(isSame, std, S)); // false writeln(__traits(isSame, std, std)); // true } ``` If the two arguments are expressions made up of literals or enums that evaluate to the same value, true is returned. If the two arguments are both [lambda functions](expression#function_literals) (or aliases to lambda functions), then they are compared for equality. For the comparison to be computed correctly, the following conditions must be met for both lambda functions: 1. The lambda function arguments must not have a template instantiation as an explicit argument type. Any other argument types (basic, user-defined, template) are supported. 2. The lambda function body must contain a single expression (no return statement) which contains only numeric values, manifest constants, enum values, function arguments and function calls. If the expression contains local variables or return statements, the function is considered incomparable. If these constraints aren't fulfilled, the function is considered incomparable and `isSame` returns `false`. ``` int f() { return 2; } void test(alias pred)() { // f() from main is a different function from top-level f() static assert(!__traits(isSame, (int a) => a + f(), pred)); } void main() { static assert(__traits(isSame, (a, b) => a + b, (c, d) => c + d)); static assert(__traits(isSame, a => ++a, b => ++b)); static assert(!__traits(isSame, (int a, int b) => a + b, (a, b) => a + b)); static assert(__traits(isSame, (a, b) => a + b + 10, (c, d) => c + d + 10)); // lambdas accessing local variables are considered incomparable int b; static assert(!__traits(isSame, a => a + b, a => a + b)); // lambdas calling other functions are comparable int f() { return 3;} static assert(__traits(isSame, a => a + f(), a => a + f())); test!((int a) => a + f())(); class A { int a; this(int a) { this.a = a; } } class B { int a; this(int a) { this.a = a; } } static assert(__traits(isSame, (A a) => ++a.a, (A b) => ++b.a)); // lambdas with different data types are considered incomparable, // even if the memory layout is the same static assert(!__traits(isSame, (A a) => ++a.a, (B a) => ++a.a)); } ``` If the two arguments are tuples then `isSame` returns `true` if the two tuples, after expansion, have the same length and if each pair of nth argument respects the constraints previously specified. ``` import std.stdio; import std.meta; struct S { } void main() { // true, like __traits(isSame(0,0)) && __traits(isSame(1,1)) writeln(__traits(isSame, AliasSeq!(0,1), AliasSeq!(0,1))); // false, like __traits(isSame(S,std.meta)) && __traits(isSame(1,1)) writeln(__traits(isSame, AliasSeq!(S,1), AliasSeq!(std.meta,1))); // false, the length of the sequences is different writeln(__traits(isSame, AliasSeq!(1), AliasSeq!(1,2))); } ``` compiles -------- Returns a bool `true` if all of the arguments compile (are semantically correct). The arguments can be symbols, types, or expressions that are syntactically correct. The arguments cannot be statements or declarations. If there are no arguments, the result is `false`. ``` import std.stdio; struct S { static int s1; int s2; } int foo(); int bar(); void main() { writeln(__traits(compiles)); // false writeln(__traits(compiles, foo)); // true writeln(__traits(compiles, foo + 1)); // true writeln(__traits(compiles, &foo + 1)); // false writeln(__traits(compiles, typeof(1))); // true writeln(__traits(compiles, S.s1)); // true writeln(__traits(compiles, S.s3)); // false writeln(__traits(compiles, 1,2,3,int,long,std)); // true writeln(__traits(compiles, 3[1])); // false writeln(__traits(compiles, 1,2,3,int,long,3[1])); // false } ``` This is useful for: * Giving better error messages inside generic code than the sometimes hard to follow compiler ones. * Doing a finer grained specialization than template partial specialization allows for.
programming_docs