fun box shl(
y: U128 val)
: I128 val

Parameters¶

y: U128 val

Returns¶

I128 val

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

Parameters¶


var s' = create()
for v in iter do
if contains(v) then
s' = s' + v
end
end
s'

fun val op_xor(that: (HashSet[A, H] | Iterator[A])): HashSet[A, H] =>
"""
Return a set with elements that are in either this or that, but not both.
"""
let iter =
match that
| let s: HashSet[A, H] => s.values()
| let i: Iterator[A] => i
end
var s' = this
for v in iter do
if contains(v) then


Public Types¶

primitive Debug
primitive DebugErr
primitive DebugOut
type DebugStream


fun box so_vm_sockets_peer_host_vm_id()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_wantmore¶
[Source]


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


852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871


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


## Fields

Pony struct fields are defined in the same way as they are for Pony classes, using `embed`, `let`, and `var`.  An embed field is embedded in its parent object, like a C struct inside C struct. A var/let field is a pointer to an object allocated separately.

For example:

```pony
struct Inner
var x: I32 = 0

struct Outer
embed inner_embed: Inner = Inner
var inner_var: Inner = Inner

```


else
backtrack = s.size().isize()
end

while i < n do
c = path(i)?

if is_sep(c) then
match state
| _PathDot2 =>
if backtrack == -1 then
s.append("..")
s.append(sep())
else
s.delete(backtrack, -1)

try
backtrack = s.rfind(sep(), backtrack - 2)? + 1
else
backtrack = vol.size().isize()


Returns¶

(A , Bool val)

op_and¶
[Source]
fun box op_and(
y: A)
: A

Parameters¶

y: A

Returns¶

A


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

Parameters¶

y: ULong val

Returns¶

Bool val

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

Parameters¶


F64.from_bits(peek_u64_le(offset)?)

fun _peek_byte(offset: USize = 0): U8 ? =>
"""
Get the byte at the given offset without moving the cursor forward.
Raise an error if the given offset is not yet available.
"""
var offset' = offset
var iter = _chunks.nodes()

while true do
let node = iter.next()?
(var data, var node_offset) = node()?
offset' = offset' + node_offset

let data_size = data.size()
if offset' >= data_size then
offset' = offset' - data_size
else
return data(offset')?


Returns the arg value as a ReadSeq[String], defaulting to empty.
fun box string_seq()
: ReadSeq[String val] val

Returns¶

ReadSeq[String val] val

deb_string¶
[Source]
fun box deb_string()
: String val

Returns¶

String val


fun box so_rfcomm_fc_info()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_rxq_ovfl¶
[Source]


# What counts as making an alias?

There are three things that count as making an alias:

1. When you __assign__ a value to a variable or a field.
2. When you __pass__ a value as an argument to a method.
3. When you __call a method__, an alias of the receiver of the call is created. It is accessible as `this` within the method body.

In all three cases, you are making a new _name_ for the object. This might be the name of a local variable, the name of a field, or the name of a parameter to a method.


"""
Returns the length of the string data in bytes.
"""
_size

fun codepoints(from: ISize = 0, to: ISize = ISize.max_value()): USize =>
"""
Returns the number of unicode code points in the string between the two
offsets. Index range [`from` .. `to`) is half-open.
"""
if _size == 0 then
return 0
end

var i = offset_to_index(from)
let j = offset_to_index(to).min(_size)
var n = USize(0)

while i < j do
if (_ptr._apply(i) and 0xC0) != 0x80 then


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
supposed to be used with `getsockopt(2)` and `setsockopt(2)`.
Please consult your platform's documentation to verify the names
of the option level and option name macros.

The following code fragments are equivalent: set the socket
receive buffer size for the file descriptor `fd` to `4455`.


list.
If the ListNode is not contained within a List the prepend will fail.
fun ref prepend(
that: ListNode[A] ref)
: Bool val

Parameters¶

that: ListNode[A] ref

Returns¶

Bool val

append¶
[Source]
Append a node to this one. If that is already in a list, it is removed
before it is appended. Returns true if that was removed from another
list.


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


Range[optional A: (Real[A] val & (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))]¶
[Source]
Produces [min, max) with a step of inc for any Number type.
// iterating with for-loop
for i in Range(0, 10) do
env.out.print(i.string())
end

// 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()?)


Bool val

next¶
[Source]
fun ref next()
: USize val

Returns¶

USize val


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


fun box u128()
: U128 val

Returns¶

U128 val

ulong¶
[Source]
fun box ulong()
: ULong val

Returns¶

ULong val

usize¶
[Source]


fun box ipx_reripnetnumber()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipx_rt_8022¶
[Source]


ILong val

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

Returns¶

ISize val

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

Returns¶


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

Returns¶

U64 val

has_next¶
[Source]
fun tag has_next()
: Bool val

Returns¶

Bool val

u8¶


# Object Literals

Sometimes it's really convenient to be able to write a whole object inline. In Pony, this is called an object literal, and it does pretty much exactly what an object literal in JavaScript does: it creates an object that you can use immediately.

But Pony is statically typed, so an object literal also creates an anonymous type that the object literal fulfills. This is similar to anonymous classes in Java and C#. In Pony, an anonymous type can provide any number of traits and interfaces.


fun box sctp_pcb_flags_wakeinput()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_pcb_flags_was_aborted¶
[Source]


| `<`      | `lt()`           | Less than                     |
| `<=`     | `le()`           | Less than or equal            |
| `>=`     | `ge()`           | Greater than or equal         |
| `>`      | `gt()`           | Greater than                  |
| `>~`     | `gt_unsafe()`    | Unsafe greater than           |
| `+~`     | `add_unsafe()`   | Unsafe Addition               |
| `-~`     | `sub_unsafe()`   | Unsafe Subtraction            |
| `*~`     | `mul_unsafe()`   | Unsafe Multiplication         |
| `/~`     | `div_unsafe()`   | Unsafe Division               |
| `%~`     | `rem_unsafe()`   | Unsafe Remainder              |
| `%%~`    | `mod_unsafe()`   | Unsafe Modulo                 | Starting with version `0.26.1` |
| `<<~`    | `shl_unsafe()`   | Unsafe left bit shift         |
| `>>~`    | `shr_unsafe()`   | Unsafe right bit shift        |
| `==~`    | `eq_unsafe()`    | Unsafe equality               |
| `!=~`    | `ne_unsafe()`    | Unsafe non-equality           |
| `<~`     | `lt_unsafe()`    | Unsafe less than              |
| `<=~`    | `le_unsafe()`    | Unsafe less than or equal     |
| `>=~`    | `ge_unsafe()`    | Unsafe greater than or equal  |
| `+?`     | `add_partial()?` | Partial Addition              |
| `-?`     | `sub_partial()?` | Partial Subtraction           |


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


Bool val

infinite¶
[Source]
fun box infinite()
: Bool val

Returns¶

Bool val

nan¶
[Source]
fun box nan()
: Bool val

Returns¶


None val

is_infinite¶
[Source]
fun box is_infinite()
: Bool val

Returns¶

Bool val

is_empty¶
[Source]
fun box is_empty()
: Bool val

Returns¶


new create(
out: OutStream,
destination: NetAddress)
=>
_out = out
_destination = destination

fun ref listening(sock: UDPSocket ref) =>
sock.write("hello world", _destination)

fun ref received(
sock: UDPSocket ref,
data: Array[U8] iso,
from: NetAddress)
=>
_out.print("GOT:" + String.from_array(consume data))
sock.dispose()

fun ref not_listening(sock: UDPSocket ref) =>


benchmark.pony

1
2
3
4
5
6
7
8
9
10
11


### Example

```pony
Iter[I64]([1; 2; 3].values())
.enum()
```
`(0, 1) (1, 2) (2, 3)`
"""
Iter[(B, A)](
object
var _i: B = 0

fun ref has_next(): Bool => _iter.has_next()

fun ref next(): (B, A) ? =>
(_i = _i + 1, _iter.next()?)
end)

fun ref filter(f: {(A!): Bool ?} box): Iter[A!]^ =>
"""


Buffered Package¶
The Buffered package provides two classes, Writer and Reader, for
writing and reading messages using common encodings. These classes are
useful when dealing with things like network data and binary file
formats.
Example program¶
use "buffered"

actor Main
new create(env: Env) =>
let reader = Reader
let writer = Writer


ifdef linux or bsd then
let fd' =
@openat(_fd, target.cstring(),
@ponyint_o_rdwr()
or @ponyint_o_creat()
or @ponyint_o_cloexec(),
I32(0x1B6))
recover File._descriptor(fd', path')? end
else
recover File(path') end
end

fun open_file(target: String): File iso^ ? =>
"""
Open for read only, failing if it doesn't exist.
"""
if
not path.caps(FileRead)
or (_fd == -1)


fun ref connected(conn: TCPConnection ref) =>
conn.write("hello world")

fun ref received(
conn: TCPConnection ref,
data: Array[U8] iso,
times: USize)
: Bool
=>
_out.print("GOT:" + String.from_array(consume data))
conn.close()
true

fun ref connect_failed(conn: TCPConnection ref) =>
None

actor Main
new create(env: Env) =>
TCPConnection(TCPConnectAuth(env.root),


not an error. Non-base64 data, other than whitespace (which can appear at
any time), is an error.
fun box decode[optional A: Seq[U8 val] iso](
data: ReadSeq[U8 val] box,
at62: U8 val = 43,
at63: U8 val = 47,
pad: U8 val = 61)
: A^ ?

Parameters¶

data: ReadSeq[U8 val] box
at62: U8 val = 43
at63: U8 val = 47
pad: U8 val = 61

Returns¶

A^ ?


Create a generator for ISize values.
fun box isize(
min: ISize val = call,
max: ISize val = call)
: Generator[ISize val] box

Parameters¶

min: ISize val = call
max: ISize val = call

Returns¶

Generator[ISize val] box

byte_string¶
[Source]
Create a generator for strings
generated from the bytes returned by the generator gen,


embed _data: Array[A]

new create(len: USize) =>
"""
Create an empty heap with space for `len` elements.
"""
_data = Array[A](len)

fun ref clear() =>
"""
Remove all elements from the heap.
"""
_data.clear()

fun size(): USize =>
"""
Return the number of elements in the heap.
"""
_data.size()


sort.pony

1
2
3
4
5
6
7
8
9
10
11


112
113
114
115
116
117
118
119
120
121
122
123use @memcmp[I32](dst: Pointer[None] tag, src: Pointer[None] tag, len: USize)
use @ponyint_hash_block[USize](ptr: Pointer[None] tag, size: USize)
use @ponyint_hash_block64[U64](ptr: Pointer[None] tag, size: USize)

interface Hashable
"""
Anything with a hash method is hashable.
"""
fun hash(): USize


data: F32 val

Returns¶

None val

u64_le¶
[Source]
Write a U64 to the buffer in little-endian byte order.
fun ref u64_le(
data: U64 val)
: None val

Parameters¶

data: U64 val

Returns¶


fun box ip_router_alert()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_rss_listen_bucket¶
[Source]


"""
(@ntohl(_addr1),
@ntohl(_addr2),
@ntohl(_addr3),
@ntohl(_addr4)
)


let _iter: Iterator[A]

new create(iter: Iterator[A]) =>
_iter = iter

fun ref has_next(): Bool =>
_iter.has_next()

fun ref next(): A ? =>
_iter.next()?

new maybe(value: (A | None)) =>
_iter =
object is Iterator[A]
var _value: (A | None) = consume value

fun has_next(): Bool => _value isnt None

fun ref next(): A ? => (_value = None) as A
end


572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591


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


fun ref i128(
min: I128 val = call,
max: I128 val = call)
: I128 val

Parameters¶

min: I128 val = call
max: I128 val = call

Returns¶

I128 val

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


fun box sctp_log_at_send_2_sctp()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_log_rwnd_enable¶
[Source]


### Example
```pony
Iter[I64]([as I64: 1; -2; 4; 7; -5])
.filter_map[USize](
{(i: I64): (USize | None) => if i >= 0 then i.usize() end })
```
`1 4 7`
```
"""
filter_map_stateful[B]({(a: A!): (B^ | None) ? => f(a) ? })

fun ref flat_map[B](f: {(A!): Iterator[B] ?} box): Iter[B]^ =>
"""
Return an iterator over the values of the iterators produced from the
application of the given function.


set_ip_multicast_loop¶
[Source]
Wrapper for the FFI call setsockopt(fd, SOL_SOCKET, IP_MULTICAST_LOOP, ...)
fun ref set_ip_multicast_loop(
loopback: Bool val)
: U32 val

Parameters¶

loopback: Bool val

Returns¶

U32 val

set_ip_multicast_ttl¶
[Source]
Wrapper for the FFI call setsockopt(fd, SOL_SOCKET, IP_MULTICAST_TTL, ...)
fun ref set_ip_multicast_ttl(


1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631


fun box ge(
y: I8 val)
: Bool val

Parameters¶

y: I8 val

Returns¶

Bool val

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

Parameters¶


throttled¶
[Source]
Called when the connection starts experiencing TCP backpressure. You should
respond to this by pausing additional calls to write and writev until
you are informed that pressure has been released. Failure to respond to
the throttled notification will result in outgoing data queuing in the
connection and increasing memory usage.
fun ref throttled(
conn: TCPConnection ref)
: None val

Parameters¶

conn: TCPConnection ref

Returns¶

None val


DoNotOptimise¶
[Source]
Contains functions preventing some compiler optimisations, namely dead code
removal. This is useful for benchmarking purposes.
primitive val DoNotOptimise

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

Returns¶


Bool val

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

Parameters¶

y: I32 val

Returns¶

Bool val

ge¶
[Source]


cut¶
[Source]
Returns a version of the string with the given range deleted.
Index range [from .. to) is half-open.
fun box cut(
from: ISize val,
to: ISize val = call)
: String iso^

Parameters¶

from: ISize val
to: ISize val = call

Returns¶

String iso^

cut_in_place¶


We have `c` as an `iso` and are trying to assign it to `_c`. This creates two aliases to the same object, something that `iso` does not allow. To fix it for the `iso` case we have to `consume` the parameter. The correct constructor should be:

```pony
new create(c: String iso) =>
_c = consume c
```

A similar issue exists with the `set` method. Here we also need to consume the variable `c` that is passed in:

```pony
fun set(c: String iso) => _c = consume c
```

Now we have a version of `Foo` that is working correctly for `iso`. Note how applying the arrow type to the `get` method also works for `iso`. But here the result is a different one, by applying [viewpoint adaptation](/reference-capabilities/combining-capabilities.md) we get from `ref->iso` (with `ref` being the capability of the receiver, the `Foo` object referenced by `a`) to `iso`. Through the magic of [automatic receiver recovery](/reference-capabilities/recovering-capabilities.md) we can call the `string` method on it:

```pony
class Foo
var _c: String iso


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


# Trust Boundary

We mentioned previously that the C-FFI can be used to break pretty much every guarantee that Pony makes. This is because, once you've called into C, you are executing arbitrary machine code that can stomp memory addresses, write to anything, and generally be pretty badly behaved.


flush¶
[Source]
Flush pending data to write.
be flush()


real.pony

1
2
3
4
5
6
7
8
9
10
11


has_next¶
[Source]
Indicates whether there are any values remaining in the iterator.
fun box has_next()
: Bool val

Returns¶

Bool val

next¶
[Source]
Return the next node in the iterator, advancing the iterator by one element.
Order of return is determined by reverse argument during creation.
fun ref next()
: N->A ?

Returns¶


_SignedPartialArithmetic.rem_partial[ILong, ULong](this, y)?

fun divrem_partial(y: ILong): (ILong, ILong) ? =>
_SignedPartialArithmetic.divrem_partial[ILong, ULong](this, y)?

fun fld_partial(y: ILong): ILong ? =>
_SignedPartialArithmetic.fld_partial[ILong, ULong](this, y)?

fun mod_partial(y: ILong): ILong ? =>
_SignedPartialArithmetic.mod_partial[ILong, ULong](this, y)?

primitive ISize is SignedInteger[ISize, USize]
new create(value: ISize) => value
new from[A: (Number & Real[A] val)](a: A) => a.isize()

new min_value() =>
ifdef ilp32 then
-0x8000_0000
else
-0x8000_0000_0000_0000


: Iterator[(T^ | (T^ , Iterator[T^] ref))] ref^

Parameters¶

rnd: Randomness ref

Returns¶

Iterator[(T^ | (T^ , Iterator[T^] ref))] ref^

value_iter¶
[Source]
fun box value_iter(
rnd: Randomness ref)
: Iterator[T^] ref

Parameters¶

rnd: Randomness ref


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


Parameters¶

worker: DisposableActor tag

dispose¶
[Source]
Dispose of the actors in the set and then clear the set.
be dispose()


Subtract y from this number.
If the operation overflows/underflows this function errors.
fun box sub_partial(
y: A)
: A ?

Parameters¶

y: A

Returns¶

A ?

mul_partial¶
[Source]
Multiply y with this number.
If the operation overflows this function errors.
fun box mul_partial(


Parameters¶

a: A

Returns¶

None val

pop¶
[Source]
Removes the tail value, raising an error if the tail is empty.
let my_list = List[String].from(["a"; "b"; "c"])
try my_list.pop() end  // Returns "c" and my_list is ["a"; "b"]

fun ref pop()
: A^ ?

Returns¶


fun box so_timestamp_monotonic()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_upcallclosewait¶
[Source]


"""
if
not path.caps(FileLink)
or not path.caps(FileLookup)
or not path.caps(FileCreate)
or not source.caps(FileLink)
or (_fd == -1)
then
return false
end

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

ifdef linux or bsd then
0 == @symlinkat(source.path.cstring(), _fd, link_name.cstring())
else
source.symlink(path')
end
else


fulfill.pony

1
2
3
4
5
6
7
8
9
10
11


Public Functions¶
value¶
[Source]
fun box value()
: U32 val

Returns¶

U32 val

eq¶
[Source]
fun box eq(
that: FileRemove val)
: Bool val

Parameters¶


ReadSeq[A: A]¶
[Source]
The readable interface of a sequence.
interface box ReadSeq[A: A]

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

Returns¶


Bool val

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

Parameters¶

y: box->A

Returns¶

Bool val

gt¶
[Source]


Array[NetAddress val] iso^

ip4¶
[Source]
Gets all IPv4 addresses for a host and service.
fun box ip4(
auth: DNSAuth val,
host: String val,
service: String val)
: Array[NetAddress val] iso^

Parameters¶

auth: DNSAuth val
host: String val
service: String val

Returns¶


| (_, _) => return i
end
end
error

fun index(i: USize): (this->K, this->V) ? =>
"""
Returns the key and value at a given index.
Raise an error if the index is not populated.
"""
_array(i)? as (this->K, this->V)

fun ref compact() =>
"""
Minimise the memory used for the map.
"""
_resize(((_size * 4) / 3).next_pow2().max(8))

fun clone[H2: HashFunction[this->K!] val = H]()
: HashMap[this->K!, this->V!, H2]^


fun box ipproto_ttp()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_udplite¶
[Source]


fun box sctp_initmsg()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_i_want_mapped_v4_addr¶
[Source]


intersect¶
[Source]
The intersection of this and that.
fun ref intersect(
that: Flags[A, B] box)
: None val

Parameters¶

that: Flags[A, B] box

Returns¶

None val

difference¶
[Source]
The symmetric difference of this and that.


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


Parameters¶

target: String val
uid: U32 val
gid: U32 val

Returns¶

Bool val

touchat¶
[Source]
Set the last access and modification times of the directory to now.
fun box touchat(
target: String val)
: Bool val

Parameters¶


.intersperse(8)

0 8 1 8 2
fun ref intersperse(
value: A,
n: USize val = 1)
: Iter[A!] ref

Parameters¶

value: A
n: USize val = 1

Returns¶

Iter[A!] ref

last¶
[Source]


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

Returns¶

Bool val

next¶
[Source]
fun ref next()
: A

Returns¶

A


1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071


572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591


[Source]
Return the value if its in the set, otherwise raise an error.
fun box apply(
value: box->A!)
: this->A ?

Parameters¶

value: box->A!

Returns¶

this->A ?

contains¶
[Source]
Checks whether the set contains the value.
fun box contains(
value: box->A!)


any.pony

1interface tag Any


Fortunately, avoiding this limitation is relatively painless. Whenever you need to call an FFI function from a default method implementation, consider moving said function to a separate type:

```pony
use @printf[I32](fmt: Pointer[None] tag, ...)

trait Foo
fun apply() =>
// OK
Printf("Hello from trait Foo\n")

primitive Printf
fun apply(str: String) =>
@printf(str.cstring())

actor Main is Foo
new create(env: Env) =>
this.apply()
```


alt: Bool val
shift: Bool val

Returns¶

None val

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

Parameters¶

ctrl: Bool val
alt: Bool val


take¶
[Source]
There are no elements to take from the empty list.
fun box take(
n: USize val)
: Nil[A] val

Parameters¶

n: USize val

Returns¶

Nil[A] val

take_while¶
[Source]
There are no elements to take from the empty list.


```

The compiler can optimise a tail-recursive function to a loop, completely avoiding call stack growth. Note that this is an _optimisation_ which is only performed in release builds (i.e. builds without the `-d` flag passed to ponyc.) If you need to avoid stack growth in debug builds as well then you have to write your function as a loop manually.

If the tail-recursive version of your algorithm isn't practical to implement, there are other ways to control stack growth depending on your algorithm. For example, you can implement your algorithm using an explicit stack data structure instead of implicitly using the call stack to store data.

Note that light recursion usually doesn't cause problems. Unless your amount of recursive calls is in the hundreds, you're unlikely to encounter this problem.


### Example

```pony
Iter[I64]([1; 2; 3].values())
.fold[I64](0, {(sum, x) => sum + x })
```
`6`
"""
var acc' = consume acc
for a in _iter do
acc' = f(consume acc', a)
end
acc'

fun ref fold_partial[B](acc: B, f: {(B, A!): B^ ?} box): B^ ? =>
"""
A partial version of `fold`.
"""
var acc' = consume acc
for a in _iter do


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


I8 val

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

Returns¶

U8 val

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

Returns¶


fun box u128()
: U128 val

Returns¶

U128 val

ulong¶
[Source]
fun box ulong()
: ULong val

Returns¶

ULong val

usize¶
[Source]


The Generator for the first argument to your property4 method.
fun box gen1()
: Generator[T1] box

Returns¶

Generator[T1] box

gen2¶
[Source]
The Generator for the second argument to your property4 method.
fun box gen2()
: Generator[T2] box

Returns¶

Generator[T2] box


Parameters¶

rnd: Randomness ref

Returns¶

Iterator[(T^ , Iterator[T^] ref)] ref


y: box->A

Returns¶

Bool val

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

Parameters¶

y: box->A

Returns¶

Bool val


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

fun get(): U32 =>
_x

class Bar
fun f() =>
var a: Foo = Foo.from_int(3)
var b: U32 = a.get()
var c: U32 = g(b)

fun g(x: U32): U32 =>
x + 1

```

Constructors can also be called on an expression. Here an object is created of the same type as the specified expression - this is equivalent to directly specifying the type.

```pony


Determine if a byte is a path separator.
"""
ifdef windows then
(c == '/') or (c == '\\')
else
c == '/'
end

fun tag sep(): String =>
"""
Return the path separator as a string.
"""
ifdef windows then "\\" else "/" end

fun is_abs(path: String): Bool =>
"""
Return true if the path is an absolute path.
"""
try
ifdef windows then


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


new val from_concat(ss0: _StringSeq val, ss1: _StringSeq val) =>
strings = ss0.strings.concat(ss1.strings.values())

fun string(): String iso^ =>
let str = recover String() end
str.push('[')
for s in strings.values() do
if str.size() > 1 then str.push(',') end
str.append(s)
end
str.push(']')
str

fun size(): USize => strings.size()
fun apply(i: USize): this->String ? => strings(i)?
fun values(): Iterator[this->String]^ => strings.values()

type _Value is (Bool | String | I64 | U64 | F64 | _StringSeq val)


BenchmarkList¶
[Source]
interface tag BenchmarkList

Public Functions¶
benchmarks¶
[Source]
fun tag benchmarks(
bench: PonyBench tag)
: None val

Parameters¶


fun box shr_unsafe(
y: U8 val)
: I8 val

Parameters¶

y: U8 val

Returns¶

I8 val

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

Returns¶


new create(v: Vec[A]) => _pairs = VecPairs[A](v)

fun has_next(): Bool => _pairs.has_next()

fun ref next(): val->A ? => _pairs.next()?._2

class VecPairs[A: Any #share]
let _leaf_nodes: Array[Array[A] val]
var _idx: USize = 0
var _i: USize = 0

new create(v: Vec[A]) =>
_leaf_nodes = v._leaf_nodes()

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

fun ref next(): (USize, A) ? =>
var leaves = _leaf_nodes(0)?
let v = leaves(_idx = _idx + 1)?


MinHeapPriority[A: Comparable[A] #read]¶
[Source]
primitive val MinHeapPriority[A: Comparable[A] #read] is
_BinaryHeapPriority[A] val

Implements¶

_BinaryHeapPriority[A] val

Constructors¶
create¶
[Source]


_process.pony

1
2
3
4
5
6
7
8
9
10
11


add_partial¶
[Source]
Add y to this number.
If the operation overflows this function errors.
fun box add_partial(
y: A)
: A ?

Parameters¶

y: A

Returns¶

A ?

sub_partial¶
[Source]


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


312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331


create¶
[Source]
Wrap a Property1 to make it mimic the PonyTest
UnitTest.
If name' is given, use this as the test name.
If not, use the property's name().
new iso create(
p1: Property1[T] iso,
name': (String val | None val) = reference)
: Property1UnitTest[T] iso^

Parameters¶

p1: Property1[T] iso
name': (String val | None val) = reference

Returns¶

Property1UnitTest[T] iso^


fun box sctp_cause_resource_shortage()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_cause_stale_cookie¶
[Source]


# Nominal and structural subtyping in Pony

When discussing subtyping in Pony, it is common to say that `trait` is nominal subtyping and `interface` is structural subtyping, however, that isn't really true.

Both `trait` and `interface` can establish a relationship via nominal subtyping. Only `interface` can be used for structural subtyping.


1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471


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


USize val

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

Returns¶

F32 val

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

Returns¶


y: ULong val

Returns¶

Bool val

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

Parameters¶

y: ULong val

Returns¶


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


fun tag apply[optional A: Any tag](
key: String val)
: Promise[A] tag

Parameters¶

key: String val

Returns¶

Promise[A] tag


fun box bytewidth()
: USize val

Returns¶

USize val

min¶
[Source]
fun box min(
y: U8 val)
: U8 val

Parameters¶

y: U8 val

Returns¶


_set(_size, 0)
end
elseif (_size + 1) < _alloc then
_alloc = (_size + 1)
let old_ptr = _ptr = Pointer[U8]._alloc(_alloc)
old_ptr._copy_to(_ptr, _size)
_set(_size, 0)
end

fun ref recalc() =>
"""
Recalculates the string length. This is only needed if the string is
changed via an FFI call. If a null terminator byte is not found within the
allocated length, the size will not be changed.
"""
var s: USize = 0

while (s < _alloc) and (_ptr._apply(s) > 0) do
s = s + 1
end


Returns¶

U32 val

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

Returns¶

U32 val

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


fun size(): USize =>
"""
The number of items in the set.
"""
_map.size()

fun space(): USize =>
"""
The available space in the set.
"""
_map.space()

fun apply(value: box->A!): this->A ? =>
"""
Return the value if its in the set, otherwise raise an error.
"""
_map(value)?

fun contains(value: box->A!): Bool =>
"""


that: FileRead val

Returns¶

Bool val

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

Parameters¶

that: FileRead val

Returns¶


descriptor¶
[Source]
Initialises with the rights on the given file descriptor.
new ref descriptor(
fd: I32 val)
: CapRights0 ref^

Parameters¶

fd: I32 val

Returns¶

CapRights0 ref^

Public Functions¶
set¶
[Source]
fun ref set(


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


else
error
end

class ListValues[A, N: ListNode[A] #read] is Iterator[N->A]
"""
Iterate over the values in a `List`.
"""
var _next: (N | None)
let _reverse: Bool

new create(head: (N | None), reverse: Bool = false) =>
"""
Build the iterator over values.

`reverse` of `false` iterates forward, while
`reverse` of `true` iterates in reverse.
"""
_next = head
_reverse = reverse


fun box sock_raw()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sock_seqpacket¶
[Source]


y: F32 val

Returns¶

Bool val

gt¶
fun box gt(
y: F32 val)
: Bool val

Parameters¶

y: F32 val

Returns¶

Bool val


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


Serialise¶
[Source]
primitive val Serialise

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

Returns¶

Serialise val^


| 0 =>
// System call was successful
| let errno: U32 =>
// System call failed
end

fun ref setsockopt(
level: I32 val,
option_name: I32 val,
option: Array[U8 val] ref)
: U32 val

Parameters¶

level: I32 val
option_name: I32 val
option: Array[U8 val] ref

Returns¶


Parameters¶

y: box->A

Returns¶

Bool val

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

Parameters¶

y: box->A

Returns¶


end
else
let r = @fdatasync(_fd)
if r < 0 then
_errno = _get_error()
end
end
end
_unsynced_data = false

fun ref set_length(len: USize): Bool =>
"""
Change the file size. If it is made larger, the new contents are undefined.
"""
if path.caps(FileTruncate) and writeable and (_fd != -1) then
let pos = position()
let result = ifdef windows then
@_chsize_s(_fd, len.i64())
else
ifdef linux then


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

Implements¶

UnsignedInteger[U128 val] val

Constructors¶
create¶
[Source]


Returns true if the vector contains value, false otherwise.
fun val contains(
value: val->A,
predicate: {(A, A): Bool}[A] val = lambda)
: Bool val

Parameters¶

value: val->A
predicate: {(A, A): Bool}[A] val = lambda

Returns¶

Bool val

slice¶
[Source]
Return a vector that is a clone of a portion of this vector. The range is
exclusive and saturated.


PonyCheck¶
[Source]
primitive val PonyCheck

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

Returns¶

PonyCheck val^


UnitTest¶
[Source]
Each unit test class must provide this trait. Simple tests only need to
define the name() and apply() functions. The remaining functions specify
additional test options.
trait ref UnitTest

Public Functions¶
name¶
[Source]
Report the test name, which is used when printing test results and on the
command line to select tests to run.
fun box name()


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


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


132
133
134
135
136interface TCPConnectionNotify
"""
Notifications for TCP connections.

For an example of using this class please see the documentation for the
`TCPConnection` and `TCPListener` actors.
"""
fun ref accepted(conn: TCPConnection ref) =>
"""
Called when a TCPConnection is accepted by a TCPListener.
"""
None

fun ref proxy_via(host: String, service: String): (String, String) =>
"""
Called before before attempting to connect to the destination server


prefix_spec.pony

1
2
3
4
5
6
7
8
9
10
11trait val PrefixSpec


fun box fcntl()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

fpathconf¶
[Source]


y: U32 val

Returns¶

U32 val ?

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

Parameters¶

y: U32 val

Returns¶


572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591


fun shrink(u: U): ValueAndShrink[U] =>
"""
We can only shrink if T is a subtype of U.

This method should in general not be called on this generator
as it is always returning shrinks with the call to `generate`
and they should be used for executing the shrink, but in case
a strange hierarchy of generators is used, which does not make use of
the pre-generated shrink results, we keep this method here.
"""
match u
| let ut: T =>
(let uts: T, let shrunken: Iterator[T^]) = _gen.shrink(consume ut)
(fn(consume uts), _map_shrunken(shrunken))
else
(consume u, Poperator[U].empty())
end

fun _map_shrunken(shrunken: Iterator[T^]): Iterator[U^] =>
Iter[T^](shrunken)


72
73use "collections"

actor Custodian
"""
A Custodian keeps a set of actors to dispose. When the Custodian is disposed,
it disposes of the actors in its set and then clears the set.


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

Parameters¶

that: FileBadFileNumber val

Returns¶

Bool val

ne¶
[Source]


new iso create(n: U64) =>
_n = n

fun name(): String =>
"_Fib(" + _n.string() + ")"

fun apply() =>
DoNotOptimise[U64](_fib(_n))
DoNotOptimise.observe()

fun _fib(n: U64): U64 =>
if n < 2 then 1
else _fib(n - 1) + _fib(n - 2)
end

class iso _Timer is AsyncMicroBenchmark
// Asynchronous benchmark of timer.
let _ts: Timers = Timers
let _ns: U64


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


ifdef linux or windows then
(@ponyint_address_length(this)).u8()
else
ifdef bigendian then
((_family >> 8) and 0xff).u8()
else
(_family and 0xff).u8()
end
end

fun family() : U8 =>
"""
Returns the `family`.
"""

ifdef linux or windows then
ifdef bigendian then
((_family >> 8) and 0xff).u8()
else


Parameters¶

y: ISize val

Returns¶

ISize val

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

Parameters¶

y: ISize val

Returns¶


the `apply` method of the `TimerNotify` object that was passed to it
when it was created.

The following example waits 5 seconds and then fires every 2
seconds, and when it fires the `TimerNotify` object prints how many
times it has been called:

```pony
use "time"

actor Main
new create(env: Env) =>
let timers = Timers
let timer = Timer(Notify(env), 5_000_000_000, 2_000_000_000)
timers(consume timer)

class Notify is TimerNotify
let _env: Env
var _counter: U32 = 0


# Expressing a different type of an object

In Pony, each object is an instance of a single concrete type, which is the most specific type for that object. But the object can also be held as part of a "wider" abstract type such as an interface, trait, or type union which the concrete type is said to be a subtype of.

`as` (like `match`) allows a program to check the runtime type of an abstract-typed value to see whether or not the object matches a given type which is more specific. If it doesn't match the more specific type, then a runtime `error` is raised. For example:

```pony
class Cat
fun pet() =>
...

type Animal is (Cat | Fish | Snake)

fun pet(animal: Animal) =>
try
// raises error if not a Cat
let cat: Cat = animal as Cat
cat.pet()
end
```


fun subc(y: U32): (U32, Bool) =>
@"llvm.usub.with.overflow.i32"(this, y)

fun mulc(y: U32): (U32, Bool) =>
@"llvm.umul.with.overflow.i32"(this, y)

fun divc(y: U32): (U32, Bool) =>
_UnsignedCheckedArithmetic.div_checked[U32](this, y)

fun remc(y: U32): (U32, Bool) =>
_UnsignedCheckedArithmetic.rem_checked[U32](this, y)

fun add_partial(y: U32): U32 ? =>
_UnsignedPartialArithmetic.add_partial[U32](this, y)?

fun sub_partial(y: U32): U32 ? =>
_UnsignedPartialArithmetic.sub_partial[U32](this, y)?

fun mul_partial(y: U32): U32 ? =>


is_ip4¶
[Source]
Returns true if the host is a literal IPv4 address.
fun box is_ip4(
host: String val)
: Bool val

Parameters¶

host: String val

Returns¶

Bool val

is_ip6¶
[Source]
Returns true if the host is a literal IPv6 address.
fun box is_ip6(


let symlink: Bool = false
"""`true` if `filepath` points to a symbolic link."""

let broken: Bool = false
"""`true` if `filepath` points to a broken symlink."""

new val create(from: FilePath) ? =>
"""
This will raise an error if the FileStat capability isn't available or the
path doesn't exist.
"""
if not from.caps(FileStat) then
error
end

filepath = from

if not @pony_os_stat(from.path.cstring(), this) then
error
end


Returns¶

Bool val

gt_unsafe¶
[Source]
Unsafe operation.
If any input 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 gt_unsafe(
y: box->A)
: Bool val

Parameters¶

y: box->A

Returns¶


try
_Stringify.apply[T](_shrinker.next()?)
else
// no more shrink samples, report previous failed example
fail(failed_repr, round_num)
return
end
// callback for asynchronous shrinking or aborting on error case
let run_notify =
recover val
this~complete_shrink(failed_repr, current_repr)
end
let helper = PropertyHelper(
_env,
this,
run_notify,
this._current_round,
_params.string()
)
_pass = true // will be set to false by fail calls


Less¶
[Source]
primitive val Less is
Equatable[(Less val | Equal val | Greater val)] ref

Implements¶

Equatable[(Less val | Equal val | Greater val)] ref

Constructors¶
create¶
[Source]


fun box tcpi_opt_ecn_seen()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcpi_opt_syn_data¶
[Source]


Parameters¶

value: val->A

Returns¶

HashSet[A, H] val

sub¶
[Source]
Return a set with the value removed.
fun val sub(
value: val->A)
: HashSet[A, H] val

Parameters¶

value: val->A


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


## Windows

1. Create folder at `C:\Users\<yourusername>\pony`.
2. Right click on "Start" and click on "Control Panel". Select "System and Security", then click on "System".
3. From the menu on the left, select the "Advanced systems settings".
4. Click the "Environment Variables" button at the bottom.
5. Click "New" from the "User variables" section.
6. Type `PONYPATH` into the "Variable name" field.
7. Type `%PONYPATH%;%USERPROFILE%\pony` into the "Variable value" field.
8. Click OK.

You can also add to `PONYPATH` from the command prompt via:

```bash
setx PONYPATH %PONYPATH%;%USERPROFILE%\pony
```


for rec in _records.values() do
if rec._report(_verbose) then
pass_count = pass_count + 1
else
fail_count = fail_count + 1
end
end

// Next we print the pass / fail stats.
_env.out.print("----")
_env.out.print("---- " + _records.size().string() + " test"
+ _plural(_records.size()) + " ran.")
_env.out.print(_Color.green() + "---- Passed: " + pass_count.string()
+ _Color.reset())

if fail_count == 0 then
// Success, nothing failed.
return
end


let finish = offset_to_index(to).min(_size)

if (start < _size) and (start < finish) and (finish <= _size) then
let fragment_len = finish - start
let new_size = _size - fragment_len
var i = start

while i < new_size do
_set(i, _ptr._apply(i + fragment_len))
i = i + 1
end

_size = _size - fragment_len
_set(_size, 0)
end

fun ref remove(s: String box): USize =>
"""
Remove all instances of s from the string. Returns the count of removed
instances.


992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011


Returns the option value as an U64, defaulting to 0.
"""
try _value as U64 else U64(0) end

fun f64(): F64 =>
"""
Returns the option value as an F64, defaulting to 0.0.
"""
try _value as F64 else F64(0) end

fun string_seq(): ReadSeq[String] val =>
"""
Returns the option value as a ReadSeq[String], defaulting to empty.
"""
try
_value as _StringSeq val
else
recover val Array[String]() end
end


r.set(value)
end
end

for value in that.values() do
try
this(value)?
else
r.set(value)
end
end
r

fun without[K: HashFunction[this->A!] val = H](
that: this->HashSet[A, H])
: HashSet[this->A!, K]^
=>
"""
Create a set with the elements of this that are not in that.
"""


# A simple case

A simple case is to create a "callback" function. For example:

```pony
class Foo
var _f: F64 = 0

fun ref addmul(add: F64, mul: F64): F64 =>
_f = (_f + add) * mul

class Bar
fun apply() =>
let foo: Foo = Foo
let f = foo~addmul(3)
f(4)
```

This is a bit of a silly example, but hopefully, the idea is clear. We partially apply the `addmul` function on `foo`, binding the receiver to `foo` and the `add` argument to `3`. We get back an object, `f`, that has an `apply` method that takes a `mul` argument. When it's called, it in turn calls `foo.addmul(3, mul)`.


i: USize val)
: this->ListNode[A] ref ?

Parameters¶

i: USize val

Returns¶

this->ListNode[A] ref ?

remove¶
[Source]
Remove the i-th node, raising an error if the index is out of bounds, and
returning the removed node.
let my_list = List[String].from(["a"; "b"; "c"])
try my_list.remove(0)? end // Returns a ListNode[String] containing "a" and List now contains ["b"; "c"]

fun ref remove(


fun box u128()
: U128 val

Returns¶

U128 val

ulong¶
[Source]
fun box ulong()
: ULong val

Returns¶

ULong val

usize¶
[Source]


fun set_time(atime: (I64, I64), mtime: (I64, I64)): Bool =>
"""
Set the last access and modification times of a path to the given values.
"""
if not caps(FileTime) then
return false
end

ifdef windows then
var tv: (I64, I64) = (atime._1, mtime._1)
0 == @_utime64(path.cstring(), addressof tv)
else
var tv: (ILong, ILong, ILong, ILong) =
( atime._1.ilong(), atime._2.ilong() / 1000,
mtime._1.ilong(), mtime._2.ilong() / 1000 )

0 == @utimes(path.cstring(), addressof tv)
end

struct ref _TokenPrivileges


then
error
end

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

ifdef linux or bsd then
let fd' =
@openat(_fd, target.cstring(),
@ponyint_o_rdonly() or @ponyint_o_cloexec(),
I32(0x1B6))
recover File._descriptor(fd', path')? end
else
recover File.open(path') end
end

fun info(): FileInfo ? =>
"""
Return a FileInfo for this directory. Raise an error if the fd is invalid
or if we don't have FileStat permission.


fun box mmap()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

mmap_w¶
[Source]


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


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


[Source]
Encode for MIME (RFC 2045).
fun box encode_mime(
data: ReadSeq[U8 val] box)
: String iso^

Parameters¶

data: ReadSeq[U8 val] box

Returns¶

String iso^

encode_url[optional A: Seq[U8 val] iso]¶
[Source]
Encode for URLs (RFC 4648). Padding characters are stripped by default.
fun box encode_url[optional A: Seq[U8 val] iso](
data: ReadSeq[U8 val] box,


y: U8 val

Returns¶

U8 val

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

Returns¶

U8 val

add¶
[Source]


I8 val

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

Parameters¶

y: I8 val

Returns¶

I8 val

divrem¶
[Source]


fun box ip_pmtudisc_interface()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_pmtudisc_probe¶
[Source]


that: (Exited val | Signaled val)

Returns¶

Bool val


update_u128[optional B: (A & Real[B] val & U8 val)]¶
[Source]
Write a U128 at offset. This is only allowed for an array of U8s.
fun ref update_u128[optional B: (A & Real[B] val & U8 val)](
offset: USize val,
value: U128 val)
: U128 val ?

Parameters¶

offset: USize val
value: U128 val

Returns¶

U128 val ?


from_cpointer(start_ptr._unsafe(), size', alloc)
else
create()
end
end

(consume this, consume right)

fun iso unchop(b: Array[A] iso):
((Array[A] iso^, Array[A] iso^) | Array[A] iso^)
=>
"""
Unchops two iso arrays to return the original array they were chopped from.
Both input arrays are isolated and mutable and were originally chopped from
a single array. This function checks that they are indeed two arrays chopped
from the same original array and can be unchopped before doing the
unchopping and returning the unchopped array. If the two arrays cannot be
unchopped it returns both arrays without modifying them.
The operation does not allocate a new array pointer nor copy elements.


y: I8 val

Returns¶

I8 val

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

Parameters¶

y: I8 val

Returns¶


map.pony

1
2
3
4
5
6
7
8
9
10
11


As the returned value can also be iso, it needs to be consumed and
returned.
It is preferred to already return a ValueAndShrink from generate.
fun box shrink(
t: T)
: (T^ , Iterator[T^] ref)

Parameters¶

t: T

Returns¶

(T^ , Iterator[T^] ref)

generate_value¶
[Source]
fun box generate_value(
rnd: Randomness ref)


fun sctp_partial_delivery_point():I32 => @pony_os_sockopt_option(I32(682))
fun sctp_pcb_copy_flags():I32 => @pony_os_sockopt_option(I32(683))
fun sctp_pcb_flags_accepting():I32 => @pony_os_sockopt_option(I32(684))
fun sctp_pcb_flags_adaptationevnt():I32 => @pony_os_sockopt_option(I32(685))
fun sctp_pcb_flags_assoc_resetevnt():I32 => @pony_os_sockopt_option(I32(686))
fun sctp_pcb_flags_authevnt():I32 => @pony_os_sockopt_option(I32(687))
fun sctp_pcb_flags_autoclose():I32 => @pony_os_sockopt_option(I32(688))
fun sctp_pcb_flags_auto_asconf():I32 => @pony_os_sockopt_option(I32(689))
fun sctp_pcb_flags_blocking_io():I32 => @pony_os_sockopt_option(I32(690))
fun sctp_pcb_flags_boundall():I32 => @pony_os_sockopt_option(I32(691))
fun sctp_pcb_flags_bound_v6():I32 => @pony_os_sockopt_option(I32(692))
fun sctp_pcb_flags_close_ip():I32 => @pony_os_sockopt_option(I32(693))
fun sctp_pcb_flags_connected():I32 => @pony_os_sockopt_option(I32(694))
fun sctp_pcb_flags_donot_heartbeat():I32 => @pony_os_sockopt_option(I32(695))
fun sctp_pcb_flags_dont_wake():I32 => @pony_os_sockopt_option(I32(696))
fun sctp_pcb_flags_do_asconf():I32 => @pony_os_sockopt_option(I32(697))
fun sctp_pcb_flags_do_not_pmtud():I32 => @pony_os_sockopt_option(I32(698))
fun sctp_pcb_flags_dryevnt():I32 => @pony_os_sockopt_option(I32(699))
fun sctp_pcb_flags_explicit_eor():I32 => @pony_os_sockopt_option(I32(700))
fun sctp_pcb_flags_ext_rcvinfo():I32 => @pony_os_sockopt_option(I32(701))


Public Functions¶
value¶
[Source]
fun box value()
: U32 val

Returns¶

U32 val

eq¶
[Source]
fun box eq(
that: FileExec val)
: Bool val

Parameters¶


# Partial application is just a lambda

Under the hood, we're assembling an object literal for partial application, just as if you had written a lambda yourself. It captures aliases of some of the lexical scope as fields and has an `apply` function that takes some, possibly reduced, number of arguments. This is actually done as sugar, by rewriting the abstract syntax tree for partial application to be an object literal, before code generation.

That means partial application results in an anonymous class and returns a `ref`. If you need another reference capability, you can wrap partial application in a `recover` expression. It also means that we can't consume unique fields for a lambda, as the apply method might be called many times.


var ponygcinitial: USize = 14
"""
Defer garbage collection until an actor is using at least 2^N bytes.
Defaults to 2^14.
"""

var ponygcfactor: F64 = 2.0
"""
After GC, an actor will next be GC'd at a heap memory usage N times its
current value. This is a floating point value. Defaults to 2.0.
"""

var ponynoyield: Bool = false
"""
Do not yield the CPU when no work is available.
"""

var ponynoblock: Bool = false
"""


trait Bald
fun hair(): Bool => false

class Bob is (Named & Bald)
```

It is possible for a class to have relationships with multiple categories. In the above example, the class `Bob` _provides both Named and Bald_.

```pony
trait Named
fun name(): String => "Bob"

trait Bald is Named
fun hair(): Bool => false

class Bob is Bald
```

It is also possible to combine categories together. In the example above, all `Bald` classes are automatically `Named`. Consequently, the `Bob` class has access to both hair() and name() default implementation of their respective trait. One can think of the `Bald` category to be more specific than the `Named` one.


If this is 0, the result is undefined.
"""
@"llvm.ctlz.i8"(this.u8(), true)

fun ctz_unsafe(): U8 =>
"""
Unsafe operation.
If this is 0, the result is undefined.
"""
@"llvm.cttz.i8"(this.u8(), true)

fun bitwidth(): U8 => 8

fun bytewidth(): USize => bitwidth().usize() / 8

fun min(y: I8): I8 => if this < y then this else y end
fun max(y: I8): I8 => if this > y then this else y end

fun fld(y: I8): I8 =>
_SignedArithmetic.fld[I8, U8](this, y)


fun box ip_fw_table_add()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_fw_table_flush¶
[Source]


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


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


exclusion_group¶
fun box exclusion_group()
: String val

Returns¶

String val

timed_out¶
fun ref timed_out(
h: TestHelper val)
: None val

Parameters¶

h: TestHelper val

Returns¶


0 4 1 5 2
fun ref interleave_shortest(
other: Iterator[A] ref)
: Iter[A!] ref

Parameters¶

other: Iterator[A] ref

Returns¶

Iter[A!] ref

intersperse¶
[Source]
Return an iterator that yields the value after every n elements of the
original iterator.
Example¶
Iter[USize](Range(0, 3))


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


with the same probability, returning a union type of this generator and
the other one.
"""
Generator[(T | U)](
object is GenObj[(T | U)]
fun generate(rnd: Randomness): GenerateResult[(T | U)] ? =>
if rnd.bool() then
_gen.generate_and_shrink(rnd)?
else
other.generate_and_shrink(rnd)?
end

fun shrink(t: (T | U)): ValueAndShrink[(T | U)] =>
match consume t
| let tt: T => _gen.shrink(consume tt)
| let tu: U => other.shrink(consume tu)
end
end
)


Returns¶

USize val

eq¶
[Source]
Use the structural equality function from the type parameter.
fun box eq(
x: box->A,
y: box->A)
: Bool val

Parameters¶

x: box->A
y: box->A

Returns¶


[Source]
fun box signal()
: U32 val

Returns¶

U32 val

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

Returns¶

U32 val

oneshot¶


fun box ip_bound_if()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_default_multicast_loop¶
[Source]


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


ByteSeq¶
[Source]
type ByteSeq is
(String val | Array[U8 val] val)

Type Alias For¶

(String val | Array[U8 val] val)


SetIs[A: Any #share]¶
[Source]
type SetIs[A: Any #share] is
HashSet[A, HashIs[A] val] val

Type Alias For¶

HashSet[A, HashIs[A] val] val


fun box mcast_undefined()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

mrt_add_mfc¶
[Source]


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


552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571


## Open world enumerations

Traits allow you to create "open world enumerations" that others can participate in. For example:

```pony
trait Color

primitive Red is Color
primitive Blue is Color
```

Here we are using a trait to provide a category of things, `Color`, that any other types can opt into by declaring itself to be a `Color`. This creates an "open world" of enumerations that you can't do using the more traditional Pony approach using type unions.

```pony
primitive Red
primitive Blue

type Color is (Red | Blue)
```


Parameters¶

auth: OutputSerialisedAuth val

Returns¶

Array[U8 val] val


fun ref not_listening(sock: UDPSocket ref) =>
None

actor Main
new create(env: Env) =>
try
let destination =
DNS.ip4(DNSAuth(env.root), "localhost", "8989")(0)?
UDPSocket(UDPAuth(env.root),
recover MyUDPNotify(env.out, consume destination) end)
end

actor tag UDPSocket is
AsioEventNotify tag

Implements¶

AsioEventNotify tag


=>
"""
Generate a `Seq[T]` where `T` must be sendable (i.e. it must have a
reference capability of either `tag`, `val`, or `iso`).

The constraint of the elements being sendable stems from the fact that
there is no other way to populate the iso seq if the elements might be
non-sendable (i.e. ref), as then the seq would leak references via
its elements.
"""
Generator[S](
object is GenObj[S]
let _gen: GenObj[T] = gen
fun generate(rnd: Randomness): GenerateResult[S] =>
let size = rnd.usize(min, max)

let result: S = recover iso S.create(size) end
let iter = _gen.value_iter(rnd)
var i = USize(0)


y: I64 val

Returns¶

I64 val ?

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

Parameters¶

y: I64 val

Returns¶


"""
Return an iterator over the values in the set.
"""
_map.values()


fun box ipv6_fl_f_create()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_fl_f_reflect¶
[Source]


412
413
414
415
416
417
418
419use "time"

use @_mkdir[I32](dir: Pointer[U8] tag) if windows
use @mkdir[I32](path: Pointer[U8] tag, mode: U32) if not windows
use @_rmdir[I32](path: Pointer[U8] tag) if windows
use @rmdir[I32](path: Pointer[U8] tag) if not windows
use @_unlink[I32](path: Pointer [U8] tag) if windows
use @unlink[I32](path: Pointer [U8] tag) if not windows
use @rename[I32](old_path: Pointer[U8] tag, new_path: Pointer[U8] tag)
use @pony_os_eexist[I32]()
use @CreateSymbolicLinkA[U8](src_name: Pointer[U8] tag,
target_name: Pointer[U8] tag, flags: U32) if windows
use @symlink[I32](path: Pointer[U8] tag, path2: Pointer[U8] tag)


(this, this)

fun drop(n: USize): Nil[A] =>
"""
There are no elements to drop from the empty list.
"""
this

fun drop_while(f: {(val->A): Bool} box): Nil[A] =>
"""
There are no elements to drop from the empty list.
"""
this

fun take(n: USize): Nil[A] =>
"""
There are no elements to take from the empty list.
"""
this


var any_exec: Bool = false
"""`true if every user can execute the file."""

fun ref exec() =>
"""
Set the executable flag for everyone.
"""
owner_exec = true
group_exec = true
any_exec = true

fun ref shared() =>
"""
Set the write flag for everyone to the same as owner_write.
"""
group_write = owner_write
any_write = owner_write

fun ref group() =>
"""


fun box shr(
y: USize val)
: USize val

Parameters¶

y: USize val

Returns¶

USize val

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

Parameters¶


VecPairs[A: Any #share]¶
[Source]
class ref VecPairs[A: Any #share]

Constructors¶
create¶
[Source]
new ref create(
v: Vec[A] val)
: VecPairs[A] ref^

Parameters¶


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


12primitive Bool is Stringable
new create(from: Bool) => from

fun eq(y: Bool): Bool => this == y
fun ne(y: Bool): Bool => this != y
fun op_and(y: Bool): Bool => this and y
fun op_or(y: Bool): Bool => this or y
fun op_xor(y: Bool): Bool => this xor y
fun op_not(): Bool => not this

fun string(): String iso^ =>
(if this then "true" else "false" end).string()


NetAddress¶
[Source]
Represents an IPv4 or IPv6 address. The family field indicates the address
type. The addr field is either the IPv4 address or the IPv6 flow info. The
addr1-4 fields are the IPv6 address, or invalid for an IPv4 address. The
scope field is the IPv6 scope, or invalid for an IPv4 address.
This class is modelled after the C data structure for holding socket
addresses for both IPv4 and IPv6 sockaddr_storage.
Use the name method to obtain address/hostname and port/service as Strings.
class val NetAddress is
Equatable[NetAddress val] ref

Implements¶


Returns¶

U128 val

ctz_unsafe¶
[Source]
Unsafe operation.
If this is 0, the result is undefined.
fun box ctz_unsafe()
: U128 val

Returns¶

U128 val

bitwidth¶
[Source]


fun box so_wantmore()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_wifi_status¶
[Source]


// to see if it's ok to unsubscribe.
if not @pony_asio_event_get_disposable(event) then
@pony_asio_event_unsubscribe(event)
end
@pony_os_socket_close(fd)
_try_shutdown()
end
else
// It's not our event.
if AsioEvent.disposable(flags) then
// It's disposable, so dispose of it.
@pony_asio_event_destroy(event)
end
end
else
// At this point, it's our event.
if AsioEvent.writeable(flags) then
_writeable = true
_complete_writes(arg)
ifdef not windows then


Zip four generators into a generator of a 4-tuple
containing the values generated by those four generators.
"""
Generator[(T1, T2, T3, T4)](
object is GenObj[(T1, T2, T3, T4)]
fun generate(rnd: Randomness): GenerateResult[(T1, T2, T3, T4)] ? =>
(let v1: T1, let shrinks1: Iterator[T1^]) =
gen1.generate_and_shrink(rnd)?
(let v2: T2, let shrinks2: Iterator[T2^]) =
gen2.generate_and_shrink(rnd)?
(let v3: T3, let shrinks3: Iterator[T3^]) =
gen3.generate_and_shrink(rnd)?
(let v4: T4, let shrinks4: Iterator[T4^]) =
gen4.generate_and_shrink(rnd)?
((consume v1, consume v2, consume v3, consume v4),
Iter[T1^](shrinks1).zip3[T2^, T3^, T4^](shrinks2, shrinks3, shrinks4))

fun shrink(t: (T1, T2, T3, T4)): ValueAndShrink[(T1, T2, T3, T4)] =>
(let t1, let t2, let t3, let t4) = consume t
(let t11, let t1_shrunken) = gen1.shrink(consume t1)


directory, or if FileRead or FileStat permission isn't available.
new ref create(
from: FilePath val)
: Directory ref^ ?

Parameters¶

from: FilePath val

Returns¶

Directory ref^ ?

Public fields¶
let path: FilePath val¶
[Source]
This is the filesystem path locating this directory on the file system
and an object capability granting access to operate on this directory.


fun box tcp_thin_dupack()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcp_timestamp¶
[Source]


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


ULong val

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

Parameters¶

y: ULong val

Returns¶

ULong val

modc¶
[Source]


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

Parameters¶

y: I32 val

Returns¶

I32 val ?

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

Parameters¶


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


# Setting up and tearing down a test environment


else
error
end

fun ref update_u32[B: (A & Real[B] val & U8) = A](offset: USize, value: U32): U32 ? =>
"""
Write a U32 at offset. This is only allowed for an array of U8s.
"""
let u32_bytes = U32(0).bytewidth()
if (offset + u32_bytes) <= _size then
_ptr._offset(offset)._convert[U32]()._update(0, value)
else
error
end

fun ref update_u64[B: (A & Real[B] val & U8) = A](offset: USize, value: U64): U64 ? =>
"""
Write a U64 at offset. This is only allowed for an array of U8s.
"""
let u64_bytes = U64(0).bytewidth()


# A note on compiler versions

The error messages shown in this section are from ponyc `0.2.1-1063-g6ae110f` release, the current head of the main branch at the time this is written. The messages from other versions of the compiler may be different, to a greater or lesser degree.


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


// use the new size' for alloc if we're not including the last used byte
// from the original data and only include the extra allocated bytes if
// we're including the last byte.
let alloc = if last == _size then _alloc - offset else size' end

if size' > 0 then
from_cpointer(_ptr._offset(offset)._unsafe(), size', alloc)
else
create()
end
end

fun iso chop(split_point: USize): (String iso^, String iso^) =>
"""
Chops the string in half at the split point requested and returns both
the left and right portions. The original string is trimmed in place and
returned as the left portion. If the split point is larger than the
string, the left portion is the original string and the right portion
is a new empty string.


Returns¶

Registrar tag^

Public Behaviours¶
update¶
[Source]
Add, or change, a lookup mapping.
be update(
key: String val,
value: Any tag)

Parameters¶

key: String val
value: Any tag

remove¶


: HashMap[K, V, H] val

Parameters¶

key: K
value: val->V

Returns¶

HashMap[K, V, H] val

sub¶
[Source]
Return this Map without the given key.
fun val sub(
key: K)
: HashMap[K, V, H] val

Parameters¶


: U64 val

Returns¶

U64 val

has_next¶
[Source]
fun tag has_next()
: Bool val

Returns¶

Bool val

u8¶
[Source]
fun ref u8()


consume list
end

fun open(target: String): Directory iso^ ? =>
"""
Open a directory relative to this one. Raises an error if the path is not
within this directory hierarchy.
"""
if _fd == -1 then
error
end

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

ifdef linux or bsd then
let fd' =
@openat(_fd, target.cstring(),
@ponyint_o_rdonly()
or @ponyint_o_directory()


Ini val^

Public Functions¶
apply¶
[Source]
This accepts a string iterator and calls the IniNotify for each new entry.
If any errors are encountered, this will return false. Otherwise, it
returns true.
fun box apply(
lines: Iterator[String box] ref,
f: IniNotify ref)
: Bool val

Parameters¶

lines: Iterator[String box] ref
f: IniNotify ref

Returns¶


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


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

Parameters¶

that: MaxHeapPriority[A] val

Returns¶

Bool val


U32 val

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

Returns¶

U32 val

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

Returns¶


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


fun mulc(y: ISize): (ISize, Bool) =>
ifdef ilp32 then
(let r, let o) =
@"llvm.smul.with.overflow.i32"(this.i32(), y.i32())
(r.isize(), o)
else
_SignedCheckedArithmetic._mul_checked[USize, ISize](this, y)
end

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

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

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

fun modc(y: ISize): (ISize, Bool) =>


let _addr4: U32 = 0
"""
Bits 97-128 of the IPv6 address in network byte order.

`0` if this is an IPv4 address. Check with `ipv4()` and `ipv6()`.
"""

let _scope: U32 = 0
"""IPv6 scope identifier: Unicast, Anycast, Multicast and unassigned scopes."""

fun ip4(): Bool =>
"""
Returns true for an IPv4 address.
"""
@pony_os_ipv4(this)

fun ip6(): Bool =>
"""
Returns true for an IPv6 address.
"""


MinHeap[A: Comparable[A] #read]¶
[Source]
type MinHeap[A: Comparable[A] #read] is
BinaryHeap[A, MinHeapPriority[A] val] ref

Type Alias For¶

BinaryHeap[A, MinHeapPriority[A] val] ref


# Update

The `update` sugar allows any class to use an assignment to accept data. Many languages allow this for assigning into collections, for example, a simple C array, `a[3] = x;`.

In any assignment where the left-hand side is a function call, Pony will translate this to a call to update, with the value from the right-hand side as an extra argument. So:

```pony
foo(37) = x
```

becomes:

```pony
foo.update(37 where value = x)
```

The value from the right-hand side of the assignment is always passed to a parameter named `value`. Any object can allow this syntax simply by providing an appropriate function `update` with an argument `value`.

__Does my update function have to have a single parameter that takes an integer?__ No, you can define update to take whatever parameters you like, as long as there is one called `value`. The following are all fine:


be write(data: ByteSeq)
"""
Print some bytes without inserting a newline afterwards.
"""

be printv(data: ByteSeqIter)
"""
Print an iterable collection of ByteSeqs.
"""

be writev(data: ByteSeqIter)
"""
Write an iterable collection of ByteSeqs.
"""

be flush()
"""
Flush the stream.
"""


1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326use @pony_os_sockopt_level[I32](option: I32)
use @pony_os_sockopt_option[I32](option: I32)

primitive OSSockOpt
"""
Convenience functions to fetch the option level and option


fun box u8_unsafe()
: U8 val

Returns¶

U8 val

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

Returns¶

U16 val

u32_unsafe¶
[Source]


Return a FileInfo for some path relative to this directory.
fun box infoat(
target: String val)
: FileInfo val ?

Parameters¶

target: String val

Returns¶

FileInfo val ?

chmodat¶
[Source]
Set the FileMode for some path relative to this directory.
fun box chmodat(
target: String val,
mode: FileMode box)


be complete(s: String) =>
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)

fun box expect_action(
name: String val)
: None val


1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071


Add a U128 to the end of the array. This is only allowed for an array of U8s.
"""
let u128_bytes = U128(0).bytewidth()
reserve(_size + u128_bytes)
_ptr._offset(_size)._convert[U128]()._update(0, value)
_size = _size + u128_bytes

fun ref push(value: A) =>
"""
Add an element to the end of the array.
"""
reserve(_size + 1)
_ptr._update(_size, consume value)
_size = _size + 1

fun ref pop(): A^ ? =>
"""
Remove an element from the end of the array.
The removed element is returned.
"""


fun box bytewidth()
: USize val

Returns¶

USize val

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

Parameters¶

y: U32 val

Returns¶


fun box mrt_pim()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

msg_notification¶
[Source]


USize val

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

Parameters¶

that: U128 val

Returns¶

(Less val | Equal val | Greater val)


peek_u32_be¶
[Source]
Peek at a big-endian U32.
fun box peek_u32_be(
offset: USize val = 0)
: U32 val ?

Parameters¶

offset: USize val = 0

Returns¶

U32 val ?

peek_u32_le¶
[Source]


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


Parameters¶

acc: B
f: {(B, A!): B^ ?}[A, B] box

Returns¶

B^ ?

interleave¶
[Source]
Return an iterator that alternates the values of the original iterator and
the other until both run out.
Example¶
Iter[USize](Range(0, 4))
.interleave(Range(4, 6))

0 4 1 5 2 3
fun ref interleave(


"""
ifdef osx then
var ts: (I64, I64) = (0, 0)
@gettimeofday(addressof ts, USize(0))
(ts._1, ts._2 * 1000)
elseif linux or bsd then
_clock_gettime(_ClockRealtime)
elseif windows then
var ft: (U32, U32) = (0, 0)
@GetSystemTimeAsFileTime(addressof ft)
var qft = ft._1.u64() or (ft._2.u64() << 32)
var epoch = qft.i64() - 116444736000000000
var sec = epoch / 10000000
var nsec = (epoch - (sec * 10000000)) * 100
(sec, nsec)
else
compile_error "unsupported platform"
end

fun seconds(): I64 =>


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


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


fun box ipx_dltitf()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipx_extended_address¶
[Source]


U8 val

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

Returns¶

U16 val

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

Returns¶


972
973
974
975
976
977
978
979
980
981class List[A] is Seq[A]
"""
A doubly linked list.

The following is paraphrased from [Wikipedia](https://en.wikipedia.org/wiki/Doubly_linked_list).

A doubly linked list is a linked data structure that consists of a set of sequentially
linked records called nodes (implemented in Pony via the collections.ListNode class). Each
node contains four fields: two link fields (references to the previous and to the next node in
the sequence of nodes), one data field, and the reference to the List in which it resides. A doubly
linked list can be conceptualized as two singly linked lists formed from the same data items, but


A

add¶
[Source]
fun box add(
y: A)
: A

Parameters¶

y: A

Returns¶

A

sub¶
[Source]


fun box ip_old_fw_flush()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_old_fw_resetlog¶
[Source]


if is_sep(s(s.size()-1)?) and (s.size() > 1) then
s.delete(-1, sep().size())
end
end

if s.size() > 0 then
s
else
"."
end

fun normcase(path: String): String =>
"""
Normalizes the case of path for the runtime platform.
"""
if Platform.windows() then
recover val path.lower() .> replace("/", "\\") end
elseif Platform.osx() then
path.lower()
else


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


fun box add(
y: I16 val)
: I16 val

Parameters¶

y: I16 val

Returns¶

I16 val

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

Parameters¶


if e == a then
consumed.update(i, true)?
found = true
break
end
end
if not found then
missing.push(e)
end
end

let extra = Array[box->A]
for (i, c) in consumed.pairs() do
if not c then extra.push(actual(i)?) end
end

if (extra.size() != 0) or (missing.size() != 0) then
_fail(
_fmt_msg(loc, "Assert EQ_UNORDERED failed. " + msg
+ " Expected (" + _print_array[A](expect) + ") == ("


that: FileCreate val

Returns¶

Bool val

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

Parameters¶

that: FileCreate val

Returns¶


StringBytes¶
[Source]
class ref StringBytes is
Iterator[U8 val] ref

Implements¶

Iterator[U8 val] ref

Constructors¶
create¶
[Source]


Returns¶

Bool val

lt¶
fun box lt(
y: F32 val)
: Bool val

Parameters¶

y: F32 val

Returns¶

Bool val


# Temporary unique access

We talked about aliasing and consuming, but what about when we just use a variable without making a new alias?
If `x` is `iso`, what type do we give to the expression `x`? It would be pretty useless if we could only use our `iso` variables as `tag`. We couldn't modify fields or call any methods.

What we get is the bare `iso` capability. Like `ref`, this allows us to read and write, *but* we will have to keep the destination isolated. We will get into what kind of things we can do with it later, but for now, we will talk about subtyping.

* `iso^` <: `iso`. As mentioned earlier, `iso^` can become *anything*. This isn't enormously useful, all told, but an `iso^` expression with no other names
is stronger than a expression pointing to an existing `iso` name.
* `trn^` <: `trn`. Similarly, we may use an expression that has no writable aliases, as an expression which has one unique writeable alias.
* `iso` <: `tag`. We can't coerce `iso` to anything else since the original name is still around, but we can always drop down to `tag` (which is just `iso!`).
* `trn` <: `box`. This is quite similar, we can forget our ability to write and just get a new `box` alias to store.


# Arrow Types aka Viewpoints

When we talked about __reference capability composition__ and __viewpoint adaptation__, we dealt with cases where we know the reference capability of the origin. However, sometimes we don't know the precise reference capability of the origin.

When that happens, we can write a __viewpoint adapted type__, which we call an __arrow type__ because we write it with an `->`.


312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331


=>
"""
Creates an Option with an U64 typed value that can be used like
`--count=47 -C=47`
to yield an option value like
`cmd.option("count").u64() == U64(47)`.
"""
_name = name'
_descr = descr'
_short = short'
(_typ, _default, _required) = _init(_U64Type, default')

new val f64(name': String,
descr': String = "",
short': (U8 | None) = None,
default': (F64 | None) = None)
=>
"""
Creates an Option with a F64 typed value that can be used like
`--ratio=1.039` or `-R=1.039`


Parameters¶

term: ANSITerm ref
input: U8 val

Returns¶

None val

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

Parameters¶


fun box ipv6_prefer_src_home()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_prefer_src_public¶
[Source]


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

Parameters¶

y: I32 val

Returns¶

(I32 val , Bool val)

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

Parameters¶


fun box sctp_enable_reset_assoc_req()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_enable_stream_reset¶
[Source]


fun box setsockopt()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

bindat¶
[Source]


U64 val

eq¶
[Source]
Determine equality by identity rather than structurally.
fun box eq(
x: box->A!,
y: box->A!)
: Bool val

Parameters¶

x: box->A!
y: box->A!

Returns¶

Bool val


# Scheduling

The Pony scheduler is not preemptive. This means that your actor has to yield control of the scheduler thread in order for another actor to execute. The normal way to do this is for your behavior to end. If your behavior doesn't end, you will continue to monopolize a scheduler thread and bad things will happen.


fun box div_partial(
y: A)
: A ?

Parameters¶

y: A

Returns¶

A ?

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

Parameters¶


env.out.print("\t" + n.string())
end

// Filter the new list to extract 2 elements
let filtered_list = new_list.filter({ (n) => n.string().contains("d BOOM!") })
env.out.print("Filtering our three-node list produces a new list of size: "
+ filtered_list.size().string()) // 2
for n in filtered_list.values() do
env.out.print("\t" + n.string()) // Second BOOM!\nThird BOOM!
end

// Partition the filtered list
let partitioned_lists = filtered_list.partition({ (n) => n.string().contains("Second") })
env.out.print("The size of our first partitioned list (matches predicate): " + partitioned_lists._1.size().string())        // 1
env.out.print("The size of our second partitioned list (doesn't match predicate): " + partitioned_lists._2.size().string())  // 1
env.out.print("Our matching partition elements are:")
for n in partitioned_lists._1.values() do
env.out.print("\t" + n.string()) // Second BOOM!
end
```


## Custom Serialisation

In order to serialise an object from a pointer field, Pony needs to know how much space to set aside for that object and how to write a representation of that object into the reserved space. The programmer must provide two methods on the object:

* `fun _serialise_space(): USize` -- This method returns the number of bytes that must be reserved for the object.
* `fun _serialise(bytes: Pointer[U8] tag)` -- This method receives a pointer to the memory that has been set aside for serialising the object. The programmer must not write more bytes than were returned by the `_serialise_space` method.


ILong val

popcount¶
[Source]
fun box popcount()
: ULong val

Returns¶

ULong val

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

Returns¶


let my_list = List[String].from(["a"; "b"; "c"])
let rnodes = my_list.rnodes()  // node with "c" is before node with "a"
```
"""
ListNodes[A, this->ListNode[A]](_head, true)

fun values(): ListValues[A, this->ListNode[A]]^ =>
"""
Return an iterator on the values in the `List` in forward order.

```pony
let my_list = List[String].from(["a"; "b"; "c"])
let values = my_list.values()  // value "a" is before value "c"
```
"""
ListValues[A, this->ListNode[A]](_head)

fun rvalues(): ListValues[A, this->ListNode[A]]^ =>
"""
Return an iterator on the values in the `List` in reverse order.


AsioEventNotify¶
[Source]
trait tag AsioEventNotify


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

Returns¶

U64 val

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

Returns¶

U128 val


EnvVars¶
[Source]
primitive val EnvVars

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

Returns¶

EnvVars val^


env: Env val
list: BenchmarkList tag

Returns¶

PonyBench tag^

Public Behaviours¶
apply¶
[Source]
be apply(
bench: (MicroBenchmark iso | AsyncMicroBenchmark iso))

Parameters¶

bench: (MicroBenchmark iso | AsyncMicroBenchmark iso)


```

Those are all type aliases used by the standard library.

__Is `Number` a type alias for a type expression that contains other type aliases?__ Yes! Fun, and convenient.


12
13
14
15
16
17
18interface Proxy
fun apply(wrap: TCPConnectionNotify iso): TCPConnectionNotify iso^

class val NoProxy is Proxy
"""
Default implementation of a proxy that does not alter the supplied `TCPConnectionNotify`.

```pony
actor MyClient
new create(host: String, service: String, proxy: Proxy = NoProxy) =>
let conn: TCPConnection = TCPConnection.create(
TCPConnectAuth(env.root),
proxy.apply(MyConnectionNotify.create()),
"localhost",


end

if not FileInfo(from)?.directory then
error
end

path = from

ifdef posix then
_fd =
@open(from.path.cstring(),
@ponyint_o_rdonly()
or @ponyint_o_directory()
or @ponyint_o_cloexec())

if _fd == -1 then
error
end
elseif windows then
_fd = 0


fun box ne(
that: Flags[A, B] box)
: Bool val

Parameters¶

that: Flags[A, B] box

Returns¶

Bool val


F64 val

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

Returns¶

F64 val

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

Returns¶


min: F32 val = 0.0,
max: F32 val = 1.0)
: F32 val

Parameters¶

min: F32 val = 0.0
max: F32 val = 1.0

Returns¶

F32 val

f64¶
[Source]
Generate a F64 in closed interval [min, max]
(default: [0.0, 1.0]).
fun ref f64(
min: F64 val = 0.0,


tcp_connection_notify.pony

1
2
3
4
5
6
7
8
9
10
11


fun box so_wifi_status()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcpci_flag_lossrecovery¶
[Source]


let avail = data.size() - offset
let need = len - i
let copy_len = need.min(avail)

out = recover
let r = consume ref out
data.copy_to(r, offset, i, copy_len)
consume r
end

if avail > need then
node()? = (data, offset + need)
break
end

i = i + copy_len
_chunks.shift()?
end


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


# Use Statement

To use a package in your code you need to have a __use__ command. This tells the compiler to find the package you need and make the types defined in it available to you. Every Pony file that needs to know about a type from a package must have a use command for it.

Use commands are a similar concept to Python and Java "import", C/C++ "#include" and C# "using" commands, but not exactly the same. They come at the beginning of Pony files and look like this:

```pony
use "collections"
```

This will find all of the publicly visible types defined in the _collections_ package and add them to the type namespace of the file containing the `use` command. These types are then available to use within that file, just as if they were defined locally.

For example, the standard library contains the package _time_. This contains the following definition (among others):

```pony
primitive Time
fun now(): (I64, I64)
```

To access the _now_ function just add a use command:


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


[Source]
Return an iterator over the values in the vector.
fun val values()
: VecValues[A] ref^

Returns¶

VecValues[A] ref^

pairs¶
[Source]
Return an iterator over the (index, value) pairs in the vector.
fun val pairs()
: VecPairs[A] ref^

Returns¶

VecPairs[A] ref^


let b = Foo[String ref](recover ref "World".clone() end)
env.out.print(b.get().string())

let c = Foo[U8](42)
env.out.print(c.get().string())
```

It's quite a bit of work to get a generic class or method to work across all capability types, in particular for `iso`. There are ways of restricting the generic to subsets of capabilities and that's the topic of the next section.


obj2.other = obj1
[obj1; obj2]
end

fun iso chop[optional B: (A & Any #send)](
split_point: USize val)
: (Array[A] iso^ , Array[A] iso^)

Parameters¶

split_point: USize val

Returns¶

(Array[A] iso^ , Array[A] iso^)

unchop¶
[Source]
Unchops two iso arrays to return the original array they were chopped from.


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


fun box ipproto_hopopts()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_icmpv6¶
[Source]


i64_le¶
[Source]
Write an I64 to the buffer in little-endian byte order.
fun ref i64_le(
data: I64 val)
: None val

Parameters¶

data: I64 val

Returns¶

None val

i64_be¶
[Source]
Write an I64 to the buffer in big-endian byte order.
fun ref i64_be(


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


yield_after_writing: USize = 16384)
=>
"""
Listens for IPv6 connections.
"""
_limit = limit
_notify = consume notify
_event =
@pony_os_listen_tcp6(this, host.cstring(), service.cstring())
_read_buffer_size = read_buffer_size
_yield_after_reading = yield_after_reading
_yield_after_writing = yield_after_writing
_fd = @pony_asio_event_fd(_event)
_notify_listening()

be set_notify(notify: TCPListenNotify iso) =>
"""
Change the notifier.
"""
_notify = consume notify


UDPSocket¶
[Source]
Creates a UDP socket that can be used for sending and receiving UDP messages.
The following examples create:

an echo server that listens for connections and returns whatever message it
receives
a client that connects to the server, sends a message, and prints the
message it receives in response

The server is implemented like this:
use "net"


// Push a String literal onto our empty List
my_list.push("A single String")
env.out.print("Adding one node to our empty list means it now has a size of "
+ my_list.size().string() + ".") // 1

// Get the first element of our List
try env.out.print("The first (index 0) node has the value: "
+ my_list.index(0)?()?.string()) end // A single String

// Create a second List from a single String literal
let my_second_list = List[String].unit("Another String")

// Append the second List to the first
my_list.append_list(my_second_list)
env.out.print("A list created by appending our second single-node list onto our first has size: "
+ my_list.size().string()) // 2
env.out.print("The List nodes of our first list are now:")
for n in my_list.values() do
env.out.print("\t" + n.string())


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


[Source]
Creates an iterator for the given set.
new ref create(
set: S)
: SetValues[A, H, S] ref^

Parameters¶

set: S

Returns¶

SetValues[A, H, S] ref^

Public Functions¶
has_next¶
[Source]
True if it believes there are remaining entries. May not be right if values
were added or removed from the set.


fun box i16_unsafe()
: I16 val

Returns¶

I16 val

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

Returns¶

I32 val

i64_unsafe¶
[Source]


Sig val^

Public Functions¶
hup¶
[Source]
fun box hup()
: U32 val

Returns¶

U32 val

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


Set[A: (Hashable val & Equatable[A])]¶
[Source]
type Set[A: (Hashable val & Equatable[A])] is
HashSet[A, HashEq[A] val] val

Type Alias For¶

HashSet[A, HashEq[A] val] val


fun box f64()
: F64 val

Returns¶

F64 val

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

Returns¶

I8 val

i16_unsafe¶
[Source]


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


Returns the option value as a ReadSeq[String], defaulting to empty.
fun box string_seq()
: ReadSeq[String val] val

Returns¶

ReadSeq[String val] val

deb_string¶
[Source]
fun box deb_string()
: String val

Returns¶

String val


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


HashFunction64[A] val^

Public Functions¶
hash64¶
[Source]
Calculate the hash of some type. This is an alias of the type parameter to
allow data structures to hash things without consuming them.
fun box hash64(
x: box->A!)
: U64 val

Parameters¶

x: box->A!

Returns¶

U64 val


Bool val


fun ipx_address_notify():I32 => @pony_os_sockopt_option(I32(202))
fun ipx_crtitf():I32 => @pony_os_sockopt_option(I32(203))
fun ipx_dltitf():I32 => @pony_os_sockopt_option(I32(204))
fun ipx_dstype():I32 => @pony_os_sockopt_option(I32(205))
fun ipx_extended_address():I32 => @pony_os_sockopt_option(I32(206))
fun ipx_filterptype():I32 => @pony_os_sockopt_option(I32(207))
fun ipx_frame_8022():I32 => @pony_os_sockopt_option(I32(208))
fun ipx_frame_8023():I32 => @pony_os_sockopt_option(I32(209))
fun ipx_frame_etherii():I32 => @pony_os_sockopt_option(I32(210))
fun ipx_frame_none():I32 => @pony_os_sockopt_option(I32(211))
fun ipx_frame_snap():I32 => @pony_os_sockopt_option(I32(212))
fun ipx_frame_tr_8022():I32 => @pony_os_sockopt_option(I32(213))
fun ipx_getnetinfo():I32 => @pony_os_sockopt_option(I32(214))
fun ipx_getnetinfo_norip():I32 => @pony_os_sockopt_option(I32(215))
fun ipx_immediatespxack():I32 => @pony_os_sockopt_option(I32(216))
fun ipx_internal():I32 => @pony_os_sockopt_option(I32(217))
fun ipx_maxsize():I32 => @pony_os_sockopt_option(I32(218))
fun ipx_max_adapter_num():I32 => @pony_os_sockopt_option(I32(219))
fun ipx_mtu():I32 => @pony_os_sockopt_option(I32(220))
fun ipx_node_len():I32 => @pony_os_sockopt_option(I32(221))


fun box sctp_cause_deleting_src_addr()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_cause_invalid_param¶
[Source]


Returns¶

Promise[A] tag^

Public Behaviours¶
apply¶
[Source]
Fulfill the promise.
be apply(
value: A)

Parameters¶

value: A

reject¶
[Source]
Reject the promise.


peek_u64_le¶
[Source]
Peek at a little-endian U64.
fun box peek_u64_le(
offset: USize val = 0)
: U64 val ?

Parameters¶

offset: USize val = 0

Returns¶

U64 val ?

peek_i64_be¶
[Source]


String val

yellow_bg¶
[Source]
Yellow background.
fun box yellow_bg()
: String val

Returns¶

String val

blue_bg¶
[Source]
Blue background.
fun box blue_bg()
: String val


expect: ReadSeq[A],
actual: ReadSeq[A],
msg: String = "",
loc: SourceLoc = __loc)
: Bool
=>
"""
Assert that the contents of the 2 given ReadSeqs are equal.
"""
var ok = true

if expect.size() != actual.size() then
ok = false
else
try
var i: USize = 0
while i < expect.size() do
if expect(i)? != actual(i)? then
ok = false
break


fun addc(y: USize): (USize, Bool) =>
ifdef ilp32 then
(let r, let o) =
@"llvm.uadd.with.overflow.i32"(this.u32(), y.u32())
(r.usize(), o)
else
(let r, let o) =
@"llvm.uadd.with.overflow.i64"(this.u64(), y.u64())
(r.usize(), o)
end

fun subc(y: USize): (USize, Bool) =>
ifdef ilp32 then
(let r, let o) =
@"llvm.usub.with.overflow.i32"(this.u32(), y.u32())
(r.usize(), o)
else
(let r, let o) =
@"llvm.usub.with.overflow.i64"(this.u64(), y.u64())
(r.usize(), o)


y: A)
: A

Parameters¶

y: A

Returns¶

A

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

Returns¶

A


ForAll3[T1: T1, T2: T2, T3: T3]¶
[Source]
class ref ForAll3[T1: T1, T2: T2, T3: T3]

Constructors¶
create¶
[Source]
new ref create(
gen1': Generator[T1] val,
gen2': Generator[T2] val,
gen3': Generator[T3] val,
h: TestHelper val)
: ForAll3[T1, T2, T3] ref^


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


872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891


 Random package

The Random package provides support generating random numbers. The package
provides random number generators you can use in your code, a dice roller and
a trait for implementing your own random number generator.

If your application does not require a specific generator, use Rand.

Seed values can contain up to 128 bits of randomness in the form of two U64s.
A common non-cryptographically secure way to seed a generator is with
`Time.now`.

```pony
let rand = Rand
let n = rand.next()
```
"""
type Rand is XorOshiro128Plus

trait Random


fun box tcpopt_sack_hdr()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcpopt_sack_permit_hdr¶
[Source]


ASCIILettersLower¶
[Source]
primitive val ASCIILettersLower

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

Returns¶

ASCIILettersLower val^


reverse¶
[Source]
Create a new array with the elements in reverse order.
The new array contains references to the same elements that the old array
contains, the elements themselves are not copied.
fun box reverse()
: Array[this->A!] ref^

Returns¶

Array[this->A!] ref^

reverse_in_place¶
[Source]
Reverse the array in place.
fun ref reverse_in_place()
: None val


U8 val

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

Returns¶

U16 val

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

Returns¶


"""
encode(data, '+', '/', '=', 64)

fun encode_mime(data: ReadSeq[U8]): String iso^ =>
"""
Encode for MIME (RFC 2045).
"""
encode(data, '+', '/', '=', 76)

fun encode_url[A: Seq[U8] iso = String iso](
data: ReadSeq[U8],
pad: Bool = false)
: A^
=>
"""
Encode for URLs (RFC 4648). Padding characters are stripped by default.
"""
let c: U8 = if pad then '=' else 0 end
encode[A](data, '-', '_', c)


Add a byte to the end of the string.
fun ref push(
value: U8 val)
: None val

Parameters¶

value: U8 val

Returns¶

None val

pop¶
[Source]
Remove a byte from the end of the string.
fun ref pop()
: U8 val ?


: B^

Parameters¶

acc: B
f: {(B, A!): B^}[A, B] box

Returns¶

B^

fold_partial[B: B]¶
[Source]
A partial version of fold.
fun ref fold_partial[B: B](
acc: B,
f: {(B, A!): B^ ?}[A, B] box)
: B^ ?


Bool val

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

Parameters¶

that: TCPAuth val

Returns¶

Bool val


fun box i64()
: I64 val

Returns¶

I64 val

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

Returns¶

I128 val

ilong¶
[Source]


let _term: ANSITerm tag

new create(term: ANSITerm tag) =>
_term = term

fun apply(times: U32): Bool =>
_term.size()
true

primitive _TIOCGWINSZ
fun apply(): ULong =>
ifdef linux then
21523
elseif osx or bsd then
1074295912
else
0
end

actor ANSITerm


fun ref union(that: Flags[A, B] box) =>
"""
The union of this and that.
"""
_value = this._value or that._value

fun ref intersect(that: Flags[A, B] box) =>
"""
The intersection of this and that.
"""
_value = this._value and that._value

fun ref difference(that: Flags[A, B] box) =>
"""
The symmetric difference of this and that.
"""
_value = this._value xor that._value

fun ref remove(that: Flags[A, B] box) =>
"""


end
elseif y < 0 then
q' = -q'
end

(q', r')
end

fun div(y: I128): I128 =>
ifdef native128 then
this / y
else
(let q, let r) = divrem(y)
q
end

fun rem(y: I128): I128 =>
ifdef native128 then
this % y
else


fun _leaf_nodes(): Array[Array[A] val]^ =>
let lns = Array[Array[A] val](_size / 32)
match _root
| let vn: _VecNode[A] => vn.leaf_nodes(lns)
end
if _tail.size() > 0 then lns.push(_tail) end
lns

class VecKeys[A: Any #share]
embed _pairs: VecPairs[A]

new create(v: Vec[A]) => _pairs = VecPairs[A](v)

fun has_next(): Bool => _pairs.has_next()

fun ref next(): USize ? => _pairs.next()?._1

class VecValues[A: Any #share]
embed _pairs: VecPairs[A]


to: NetAddress val)

Parameters¶

data: (String val | Array[U8 val] val)
to: NetAddress val

writev¶
[Source]
Write a sequence of sequences of bytes.
be writev(
data: ByteSeqIter val,
to: NetAddress val)

Parameters¶

data: ByteSeqIter val
to: NetAddress val


fun box ipv6_pmtudisc_interface()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_pmtudisc_probe¶
[Source]


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


Cons[A: A]¶
[Source]
A list with a head and a tail, where the tail can be empty.
class val Cons[A: A] is
ReadSeq[val->A] box

Implements¶

ReadSeq[val->A] box

Constructors¶
create¶


end
end
end

fun ref upsert(key: K, value: V, f: {(V, V): V^} box): V! =>
"""
Combines a provided value with the current value for the provided key
using the provided function. If the provided key has not been added to
the map yet, it sets its value to the provided value and ignores the
provided function.

As a simple example, say we had a map with I64 values and we wanted to
add 4 to the current value for key "test", which let's say is currently 2.
We call

m.upsert("test", 4, {(current, provided) => current + provided })

This changes the value associated with "test" to 6.

If we have not yet added the key "new-key" to the map and we call


# Terminology

**Braces**: { }. Synonymous with curly brackets.

**Brackets**: This term is ambiguous. In the UK it usually means ( ) in the US is usually means [ ]. It should, therefore, be avoided for use for either of these. Can be used as a general term for any unspecified grouping punctuation, including { }.

**Compatible type**: Two types are compatible if there can be any single object which is an instance of both types. Note that a suitable type for the single object does not have to have been defined, as long as it could be. For example, any two traits are compatible because a class could be defined that provides both of them, even if such a class has not been defined. Conversely, no two classes can ever be compatible because no object can be an instance of both.

**Compound type**: A type combining multiple other types, i.e. union, intersection, and tuple. Opposite of a single type.

**Concrete type**: An actor, class or primitive.

**Curly brackets**: { }. Synonymous with braces.

**Declaration** and **definition**: synonyms for each other, we do not draw the C distinction between forward declarations and full definitions.

**Default method body**: Method body defined in a trait and optionally used by concrete types.

**Entity**: Top level definition within a file, i.e. alias, trait, actor, class, primitive.


y: A

Returns¶

A

sub_unsafe¶
[Source]
fun box sub_unsafe(
y: A)
: A

Parameters¶

y: A

Returns¶


msg: String val = "Test failed")
: None val

Parameters¶

msg: String val = "Test failed"

Returns¶

None val

assert_false¶
[Source]
Assert that the given expression is false.
fun box assert_false(
predicate: Bool val,
msg: String val = "",
loc: SourceLoc val = __loc)
: Bool val


| 3 => "U64(" + int.u64().string() + ")"
| 4 => "ULong(" + int.ulong().string() + ")"
| 5 => "USize(" + int.usize().string() + ")"
| 6 => "U128(" + int.string() + ")"
| 7 => "I8(" + int.i8().string() + ")"
| 8 => "I16(" + int.i16().string() + ")"
| 9 => "I32(" + int.i32().string() + ")"
| 10 => "I64(" + int.i64().string() + ")"
| 11 => "ILong(" + int.ilong().string() + ")"
| 12 => "ISize(" + int.isize().string() + ")"
| 13 => "I128(" + int.i128().string() + ")"
else
""
end
num.clone()

class IntPropertySample is Stringable
let choice: U8
let int: U128


end

fun ref insert_if_absent(key: K, value: V): V! =>
"""
Set a value in the map if the key doesn't already exist in the Map.
Saves an extra lookup when doing a pattern like:

```pony
if not my_map.contains(my_key) then
my_map(my_key) = my_value
end
```

Returns the value, the same as `insert`, allowing 'insert_if_absent'
to be used as a drop-in replacement for `insert`.
"""
let value' = value

try
(let i, let found) = _search(key)


use @ponyint_windows_readdir[Pointer[U8] iso^](data: Pointer[_DirectoryEntry])
if windows
use @FindFirstFileA[Pointer[_DirectoryHandle]](file_name: Pointer[U8] tag, data: Pointer[_DirectoryEntry])
if windows
use @FindNextFileA[Bool](handle: Pointer[None] tag, data: Pointer[_DirectoryEntry])
if windows
use @FindClose[Bool](handle: Pointer[_DirectoryHandle] tag) if windows

primitive _DirectoryHandle
primitive _DirectoryEntry

class Directory
"""
Operations on a directory.

The directory-relative functions (open, etc) use the *at interface on FreeBSD
and Linux. This isn't available on OS X prior to 10.10, so it is not used. On
FreeBSD, this allows the directory-relative functions to take advantage of
Capsicum.
"""


192
193
194
195
196
197
198
199
200
201use "time"

class val PropertyParams is Stringable
"""
Parameters to control Property Execution.

* seed: the seed for the source of Randomness
* num_samples: the number of samples to produce from the property generator
* max_shrink_rounds: the maximum rounds of shrinking to perform
* max_generator_retries: the maximum number of retries to do if a generator fails to generate a sample
* timeout: the timeout for the PonyTest runner, in nanoseconds


set.pony

1
2
3
4
5
6
7
8
9
10
11


fail¶
[Source]
fun box fail()
: None val

Returns¶

None val


while n < offset do
if iter.has_next() then
iter.next()?
else
return
end

n = n + 1
end

n = 0

while n < len do
if iter.has_next() then
push(iter.next()?)
else
return
end


fun box add_unsafe(
y: F32 val)
: F32 val

Parameters¶

y: F32 val

Returns¶

F32 val

sub_unsafe¶
fun box sub_unsafe(
y: F32 val)
: F32 val

Parameters¶


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


ULong val

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

Returns¶

ULong val

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

Returns¶


fun tag next[B: Any #share](
fulfill: Fulfill[A, B],
rejected: Reject[B] = RejectAlways[B])
: Promise[B]
=>
"""
Chain a promise after this one.

When this promise is fulfilled, the result of type A is passed to the
fulfill function, generating in an intermediate result of type B. This
is then used to fulfill the next promise in the chain.

If there is no fulfill function, or if the fulfill function raises an
error, then the next promise in the chain will be rejected.

If this promise is rejected, this step's reject function is called with no
input, generating an intermediate result of type B which is used to
fulfill the next promise in the chain.