from: (AmbientAuth val | NetAuth val)

Returns¶

TCPAuth val^

Public Functions¶
eq¶
[Source]
fun box eq(
that: TCPAuth val)
: Bool val

Parameters¶

that: TCPAuth val

Returns¶


| let wr: _WaitResult =>
None
else
match _child.wait()
| let sr: _StillRunning =>
if not _polling_child then
_polling_child = true
let timers = _ensure_timers()
let pm: ProcessMonitor tag = this
let tn =
object iso is TimerNotify
fun ref apply(timer: Timer, count: U64): Bool =>
pm._wait_for_child()
true
end
let timer = Timer(consume tn, _process_poll_interval, _process_poll_interval)
timers(consume timer)
end
| let exit_status: ProcessExitStatus =>
// process child exit code or termination signal


fun deb_string(): String =>
_spec.deb_string() + "=" + _value.string()

class val Arg
"""
Arg contains a spec and an effective value for a given arg.
"""
let _spec: ArgSpec
let _value: _Value

new val create(spec': ArgSpec, value': _Value) =>
_spec = spec'
_value = value'

fun _append(next: Arg): Arg =>
Arg(_spec, _spec._typ_p().append(_value, next._value))

fun spec(): ArgSpec => _spec

fun bool(): Bool =>


fun box sctp_max_cwnd()
: I32 val

Returns¶

I32 val

sctp_max_hb_interval¶
[Source]
fun box sctp_max_hb_interval()
: I32 val

Returns¶

I32 val

sctp_max_sack_delay¶
[Source]


y: U128 val

Returns¶

(U128 val , Bool val)

fld_partial¶
[Source]
fun box fld_partial(
y: U128 val)
: U128 val ?

Parameters¶

y: U128 val

Returns¶


fun box u32()
: U32 val

Returns¶

U32 val

u64¶
[Source]
fun box u64()
: U64 val

Returns¶

U64 val

u128¶
[Source]


[Source]
fun box shl(
y: ULong val)
: ILong val

Parameters¶

y: ULong val

Returns¶

ILong val

shr¶
[Source]
fun box shr(
y: ULong val)
: ILong val


y: I32 val

Returns¶

I32 val

fld¶
[Source]
fun box fld(
y: I32 val)
: I32 val

Parameters¶

y: I32 val

Returns¶


else
0 == @unlink(path.cstring())
end
end
else
false
end

fun rename(new_path: FilePath): Bool =>
"""
Rename a file or directory.
"""
if not caps(FileRename) or not new_path.caps(FileCreate) then
return false
end

0 == @rename(path.cstring(), new_path.path.cstring())

fun val symlink(link_name: FilePath): Bool =>
"""


dispose¶
[Source]
Stop accepting input, inform the notifier we have closed, and dispose of
our source.
be dispose()


192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211


212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231


[Source]
Return the next node.
fun box next()
: (this->ListNode[A] ref | None val)

Returns¶

(this->ListNode[A] ref | None val)


Reads a U128 from offset. This is only allowed for an array of U8s.
fun box read_u128[optional B: (A & Real[B] val & U8 val)](
offset: USize val)
: U128 val ?

Parameters¶

offset: USize val

Returns¶

U128 val ?

apply¶
[Source]
Get the i-th element, raising an error if the index is out of bounds.
fun box apply(
i: USize val)
: this->A ?


let cloned = array.clone()
rnd.shuffle[this->T!](cloned)
cloned.values()
end
)

fun list_of[T](
gen: Generator[T],
min: USize = 0,
max: USize = 100)
: Generator[List[T]]
=>
Generators.seq_of[T, List[T]](gen, min, max)

fun set_of[T: (Hashable #read & Equatable[T] #read)](
gen: Generator[T],
max: USize = 100)
: Generator[Set[T]]
=>
"""


272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291


fun mod(y: I64): I64 =>
_SignedArithmetic.mod[I64, U64](this, y)

fun mod_unsafe(y: I64): I64 =>
_SignedUnsafeArithmetic.mod_unsafe[I64, U64](this, y)

fun hash(): USize => u64().hash()

fun addc(y: I64): (I64, Bool) =>
@"llvm.sadd.with.overflow.i64"(this, y)

fun subc(y: I64): (I64, Bool) =>
@"llvm.ssub.with.overflow.i64"(this, y)

fun mulc(y: I64): (I64, Bool) =>
_SignedCheckedArithmetic._mul_checked[U64, I64](this, y)

fun divc(y: I64): (I64, Bool) =>
_SignedCheckedArithmetic.div_checked[I64, U64](this, y)


# Opaque reference capabilities

There's only one __opaque__ reference capability, which is `tag`. A `tag` variable makes no guarantees about other variables at all. As a result, it can't be used to either read from or write to the object; hence the name __opaque__.

It's still useful though: you can do identity comparison with it, you can call behaviours on it, and you can call functions on it that only need a `tag` receiver.

__Why can't `tag` be used to read or write?__ Because `tag` doesn't stop _other_ actors from writing to the object. That means if we tried to read, we would have no guarantee that there wasn't some other actor writing to the object, so we might get a race condition.


_count = _count + 1
else
@pony_os_socket_close(ns)
end

fun ref _notify_listening() =>
"""
Inform the notifier that we're listening.
"""
if not _event.is_null() then
_notify.listening(this)
else
_closed = true
_notify.not_listening(this)
end

fun ref close() =>
"""
Dispose of resources.
"""


line: String val

Returns¶

Seq[String val] box


672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691


fun box icmp_redir_nettos()
: I32 val

Returns¶

I32 val

icmp_source_quench¶
[Source]
fun box icmp_source_quench()
: I32 val

Returns¶

I32 val

icmp_sr_failed¶
[Source]


"""
The `Random` trait should be implemented by all random number generators. The
only method you need to implement is `fun ref next(): 64`. Once that method
has been implemented, the `Random` trait provides default implementations of
conversions to other number types.
"""
new create(x: U64 = 5489, y: U64 = 0)
"""
Create with the specified seed. Returned values are deterministic for a
given seed.
"""

fun tag has_next(): Bool =>
"""
If used as an iterator, this always has another value.
"""
true

fun ref next(): U64
"""


1432
1433
1434
1435
1436
1437
1438
1439use "collections"
use "assert"
use "itertools"
use "debug"

type ValueAndShrink[T1] is (T1^, Iterator[T1^])
"""
Possible return type for
[`Generator.generate`](pony_check-Generator.md#generate).
Represents a generated value and an Iterator of shrunken values.
"""

type GenerateResult[T2] is (T2^ | ValueAndShrink[T2])


if _size == that._size then
@memcmp(_ptr, that._ptr, _size) == 0
else
false
end

fun lt(that: String box): Bool =>
"""
Returns true if this is lexically less than that. Needs to be made UTF-8
safe.
"""
let len = _size.min(that._size)
var i: USize = 0

while i < len do
if _ptr._apply(i) < that._ptr._apply(i) then
return true
elseif _ptr._apply(i) > that._ptr._apply(i) then
return false
end


# Generics and Reference Capabilities

In the examples presented previously we've explicitly set the reference capability to `val`:

```pony
class Foo[A: Any val]
```

If the capability is left out of the type parameter then the generic class or function can accept any reference capability. This would look like:

```pony
class Foo[A: Any]
```

It can be made shorter because `Any` is the default constraint, leaving us with:

```pony
class Foo[A]
```


HashMap[K, V, H] val ?

get_or_else¶
[Source]
Get the value associated with provided key if present. Otherwise,
return the provided alternate value.
fun val get_or_else(
k: K,
alt: val->V)
: val->V

Parameters¶

k: K
alt: val->V

Returns¶

val->V


new val create()
: None val^

Returns¶

None val^

Public Functions¶
string¶
[Source]
fun box string()
: String iso^

Returns¶

String iso^

eq¶


Returns¶

F64 val

exp¶
[Source]
fun box exp()
: F64 val

Returns¶

F64 val

exp2¶
[Source]
fun box exp2()
: F64 val


"""
Red background.
"""
"\x1B[41m"

fun green_bg(): String =>
"""
Green background.
"""
"\x1B[42m"

fun yellow_bg(): String =>
"""
Yellow background.
"""
"\x1B[43m"

fun blue_bg(): String =>
"""
Blue background.


fun box so_timestamping()
: I32 val

Returns¶

I32 val

so_timestampns¶
[Source]
fun box so_timestampns()
: I32 val

Returns¶

I32 val

so_timestamp_monotonic¶
[Source]


Hashable¶
[Source]
Anything with a hash method is hashable.
interface ref Hashable

Public Functions¶
hash¶
[Source]
fun box hash()
: USize val

Returns¶


### Example

```pony
Iter[I64]([1; 2; 3].values())
.map[None]({(x) => env.out.print(x.string()) })
.run()
```
```
1
2
3
```
"""
if not _iter.has_next() then return end
try
_iter.next()?
run(on_error)
else
on_error()
end


(ULong val , ULong val)

rem¶
[Source]
fun box rem(
y: ULong val)
: ULong val

Parameters¶

y: ULong val

Returns¶

ULong val

neg¶
[Source]


fun box sctp_established()
: I32 val

Returns¶

I32 val

sctp_event¶
[Source]
fun box sctp_event()
: I32 val

Returns¶

I32 val

sctp_events¶
[Source]


apply¶
[Source]
fun ref apply()
: None val

Returns¶

None val

config¶
[Source]
fun box config()
: BenchConfig val

Returns¶

BenchConfig val


52
53
54
55
56
57
58
59
60
61
62use @pony_asio_event_create[AsioEventID](
owner: AsioEventNotify,
fd: U32,
flags: U32,
nsec: U64,
noisy: Bool)
use @pony_asio_event_unsubscribe[None](event: AsioEventID)
use @pony_asio_event_destroy[None](event: AsioEventID)

actor SignalHandler is AsioEventNotify


452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471


mod_unsafe¶
[Source]
Calculates the modulo of this number after floored division by y.
Unsafe Operation.
If y is 0, the result is undefined.
If the operation overflows, the result is undefined.
fun box mod_unsafe(
y: A)
: A

Parameters¶

y: A

Returns¶

A


ILong val

isize_unsafe¶
[Source]
fun box isize_unsafe()
: ISize val

Returns¶

ISize val

u8_unsafe¶
[Source]
fun box u8_unsafe()
: U8 val

Returns¶


Bool val


Returns¶

U32 val

stkflt¶
[Source]
fun box stkflt()
: U32 val

Returns¶

U32 val

stop¶
[Source]
fun box stop()
: U32 val


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151


fun box i16_unsafe()
: I16 val

Returns¶

I16 val

i32_unsafe¶
[Source]
fun box i32_unsafe()
: I32 val

Returns¶

I32 val

i64_unsafe¶
[Source]


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130use "files"
use @__cap_rights_init[Pointer[U64]](version: I32, ...)


512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531


fun box sctp_ltrace_error_enable()
: I32 val

Returns¶

I32 val

sctp_map_logging_enable¶
[Source]
fun box sctp_map_logging_enable()
: I32 val

Returns¶

I32 val

sctp_maxburst¶
[Source]


fun _help_name(): String =>
_root_spec().help_name()

primitive _OptionParser
fun parse(
spec: OptionSpec,
targ: (String|None),
args: Array[String] ref)
: (Option | SyntaxError)
=>
// Grab the token-arg if provided, else consume an arg if one is required.
let arg = match targ
| (let fn: None) if spec._requires_arg() =>
try args.shift()? else None end
else
targ
end
// Now convert the arg to Type, detecting missing or mis-typed args
match arg
| let a: String =>


"""
Unsafe operation.
If the value doesn't fit in the destination type, the result is undefined.
"""
compile_intrinsic

fun isize_unsafe(): ISize =>
"""
Unsafe operation.
If the value doesn't fit in the destination type, the result is undefined.
"""
compile_intrinsic

fun u8_unsafe(): U8 =>
"""
Unsafe operation.
If the value doesn't fit in the destination type, the result is undefined.
"""
compile_intrinsic


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111


# Running the program

Now we can run the program:

```bash
$ ./helloworld
Hello, world!
```

Congratulations, you've written your first Pony program! Next, we'll explain what some of that code does.


U128 val ?

div_partial¶
[Source]
fun box div_partial(
y: U128 val)
: U128 val ?

Parameters¶

y: U128 val

Returns¶

U128 val ?

rem_partial¶
[Source]


fun box sub_partial(
y: U64 val)
: U64 val ?

Parameters¶

y: U64 val

Returns¶

U64 val ?

mul_partial¶
[Source]
fun box mul_partial(
y: U64 val)
: U64 val ?

Parameters¶


class Foo
var _x: U32

new create() =>
_x = 0

new from_int(x: U32) =>
_x = x

class Bar
fun f() =>
var a: Foo = Foo.create()
var b: Foo = a.from_int(3)
```

We can even reuse the variable name in the assignment expression to call the constructor.

```pony
class Bar
fun f() =>


div_unsafe¶
[Source]
Unsafe operation.
If any input or output of the operation is +/- infinity or NaN, the result
is undefined.
The operation isn't required to fully comply to IEEE 754 semantics.
fun box div_unsafe(
y: A)
: A

Parameters¶

y: A

Returns¶

A


x: (String box | Array[U8 val] box)

Returns¶

USize val

hash64¶
[Source]
fun box hash64(
x: (String box | Array[U8 val] box))
: U64 val

Parameters¶

x: (String box | Array[U8 val] box)

Returns¶

U64 val


Custodian tag^

Public Behaviours¶
apply¶
[Source]
Add an actor to be disposed of.
be apply(
worker: DisposableActor tag)

Parameters¶

worker: DisposableActor tag

remove¶
[Source]
Removes an actor from the set of things to be disposed.
be remove(
worker: DisposableActor tag)


172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


ilong¶
[Source]
Create a generator for ILong values.
fun box ilong(
min: ILong val = call,
max: ILong val = call)
: Generator[ILong val] box

Parameters¶

min: ILong val = call
max: ILong val = call

Returns¶

Generator[ILong val] box

isize¶
[Source]


value: val->V

Returns¶

HashMap[K, V, H] val

remove¶
[Source]
Try to remove the provided key from the Map.
fun val remove(
k: K)
: HashMap[K, V, H] val ?

Parameters¶

k: K

Returns¶


fun box sub_partial(
y: ULong val)
: ULong val ?

Parameters¶

y: ULong val

Returns¶

ULong val ?

mul_partial¶
[Source]
fun box mul_partial(
y: ULong val)
: ULong val ?

Parameters¶


_dispose()

fun ref _dispose() =>
for disposable in Poperator[DisposableActor](_disposables) do
disposable.dispose()
end

be log(msg: String, verbose: Bool = false) =>
_logger.log(msg, verbose)

// end interface towards PropertyHelper

fun ref complete() =>
"""
Complete the Property execution successfully.
"""
_notify.complete(true)

fun ref fail(repr: String, rounds: USize = 0, err: Bool = false) =>
"""


p1("first")
```
"""
let p' = Promise[Array[A] val]
let ps' = Array[Promise[A]] .> concat(consume ps)

if ps'.size() == 0 then
p'(recover Array[A] end)
return p'
end

let j = _Join[A](p', ps'.size())
for p in ps'.values() do
p.next[None]({(a)(j) => j(a)}, {() => p'.reject()})
end

p'

actor _Join[A: Any #share]
embed _xs: Array[A]


fun box so_bsp_state()
: I32 val

Returns¶

I32 val

so_busy_poll¶
[Source]
fun box so_busy_poll()
: I32 val

Returns¶

I32 val

so_conaccess¶
[Source]


else
_i
end

class ArrayValues[A, B: Array[A] #read] is Iterator[B->A]
let _array: B
var _i: USize

new create(array: B) =>
_array = array
_i = 0

fun has_next(): Bool =>
_i < _array.size()

fun ref next(): B->A ? =>
_array(_i = _i + 1)?

fun ref rewind(): ArrayValues[A, B] =>
_i = 0


USize val

clz¶
[Source]
fun box clz()
: USize val

Returns¶

USize val

ctz¶
[Source]
fun box ctz()
: USize val

Returns¶


(U16 val , Bool val)

divc¶
[Source]
fun box divc(
y: U16 val)
: (U16 val , Bool val)

Parameters¶

y: U16 val

Returns¶

(U16 val , Bool val)

remc¶
[Source]


[Source]
fun box div(
y: ISize val)
: ISize val

Parameters¶

y: ISize val

Returns¶

ISize val

divrem¶
[Source]
fun box divrem(
y: ISize val)
: (ISize val , ISize val)


U8 val

precision2¶
[Source]
fun tag precision2()
: U8 val

Returns¶

U8 val

precision10¶
[Source]
fun tag precision10()
: U8 val

Returns¶


752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771


fun box popcount()
: A

Returns¶

A

clz¶
[Source]
fun box clz()
: A

Returns¶

A

ctz¶
[Source]


r(key) = value
r

fun sub[H2: HashFunction[this->K!] val = H](key: this->K!)
: HashMap[this->K!, this->V!, H2]^
=>
"""
This without the given key.
"""
let r = clone[H2]()
try r.remove(key)? end
r

fun next_index(prev: USize = -1): USize ? =>
"""
Given an index, return the next index that has a populated key and value.
Raise an error if there is no next populated index.
"""
for i in Range(prev + 1, _array.size()) do
match _array(i)?


## `nodoc`

Recognised on objects and methods (`actor`, `class`, `struct`, `primitive`, `trait`, `interface`, `new`, `be`, `fun`). Indicates to the documentation system that the item and any of its children shouldn't be included in generated output.

```pony
class \nodoc\Foo
"""
We don't want this class and its methods to appear in generated documentation
"""
```


primitive U32
primitive U64
primitive U8
primitive ULong
primitive USize
type Unsigned
trait UnsignedInteger


ossockopt.pony

1
2
3
4
5
6
7
8
9
10
11


272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291


fun box sctp_pcb_flags_autoclose()
: I32 val

Returns¶

I32 val

sctp_pcb_flags_auto_asconf¶
[Source]
fun box sctp_pcb_flags_auto_asconf()
: I32 val

Returns¶

I32 val

sctp_pcb_flags_blocking_io¶
[Source]


process_notify.pony

1
2
3
4
5
6
7
8
9
10
11


=>
"""
Create a clone. The key and value types may be different due to aliasing
and viewpoint adaptation.
"""
let r = HashMap[this->K!, this->V!, H2](_size)

for (k, v) in pairs() do
r(k) = v
end
r

fun ref clear() =>
"""
Remove all entries.
"""
_size = 0
// Our default prealloc of 6 corresponds to an array alloc size of 8.
let n: USize = 8
_array = _array.init(_MapEmpty, n)


fun box mrt_init()
: I32 val

Returns¶

I32 val

mrt_mfc_bw_upcall¶
[Source]
fun box mrt_mfc_bw_upcall()
: I32 val

Returns¶

I32 val

mrt_mfc_flags_all¶
[Source]


"""
for worker in _workers.values() do
worker.dispose()
end

_workers.clear()


472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491


fun tag _make_cmdline(args: Array[String] val): String =>
var cmdline: String = ""
for arg in args.values() do
// quote args with spaces on Windows
var next = arg
ifdef windows then
try
if arg.contains(" ") and (not arg(0)? == '"') then
next = "\"" + arg + "\""
end
end
end
cmdline = cmdline + next + " "
end
cmdline

fun tag _make_environ(vars: Array[String] val): Array[U8] =>
var size: USize = 0
for varr in vars.values() do
size = size + varr.size() + 1 // name=value\0


432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451


# Capability Constraints

The type parameter constraint for a generic class or method can constrain to a particular capability as seen previously:

```pony
class Foo[A: Any val]
```

Without the constraint, the generic must work for all possible capabilities. Sometimes you don't want to be limited to a specific capability and you can't support all capabilities. The solution for this is generic constraint qualifiers. These represent classes of capabilities that are accepted in the generic. The valid qualifiers are:

| ▷ | Capabilities allowed         | Description                                                     |
| -------- | ---------------------------- | --------------------------------------------------------------- |
| `#read`    | `ref`, `val`, `box`                | Anything you can read from                                      |
| `#send`    | `iso`, `val`, `tag`                | Anything you can send to an actor                               |
| `#share`   | `val`, `tag`                     | Anything you can send to more than one actor                    |
| `#any`     | `iso`, `trn`, `ref`, `val`, `box`, `tag` | Default of a constraint                                         |
| `#alias`   | `ref`, `val`, `box`, `tag`           | Set of capabilities that alias as themselves (used by compiler) |

In the previous section, we went through extra work to support `iso`. If there's no requirement for `iso` support we can use `#read` and support `ref`, `val`, and `box`:


Iter[(A , B , C , D)] ref^

zip4[B: B, C: C, D: D, E: E]¶
[Source]
Zip five iterators together so that each call to next() results in
a tuple with the next value of each of the iterators. The number of
items returned is the minimum of the number of items returned by the
iterators.
fun ref zip4[B: B, C: C, D: D, E: E](
i2: Iterator[B] ref,
i3: Iterator[C] ref,
i4: Iterator[D] ref,
i5: Iterator[E] ref)
: Iter[(A , B , C , D , E)] ref^

Parameters¶

i2: Iterator[B] ref
i3: Iterator[C] ref


fun box sctp_packet_truncated()
: I32 val

Returns¶

I32 val

sctp_pad_chunk¶
[Source]
fun box sctp_pad_chunk()
: I32 val

Returns¶

I32 val

sctp_partial_delivery_point¶
[Source]


# Precedence

In Pony, unary operators always bind stronger than any infix operators: `not a == b` will be interpreted as `(not a) == b` instead of `not (a == b)`.

When using infix operators in complex expressions a key question is the __precedence__, i.e. which operator is evaluated first. Given this expression:

```pony
1 + 2 * 3  // Compilation failed.
```

We will get a value of 9 if we evaluate the addition first and 7 if we evaluate the multiplication first. In mathematics, there are rules about the order in which to evaluate operators and most programming languages follow this approach.

The problem with this is that the programmer has to remember the order and people aren't very good at things like that. Most people will remember to do multiplication before addition, but what about left bit shifting versus bitwise and? Sometimes people misremember (or guess wrong) and that leads to bugs. Worse, those bugs are often very hard to spot.

Pony takes a different approach and outlaws infix precedence. Any expression where more than one infix operator is used __must__ use parentheses to remove the ambiguity. If you fail to do this the compiler will complain.

This means that the example above is illegal in Pony and should be rewritten as:

```pony
1 + (2 * 3)  // 7


hashable.pony

1
2
3
4
5
6
7
8
9
10
11


prefix: String val = ""
caps': Flags[(FileCreate val | FileChmod val | FileChown val | FileLink val | FileLookup val | FileMkdir val | FileRead val | FileRemove val | FileRename val | FileSeek val | FileStat val | FileSync val | FileTime val | FileTruncate val | FileWrite val | FileExec val), U32 val] val = recover

Returns¶

FilePath val^ ?

Public fields¶
let path: String val¶
[Source]
Absolute filesystem path.

let caps: Flags[(FileCreate val | FileChmod val | FileChown val | FileLink val | FileLookup val | FileMkdir val | FileRead val | FileRemove val | FileRename val | FileSeek val | FileStat val | FileSync val | FileTime val | FileTruncate val | FileWrite val | FileExec val), U32 val] ref¶
[Source]
Set of capabilities for operations on path.

Public Functions¶
join¶
[Source]


new create(env: Env) =>
let actor1 = Actor1
let actor2 = Actor2
let actor3 = Actor3

let custodian = Custodian
custodian(actor1)
custodian(actor2)
custodian(actor3)

SignalHandler(TermHandler(custodian), Sig.term())

class TermHandler is SignalNotify
let _custodian: Custodian

new iso create(custodian: Custodian) =>
_custodian = custodian

fun ref apply(count: U32): Bool =>
_custodian.dispose()


The For-loop provides a more concise way of iteration:
for elem in iterator do
// do something with elem
end

Iteration using While is more flexible as it allows to continue iterating if a call to next() errors.
The For-loop does not allow this.
Implementing Iterators¶
Iterator implementations need to adhere to the following rules to be considered well-behaved:

If the Iterator is exhausted, has_next() needs to return false.
Once has_next() returned false it is not allowed to switch back to true
(Unless the Iterator supports rewinding)
has_next() does not change its returned value if next() has not been called.
That means, that between two calls to next() any number of calls to has_next()
need to return the same value. (Unless the Iterator supports rewinding)
A call to next() erroring does not necessarily denote exhaustiveness.

Example¶


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


fun box mcast_leave_group()
: I32 val

Returns¶

I32 val

mcast_leave_source_group¶
[Source]
fun box mcast_leave_source_group()
: I32 val

Returns¶

I32 val

mcast_msfilter¶
[Source]


connecting¶
[Source]
Called if name resolution succeeded for a TCPConnection and we are now
waiting for a connection to the server to succeed. The count is the number
of connections we're trying. The notifier will be informed each time the
count changes, until a connection is made or connect_failed() is called.
fun ref connecting(
conn: TCPConnection ref,
count: U32 val)
: None val

Parameters¶

conn: TCPConnection ref
count: U32 val

Returns¶


"""
_started = _started + 1

try
if not _no_prog then
_env.out.print(
_started.string() + " test" + _plural(_started)
+ " started, " + _finished.string() + " complete: "
+ _records(id)?.name + " started")
end
end

be _test_complete(id: USize, pass: Bool, log: Array[String] val) =>
"""
A test has completed, restore its result and update our status info.
The id parameter is the test identifier handed out when we created the test
helper.
"""
_finished = _finished + 1


while i < _size do
if predicate(_ptr._apply(i), value) then
if n == nth then
return i
end

n = n + 1
end

i = i + 1
end

error

fun contains(
value: A!,
predicate: {(box->A!, box->A!): Bool} val =
{(l: box->A!, r: box->A!): Bool => l is r })
: Bool
=>


fun box sctp_reuse_port()
: I32 val

Returns¶

I32 val

sctp_rtoinfo¶
[Source]
fun box sctp_rtoinfo()
: I32 val

Returns¶

I32 val

sctp_rttvar_logging_enable¶
[Source]


alloc: USize val = 0

Returns¶

String ref^

from_cstring¶
[Source]
Return a string from a pointer to a null-terminated cstring
without making a copy. The data is not copied. This must be done
only with C-FFI functions that return pony_alloc'd character
arrays. The pointer is scanned for the first null byte, which will
be interpreted as the null terminator. Note that the scan is
unbounded; the pointed to data must be null-terminated within
the allocated array to preserve memory safety. If a null pointer
is given then an empty string is returned.
new ref from_cstring(
str: Pointer[U8 val] ref)
: String ref^


192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211


actor Main
new create(env: Env) =>
let promise = Promise[String]
promise.next[String](recover PrintFulfill(env, "foo") end)
promise.next[String](recover PrintFulfill(env, "bar") end)
promise.next[String](recover PrintFulfill(env, "baz") end)
promise("fulfilled")

In the following code, the fulfill functions are chained together so
that the fulfilled value of the first one is used to generate a value
which fulfills the second one, which in turn is used to compute a
value which fulfills the third one, which in turn is used to compute a
value which fulfills the fourth one. The output is the average length
of the words passed on the command line or 0 if there are no command
line arguments.
use "promises"

primitive Computation
fun tag string_to_strings(s: String): Array[String] val =>
recover s.split() end


fun ref zip2[B, C](i2: Iterator[B], i3: Iterator[C]): Iter[(A, B, C)]^ =>
"""
Zip three iterators together so that each call to next() results in
a tuple with the next value of the first iterator, the next value
of the second iterator, and the value of the third iterator. The
number of items returned is the minimum of the number of items
returned by the three iterators.
"""
Iter[(A, B, C)](
object is Iterator[(A, B, C)]
let _i1: Iterator[A] = _iter
let _i2: Iterator[B] = i2
let _i3: Iterator[C] = i3

fun ref has_next(): Bool =>
_i1.has_next() and _i2.has_next() and _i3.has_next()

fun ref next(): (A, B, C) ? =>
(_i1.next()?, _i2.next()?, _i3.next()?)
end)


new ref chain(
outer_iterator: Iterator[Iterator[A] ref] ref)
: Iter[A] ref^

Parameters¶

outer_iterator: Iterator[Iterator[A] ref] ref

Returns¶

Iter[A] ref^

repeat_value¶
[Source]
Create an iterator that returns the given value forever.
Example¶
Iter[U32].repeat_value(7)

7 7 7 7 7 7 7 7 7 ...


fun box sctp_pcb_flags_needs_mapped_v4()
: I32 val

Returns¶

I32 val

sctp_pcb_flags_nodelay¶
[Source]
fun box sctp_pcb_flags_nodelay()
: I32 val

Returns¶

I32 val

sctp_pcb_flags_no_fragment¶
[Source]


fun box u32()
: U32 val

Returns¶

U32 val

u64¶
[Source]
fun box u64()
: U64 val

Returns¶

U64 val

u128¶
[Source]


let mask = U64(0x00000000FFFFFFFF)

var lo = (x_lo and mask) * (y_lo and mask)
var t = lo >> 32
lo = lo and mask
t = t + ((x_lo >> 32) * (y_lo and mask))
lo = lo + ((t and mask) << 32)

var hi = t >> 32
t = lo >> 32
lo = lo and mask
t = t + ((y_lo >> 32) * (x_lo and mask))
lo = lo + ((t and mask) << 32)
hi = hi + (t >> 32)
hi = hi + ((x_lo >> 32) * (y_lo >> 32))
hi = hi + (x_hi * y_lo) + (x_lo * y_hi)

(hi.u128() << 64) or lo.u128()
end


if not args.contains(ars.name()) then // latest arg may be a seq
if ars.required() then
return SyntaxError(ars.name(), "missing value for required argument")
end
args.update(ars.name(), Arg(ars, ars._default_p()))
end
end
arg_pos = arg_pos + 1
end

// Specifying only the parent and not a leaf command is an error.
if _spec.is_parent() then
return SyntaxError(_spec.name(), "missing subcommand")
end

// A successfully parsed and populated leaf Command.
Command._create(_spec, _fullname(), consume options, args)

fun _parse_long_option(
token: String,


I64 val

i128_unsafe¶
[Source]
fun box i128_unsafe()
: I128 val

Returns¶

I128 val

ilong_unsafe¶
[Source]
fun box ilong_unsafe()
: ILong val

Returns¶


fun box rds_rdma_readwrite()
: I32 val

Returns¶

I32 val

rds_rdma_remote_error¶
[Source]
fun box rds_rdma_remote_error()
: I32 val

Returns¶

I32 val

rds_rdma_silent¶
[Source]


None

class MyTCPListenNotify is TCPListenNotify
fun ref connected(listen: TCPListener ref): TCPConnectionNotify iso^ =>
MyTCPConnectionNotify

fun ref not_listening(listen: TCPListener ref) =>
None

actor Main
new create(env: Env) =>
TCPListener(TCPListenAuth(env.root),
recover MyTCPListenNotify end, "", "8989")
```
"""
var _notify: TCPListenNotify
var _fd: U32
var _event: AsioEventID = AsioEvent.none()
var _closed: Bool = false
let _limit: USize


Number¶
[Source]
type Number is
(I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val)

Type Alias For¶

(I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val)


fun box ipproto_hip()
: I32 val

Returns¶

I32 val

ipproto_hmp¶
[Source]
fun box ipproto_hmp()
: I32 val

Returns¶

I32 val

ipproto_hopopts¶
[Source]


end
// reset position to not disturb other operations on the file
// we only actually advance the cursor if the line is returned.
_file.seek_start(current_pos)
result

fun ref _read_last_line(): String iso^ ? =>
let block = _reader.block(_reader.size())?
_inc_public_file_cursor(block.size())
String.from_iso_array(consume block)

fun ref _inc_public_file_cursor(amount: USize) =>
_cursor = _cursor + amount
_file.seek_start(_cursor)


try
that(value)?
r.set(value)
end
end
r

fun op_xor[K: HashFunction[this->A!] val = H](
that: this->HashSet[A, H])
: HashSet[this->A!, K]^
=>
"""
Create a set with the elements that are in either set but not both.
"""
let r = HashSet[this->A!, K](size().max(that.size()))

for value in values() do
try
that(value)?
else


)
elseif value < 0xE000 then
// UTF-16 surrogate pairs are not allowed.
(3, 0xEF, 0xBF, 0xBD, 0)
elseif value < 0x10000 then
( 3,
((value >> 12) or 0xE0).u8(),
(((value >> 6) and 0x3F) or 0x80).u8(),
((value and 0x3F) or 0x80).u8(),
0
)
elseif value < 0x110000 then
( 4,
((value >> 18) or 0xF0).u8(),
(((value >> 12) and 0x3F) or 0x80).u8(),
(((value >> 6) and 0x3F) or 0x80).u8(),
((value and 0x3F) or 0x80).u8()
)
else
// Code points beyond 0x10FFFF are not allowed.


I16 val

i32_unsafe¶
[Source]
fun box i32_unsafe()
: I32 val

Returns¶

I32 val

i64_unsafe¶
[Source]
fun box i64_unsafe()
: I64 val

Returns¶


Parameters¶

y: ISize val

Returns¶

ISize val

mul_unsafe¶
[Source]
fun box mul_unsafe(
y: ISize val)
: ISize val

Parameters¶

y: ISize val

Returns¶


chown¶
[Source]
Set the owner and group for a path. Does nothing on Windows.
fun box chown(
uid: U32 val,
gid: U32 val)
: Bool val

Parameters¶

uid: U32 val
gid: U32 val

Returns¶

Bool val

touch¶


```pony
interface Equatable[A: Equatable[A] #read]
fun eq(that: box->A): Bool => this is that
fun ne(that: box->A): Bool => not eq(that)
```


252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271


_ptr = Pointer[U8]._alloc(_alloc)
_set(0, encoded._2)
if encoded._1 > 1 then
_set(1, encoded._3)
if encoded._1 > 2 then
_set(2, encoded._4)
if encoded._1 > 3 then
_set(3, encoded._5)
end
end
end
_set(_size, 0)

fun ref push_utf32(value: U32) =>
"""
Push a UTF-32 code point.
"""
let encoded = _UTF32Encoder.encode(value)
let i = _size
_size = _size + encoded._1


Generator[T] box

seq_of[T: T, S: Seq[T] ref]¶
[Source]
Create a Seq from the values of the given Generator with an optional
minimum and maximum size.
Defaults are 0 and 100, respectively.
fun box seq_of[T: T, S: Seq[T] ref](
gen: Generator[T] box,
min: USize val = 0,
max: USize val = 100)
: Generator[S] box

Parameters¶

gen: Generator[T] box
min: USize val = 0
max: USize val = 100


false
end

fun remove(target: String): Bool =>
"""
Remove the file or directory. The directory contents will be removed as
well, recursively. Symlinks will be removed but not traversed.
"""
if
not path.caps(FileLookup)
or not path.caps(FileRemove)
or (_fd == -1)
then
return false
end

try
let path' = FilePath.from(path, target, path.caps)?

ifdef linux or bsd then


fun box has_next()
: Bool val

Returns¶

Bool val

next¶
[Source]
Returns the next key, or raises an error if there isn't one. If keys are
added during iteration, this may not return all keys.
fun ref next()
: M->K ?

Returns¶

M->K ?


/* NOTE: if you change any of the field docstrings, update `options.h` in
*       the runtime to keep them in sync.
*/

var ponymaxthreads: U32 = 0
"""
Use N scheduler threads. Defaults to the number of cores (not hyperthreads)
available.
This can't be larger than the number of cores available.
"""

var ponyminthreads: U32 = 0
"""
Minimum number of active scheduler threads allowed.
Defaults to 0, meaning that all scheduler threads are allowed to be
suspended when no work is available.
This can't be larger than --ponymaxthreads if provided, or the physical
cores available.
"""


f32_unsafe¶
[Source]
fun box f32_unsafe()
: F32 val

Returns¶

F32 val

f64_unsafe¶
[Source]
fun box f64_unsafe()
: F64 val

Returns¶

F64 val


# Actors are cheap

If you've done concurrent programming before, you'll know that threads can be expensive. Context switches can cause problems, each thread needs a stack (which can be a lot of memory), and you need lots of locks and other mechanisms to write thread-safe code.

But actors are cheap. Really cheap. The extra cost of an actor, as opposed to an object, is about 256 bytes of memory. Bytes, not kilobytes! And there are no locks and no context switches. An actor that isn't executing consumes no resources other than the few extra bytes of memory.

It's pretty normal to write a Pony program that uses hundreds of thousands of actors.


fun box usize_unsafe()
: USize val

Returns¶

USize val

f32_unsafe¶
[Source]
fun box f32_unsafe()
: F32 val

Returns¶

F32 val

f64_unsafe¶
[Source]


F64 val) & Real[A] val)](
a: A)
: I64 val^

Parameters¶

a: A

Returns¶

I64 val^

min_value¶
[Source]
new val min_value()
: I64 val^

Returns¶


AsioEventID¶
[Source]
type AsioEventID is
Pointer[AsioEvent val] tag

Type Alias For¶

Pointer[AsioEvent val] tag


concurrent tests.
fun box log(
msg: String val,
verbose: Bool val = false)
: None val

Parameters¶

msg: String val
verbose: Bool val = false

Returns¶

None val

fail¶
[Source]
Flag the test as having failed.
fun box fail(


Multiple objects can be set up for disposal:

```pony
with obj = SomeObjectThatNeedsDisposing(), other = SomeOtherDisposableObject() do
// use obj
end
```

The value of a `with` expression is the value of the last expression in the block.


if with_ext then
b
else
let e_size = ext(b).size()

if e_size > 0 then
b.trim(0, b.size() - e_size - 1)
else
b
end
end

fun dir(path: String): String =>
"""
Return a cleaned path before the last separator, or the whole path if there
is no separator.
"""
try
clean(path.trim(0, path.rfind(sep())?.usize()))
else


fun box ipproto_maxid()
: I32 val

Returns¶

I32 val

ipproto_meas¶
[Source]
fun box ipproto_meas()
: I32 val

Returns¶

I32 val

ipproto_mh¶
[Source]


"""
this >~ y

fun abs(): A
fun ceil(): A
fun floor(): A
fun round(): A
fun trunc(): A

fun finite(): Bool
fun infinite(): Bool
fun nan(): Bool

fun ldexp(x: A, exponent: I32): A
fun frexp(): (A, U32)
fun log(): A
fun log2(): A
fun log10(): A
fun logb(): A


332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351


F64¶
[Source]
primitive val F64 is
FloatingPoint[F64 val] val

Implements¶

FloatingPoint[F64 val] val

Constructors¶
create¶
[Source]


fun box i64_unsafe()
: I64 val

Returns¶

I64 val

i128_unsafe¶
[Source]
fun box i128_unsafe()
: I128 val

Returns¶

I128 val

ilong_unsafe¶
[Source]


fun box so_label()
: I32 val

Returns¶

I32 val

so_linger¶
[Source]
fun box so_linger()
: I32 val

Returns¶

I32 val

so_linger_sec¶
[Source]


NullablePointer[A: A]¶
[Source]
A NullablePointer[A] is used to encode a possibly-null type. It should
only be used for structs that need to be passed to and from the C FFI.
An optional type for anything that isn't a struct should be encoded as a
union type, for example (A | None).
struct ref NullablePointer[A: A]

Constructors¶
create¶
[Source]
This re-encodes the type of that from A to NullablePointer[A], allowing
that to be assigned to a field or variable of type NullablePointer[A]. It


new val create(
value: ISize val)
: ISize val^

Parameters¶

value: ISize val

Returns¶

ISize val^

from[A: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val) & Real[A] val)]¶
[Source]
new val from[A: ((I8 val | I16 val | I32 val |
I64 val | I128 val | ILong val |
ISize val | U8 val | U16 val |
U32 val | U64 val | U128 val |
ULong val | USize val | F32 val |


new chain(outer_iterator: Iterator[Iterator[A]]) =>
"""
Take an iterator of iterators and return an Iter containing the
items of the first one, then the second one, and so on.


fun box div_partial(
y: I16 val)
: I16 val ?

Parameters¶

y: I16 val

Returns¶

I16 val ?

rem_partial¶
[Source]
fun box rem_partial(
y: I16 val)
: I16 val ?

Parameters¶


Alternatively, these fields could be assigned in the constructor method:

```pony
class Wombat
let name: String
var _hunger_level: U32

new create(hunger: U32) =>
name = "Fantastibat"
_hunger_level = hunger
```

If the assignment is not done at the definition level or in the constructor, an error is raised by the compiler. This is true for both `var` and `let` fields.

Please note that the assignment of a value to a field has to be explicit. The below example raises an error when compiled, even when the field is of `var` type:

```pony
class Wombat
let name: String


fun name(): String => "my_property"

fun gen(): Generator[String] =>
Generators.ascii_printable()

fun property(arg1: String, h: PropertyHelper) =>
h.assert_true(arg1.size() > 0)

actor Main is TestList
new create(env: Env) => PonyTest(env, this)

fun tag tests(test: PonyTest) =>
test(Property1UnitTest[String](MyProperty))

```
"""

var _prop1: ( Property1[T] iso | None )
let _name: String


be eat(amount: U64) =>
_hunger_level = _hunger_level - amount.min(_hunger_level)
```

Here we have an `Aardvark` that can eat asynchronously. Clever Aardvark.


I8 val ?

mul_partial¶
[Source]
fun box mul_partial(
y: I8 val)
: I8 val ?

Parameters¶

y: I8 val

Returns¶

I8 val ?

div_partial¶
[Source]


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


create¶
[Source]
Create infrastructure to communicate with a forked child process and
register the asio events. Fork child process and notify our user about
incoming data via the notifier.
new tag create(
auth: StartProcessAuth val,
backpressure_auth: ApplyReleaseBackpressureAuth val,
notifier: ProcessNotify iso,
filepath: FilePath val,
args: Array[String val] val,
vars: Array[String val] val,
wdir: (FilePath val | None val) = reference,
process_poll_interval: U64 val = call)
: ProcessMonitor tag^

Parameters¶

auth: StartProcessAuth val
backpressure_auth: ApplyReleaseBackpressureAuth val


Returns¶

Bool val

dispose¶
[Source]
Close the directory.
fun ref dispose()
: None val

Returns¶

None val


Public Functions¶
eq¶
[Source]
fun box eq(
that: DebugOut val)
: Bool val

Parameters¶

that: DebugOut val

Returns¶

Bool val

ne¶
[Source]


USize¶
[Source]
primitive val USize is
UnsignedInteger[USize val] val

Implements¶

UnsignedInteger[USize val] val

Constructors¶
create¶
[Source]


## Functions

Like Pony classes, Pony structs can also have functions. Everything you know about functions on Pony classes applies to structs as well.


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131


272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911


fun box so_atmpvc()
: I32 val

Returns¶

I32 val

so_atmqos¶
[Source]
fun box so_atmqos()
: I32 val

Returns¶

I32 val

so_atmsap¶
[Source]


1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211


Parameters¶

y: ISize val

Returns¶

ISize val

neg_unsafe¶
[Source]
fun box neg_unsafe()
: ISize val

Returns¶

ISize val

op_and¶


trait HasName
fun name(): String => "Bob"

trait HasAge
fun age(): U32 => 42

trait HasFeelings
fun feeling(): String => "Great!"

type Person is (HasName & HasAge & HasFeelings)
```

There's another new concept here: the type has a `&` in it. This is similar to the `|` of a __union__ type: it means this is an __intersection__ type. That is, it's something that must be _all_ of `HasName`, `HasAge` _and_ `HasFeelings`.

But the use of `type` here is exactly the same as the enumeration example above, it's just providing a name for a type that is otherwise a bit tedious to type out over and over.

Another example, this time from the standard library, is `SetIs`. Here's the actual definition:

```pony
type SetIs[A] is HashSet[A, HashIs[A!]]


Public Functions¶
eq¶
[Source]
fun box eq(
that: FileExists val)
: Bool val

Parameters¶

that: FileExists val

Returns¶

Bool val

ne¶
[Source]


fun box modc(
y: U64 val)
: (U64 val , Bool val)

Parameters¶

y: U64 val

Returns¶

(U64 val , Bool val)

mod_partial¶
[Source]
fun box mod_partial(
y: U64 val)
: U64 val ?

Parameters¶


y: I128 val

Returns¶

Bool val

ne¶
[Source]
fun box ne(
y: I128 val)
: Bool val

Parameters¶

y: I128 val

Returns¶


sample: IntPropertySample ref,
h: PropertyHelper val)
: None val ?

Parameters¶

sample: IntPropertySample ref
h: PropertyHelper val

Returns¶

None val ?

int_property[T: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Integer[T] val)]¶
[Source]
fun ref int_property[T: ((I8 val | I16 val | I32 val |
I64 val | I128 val | ILong val |
ISize val | U8 val | U16 val |
U32 val | U64 val | U128 val |


else
_current.push_u128(data.bswap())
end
_size = _size + num_bytes

fun ref i128_le(data: I128) =>
"""
Write an I128 to the buffer in little-endian byte order.
"""
u128_le(data.u128())

fun ref i128_be(data: I128) =>
"""
Write an I128 to the buffer in big-endian byte order.
"""
u128_be(data.u128())

fun ref write(data: ByteSeq) =>
"""
Write a ByteSeq to the buffer.


292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311


352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371


Returns the i-th byte. Raise an error if the index is out of bounds.
"""
if i < _size then _ptr._apply(i) else error end

fun ref update(i: USize, value: U8): U8 ? =>
"""
Change the i-th byte. Raise an error if the index is out of bounds.
"""
if i < _size then
_set(i, value)
else
error
end

fun at_offset(offset: ISize): U8 ? =>
"""
Returns the byte at the given offset. Raise an error if the offset is out
of bounds.
"""
this(offset_to_index(offset))?


192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211"""


1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371


if (s.size() % 2) == 0 then
_ph.complete_action("is_even")
else
_ph.fail_action("is_even")

class EvenStringProperty is Property1[String]
fun name(): String => "even_string"

fun gen(): Generator[String] =>
Generators.ascii()

fun property(arg1: String, ph: PropertyHelper) =>
ph.expect_action("is_even")
AsyncActor(ph).check(arg1)
```

"""
_runner.expect_action(name, _run)

fun val complete_action(name: String) =>


fun box tcpolen_timestamp()
: I32 val

Returns¶

I32 val

tcpolen_tstamp_appa¶
[Source]
fun box tcpolen_tstamp_appa()
: I32 val

Returns¶

I32 val

tcpolen_window¶
[Source]


// Try again
primitive _EAGAIN
fun apply(): I32 =>
ifdef bsd or osx then 35
elseif linux then 11
elseif windows then 22
else compile_error "no EAGAIN" end

// Invalid argument
primitive _EINVAL
fun apply(): I32 => 22

primitive _EXOSERR
fun apply(): I32 => 71

// For handling errors between @fork and @execve
primitive _StepChdir
fun apply(): U8 => 1


None val


Bool val

ne¶
[Source]
fun box ne(
that: NetAuth val)
: Bool val

Parameters¶

that: NetAuth val

Returns¶

Bool val


1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671


fun box fchmod()
: U64 val

Returns¶

U64 val

fchmodat¶
[Source]
fun box fchmodat()
: U64 val

Returns¶

U64 val

fchown¶
[Source]


Int¶
[Source]
type Int is
(I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val)

Type Alias For¶

(I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val)


fun so_no_ddp():I32 => @pony_os_sockopt_option(I32(862))
fun so_no_offload():I32 => @pony_os_sockopt_option(I32(863))
fun so_np_extensions():I32 => @pony_os_sockopt_option(I32(864))
fun so_nread():I32 => @pony_os_sockopt_option(I32(865))
fun so_numrcvpkt():I32 => @pony_os_sockopt_option(I32(866))
fun so_nwrite():I32 => @pony_os_sockopt_option(I32(867))
fun so_oobinline():I32 => @pony_os_sockopt_option(I32(868))
fun so_original_dst():I32 => @pony_os_sockopt_option(I32(869))
fun so_passcred():I32 => @pony_os_sockopt_option(I32(870))
fun so_passsec():I32 => @pony_os_sockopt_option(I32(871))
fun so_peek_off():I32 => @pony_os_sockopt_option(I32(872))
fun so_peercred():I32 => @pony_os_sockopt_option(I32(873))
fun so_peerlabel():I32 => @pony_os_sockopt_option(I32(874))
fun so_peername():I32 => @pony_os_sockopt_option(I32(875))
fun so_peersec():I32 => @pony_os_sockopt_option(I32(876))
fun so_port_scalability():I32 => @pony_os_sockopt_option(I32(877))
fun so_priority():I32 => @pony_os_sockopt_option(I32(878))
fun so_protocol():I32 => @pony_os_sockopt_option(I32(879))
fun so_protocol_info():I32 => @pony_os_sockopt_option(I32(880))
fun so_prototype():I32 => @pony_os_sockopt_option(I32(881))


# Memory allocation
Array allocates contiguous memory. It always allocates at least enough memory
space to hold all of its elements. Space is the number of elements the Array
can hold without allocating more memory. The `space()` method returns the
number of elements an Array can hold. The `size()` method returns the number
of elements the Array holds.

Different data types require different amounts of memory. Array[U64] with size
of 6 will take more memory than an Array[U8] of the same size.

When creating an Array or adding more elements will calculate the next power
of 2 of the requested number of elements and allocate that much space, with a
lower bound of space for 8 elements.

Here's a few examples of the space allocated when initialising an Array with
various number of elements:

| size | space |
|------|-------|
| 0    | 0     |


fun box icmp_timestampreply()
: I32 val

Returns¶

I32 val

icmp_time_exceeded¶
[Source]
fun box icmp_time_exceeded()
: I32 val

Returns¶

I32 val

ipctl_acceptsourceroute¶
[Source]


fun box lt(
y: I64 val)
: Bool val

Parameters¶

y: I64 val

Returns¶

Bool val

le¶
[Source]
fun box le(
y: I64 val)
: Bool val

Parameters¶


Bool val

ne¶
[Source]
fun box ne(
that: FileAuth val)
: Bool val

Parameters¶

that: FileAuth val

Returns¶

Bool val


new val create()
: FormatHexSmall val^

Returns¶

FormatHexSmall val^

Public Functions¶
eq¶
[Source]
fun box eq(
that: FormatHexSmall val)
: Bool val

Parameters¶

that: FormatHexSmall val

Returns¶


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


fun box icmp_echoreply()
: I32 val

Returns¶

I32 val

icmp_exc_fragtime¶
[Source]
fun box icmp_exc_fragtime()
: I32 val

Returns¶

I32 val

icmp_exc_ttl¶
[Source]


Parameters¶

y: A

Returns¶

A

fldc¶
[Source]
fun box fldc(
y: A)
: (A , Bool val)

Parameters¶

y: A

Returns¶


: I64 val

Returns¶

I64 val

i128¶
[Source]
fun ref i128()
: I128 val

Returns¶

I128 val

ilong¶
[Source]
fun ref ilong()


232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251


fun box ipx_address_notify()
: I32 val

Returns¶

I32 val

ipx_crtitf¶
[Source]
fun box ipx_crtitf()
: I32 val

Returns¶

I32 val

ipx_dltitf¶
[Source]


XorShift128Plus¶
[Source]
This is an implementation of xorshift+, as detailed at:
http://xoroshiro.di.unimi.it
This should only be used for legacy applications that specifically require
XorShift128Plus, otherwise use Rand.
class ref XorShift128Plus is
Random ref

Implements¶

Random ref


### Example

```pony
Iter[I64]([1; 2; 3; 4; 5; 6].values())
.take(3)
```
`1 2 3`
"""
Iter[A](
object
var _countdown: USize = n

fun ref has_next(): Bool =>
(_countdown > 0) and _iter.has_next()

fun ref next(): A ? =>
if _countdown > 0 then
_countdown = _countdown - 1
_iter.next()?
else


that: box->A

Returns¶

(Less val | Equal val | Greater val)


Bool val


## Repeat

The final loop construct that Pony provides is `repeat` `until`. Here we evaluate the expression in the loop and then evaluate a condition expression to see if we're done or we should go round again.

This is similar to `do` `while` in C++, C# and Java, except that the termination condition is reversed; i.e. those languages terminate the loop when the condition expression is false, but Pony terminates the loop when the condition expression is true.

The differences between `while` and `repeat` in Pony are:

1. We always go around the loop at least once with `repeat`, whereas with `while` we may not go round at all.
2. The termination condition is reversed.

Suppose we're trying to create something and we want to keep trying until it's good enough:

```pony
actor Main
new create(env: Env) =>
var counter = U64(1)
repeat
env.out.print("hello!")
counter = counter + 1


fun ref _set_time(): U64 =>
"""
Set the current time with precision reduced by the slop bits. Return the
elapsed time.
"""
let previous = _current = Time.nanos() >> _slop.u64()
_current - previous

fun ref _get_wheel(rem: U64): _TimingWheel ? =>
"""
Get the hierarchical timing wheel for the given time until expiration.
"""
let t = rem.min(_expiration_max())
let i = ((t.bitwidth() - t.clz()) - 1).usize() / _bits()
_wheel(i)?

fun tag _expiration_max(): U64 =>
"""
Get the maximum time the timing wheels cover. Anything beyond this is


end

fun info(): U32 =>
ifdef bsd or osx then 29
else compile_error "no SIGINFO"
end

fun pwr(): U32 =>
ifdef linux then 30
else compile_error "no SIGPWR"
end

fun usr1(): U32 =>
ifdef bsd or osx then 30
elseif linux then 10
else compile_error "no SIGUSR1"
end

fun usr2(): U32 =>
ifdef not "scheduler_scaling_pthreads" then


Parameters¶

from: Random ref

Returns¶

Dice ref^

Public fields¶
var r: Random ref¶
[Source]

Public Functions¶
apply¶
[Source]
Return the sum of count rolls of a die with the given number of sides.
The die is numbered from 1 to sides. For example, count = 2 and
sides = 6 will return a value between 2 and 12.
fun ref apply(


any double underscore (__) is converted to a
single underscore (_).

These constants are not stable between Pony releases.
Values returned by this function may be held by long-lived variables
by the calling process: values cannot change while the process runs.
Programmers must not cache any of these values for purposes of
sharing them for use by any other Pony program (for example,
sharing via serialization & deserialization or via direct
shared memory).
Many functions may return -1, which means that the constant's
value could not be determined at the Pony runtime library compile
time.  One cause may be that the option truly isn't available,
for example, the option level constant IPPROTO_3PC is available
on MacOS 10.x but not on Linux 4.4.  Another cause may be the
Pony runtime library's compilation did not include the correct
header file(s) for the target OS platform.
A third cause of error is due to the regular expression-based
approach used to harvest desirable constants.  It is not fool-proof.
The regexp used is too broad and finds some macros that are not


cycles¶
[Source]
Processor cycle count. Don't use this for performance timing, as it does
not control for out-of-order execution.
fun box cycles()
: U64 val

Returns¶

U64 val

perf_begin¶
[Source]
Get a cycle count for beginning a performance testing block. This will
will prevent instructions from before this call leaking into the block and
instructions after this call being executed earlier.
fun box perf_begin()
: U64 val


HashMap[K: Any #share, V: Any #share, H: HashFunction[K] val]¶
[Source]
A persistent map based on the Compressed Hash Array Mapped Prefix-tree from
'Optimizing Hash-Array Mapped Tries for Fast and Lean Immutable JVM
Collections' by Michael J. Steindorfer and Jurgen J. Vinju
Usage¶
use "collections/persistent"

actor Main
new create(env: Env) =>
try
let m1 = Map[String, U32] // {}
// Update returns a new map with the provided key set


message for a given CommandSpec, optionally with a specific command
identified to print help about. Use `Help.general()` or `Help.for_command()`
to create a CommandHelp instance.
"""
let _parent: (CommandHelp box | None)
let _spec: CommandSpec box

new _create(parent': (CommandHelp box | None), spec': CommandSpec box) =>
_parent = parent'
_spec = spec'

fun fullname(): String =>
match _parent
| let p: CommandHelp => p.fullname() + " " + _spec.name()
else
_spec.name()
end

fun string(): String => fullname()


212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231


fun box sctp_data()
: I32 val

Returns¶

I32 val

sctp_data_first_frag¶
[Source]
fun box sctp_data_first_frag()
: I32 val

Returns¶

I32 val

sctp_data_frag_mask¶
[Source]


due to the use of type identifiers rather than a heavy-weight self-describing
serialisation schema. This also means it isn't safe to deserialise something
serialised by the same program compiled for a different platform.
The Serialise.signature method is provided
for the purposes of comparing communicating Pony binaries to determine if they
are the same. Confirming this before deserialising data can help mitigate the
risk of accidental serialisation across different Pony binaries, but does not on
its own address the security issues of accepting data from untrusted sources.
Public Types¶

primitive DeserialiseAuth
primitive InputSerialisedAuth
primitive OutputSerialisedAuth
primitive Serialise
primitive SerialiseAuth
class Serialised


I64 val

i128_unsafe¶
[Source]
fun box i128_unsafe()
: I128 val

Returns¶

I128 val

ilong_unsafe¶
[Source]
fun box ilong_unsafe()
: ILong val

Returns¶


Parameters¶

that: CommonPrefix val

Returns¶

Bool val


fun box rem(
y: A)
: A

Parameters¶

y: A

Returns¶

A

neg¶
[Source]
fun box neg()
: A

Returns¶


Parameters¶

i: USize val
value: val->A

Returns¶

Vec[A] val ?

delete¶
[Source]
Return a vector with an element deleted. Elements after this are moved
down by one index, compacting the vector. An out of bounds index raises an
error.
fun val delete(
i: USize val)
: Vec[A] val ?


BinaryHeapPriority[A: Comparable[A] #read]¶
[Source]
type BinaryHeapPriority[A: Comparable[A] #read] is
(_BinaryHeapPriority[A] val & (MinHeapPriority[A] val | MaxHeapPriority[A] val))

Type Alias For¶

(_BinaryHeapPriority[A] val & (MinHeapPriority[A] val | MaxHeapPriority[A] val))


252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271


after_iteration¶
[Source]
fun ref after_iteration(
c: AsyncBenchContinue val)
: None val

Parameters¶

c: AsyncBenchContinue val

Returns¶

None val


152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111


fun box kqueue_change()
: U64 val

Returns¶

U64 val

kqueue¶
[Source]
fun box kqueue()
: U64 val

Returns¶

U64 val

eq¶
[Source]


USize val

f32¶
[Source]
fun box f32()
: F32 val

Returns¶

F32 val

f64¶
[Source]
fun box f64()
: F64 val

Returns¶


fun box u8_unsafe()
: U8 val

Returns¶

U8 val

u16_unsafe¶
[Source]
fun box u16_unsafe()
: U16 val

Returns¶

U16 val

u32_unsafe¶
[Source]


var _current: Array[U8] iso = recover Array[U8] end
var _size: USize = 0

fun ref reserve_chunks(size': USize) =>
"""
Reserve space for size' chunks.

This needs to be recalled after every call to `done`
as `done` resets the chunks.
"""
_chunks.reserve(size')

fun ref reserve_current(size': USize) =>
"""
Reserve space for size bytes in `_current`.
"""
_current.reserve(_current.size() + size')

fun size(): USize =>
_size


m.upsert("new-key", 4, {(current, provided) => current + provided })

then "new-key" is added to the map with a value of 4.

Returns the value that we set the key to
"""

(let i, let found) = _search(key)
let value' = value

try
if found then
(let pkey, let pvalue) = (_array(i)? = _MapEmpty) as (K^, V^)

let new_value = f(consume pvalue, consume value)
let new_value' = new_value

_array(i)? = (consume pkey, consume new_value)


ISize val

neg¶
[Source]
fun box neg()
: ISize val

Returns¶

ISize val

eq¶
[Source]
fun box eq(
y: ISize val)
: Bool val


create¶
[Source]
new val create()
: HashSet[A, H] val^

Returns¶

HashSet[A, H] val^

Public Functions¶
size¶
[Source]
Return the number of elements in the set.
fun box size()
: USize val

Returns¶

USize val


|         | (2) to indicate a function return type                                          |
|         | (3) a type constraint                                                           |
| `;`     | only used to separate expressions on the same line                              |
| `=`     | (1) (destructive) assignment                                                    |
|         | (2) in: use alias = package name                                                    |
|         | (3) supply default argument for method                                          |
|         | (4) supply default type for generics                                            |
| `!`     | (1) boolean negation                                                            |
|         | (2) a type that is an alias of another type                                     |
| `?`     | (1) partial functions                                                           |
|         | (2) a call to a C function that could raise an error                            |
| `-`     | (1) start of line: unary negation                                               |
|         | (2) middle of line: subtraction                                                 |
| `_`     | (1) to indicate a private variable, constructor, function, behavior             |
|         | (2) to ignore a tuple item in a pattern match                                   |
| `~`     | partial application                                                             |
| `^`     | an ephemeral type                                                               |
| |  | (1) separates the types in an enumeration (the value can be any of these types) |
|         | (2) starts a branch in a match                                                  |
| `&`     | (1) separates the types in a complex type (the value is of all of these types)  |


fun box f64()
: F64 val

Returns¶

F64 val

i8_unsafe¶
[Source]
fun box i8_unsafe()
: I8 val

Returns¶

I8 val

i16_unsafe¶
[Source]


ForkError¶
[Source]
primitive val ForkError

Constructors¶
create¶
[Source]
new val create()
: ForkError val^

Returns¶

ForkError val^


fun box i16()
: I16 val

Returns¶

I16 val

i32¶
[Source]
fun box i32()
: I32 val

Returns¶

I32 val

i64¶
[Source]


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151


Public Functions¶
general¶
[Source]
Creates a command help that can print a general program help message.
fun box general(
cs: CommandSpec box)
: CommandHelp box

Parameters¶

cs: CommandSpec box

Returns¶

CommandHelp box

for_command¶


612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631


and the actual property function. (Note that the property function is supplied
in a second application of the result to `for_all`.)

```pony
class ListReversePropertyWithinAUnitTest is UnitTest
fun name(): String => "list/reverse/forall"

fun apply(h: TestHelper) =>
let gen = recover val Generators.list_of[USize](Generators.usize()) end
PonyCheck.for_all[List[USize]](gen, h)(
{(sample, ph) =>
ph.array_eq[Usize](arg1, arg1.reverse().reverse())
})
// ... possibly more properties, using `PonyCheck.for_all`
```

Independently of how you integrate with [PonyTest](pony_test--index.md),
the PonyCheck machinery will instantiate the provided Generator, and will
execute it for a configurable number of samples.


392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411


fun apply(data: ReadSeq[Stringable]): String iso^ =>
var res = "".clone()
try
let iter = data.values()
if iter.has_next() then
res = iter.next()?.string()
for d in iter do
var idx: USize = 0
let s = d.string()
while (idx < res.size()) and (idx < s.size()) do
if res(idx)? != s(idx)? then
break
end
idx = idx + 1
end
res = res.substring(0, idx.isize())
end
end
end
res


fun box f64_unsafe()
: F64 val

Returns¶

F64 val

compare¶
[Source]
fun box compare(
that: I64 val)
: (Less val | Equal val | Greater val)

Parameters¶

that: I64 val

Returns¶


Bool val


y: A

Returns¶

A ?

sub_partial¶
[Source]
fun box sub_partial(
y: A)
: A ?

Parameters¶

y: A

Returns¶


not.
"""
var cur: List[A] = this
var res: List[A] = Nil[A]
while true do
match cur
| let cons: Cons[A] =>
if f(cons.head()) then
res = res.prepend(cons.head())
cur = cons.tail()
else
break
end
else
return res.reverse()
end
end
res.reverse()


[Source]
fun ref int_fp_mult[optional N: ((U8 val | U16 val | U32 val |
U64 val | U128 val | ULong val |
USize val) & Real[N] val)](
n: N)
: N

Parameters¶

n: N

Returns¶

N

int[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]¶
[Source]
fun ref int[optional N: ((U8 val | U16 val | U32 val |
U64 val | U128 val | ULong val |


1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311


gen3¶
[Source]
The Generator for the third argument to your property4 method.
fun box gen3()
: Generator[T3] box

Returns¶

Generator[T3] box

gen4¶
[Source]
The Generator for the fourth argument to your property4 method.
fun box gen4()
: Generator[T4] box

Returns¶

Generator[T4] box


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271


(this - y, overflow)
end

fun mulc(y: I128): (I128, Bool) =>
// using llvm.smul.with.overflow.i128 would require to link
// llvm compiler-rt where the function implementing it lives: https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/muloti4.c
// See this bug for reference:
// the following implementation is more or less exactly was __muloti4 is
// doing
_SignedCheckedArithmetic._mul_checked[U128, I128](this, y)

fun divc(y: I128): (I128, Bool) =>
_SignedCheckedArithmetic.div_checked[I128, U128](this, y)

fun remc(y: I128): (I128, Bool) =>
_SignedCheckedArithmetic.rem_checked[I128, U128](this, y)

fun fldc(y: I128): (I128, Bool) =>
_SignedCheckedArithmetic.fld_checked[I128, U128](this, y)


fun box ipv6_nexthop()
: I32 val

Returns¶

I32 val

ipv6_origdstaddr¶
[Source]
fun box ipv6_origdstaddr()
: I32 val

Returns¶

I32 val

ipv6_pathmtu¶
[Source]


Backpressure¶
[Source]
primitive val Backpressure

Constructors¶
create¶
[Source]
new val create()
: Backpressure val^

Returns¶

Backpressure val^


: Bool val

Returns¶

Bool val

next¶
[Source]
A random integer in [0, 2^64)
fun ref next()
: U64 val

Returns¶

U64 val

u8¶
[Source]


Returns¶

String iso^

int[A: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Integer[A])]¶
[Source]
fun box int[A: ((I8 val | I16 val | I32 val |
I64 val | I128 val | ILong val |
ISize val | U8 val | U16 val |
U32 val | U64 val | U128 val |
ULong val | USize val) & Integer[A])](
x: A,
fmt: (FormatDefault val | FormatUTF32 val | FormatBinary val |
FormatBinaryBare val | FormatOctal val | FormatOctalBare val |
FormatHex val | FormatHexBare val | FormatHexSmall val |
FormatHexSmallBare val) = reference,
prefix: (PrefixDefault val | PrefixSpace val | PrefixSign val) = reference,
prec: USize val = call,
width: USize val = 0,


lt¶
[Source]
fun box lt(
y: box->A)
: Bool val

Parameters¶

y: box->A

Returns¶

Bool val

le¶
[Source]
fun box le(


y: F64 val

Returns¶

F64 val

div¶
fun box div(
y: F64 val)
: F64 val

Parameters¶

y: F64 val

Returns¶

F64 val


832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851


# Long tests

Simple tests run within a single function. When that function exits, either
returning or raising an error, the test is complete. This is not viable for
tests that need to use actors.

Long tests allow for delayed completion. Any test can call long_test() on its
TestHelper to indicate that it needs to keep running. When the test is finally
complete it calls complete() on its TestHelper.

The complete() function takes a Bool parameter to specify whether the test was
a success. If any asserts fail then the test will be considered a failure
regardless of the value of this parameter. However, complete() must still be
called.

Since failing tests may hang, a timeout must be specified for each long test.
When the test function exits a timer is started with the specified timeout. If
this timer fires before complete() is called the test is marked as a failure
and the timeout is reported.


952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971


let r = (x * 5).rotl(7) * 9
y = x xor y

_x = x.rotl(24) xor y xor (y << 16)
_y = y.rotl(37)
r


Bool val

le¶
[Source]
fun box le(
y: I16 val)
: Bool val

Parameters¶

y: I16 val

Returns¶

Bool val

ge¶
[Source]


fun box ip_mtu()
: I32 val

Returns¶

I32 val

ip_mtu_discover¶
[Source]
fun box ip_mtu_discover()
: I32 val

Returns¶

I32 val

ip_multicast_all¶
[Source]


fun box mulc(
y: I8 val)
: (I8 val , Bool val)

Parameters¶

y: I8 val

Returns¶

(I8 val , Bool val)

divc¶
[Source]
fun box divc(
y: I8 val)
: (I8 val , Bool val)

Parameters¶


fun val drop_while(f: {(val->A): Bool} box): List[A] =>
"""
Builds a list by dropping elements from the front of the list until one
fails to satisfy the provided predicate.
"""
var cur: List[A] = this
while true do
match cur
| let cons: Cons[A] =>
if f(cons.head()) then cur = cons.tail() else break end
else
return Nil[A]
end
end
cur

fun val take(n: USize): List[A] =>
"""
Builds a list of the first n elements.


412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431


y: U8 val

Returns¶

U8 val

fldc¶
[Source]
fun box fldc(
y: U8 val)
: (U8 val , Bool val)

Parameters¶

y: U8 val

Returns¶


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71


fun sqrt_unsafe(): F64 =>
"""
Unsafe operation.
If this is negative, the result is undefined.
"""
@"llvm.sqrt.f64"(this)

fun cbrt(): F64 => @cbrt(this)
fun exp(): F64 => @"llvm.exp.f64"(this)
fun exp2(): F64 => @"llvm.exp2.f64"(this)

fun cos(): F64 => @"llvm.cos.f64"(this)
fun sin(): F64 => @"llvm.sin.f64"(this)
fun tan(): F64 => @tan(this)

fun cosh(): F64 => @cosh(this)
fun sinh(): F64 => @sinh(this)
fun tanh(): F64 => @tanh(this)


# Trust boundaries

When we talk about trust, we don't mean things you trust because you think they are perfect. Instead, we mean things you _have_ to trust in order to get things done, even though you know they are _imperfect_.

In Pony, when you use the C-FFI, you are basically declaring that you trust the C code that's being executed. That's fine, because you may need it to get work done. But what about trusting someone else's code to use the C-FFI? You may need to, but you definitely want to know that it's happening.


Add a byte to the end of the string.
"""
reserve(_size + 1)
_set(_size, value)
_size = _size + 1
_set(_size, 0)

fun ref pop(): U8 ? =>
"""
Remove a byte from the end of the string.
"""
if _size > 0 then
_size = _size - 1
_ptr._offset(_size)._delete(1, 0)
else
error
end

fun ref unshift(value: U8) =>
"""


key: box->K!)
: this->V ?

Parameters¶

key: box->K!

Returns¶

this->V ?

update¶
[Source]
Sets a value in the map. Returns the old value if there was one, otherwise
returns None. If there was no previous value, this may trigger a resize.
fun ref update(
key: K,
value: V)
: (V^ | None val)


# Line 2

```pony
new create(env: Env) =>
```

This is a __constructor__. The keyword `new` means it's a function that creates a new instance of the type. In this case, it creates a new __Main__.

Unlike other languages, constructors in Pony have names. That means there can be more than one way to construct an instance of a type. In this case, the name of the constructor is `create`.

The parameters of a function come next. In this case, our constructor has a single parameter called `env` that is of the type `Env`.

In Pony, the type of something always comes after its name and is separated by a colon. In C, C++, Java or C#, you might say `Env env`, but we do it the other way around (like Go, Pascal, Rust, TypeScript, and a bunch of other languages).

It turns out, our `Main` actor __has__ to have a constructor called `create` that takes a single parameter of type `Env`. That's how all programs start! So the beginning of your program is essentially the body of that constructor.

__Wait, what's the body?__ It's the code that comes after the `=>`.


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


new create(m: HashMap[K, V, H]) =>
_stack.push(m._root_node().iter())

fun has_next(): Bool =>
_stack.size() > 0

fun ref next(): (K, V) ? =>
let iter = _stack(_stack.size() - 1)?
let x = iter.next()?
if not iter.has_next() then _stack.pop()? end
match x
| let e: _MapEntry[K, V, H] => (e.key, e.value)
| let i: _MapIter[K, V, H] =>
_stack.push(i)
next()?
end


String.from_iso_array(consume arr)

fun shrink(s: String): ValueAndShrink[String] =>
"""
shrink string until `min` length.
"""
var str: String = s.trim(0, s.size()-1)
let shorten_iter: Iterator[String^] =
object is Iterator[String^]
fun ref has_next(): Bool => str.size() > min
fun ref next(): String^ =>
str = str.trim(0, str.size()-1)
end
let min_iter =
if s.size() > min then
Poperator[String]([s.trim(0, min)])
else
Poperator[String].empty()
end
let shrink_iter =


+ _print_array[A](actual) + "):"
+ "\nMissing: " + _print_array[box->A](missing)
+ "\nExtra: " + _print_array[box->A](extra)
)
)
return false
end
_runner.log(
_fmt_msg(
loc,
"Assert EQ_UNORDERED passed. "
+ msg
+ " Got ("
+ _print_array[A](expect)
+ ") == ("
+ _print_array[A](actual)
+ ")"
),
true
)


from¶
[Source]
Creates a list equivalent to the provided Array (both node number and order are preserved).
let my_list = List[String].from(["a"; "b"; "c"])

new ref from(
seq: Array[A^] ref)
: List[A] ref^

Parameters¶

seq: Array[A^] ref

Returns¶

List[A] ref^


_pending.push((data, 0))
Backpressure.apply(_backpressure_auth)
else
// Notify caller of error, close fd and done.
_notifier.failed(this, ProcessError(WriteError))
_stdin.close_near()
end
elseif len.usize() < data.size() then
// Send any remaining data later.
_pending.push((data, len.usize()))
Backpressure.apply(_backpressure_auth)
end
else
// Send later, when the pipe is available for writing.
_pending.push((data, 0))
Backpressure.apply(_backpressure_auth)
end

fun ref _pending_writes() =>
"""


fun modc(y: A): (A, Bool)
"""
Calculate the modulo of this number after floored division by `y` and return the result and a flag indicating division by zero or overflow.

The result will have the sign of the divisor.
"""

fun op_and(y: A): A => this and y
fun op_or(y: A): A => this or y
fun op_xor(y: A): A => this xor y
fun op_not(): A => not this

fun bit_reverse(): A
"""
Reverse the order of the bits within the integer.
For example, 0b11101101 (237) would return 0b10110111 (183).
"""

fun bswap(): A


# Test names

Tests are identified by names, which are used when printing test results and on
the command line to select which tests to run. These names are independent of
the names of the test classes in the Pony source code.

Arbitrary strings can be used for these names, but for large projects it is
strongly recommended to use a hierarchical naming scheme to make it easier to
select groups of tests.

You can skip any tests whose names start with a given string by using the
`--exclude=[prefix]` command line option.

You can run only tests whose names start with a given string by using the
`--only=[prefix]` command line option.


end
end
end
// close file
ifdef windows then
@_close(_fd)
else
@close(_fd)
end
end


let line = _queue.shift()?
_add_history(line)
_out.print(_cur_prompt + line)
_handle_line(term, line)
else
_refresh_line()
end

fun ref closed() =>
"""
No more input is available.
"""
_save_history()

fun ref up(ctrl: Bool = false, alt: Bool = false, shift: Bool = false) =>
"""
Previous line.
"""
try
if _cur_line > 0 then


that: KillError val

Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: KillError val)
: Bool val

Parameters¶

that: KillError val

Returns¶


fun box sctp_asconf()
: I32 val

Returns¶

I32 val

sctp_asconf_ack¶
[Source]
fun box sctp_asconf_ack()
: I32 val

Returns¶

I32 val

sctp_asconf_supported¶
[Source]


fun box ipproto_st()
: I32 val

Returns¶

I32 val

ipproto_svmtp¶
[Source]
fun box ipproto_svmtp()
: I32 val

Returns¶

I32 val

ipproto_swipe¶
[Source]


fun box op_and(
that: Flags[A, B] box)
: Flags[A, B] iso^

Parameters¶

that: Flags[A, B] box

Returns¶

Flags[A, B] iso^

op_xor¶
[Source]
The symmetric difference of this and that.
fun box op_xor(
that: Flags[A, B] box)
: Flags[A, B] iso^


1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351


172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


## For

For iterating over a collection of items Pony uses the `for` keyword. This is very similar to `foreach` in C#, `for`..`in` in Python and `for` in Java when used with a collection. It is very different to `for` in C and C++.

The Pony `for` loop iterates over a collection of items using an iterator. On each iteration, round the loop, we ask the iterator if there are any more elements to process, and if there are, we ask it for the next one.

The format of `for` loop looks like that:
```pony
for loop_var in collection_iterator do
loop_body
end
```

For example, to print out all the strings in an array:

```pony
for name in ["Bob"; "Fred"; "Sarah"].values() do
env.out.print(name)
end
```


Returns¶

List[this->A!] ref^

take¶
[Source]
Builds a List by keeping the first n elements.
let my_list = List[String].from(["a"; "b"; "c"])
let other_list = my_list.drop(1)  // ["a"]

fun box take(
n: USize val)
: List[this->A!] ref

Parameters¶

n: USize val

Returns¶


fun box sub_unsafe(
y: U16 val)
: U16 val

Parameters¶

y: U16 val

Returns¶

U16 val

mul_unsafe¶
[Source]
fun box mul_unsafe(
y: U16 val)
: U16 val

Parameters¶


fun box sctp_cause_stale_cookie()
: I32 val

Returns¶

I32 val

sctp_cause_unrecog_chunk¶
[Source]
fun box sctp_cause_unrecog_chunk()
: I32 val

Returns¶

I32 val

sctp_cause_unrecog_param¶
[Source]


I32 val

shl_unsafe¶
[Source]
fun box shl_unsafe(
y: U32 val)
: I32 val

Parameters¶

y: U32 val

Returns¶

I32 val

shr_unsafe¶
[Source]


F32 val

pow¶
[Source]
fun box pow(
y: F32 val)
: F32 val

Parameters¶

y: F32 val

Returns¶

F32 val

powi¶
[Source]


U32 val

u64¶
[Source]
fun box u64()
: U64 val

Returns¶

U64 val

u128¶
[Source]
fun box u128()
: U128 val

Returns¶


fun box tcp_pcap_out()
: I32 val

Returns¶

I32 val

tcp_queue_seq¶
[Source]
fun box tcp_queue_seq()
: I32 val

Returns¶

I32 val

tcp_quickack¶
[Source]


range.pony

1
2
3
4
5
6
7
8
9
10
11


f32_be¶
[Source]
Get a big-endian F32.
fun ref f32_be()
: F32 val ?

Returns¶

F32 val ?

f32_le¶
[Source]
Get a little-endian F32.
fun ref f32_le()
: F32 val ?

Returns¶


// iterating over Range of U8 with while-loop
let range = Range[U8](5, 100, 5)
while range.has_next() do
try
handle_u8(range.next()?)
end
end
```

Supports `min` being smaller than `max` with negative `inc`
but only for signed integer types and floats:

```pony
var previous = 11
for left in Range[I64](10, -5, -1) do
if not (left < previous) then
error
end
previous = left
end


Returns¶

Pointer[A] ref^

Public Functions¶
offset¶
[Source]
Return a tag pointer to the n-th element.
fun tag offset(
n: USize val)
: Pointer[A] tag

Parameters¶

n: USize val

Returns¶


size¶
[Source]
fun box size()
: USize val

Returns¶

USize val

u8¶
[Source]
Write a byte to the buffer.
fun ref u8(
data: U8 val)
: None val

Parameters¶


: Bool val

Parameters¶

that: AmbientAuth val

Returns¶

Bool val


Returns¶

U16 val ?

read_u32[optional B: (A & Real[B] val & U8 val)]¶
[Source]
Reads a U32 from offset. This is only allowed for an array of U8s.
fun box read_u32[optional B: (A & Real[B] val & U8 val)](
offset: USize val)
: U32 val ?

Parameters¶

offset: USize val

Returns¶

U32 val ?


let search = path' + "\\*"
let h = @FindFirstFileA(search.cstring(), find)

if h.usize() == -1 then
error
end

repeat
let p = @ponyint_windows_readdir(find)

if not p.is_null() then
list.push(recover String.from_cstring(consume p) end)
end
until not @FindNextFileA(h, find) end

@FindClose(h)
@ponyint_windows_find_data_free(find)
else
compile_error "unsupported platform"
end


set.pony

1
2
3
4
5
6
7
8
9
10
11


572
573use "collections"

use @pony_os_listen_udp[AsioEventID](owner: AsioEventNotify,
host: Pointer[U8] tag, service: Pointer[U8] tag)
use @pony_os_listen_udp4[AsioEventID](owner: AsioEventNotify,
host: Pointer[U8] tag, service: Pointer[U8] tag)
use @pony_os_listen_udp6[AsioEventID](owner: AsioEventNotify,
host: Pointer[U8] tag, service: Pointer[U8] tag)
use @pony_os_sendto[USize](fd: U32, buffer: Pointer[U8] tag,
size: USize, to: NetAddress tag) ?
use @pony_os_recvfrom[USize](event: AsioEventID, buffer: Pointer[U8] tag,
size: USize, from: NetAddress tag) ?
use @pony_os_multicast_join[None](fd: U32, group: Pointer[U8] tag,
to: Pointer[U8] tag)
use @pony_os_multicast_leave[None](fd: U32, group: Pointer[U8] tag,
to: Pointer[U8] tag)
use @pony_os_multicast_interface[None](fd: U32, from: Pointer[U8] tag)

actor UDPSocket is AsioEventNotify


2. An undefined value that must be ignored.
"""
_OSSocket.getsockopt_u32(_fd, level, option_name)

fun ref setsockopt(level: I32, option_name: I32, option: Array[U8]): U32 =>
"""
General wrapper for TCP sockets to the `setsockopt(2)` system call.

The caller is responsible for the correct size and byte contents of
the `option` array for the requested `level` and `option_name`,
including using the appropriate machine endian byte order.

This function returns `0` on success, else the value of `errno` on
failure.

Usage example:

```pony
// connected() is a callback function for class TCPConnectionNotify
fun ref connected(conn: TCPConnection ref) =>


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811


fun box ipproto_satmon()
: I32 val

Returns¶

I32 val

ipproto_sccsp¶
[Source]
fun box ipproto_sccsp()
: I32 val

Returns¶

I32 val

ipproto_sctp¶
[Source]


 Serialise package

This package provides support for serialising and deserialising arbitrary data
structures.

The API is designed to require capability tokens, as otherwise serialising
would leak the bit patterns of all private information in a type if the
resulting Array[U8] could be examined.

Deserialisation is fundamentally unsafe currently: there isn't yet a
verification pass to check that the resulting object graph maintains a
well-formed heap or that individual objects maintain any expected local
invariants. However, if only "trusted" data (i.e. data produced by Pony
serialisation from the same binary) is deserialised, it will always maintain a
well-formed heap and all object invariants.

Note that serialised data is not usable between different Pony binaries. This is
due to the use of type identifiers rather than a heavy-weight self-describing
serialisation schema. This also means it isn't safe to deserialise something
serialised by the same program compiled for a different platform.


if not windows
use @_chmod[I32](path: Pointer[U8] tag, mode: U32)
if windows
use @chmod[I32](path: Pointer[U8] tag, mode: U32)
if not windows
use @chown[I32](path: Pointer[U8] tag, uid: U32, gid: U32)
if not windows
use @utimes[I32](path: Pointer[U8] tag,
tv: Pointer[(ILong, ILong, ILong, ILong)]) if not windows
use @_utime64[I32](path: Pointer[U8] tag, times: Pointer[(I64, I64)])
if windows
use @LookupPrivilegeValueA[U8](system_name: Pointer[None] tag,
priv_name: Pointer[U8] tag, luid: Pointer[U64]) if windows
use @GetCurrentProcess[USize]() if windows
use @OpenProcessToken[U8](handle: Pointer[None] tag, access: U32,
token_handle: Pointer[None] tag) if windows
use @AdjustTokenPrivileges[U8](handle: Pointer[None], disable_privileges: U8,
new_state: _TokenPrivileges, buf_len: U32, prev_state: Pointer[None],
ret_len: Pointer[None]) if windows
use @CloseHandle[Bool](handle: Pointer[None]) if windows


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27interface box ReadSeq[A]
"""
The readable interface of a sequence.
"""
fun size(): USize


## Read

If your application is unable to keep up with data being sent to it over
a `TCPConnection` you can use the builtin read backpressure support to
pause reading the socket which will in turn start to exert backpressure on
the corresponding writer on the other end of that socket.

The `mute` behavior allow any other actors in your application to request
the cessation of additional reads until such time as `unmute` is called.
Please note that this cessation is not guaranteed to happen immediately as
it is the result of an asynchronous behavior call and as such will have to
wait for existing messages in the `TCPConnection`'s mailbox to be handled.

On non-windows platforms, your `TCPConnection` will not notice if the
other end of the connection closes until you unmute it. Unix type systems
like FreeBSD, Linux and OSX learn about a closed connection upon read. On
these platforms, you **must** call `unmute` on a muted connection to have
it close. Without calling `unmute` the `TCPConnection` actor will never
exit.


fun ref u8(
min: U8 val = call,
max: U8 val = call)
: U8 val

Parameters¶

min: U8 val = call
max: U8 val = call

Returns¶

U8 val

u16¶
[Source]
Generate a U16 in closed interval [min, max]
(default: [min_value, max_value]).
Behavior is undefined if min > max.


new ref create(
array: B)
: ArrayValues[A, B] ref^

Parameters¶

array: B

Returns¶

ArrayValues[A, B] ref^

Public Functions¶
has_next¶
[Source]
fun box has_next()
: Bool val

Returns¶


Remove a value from the set.
fun ref unset(
value: box->A!)
: None val

Parameters¶

value: box->A!

Returns¶

None val

extract¶
[Source]
Remove a value from the set and return it. Raises an error if the value
wasn't in the set.
fun ref extract(
value: box->A!)


## `As` Expression

It is also possible to give the literal a hint on what kind of type it should coerce the array elements to using an `as` Expression. The expression with the desired array element type needs to be added right after the opening square bracket, delimited by a colon:

```pony
let my_as_array =
[ as Stringable:
U64(0xFFEF)
"0xFFEF"
U64(1 + 1)
]
```

This array literal is coerced to be an `Array[Stringable] ref` according to the `as` expression.

If a type is specified on the left-hand side, it needs to exactly match the type in the `as` expression.


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


peek_i8¶
[Source]
Peek at an I8.
fun box peek_i8(
offset: USize val = 0)
: I8 val ?

Parameters¶

offset: USize val = 0

Returns¶

I8 val ?

peek_u16_be¶
[Source]


"""
Log the given message.

The verbose parameter allows messages to be printed only when the
`--verbose` command line option is used. For example, by default assert
failures are logged, but passes are not. With `--verbose`, both passes and
fails are reported.

Logs are printed one test at a time to avoid interleaving log lines from
concurrent tests.
"""
_runner.log(msg, verbose)

fun fail(msg: String = "Test failed") =>
"""
Flag the test as having failed.
"""
_fail(msg)

fun assert_false(


fun box usize()
: USize val

Returns¶

USize val

f32¶
[Source]
fun box f32()
: F32 val

Returns¶

F32 val

f64¶
[Source]


Debug¶
[Source]
This is a debug only print utility.
primitive val Debug

Constructors¶
create¶
[Source]
new val create()
: Debug val^

Returns¶


@pony_asio_event_unsubscribe(_event)
_readable = false
_writeable = false
@pony_asio_event_set_readable(_event, false)
@pony_asio_event_set_writeable(_event, false)

// On windows, this will also cancel all outstanding IOCP operations.
@pony_os_socket_close(_fd)
_fd = -1

_notify.closed(this)

try (_listen as TCPListener)._conn_closed() end

// Check this when a connection gets its first writeable event.
fun _is_sock_connected(fd: U32): Bool =>
ifdef windows then
(let errno: U32, let value: U32) = _OSSocket.get_so_connect_time(fd)
(errno == 0) and (value != 0xffffffff)


Bool val

op_and¶
[Source]
fun box op_and(
y: Bool val)
: Bool val

Parameters¶

y: Bool val

Returns¶

Bool val

op_or¶


fun sctp_max_burst():I32 => @pony_os_sockopt_option(I32(662))
fun sctp_max_cookie_life():I32 => @pony_os_sockopt_option(I32(663))
fun sctp_max_cwnd():I32 => @pony_os_sockopt_option(I32(664))
fun sctp_max_hb_interval():I32 => @pony_os_sockopt_option(I32(665))
fun sctp_max_sack_delay():I32 => @pony_os_sockopt_option(I32(666))
fun sctp_mbcnt_logging_enable():I32 => @pony_os_sockopt_option(I32(667))
fun sctp_mbuf_logging_enable():I32 => @pony_os_sockopt_option(I32(668))
fun sctp_mobility_base():I32 => @pony_os_sockopt_option(I32(669))
fun sctp_mobility_fasthandoff():I32 => @pony_os_sockopt_option(I32(670))
fun sctp_mobility_prim_deleted():I32 => @pony_os_sockopt_option(I32(671))
fun sctp_nagle_logging_enable():I32 => @pony_os_sockopt_option(I32(672))
fun sctp_nodelay():I32 => @pony_os_sockopt_option(I32(673))
fun sctp_nrsack_supported():I32 => @pony_os_sockopt_option(I32(674))
fun sctp_nr_selective_ack():I32 => @pony_os_sockopt_option(I32(675))
fun sctp_operation_error():I32 => @pony_os_sockopt_option(I32(676))
fun sctp_packed():I32 => @pony_os_sockopt_option(I32(677))
fun sctp_packet_dropped():I32 => @pony_os_sockopt_option(I32(678))
fun sctp_packet_log_size():I32 => @pony_os_sockopt_option(I32(679))
fun sctp_packet_truncated():I32 => @pony_os_sockopt_option(I32(680))
fun sctp_pad_chunk():I32 => @pony_os_sockopt_option(I32(681))


AsyncOverheadBenchmark¶
[Source]
Default benchmark for measuring asynchronous overhead.
class iso AsyncOverheadBenchmark is
AsyncMicroBenchmark iso

Implements¶

AsyncMicroBenchmark iso

Constructors¶
create¶


var _list: (List[A] | None) = None
var _prev: (ListNode[A] | None) = None
var _next: (ListNode[A] | None) = None

new create(item: (A | None) = None) =>
"""
Create a node. Initially, it is not in any list.
"""
_item = consume item

fun apply(): this->A ? =>
"""
Return the item, if we have one, otherwise raise an error.
"""
_item as this->A

fun ref update(value: (A | None)): A^ ? =>
"""
Replace the item and return the previous one. Raise an error if we have no
previous value.


ctrl: Bool val
alt: Bool val
shift: Bool val

Returns¶

None val

page_up¶
[Source]
fun ref page_up(
ctrl: Bool val,
alt: Bool val,
shift: Bool val)
: None val

Parameters¶

ctrl: Bool val


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71


Generators.ascii_printable()

fun property(arg1: String, h: PropertyHelper) =>
h.assert_true(arg1.size() > 0)

actor Main is TestList
new create(env: Env) => PonyTest(env, this)

fun tag tests(test: PonyTest) =>
test(Property1UnitTest[String](MyProperty))

class iso Property1UnitTest[T: T] is
UnitTest ref

Implements¶

UnitTest ref

Constructors¶


Bool¶
[Source]
primitive val Bool is
Stringable box

Implements¶

Stringable box

Constructors¶
create¶
[Source]


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131


fun box so_notifyconflict()
: I32 val

Returns¶

I32 val

so_no_check¶
[Source]
fun box so_no_check()
: I32 val

Returns¶

I32 val

so_no_ddp¶
[Source]


# What about global variables?

They're bad! Because you can get them without either constructing them or being passed them.

Global variables are a form of what is called _ambient authority_. Another form of ambient authority is unfettered access to the file system.

Pony has no global variables and no global functions. That doesn't mean all ambient authority is magically gone - we still need to be careful about the file system, for example. Having no global variables is necessary, but not sufficient, to eliminate ambient authority.


# Language constructs that can raise errors

The only language construct that can raise an error, other than the `error` command or calling a partial method, is the `as` command. This converts the given value to the specified type if it can be. If it can't then an error is raised. This means that the `as` command can only be used inside a try block or a partial method.


Returns¶

U32 val

emt¶
[Source]
fun box emt()
: U32 val

Returns¶

U32 val

fpe¶
[Source]
fun box fpe()
: U32 val


Iterator[A: A]¶
[Source]
Iterators generate a series of values, one value at a time on each call to next().
An Iterator is considered exhausted, once its has_next() method returns false.
Thus every call to next() should be preceeded with a call to has_next() to
check for exhaustiveness.
Usage¶
Given the rules for using Iterators mentioned above, basic usage
of an iterator looks like this:
while iterator.has_next() do
let elem = iterator.next()?
// do something with elem
end


a: B

Returns¶

F32 val^

min_value¶
[Source]
Minimum negative value representable.
new val min_value()
: F32 val^

Returns¶

F32 val^

max_value¶


h: TestHelper val)
: None val

Parameters¶

h: TestHelper val

Returns¶

None val

label¶
fun box label()
: String val

Returns¶

String val


fun box so_attach_filter()
: I32 val

Returns¶

I32 val

so_bindtodevice¶
[Source]
fun box so_bindtodevice()
: I32 val

Returns¶

I32 val

so_bintime¶
[Source]


"""
Reads a U8 from offset. This is only allowed for an array of U8s.
"""
if offset < _size then
_ptr._offset(offset)._convert[U8]()._apply(0)
else
error
end

fun read_u16[B: (A & Real[B] val & U8) = A](offset: USize): U16 ? =>
"""
Reads a U16 from offset. This is only allowed for an array of U8s.
"""
let u16_bytes = U16(0).bytewidth()
if (offset + u16_bytes) <= _size then
_ptr._offset(offset)._convert[U16]()._apply(0)
else
error
end


I16 val

i32¶
[Source]
fun box i32()
: I32 val

Returns¶

I32 val

i64¶
[Source]
fun box i64()
: I64 val

Returns¶


y: U16 val

Returns¶

U16 val

neg¶
[Source]
fun box neg()
: U16 val

Returns¶

U16 val

eq¶
[Source]


I64 val

i128¶
[Source]
fun box i128()
: I128 val

Returns¶

I128 val

ilong¶
[Source]
fun box ilong()
: ILong val

Returns¶


x = 12
^
```

What happened is that you declared `x` as a constant, by writing `let x`, and then tried to assign a new value to it, 12. To fix the error, replace `let` with `var` or reconsider what value you want `x` to have.

That one error resulted in two error messages. The first, pointing to the `x`, describes the specific problem, that `x` was defined with `let`. The second, pointing to the `=` describes a more general error, that whatever is on the left side of the assignment is not something that can be assigned to. You would get that same error message if you attempted to assign a value to a literal, like `3`.


PrefixSpace¶
[Source]
primitive val PrefixSpace is
PrefixSpec val

Implements¶

PrefixSpec val

Constructors¶
create¶
[Source]


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111


392
393
394
395
396
397
398
399
400
401
402use "collections"
use "files"
use "promises"
use strings = "strings"

class Readline is ANSINotify
"""
Line editing, history, and tab completion.
"""
let _notify: ReadlineNotify


var _pending_sent: USize = 0
var _pending_writev_total: USize = 0
var _read_buf: Array[U8] iso
var _read_buf_offset: USize = 0
var _max_received_called: USize = 50

let _read_buffer_size: USize

let _yield_after_reading: USize
let _yield_after_writing: USize

var _expect: USize = 0

var _muted: Bool = false

new create(
auth: TCPConnectAuth,
notify: TCPConnectionNotify iso,
host: String,


fun box ip_portrange_high()
: I32 val

Returns¶

I32 val

ip_portrange_low¶
[Source]
fun box ip_portrange_low()
: I32 val

Returns¶

I32 val

ip_recvdstaddr¶
[Source]


fun box icmp_info_reply()
: I32 val

Returns¶

I32 val

icmp_info_request¶
[Source]
fun box icmp_info_request()
: I32 val

Returns¶

I32 val

icmp_net_ano¶
[Source]


that: FileTime val

Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: FileTime val)
: Bool val

Parameters¶

that: FileTime val

Returns¶


Assert that the 2 given expressions are not equal.
fun box assert_ne[A: (Equatable[A] #read & Stringable #read)](
not_expect: A,
actual: A,
msg: String val = "",
loc: SourceLoc val = __loc)
: Bool val

Parameters¶

not_expect: A
actual: A
msg: String val = ""
loc: SourceLoc val = __loc

Returns¶

Bool val


acc: B

Returns¶

B

every¶
[Source]
Returns true if every element satisfies the predicate, otherwise returns false.
let my_list = List[String].from(["a"; "b"; "c"])
let all_z = my_list.every( {(s: String): Bool => s == "z"} ) // false

fun box every(
f: {(this->A!): Bool}[A] box)
: Bool val

Parameters¶

f: {(this->A!): Bool}[A] box


create¶
[Source]
new tag create(
file: File iso)
: FileStream tag^

Parameters¶

file: File iso

Returns¶

FileStream tag^

Public Behaviours¶
print¶
[Source]
Print some bytes and insert a newline afterwards.
be print(


# Line 1

```pony
actor Main
```

This is a __type declaration__. The keyword `actor` means we are going to define an actor, which is a bit like a class in Python, Java, C#, C++, etc. Pony has classes too, which we'll see later.

The difference between an actor and a class is that an actor can have __asynchronous__ methods, called __behaviours__. We'll talk more about that later.

A Pony program has to have a `Main` actor. It's kind of like the `main` function in C or C++, or the `main` method in Java, or the `Main` method in C#. It's where the action starts.


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71


Create with the specified seed. Returned values are deterministic for a
given seed.
"""
_state = Array[U64](_n())
_index = _n()

var seed = x xor y

_state.push(seed)
var i: USize = 1

while i < _n() do
seed = ((seed xor (seed >> 62)) * 6364136223846793005) + i.u64()
_state.push(seed)
i = i + 1
end

fun ref next(): U64 =>
"""
A random integer in [0, 2^64)


: USize val

Returns¶

USize val

i8¶
[Source]
fun ref i8()
: I8 val

Returns¶

I8 val

i16¶
[Source]
fun ref i16()


Applies the supplied function to every element of the list in order.
"""
_for_each(this, f)

fun _for_each(l: List[A], f: {(val->A)} box) =>
"""
Private helper for for_each, recursively working on elements.
"""
match l
| let cons: Cons[A] =>
f(cons.head())
_for_each(cons.tail(), f)
end

fun val filter(f: {(val->A): Bool} box): List[A] =>
"""
Builds a new list with those elements that satisfy a provided predicate.
"""
_filter(this, f, Nil[A])


fun box sctp_pcb_flags_portreuse()
: I32 val

Returns¶

I32 val

sctp_pcb_flags_recvassocevnt¶
[Source]
fun box sctp_pcb_flags_recvassocevnt()
: I32 val

Returns¶

I32 val

sctp_pcb_flags_recvdataioevnt¶
[Source]


fun box ipproto_etherip()
: I32 val

Returns¶

I32 val

ipproto_fragment¶
[Source]
fun box ipproto_fragment()
: I32 val

Returns¶

I32 val

ipproto_ggp¶
[Source]


fun box mod(
y: I128 val)
: I128 val

Parameters¶

y: I128 val

Returns¶

I128 val

mod_unsafe¶
[Source]
fun box mod_unsafe(
y: I128 val)
: I128 val

Parameters¶


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131


fun box hash64()
: U64 val

Returns¶

U64 val

i8¶
[Source]
fun box i8()
: I8 val

Returns¶

I8 val

i16¶
[Source]


y: U32 val

Returns¶

U32 val ?

sub_partial¶
[Source]
fun box sub_partial(
y: U32 val)
: U32 val ?

Parameters¶

y: U32 val

Returns¶


Returns¶

F64 val

tan¶
[Source]
fun box tan()
: F64 val

Returns¶

F64 val

cosh¶
[Source]
fun box cosh()
: F64 val


# Var vs. let

Local variables are declared with either a `var` or a `let`. Using `var` means the variable can be assigned and reassigned as many times as you like. Using `let` means the variable can only be assigned once.

```pony
var x: U32 = 3
let y: U32 = 4
x = 5  // OK
y = 6  // Error, y is let
```

Using `let` instead of `var` also means the variable has to be assigned immediately.

```pony
let x: U32 = 3 // Ok
let y: U32 // Error, can't declare a let local without assigning to it
y = 6 // Error, can't reassign to a let local
```

Note that a variable having been declared with `let` only restricts reassignment, and does not influence the mutability of the object it references. This is the job of reference capabilities, explained later in this tutorial.


xoroshiro.pony

1
2
3
4
5
6
7
8
9
10
11


632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651


252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271


new ref create(
array: B)
: ArrayKeys[A, B] ref^

Parameters¶

array: B

Returns¶

ArrayKeys[A, B] ref^

Public Functions¶
has_next¶
[Source]
fun box has_next()
: Bool val

Returns¶


DNS¶
[Source]
Helper functions for resolving DNS queries.
primitive val DNS

Constructors¶
create¶
[Source]
new val create()
: DNS val^

Returns¶


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311


1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051


r
end

fun mod_unsafe(y: F32): F32 =>
let r = this %~ y
if r == F32(0.0) then
r.copysign(y)
elseif (r > 0) xor (y > 0) then
r + y
else
r
end

fun finite(): Bool =>
"""
Check whether this number is finite, ie not +/-infinity and not NaN.
"""
// True if exponent is not all 1s
(bits() and 0x7F800000) != 0x7F800000