compare_sub¶
[Source]
Lexically compare at most n bytes of the substring of this starting at
offset with the substring of that starting at that_offset. The
comparison is case sensitive unless ignore_case is true.
If the substring of this is a proper prefix of the substring of that,
then this is Less than that. Likewise, if that is a proper prefix of
this, then this is Greater than that.
Both offset and that_offset can be negative, in which case the offsets
are computed from the end of the string.
If n + offset is greater than the length of this, or n + that_offset
is greater than the length of that, then the number of positions compared
will be reduced to the length of the longest substring.
Needs to be made UTF-8 safe.
fun box compare_sub(
that: String box,
n: USize val,
offset: ISize val = 0,
that_offset: ISize val = 0,
ignore_case: Bool val = false)


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


Parameters¶

y: Bool val

Returns¶

Bool val

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

Returns¶

Bool val

string¶


fun box tcp_timestamp()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcp_vendor¶
[Source]


fun box so_l2cap_iflow()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_l2cap_oflow¶
[Source]


return
end

let upper = cmd.option("upper").bool()
let words = cmd.arg("words").string_seq()
for word in words.values() do
env.out.write(if upper then word.upper() else word end + " ")
end
env.out.print("")

Public Types¶

class Arg
class ArgSpec
class Command
class CommandHelp
class CommandParser
class CommandSpec
primitive EnvVars
primitive Help


primitive ColourList
fun apply(): Array[Colour] =>
[Red; Green; Blue]

for colour in ColourList().values() do
env.out.print(colour().string())
end
```


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


fun box mul(
y: U64 val)
: U64 val

Parameters¶

y: U64 val

Returns¶

U64 val

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

Parameters¶


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


fun box sctp_recv_rwnd_logging_enable()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_reset_assoc¶
[Source]


```pony
let my_decimal_int: I32 = 1024
let my_hexadecimal_int: I32 = 0x400
let my_binary_int: I32 = 0b10000000000
```

Floating Point literals are expressed as standard floating point or scientific notation:

```pony
let my_double_precision_float: F64 = 0.009999999776482582092285156250
let my_scientific_float: F32 = 42.12e-4
```


U16 val

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

Parameters¶

y: U16 val

Returns¶

U16 val

divrem¶
[Source]


min: U128 val = call,
max: U128 val = call)
: Generator[U128 val] box

Parameters¶

min: U128 val = call
max: U128 val = call

Returns¶

Generator[U128 val] box

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


Serialised¶
[Source]
This represents serialised data. How it can be used depends on the other
capabilities a caller holds.
class val Serialised

Constructors¶
create¶
[Source]
A caller with SerialiseAuth can create serialised data from any object.
new ref create(
auth: SerialiseAuth val,
data: Any box)


FileCreate¶
[Source]
primitive val FileCreate

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

Returns¶

FileCreate val^


: None val

Parameters¶

line: String val
prompt: Promise[String val] tag

Returns¶

None val

tab¶
[Source]
Return tab completion possibilities.
fun ref tab(
line: String val)
: Seq[String val] box

Parameters¶


U32 val

u64¶
fun box u64()
: U64 val

Returns¶

U64 val

ulong¶
fun box ulong()
: ULong val

Returns¶

ULong val


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


fun rem_partial(y: U8): U8 ? =>
_UnsignedPartialArithmetic.rem_partial[U8](this, y)?

fun divrem_partial(y: U8): (U8, U8) ? =>
_UnsignedPartialArithmetic.divrem_partial[U8](this, y)?

primitive U16 is UnsignedInteger[U16]
new create(value: U16) => value
new from[A: (Number & Real[A] val)](a: A) => a.u16()

new min_value() => 0
new max_value() => 0xFFFF

fun next_pow2(): U16 =>
let x = (this - 1).clz()
1 << (if x == 0 then 0 else bitwidth() - x end)

fun abs(): U16 => this
fun bit_reverse(): U16 => @"llvm.bitreverse.i16"(this)


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


writev¶
[Source]
Write a sequence of sequences of bytes. Data will be silently discarded if
the connection has not yet been established though.
be writev(
data: ByteSeqIter val)

Parameters¶

data: ByteSeqIter val

mute¶
[Source]
Temporarily suspend reading off this TCPConnection until such time as
unmute is called.
be mute()

unmute¶


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


# Destructive read

There's another way to _move_ a value from one name to another. Earlier, we talked about how assignment in Pony returns the _old_ value of the left-hand side, rather than the new value. This is called _destructive read_, and we can use it to do what we want to do, even with fields.

```pony
class Aardvark
var buddy: Wombat iso

new create() =>
buddy = recover Wombat end

fun ref test(a: Wombat iso) =>
var b: Wombat iso = buddy = consume a // Allowed!
```

Here, we consume `a`, assign it to the field `buddy`, and assign the _old_ value of `buddy` to `b`.

__Why is it ok to destructively read fields when we can't consume them?__ Because when we do a destructive read, we assign to the field so it always has a value. Unlike `consume`, there's no time when the field is empty. That means it's safe and the compiler doesn't complain.


1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271


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


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


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


y: U16 val

Returns¶

I16 val

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

Parameters¶

y: U16 val

Returns¶


[Source]
fun box shl_unsafe(
y: USize val)
: ISize val

Parameters¶

y: USize val

Returns¶

ISize val

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


dns.pony

1
2
3
4
5
6
7
8
9
10
11


fun box so_useloopback()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_vendor¶
[Source]


## Functions

Functions in Pony are like methods in Java, C#, C++, Ruby, Python, or pretty much any other object oriented language. They are introduced with the keyword `fun`. They can have parameters like constructors do, and they can also have a result type (if no result type is given, it defaults to `None`).

```pony
class Wombat
let name: String
var _hunger_level: U64
var _thirst_level: U64 = 1

new create(name': String) =>
name = name'
_hunger_level = 0

new hungry(name': String, hunger': U64) =>
name = name'
_hunger_level = hunger'

fun hunger(): U64 => _hunger_level


fun box ipctl_stats()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipport_ephemerallast¶
[Source]


Bool val

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

Returns¶

I8 val

i16¶
[Source]
fun box i16()
: I16 val

Returns¶


fun _subseconds_from_query_performance_counter(subseconds: U64): U64 =>
(let qpc, let qpf) = _query_performance_counter()
if qpf <= subseconds then
qpc * (subseconds / qpf)
else
(qpc * subseconds) / qpf
end

fun _query_performance_counter(): (U64 /* qpc */, U64 /* qpf */) =>
"""
Return QPC and QPF.
"""
ifdef windows then
var pf: (U32, U32) = (0, 0)
var pc: (U32, U32) = (0, 0)
@QueryPerformanceFrequency(addressof pf)
@QueryPerformanceCounter(addressof pc)
let qpf = pf._1.u64() or (pf._2.u64() << 32)


fun value(): U32 => 1 << 0

primitive FileChmod
fun value(): U32 => 1 << 1

primitive FileChown
fun value(): U32 => 1 << 2

primitive FileLink
fun value(): U32 => 1 << 3

primitive FileLookup
fun value(): U32 => 1 << 4

primitive FileMkdir
fun value(): U32 => 1 << 5

primitive FileRead
fun value(): U32 => 1 << 6


(Less val | Equal val | Greater val)


OutputSerialisedAuth¶
[Source]
This is a capability token that allows the holder to examine serialised data.
This should only be provided to types that need to write serialised data to
some output stream, such as a file or socket. A type with the SerialiseAuth
capability should usually not also have OutputSerialisedAuth, as the
combination gives the holder the ability to examine the bitwise contents of
any object it has a reference to.
primitive val OutputSerialisedAuth

Constructors¶
create¶
[Source]


params: String val

Returns¶

PropertyHelper val^

Public fields¶
let env: Env val¶
[Source]

Public Functions¶
log¶
[Source]
Log the given message.
The verbose parameter allows messages to be printed only when the
--verbose command line option is used. For example, by default assert
failures are logged, but passes are not. With --verbose, both passes and
fails are reported.
Logs are printed one test at a time to avoid interleaving log lines from


fun box sctp_pcb_flags_zero_copy_active()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_peeloff¶
[Source]


USize val

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

Parameters¶

y: USize val

Returns¶

USize val

divrem¶
[Source]


: A

Returns¶

A


fun ref normal() =>
"""
Normalise all the fields of the date. For example, if the hour is 24, it is
set to 0 and the day is advanced. This allows fields to be changed naively,
eg. adding 1000 to hours to advance the time by 1000 hours, and then
normalising the date.
"""
@ponyint_gmtime(this, time(), nsec.i64())

fun format(fmt: String): String ? =>
"""
Format the time as for strftime.

Will return an empty string if the format string is "%p" or "%P".
"""
recover
String.from_cstring(@ponyint_formattime(this, fmt.cstring())?)
end


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


timers.pony

1
2
3
4
5
6
7
8
9
10
11


# Consuming a variable

Sometimes, you want to _move_ an object from one variable to another. In other words, you don't want to make a _second_ name for the object, you want to move the object from some existing name to a different one.

You can do this by using `consume`. When you `consume` a variable you take the value out of it, effectively leaving the variable empty. No code can read from that variable again until a new value is written to it. Consuming a local variable or a parameter allows you to move it to a new location, most importantly for `iso` and `trn`.

```pony
fun test(a: Wombat iso) =>
var b: Wombat iso = consume a // Allowed!
```

The compiler is happy with that because by consuming `a`, you've said the value can't be used again and the compiler will complain if you try to.

```pony
fun test(a: Wombat iso) =>
var b: Wombat iso = consume a // Allowed!
var c: Wombat tag = a // Not allowed!
```

Here's an example of that. When you try to assign `a` to `c`, the compiler will complain.


fun box f64_unsafe()
: F64 val

Returns¶

F64 val

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

Parameters¶

that: U64 val

Returns¶


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

Parameters¶

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

write¶
[Source]
Print some bytes without inserting a newline afterwards.
be write(
data: (String val | Array[U8 val] val))

Parameters¶

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

printv¶
[Source]


List[A] ref^

unit¶
[Source]
Creates a list with 1 node of element.
let my_list = List[String].unit("element")

new ref unit(
a: A)
: List[A] ref^

Parameters¶

a: A

Returns¶

List[A] ref^


new ref create(
choice': U8 val,
int': U128 val)
: IntPropertySample ref^

Parameters¶

choice': U8 val
int': U128 val

Returns¶

IntPropertySample ref^

Public fields¶
let choice: U8 val¶
[Source]

let int: U128 val¶


else
""
end

fun ref sentv(conn: TCPConnection ref, data: ByteSeqIter): ByteSeqIter =>
if not _throttled then
data
else
recover Array[String] end
end

fun ref throttled(connection: TCPConnection ref) =>
_throttled = true

fun ref unthrottled(connection: TCPConnection ref) =>
_throttled = false

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


fun box sctp_nrsack_supported()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_operation_error¶
[Source]


if event isnt _event then
if AsioEvent.writeable(flags) then
// A connection has completed.
var fd = @pony_asio_event_fd(event)
_connect_count = _connect_count - 1

if not _connected and not _closed then
// We don't have a connection yet.
if _is_sock_connected(fd) then
// The connection was successful, make it ours.
_fd = fd
_event = event
_connected = true
_writeable = true
_readable = true

_notify.connected(this)
_queue_read()
_pending_reads()


fun box ne(
that: IniIncompleteSection val)
: Bool val

Parameters¶

that: IniIncompleteSection val

Returns¶

Bool val


"""`true` if the owning user can write to the file."""

var owner_exec: Bool = false
"""`true` if the owning user can execute the file."""

var group_read: Bool = true
"""`true` if members of the owning group can read the file."""

var group_write: Bool = false
"""`true` if members of the owning group can write to the file."""

var group_exec: Bool = false
"""`true` if members of the owning group can execute the file."""

var any_read: Bool = true
"""`true` if every user can read the file."""

var any_write: Bool = false
"""`true` if every user can write to the file."""


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


```

The above example would also work if we used `Pointer[None]` for all the pointer types. By using a pointer to a primitive, we are adding a level of type safety, as the compiler will ensure that we don't pass a pointer to any other type as a parameter to `eglGetDisplay`. It is important to note that these primitives should __not be used anywhere except as a type parameter__ of `Pointer[]`, to avoid misuse.


fun box u128()
: U128 val

Returns¶

U128 val

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

Returns¶

ULong val

usize¶
[Source]


"""
_check_is[A]("is", consume expect, consume actual, msg, loc)

fun _check_is[A](
check: String,
expect: A,
actual: A,
msg: String,
loc: SourceLoc)
: Bool
=>
"""
Check that the 2 given expressions resolve to the same instance
"""
if expect isnt actual then
fail(_format_loc(loc) + "Assert " + check + " failed. " + msg
+ " Expected (" + (digestof expect).string() + ") is ("
+ (digestof actual).string() + ")")
return false
end


y: I32 val

Returns¶

I32 val

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

Parameters¶

y: I32 val

Returns¶


692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711


be dispose() =>
"""
Dispose of this set of timing wheels.
"""
for wheel in _wheel.values() do
wheel.clear()
end
_map.clear()

if not _event.is_null() then
@pony_asio_event_unsubscribe(_event)
_event = AsioEvent.none()
end

be _event_notify(event: AsioEventID, flags: U32, arg: U32) =>
"""
When the event fires, advance the timing wheels.
"""
if AsioEvent.disposable(flags) then
@pony_asio_event_destroy(event)


fun parse(typ: _ValueType, arg: String): (_Value | SyntaxError) =>
try
typ.value_of(arg)?
else
SyntaxError(arg, "unable to convert '" + arg + "' to " + typ.string())
end


: None val

Parameters¶

c: AsyncBenchContinue val

Returns¶

None val

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

Parameters¶

c: AsyncBenchContinue val


```bash
pip install mkdocs
ponyc packages/stdlib --docs && cd stdlib-docs && mkdocs serve
```

And point your web browser to [127.0.0.1:8000](http://127.0.0.1:8000) serving a live-reloading local version of the docs.

Note that there is _no built-in debugger_ to interactively step through your program and interpret the results. But ponyc creates proper DWARF symbols and you can step through your programs with a conventional debugger, such as GDB or LLDB.


Returns¶

I128 val

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

Returns¶

U128 val

i128_unsafe¶
[Source]
Unsafe operation.
If the value doesn't fit in the destination type, the result is undefined.
fun box i128_unsafe()


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

Parameters¶

that: FileError val

Returns¶

Bool val

ne¶
[Source]


(tmp_dir as FilePath).remove()
end

fun apply(h: TestHelper)? =>
let dir = tmp_dir as FilePath
// do something inside the temporary directory
```

"""

use "time"
use @ponyint_assert_disable_popups[None]()

actor PonyTest
"""
Main test framework actor that organises tests, collates information and
prints results.
"""

embed _groups: Array[(String, _Group)] = Array[(String, _Group)]


fun box rds_cong_monitor_size()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

rds_get_mr¶
[Source]


fun box commands()
: HashMap[String val, CommandSpec box, HashEq[String val] val] box

Returns¶

HashMap[String val, CommandSpec box, HashEq[String val] val] box

args¶
[Source]
Returns an array of the positional arguments of this command.
fun box args()
: Array[ArgSpec val] box

Returns¶

Array[ArgSpec val] box

is_leaf¶


fun box tipc_high_importance()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tipc_link_state¶
[Source]


Returns the number of items in the list.
let my_list = List[String].from(["a"; "b"; "c"])
my_list.size() // 3

fun box size()
: USize val

Returns¶

USize val

apply¶
[Source]
Get the i-th element, raising an error if the index is out of bounds.
let my_list = List[String].from(["a"; "b"; "c"])
try my_list.apply(1)? end // "b"

fun box apply(
i: USize val = 0)


So first we ask if there are any more names to get. If there are then we get a name and see if it's "Jack" or "Jill". If it is we're done and we break out of the loop, handing back the name we've found. If not we try again.

The line `name'` appears at the end of the loop so that will be our value returned from the last iteration if neither "Jack" nor "Jill" is found.

The `else` block provides our value of "Herbert" if there are no names available at all.

__Can I break out of multiple, nested loops like the Java labeled break?__ No, Pony does not support that. If you need to break out of multiple loops you should probably refactor your code or use a worker function.


error

be run() =>
if this._current_round.round() >= _params.num_samples then
complete() // all samples have been successful
return
end

// prepare property run
(var sample, _shrinker) =
try
_generate_with_retry(_params.max_generator_retries)?
else
// break out if we were not able to generate a sample
_notify.fail(
"Unable to generate samples from the given iterator, tried " +
_params.max_generator_retries.string() + " times." +
" (round: " + this._current_round.string() + ")")
_notify.complete(false)
return


Returns¶

U32 val

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

Returns¶

U32 val

rt¶
[Source]
fun box rt(
n: U32 val)
: U32 val ?


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


fun box ipproto_wsn()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_xtp¶
[Source]


[Source]
Remove the rights in that from this.
fun ref remove(
that: CapRights0 ref)
: None val

Parameters¶

that: CapRights0 ref

Returns¶

None val

clear¶
[Source]
Clear all rights.
fun ref clear()
: None val


ASCIIAllWithNUL¶
[Source]
Represents all ASCII characters,
including the NUL (\x00) character for its special treatment in C strings.
primitive val ASCIIAllWithNUL

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

Returns¶


Bool val

next¶
[Source]
fun ref next()
: U8 val ?

Returns¶

U8 val ?


class _EmptyIter[A]
fun ref has_next(): Bool => false
fun ref next(): A ? => error


fun box divrem(
y: U16 val)
: (U16 val , U16 val)

Parameters¶

y: U16 val

Returns¶

(U16 val , U16 val)

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

Parameters¶


Returns¶

U128 val

ulong¶
fun ref ulong()
: ULong val

Returns¶

ULong val

usize¶
fun ref usize()
: USize val

Returns¶


if _interval > 0 then
_interval = (_interval >> bits.u64()).max(1)
end

fun ref _fire(current: U64): Bool =>
"""
A timer is fired if its expiration time is in the past. The notifier is
called with a count based on the elapsed time since expiration and the
timer interval. The expiration time is set to the next expiration. Returns
true if the timer should be rescheduled, false otherwise.
"""
let elapsed = current - _expiration

if elapsed < (1 << 63) then
let count = (elapsed / _interval) + 1
_expiration = _expiration + (count * _interval)

if not _notify(this, count) then
_notify.cancel(this)


fun _stream(stream: DebugStream): Pointer[U8] =>
match stream
| DebugOut => @pony_os_stdout()
| DebugErr => @pony_os_stderr()
end


type WeightedGenerator[T] is (USize, Generator[T] box)
"""
A generator with an associated weight, used in Generators.frequency.
"""

primitive Generators
"""
Convenience combinators and factories for common types and kind of Generators.
"""

fun unit[T](t: T, do_shrink: Bool = false): Generator[box->T] =>
"""
Generate a reference to the same value over and over again.

This reference will be of type `box->T` and not just `T`
as this generator will need to keep a reference to the given value.
"""
Generator[box->T](
object is GenObj[box->T]
let _t: T = consume t


fun box u32_unsafe()
: U32 val

Returns¶

U32 val

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

Returns¶

U64 val

u128_unsafe¶
[Source]


Bool val

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

Parameters¶

that: Platform val

Returns¶

Bool val

ne¶
[Source]


## Return-type Polymorphism

We mentioned before that you should use the `Pointer[None]` type in Pony when dealing with values of `void*` type in C. This is very useful for function parameters, but when we use `Pointer[None]` for the return type of a C function, we won't be able to access the value that the pointer points to. Let's imagine a generic list in C:

```C
struct List;

struct List* list_create();
void list_free(struct List* list);

void list_push(struct List* list, void *data);
void* list_pop(struct List* list);
```

Following the advice from previous sections, we can write the following Pony declarations:

```pony
use @list_create[Pointer[_List]]()
use @list_free[None](list: Pointer[_List])


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


String iso^

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

Parameters¶

y: U16 val

Returns¶

U16 val

sub_unsafe¶
[Source]


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


fun box tipc_max_bearer_name()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tipc_max_link_name¶
[Source]


Bool val


fun box u8_unsafe()
: U8 val

Returns¶

U8 val

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

Returns¶

U16 val

u32_unsafe¶
[Source]


fun f32(): F32 => compile_intrinsic
fun f64(): F64 => compile_intrinsic

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

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

fun i32_unsafe(): I32 =>
"""


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


push_u64[optional B: (A & Real[B] val & U8 val)]¶
[Source]
Add a U64 to the end of the array. This is only allowed for an array of U8s.
fun ref push_u64[optional B: (A & Real[B] val & U8 val)](
value: U64 val)
: None val

Parameters¶

value: U64 val

Returns¶

None val

push_u128[optional B: (A & Real[B] val & U8 val)]¶
[Source]
Add a U128 to the end of the array. This is only allowed for an array of U8s.


Integer division, rounded towards zero.

Unsafe operation.
If y is 0, the result is undefined.
If the operation overflows, the result is undefined.
"""
this /~ y

fun divrem_unsafe(y: A): (A, A) =>
"""
Calculates the quotient of this number and `y` and the remainder.

Unsafe operation.
If y is 0, the result is undefined.
If the operation overflows, the result is undefined.
"""
(this /~ y, this %~ y)

fun rem_unsafe(y: A): A =>
"""


class MapPairs
class MapValues
type MaxHeap
primitive MaxHeapPriority
type MinHeap
primitive MinHeapPriority
class Range
class Reverse
class RingBuffer
type Set
type SetIs
class SetValues
primitive Sort


812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831


I16 val

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

Parameters¶

y: I16 val

Returns¶

(I16 val , I16 val)

rem_unsafe¶
[Source]


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


# Example code

```pony
use "encode/base64"

actor Main
new create(env: Env) =>
env.out.print(Base64.encode("foobar"))
try
env.out.print(Base64.decode[String iso]("Zm9vYmFy")?)
end
```
"""
use "collections"
use "assert"

primitive Base64
fun encode_pem(data: ReadSeq[U8]): String iso^ =>
"""
Encode for PEM (RFC 1421).


Bool val

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

Parameters¶

that: FormatGeneralLarge val

Returns¶

Bool val


fun box divrem(
y: I32 val)
: (I32 val , I32 val)

Parameters¶

y: I32 val

Returns¶

(I32 val , I32 val)

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

Parameters¶


fun box ipx_maxsize()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipx_mtu¶
[Source]


y: ULong val

Returns¶

ULong val ?

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

Parameters¶

y: ULong val

Returns¶


Public fields¶
let env: Env val¶
[Source]
The process environment.
This is useful for getting the root authority in
order to access the filesystem (See files) or the network
(See net) in your tests.

Public Functions¶
log¶
[Source]
Log the given message.
The verbose parameter allows messages to be printed only when the --verbose
command line option is used. For example, by default assert failures are
logged, but passes are not. With --verbose both passes and fails are
reported.
Logs are printed one test at a time to avoid interleaving log lines from
concurrent tests.
fun box log(


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


fun box sctp_from_middle_box()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_get_addr_len¶
[Source]


that: Help val

Returns¶

Bool val


fun ref next()
: (USize val , A) ?

Returns¶

(USize val , A) ?


Writer¶
[Source]
A buffer for building messages.
Writer provides an way to create byte sequences using common
data encodings. The Writer manages the underlying arrays and
sizes. It is useful for encoding data to send over a network or
store in a file. Once a message has been built you can call done()
to get the message's ByteSeqs, and you can then reuse the
Writer for creating a new message.
For example, suppose we have a TCP-based network data protocol where
messages consist of the following:

message_length - the number of bytes in the message as a


U64 val

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

Returns¶

I8 val

i16¶
[Source]
fun box i16()
: I16 val

Returns¶


h: val->A,
t: (Cons[A] val | Nil[A] val))
: (Cons[A] val | Nil[A] val)

Parameters¶

h: val->A
t: (Cons[A] val | Nil[A] val)

Returns¶

(Cons[A] val | Nil[A] val)

apply¶
[Source]
Builds a new list from an Array
fun box apply(
arr: Array[val->A] ref)
: (Cons[A] val | Nil[A] val)


492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511


FileBadFileNumber¶
[Source]
primitive val FileBadFileNumber

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

Returns¶

FileBadFileNumber val^


# What can be annotated

Annotations are allowed after any scoping keyword or symbol. The full list is:

- `actor`
- `class`
- `struct`
- `primitive`
- `trait`
- `interface`
- `new`
- `fun`
- `be`
- `if` (only as a condition, not as a guard)
- `ifdef`
- `elseif`
- `else`
- `while`
- `repeat`
- `until`


52
53
54
55
56
57
58
59
60
61
62
63class val ProcessError
let error_type: ProcessErrorType
let message: (String | None)

new val create(error_type': ProcessErrorType,
message': (String | None) = None)
=>
error_type = error_type'
message = message'


(U128 val , Bool val)

remc¶
[Source]
fun box remc(
y: U128 val)
: (U128 val , Bool val)

Parameters¶

y: U128 val

Returns¶

(U128 val , Bool val)

add_partial¶
[Source]


## Unix/Mac

Edit/add the `rc` file corresponding to your chosen shell (`echo $SHELL` will tell you what shell you are running). For example, if using bash, add the following to your `~/.bashrc`:

```bash
export PONYPATH=$PONYPATH:$HOME/pony
```

(Then run `source ~/.bashrc` to add this variable to a running session. New terminal session will automatically source `~/.bashrc`.)


A

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

Returns¶

A

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

Returns¶


# Static vs Dynamic: What's the difference?

In both kinds of language, your data has a type. So what's the difference?

With a _dynamically typed_ language, a variable can point to objects of different types at different times. This is flexible, because if you have a variable `x`, you can assign an integer to it, then assign a string to it, and your compiler or interpreter doesn't complain.

__But what if I try to do a string operation on `x` after assigning an integer to it?__ Generally speaking, your program will raise an error. You might be able to handle the error in some way, depending on the language, but if you don't, your program will crash.

When you use a _statically typed_ language, a variable has a type. That is, it can only point to objects of a certain type (although in Pony, a type can actually be a collection of types, as we'll see later). If you have an `x` that expects to point to an integer, you can't assign a string to it. Your compiler complains, and it complains __before__ you ever try to run your program.


[Source]
fun box rem(
y: ILong val)
: ILong val

Parameters¶

y: ILong val

Returns¶

ILong val

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

Returns¶


EraseLeft¶
[Source]
primitive val EraseLeft

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

Returns¶

EraseLeft val^


Returns¶

U128 val ?

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

Parameters¶

offset: USize val = 0

Returns¶

U128 val ?


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


fun box ipx_immediatespxack()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipx_maxsize¶
[Source]


Time val^

Public Functions¶
now¶
[Source]
The wall-clock adjusted system time with nanoseconds.
Return: (seconds, nanoseconds)
fun box now()
: (I64 val , I64 val)

Returns¶

(I64 val , I64 val)

seconds¶
[Source]
The wall-clock adjusted system time.
fun box seconds()


Vec[A] val^

Public Functions¶
size¶
[Source]
Return the amount of values in the vector.
fun box size()
: USize val

Returns¶

USize val

apply¶
[Source]
Get the i-th element, raising an error if the index is out of bounds.
fun box apply(


fun _save_history() =>
"""
Write the history back to a file.
"""
try
with file = File(_path as FilePath) do
for line in _history.values() do
file.print(line)
end
end
end


shuffle[A: A]¶
[Source]
Shuffle the elements of the array into a random order, mutating the array.
fun ref shuffle[A: A](
array: Array[A] ref)
: None val

Parameters¶

array: Array[A] ref

Returns¶

None val


fun box sctp_cmt_rpv2()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_connect_x¶
[Source]


shift: Bool val

Returns¶

None val

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

Parameters¶

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


F64 val

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

Parameters¶

that: box->A

Returns¶

(Less val | Equal val | Greater val)


Bool val

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

Returns¶

A

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

Returns¶


fun box tipc_err_no_port()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tipc_high_importance¶
[Source]


BenchConfig¶
[Source]
Configuration of a benchmark.
class val BenchConfig

Constructors¶
create¶
[Source]
new val create(
samples': USize val = 20,
max_iterations': U64 val = 1000000000,
max_sample_time': U64 val = 100000000)
: BenchConfig val^


fun box i64()
: I64 val

Returns¶

I64 val

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

Returns¶

I128 val

ilong¶
[Source]


return
end

if AsioEvent.readable(flags) then
_accept(arg)
end

if AsioEvent.disposable(flags) then
@pony_asio_event_destroy(_event)
_event = AsioEvent.none()
end

be _conn_closed() =>
"""
An accepted connection has closed. If we have dropped below the limit, try
to accept new connections.
"""
_count = _count - 1

if _paused and (_count < _limit) then


l4_head == 1
Lists[U32].eq(l4, Lists[U32]([1; 2; 3]))?
Lists[U32].eq(l4_tail, Lists[U32]([2; 3]))?

let doubled = l4.map[U32]({(x) => x * 2 })

Lists[U32].eq(doubled, Lists[U32]([2; 4; 6]))?
end
```
"""

primitive Lists[A]
"""
A primitive containing helper functions for constructing and
testing Lists.
"""

fun empty(): List[A] =>
"""
Returns an empty list.


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


I32 val

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

Returns¶

U32 val

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

Returns¶


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


if _pending_sent < 16 then
// If fewer than 16 asynchronous writes are scheduled, remove
// backpressure. The choice of 16 is rather arbitrary and probably
// needs to be tuned.
_release_backpressure()
end
end

be _write_again() =>
"""
Resume writing.
"""
_pending_writes()

fun ref _pending_writes(): Bool =>
"""
Send pending data. If any data can't be sent, keep it and mark as not
writeable. On an error, dispose of the connection. Returns whether
it sent all pending data or not.


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


fun dccp_sockopt_tx_ccid():I32 => @pony_os_sockopt_option(I32(22))
fun dso_acceptmode():I32 => @pony_os_sockopt_option(I32(23))
fun dso_conaccept():I32 => @pony_os_sockopt_option(I32(24))
fun dso_conaccess():I32 => @pony_os_sockopt_option(I32(25))
fun dso_condata():I32 => @pony_os_sockopt_option(I32(26))
fun dso_conreject():I32 => @pony_os_sockopt_option(I32(27))
fun dso_cork():I32 => @pony_os_sockopt_option(I32(28))
fun dso_disdata():I32 => @pony_os_sockopt_option(I32(29))
fun dso_info():I32 => @pony_os_sockopt_option(I32(30))
fun dso_linkinfo():I32 => @pony_os_sockopt_option(I32(31))
fun dso_max():I32 => @pony_os_sockopt_option(I32(32))
fun dso_maxwindow():I32 => @pony_os_sockopt_option(I32(33))
fun dso_nodelay():I32 => @pony_os_sockopt_option(I32(34))
fun dso_seqpacket():I32 => @pony_os_sockopt_option(I32(35))
fun dso_services():I32 => @pony_os_sockopt_option(I32(36))
fun dso_stream():I32 => @pony_os_sockopt_option(I32(37))
fun icmp_address():I32 => @pony_os_sockopt_option(I32(38))
fun icmp_addressreply():I32 => @pony_os_sockopt_option(I32(39))
fun icmp_dest_unreach():I32 => @pony_os_sockopt_option(I32(40))
fun icmp_echo():I32 => @pony_os_sockopt_option(I32(41))


372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391


Reserve space for len elements, including whatever elements are already in
the array. Array space grows geometrically.
"""
if _alloc < len then
_alloc = len.next_pow2().max(len).max(8)
_ptr = _ptr._realloc(_alloc, _size)
end

fun _element_size(): USize =>
"""
Element size in bytes for an element.
"""
_ptr._element_size()

fun ref compact() =>
"""
Try to remove unused space, making it available for garbage collection. The
request may be ignored.
"""
if _size <= (512 / _ptr._element_size()) then


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


ILong val

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

Returns¶

ISize val

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

Returns¶


fun box ipproto_ip()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_ipcv¶
[Source]


lower_in_place¶
[Source]
Transforms the string to lower case. Currently only knows ASCII case.
fun ref lower_in_place()
: None val

Returns¶

None val

upper¶
[Source]
Returns an upper case version of the string. Currently only knows ASCII
case.
fun box upper()
: String iso^

Returns¶


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

Implements¶

_BinaryHeapPriority[A] val

Constructors¶
create¶
[Source]


PonyTest package¶
The PonyTest package provides a unit testing framework. It is designed to be as
simple as possible to use, both for the unit test writer and the user running
the tests.
To help simplify test writing and distribution this package depends on as few
other packages as possible. Currently the required packages are:

builtin
time
collections

Each unit test is a class, with a single test function. By default all tests
run concurrently.


# Consume and Destructive Read

An important part of Pony's capabilities is being able to say "I'm done with this thing." We'll cover two means of handling this situation: consuming a variable and destructive reads.


fun box ipv6_recvrthdr()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_router_alert¶
[Source]


primitive FileRemove
fun value(): U32 => 1 << 7

primitive FileRename
fun value(): U32 => 1 << 8

primitive FileSeek
fun value(): U32 => 1 << 9

primitive FileStat
fun value(): U32 => 1 << 10

primitive FileSync
fun value(): U32 => 1 << 11

primitive FileTime
fun value(): U32 => 1 << 12

primitive FileTruncate
fun value(): U32 => 1 << 13


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


# Types are guarantees

When the compiler knows what types things are, it can make sure some things in your program work without you having to run it or test it. These things are the _guarantees_ that a language's type system provides.

The more powerful a type system is, the more things it can prove about your program without having to run it.

__Do dynamic types make guarantees too?__ Yes, but they do it at runtime. For example, if you call a method that doesn't exist, you will usually get some kind of exception. But you'll only find out when you try to run your program.


Constructors¶
create¶
[Source]
new val create(
sig: U32 val)
: Signaled val^

Parameters¶

sig: U32 val

Returns¶

Signaled val^

Public Functions¶
signal¶
[Source]
Retrieve the signal number that exited the process.


PonyTest¶
[Source]
Main test framework actor that organises tests, collates information and
prints results.
actor tag PonyTest

Constructors¶
create¶
[Source]
Create a PonyTest object and use it to run the tests from the given
TestList
new tag create(
env: Env val,


Parameters¶

gen1: Generator[T1] val
gen2: Generator[T2] val
gen3: Generator[T3] val
h: TestHelper val

Returns¶

ForAll3[T1, T2, T3] ref

for_all4[T1: T1, T2: T2, T3: T3, T4: T4]¶
[Source]
fun box for_all4[T1: T1, T2: T2, T3: T3, T4: T4](
gen1: Generator[T1] val,
gen2: Generator[T2] val,
gen3: Generator[T3] val,
gen4: Generator[T4] val,


fun box ilong()
: ILong val

Returns¶

ILong val

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

Returns¶

ISize val

u8¶
[Source]


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


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


let _space: USize
let _p: Promise[Array[A] val]

new create(p: Promise[Array[A] val], space: USize) =>
(_xs, _space, _p) = (Array[A](space), space, p)

be apply(a: A) =>
_xs.push(a)
if _xs.size() == _space then
let len = _xs.size()
let xs = recover Array[A](len) end
for x in _xs.values() do
xs.push(x)
end
_p(consume xs)
end

primitive _None


Stdin¶
[Source]
Asynchronous access to stdin. The constructor is private to ensure that
access is provided only via an environment.
Reading from stdin is done by registering an InputNotify:
actor Main
new create(env: Env) =>
// do not forget to call `env.input.dispose` at some point
env.input(
object iso is InputNotify
fun ref apply(data: Array[U8] iso) =>
env.out.write(String.from_iso_array(consume data))


fun box ipproto_rvd()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_satmon¶
[Source]


"""
Remove everything that isn't in that.
"""
let start_size = _map.size()
var seen: USize = 0
var i: USize = -1

while seen < start_size do
try
i = next_index(i)?
if not that.contains(index(i)?) then
unset(index(i)?)
end
end
seen = seen + 1
end

fun ref difference(that: Iterator[A^]) =>
"""
Remove elements in this which are also in that. Add elements in that which


32
33class Fibonacci[A: (Integer[A] val & Unsigned) = U64] is Iterator[A]
"""
Useful for microbenchmarks to impress your friends. Look y'all, Pony goes
fast! We suppose if you are into Agile planning poker that you could also
use this in conjunction with `Random` to assign User Story Points.
"""
var _last: A = 0
var _next: A = 0
var _uber_next: A = 1

fun apply(n: U8): A =>
if n == 0 then 0
elseif n == 1 then 1
else
let j = n / 2
let fib_j = apply(j)
let fib_i = apply(j - 1)

if (n % 2) == 0 then


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

Parameters¶

a: A

Returns¶

ILong val^

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

Returns¶


match CommandParser(command_spec).parse(env.args, env.vars)
| let c: Command => c
| let ch: CommandHelp =>
ch.print_help(env.out)
env.exitcode(0)
return
| let se: SyntaxError =>
env.err.print(se.string())
env.exitcode(1)
return
end
let input_source = command.arg("input").string()
let output_filename = command.option("output").string()
env.out.print("Loading data from " + input_source + ". Writing output to " + output_filename)
// ...
```


ASCIIDigits¶
[Source]
primitive val ASCIIDigits

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

Returns¶

ASCIIDigits val^


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

Parameters¶

array: B

Returns¶

ArrayPairs[A, B] ref^

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

Returns¶


_read_len = 0
_read_buf_size()

sum = sum + len.usize()
if sum > (1 << 12) then
// If we've read 4 kb, yield and read again later.
_read_again(pipe.near_fd)
return
end
end

fun ref _read_buf_size() =>
if _expect > 0 then
_read_buf.undefined(_expect)
else
_read_buf.undefined(_max_size)
end

be _read_again(near_fd: U32) =>
"""


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


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


# How is that unforgeable?

Since Pony has no pointer arithmetic and is both type-safe and memory-safe, object references can't be "invented" (i.e. forged) by the program. You can only get one by constructing an object or being passed an object.

__What about the C-FFI?__ Using the C-FFI can break this guarantee. We'll talk about the __C-FFI trust boundary__ later, and how to control it.


fun box ctz_unsafe()
: U128 val

Returns¶

U128 val

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

Returns¶

U128 val

bytewidth¶
[Source]


fun box icmp_frag_needed()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

icmp_host_isolated¶
[Source]


fun box rem_unsafe(
y: U32 val)
: U32 val

Parameters¶

y: U32 val

Returns¶

U32 val

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

Returns¶


DNSAuth¶
[Source]
primitive val DNSAuth

Constructors¶
create¶
[Source]
new val create(
from: (AmbientAuth val | NetAuth val))
: DNSAuth val^

Parameters¶


y: USize val

Returns¶

USize val ?

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

Parameters¶

y: USize val

Returns¶


from_cpointer(_ptr._offset(offset)._unsafe(), size', alloc)
else
create()
end
end

fun iso chop[B: (A & Any #send) = A](split_point: USize): (Array[A] iso^, Array[A] iso^) =>
"""
Chops the array in half at the split point requested and returns both
the left and right portions. The original array is trimmed in place and
returned as the left portion. If the split point is larger than the
array, the left portion is the original array and the right portion
is a new empty array.
The operation does not allocate a new array pointer nor copy elements.

The entry type must be sendable so that the two halves can be isolated.
Otherwise, two entries may have shared references to mutable data,
or even to each other, such as in the code below:

```pony


"""
-307

fun tag max_exp2(): I16 =>
"""
Maximum exponent value such that (2^exponent) - 1 is representable.
"""
1024

fun tag max_exp10(): I16 =>
"""
Maximum exponent value such that (10^exponent) - 1 is representable.
"""
308

fun abs(): F64 => @"llvm.fabs.f64"(this)
fun ceil(): F64 => @"llvm.ceil.f64"(this)
fun floor(): F64 => @"llvm.floor.f64"(this)
fun round(): F64 => @"llvm.round.f64"(this)
fun trunc(): F64 => @"llvm.trunc.f64"(this)


I128¶
[Source]
primitive val I128 is
SignedInteger[I128 val, U128 val] val

Implements¶

SignedInteger[I128 val, U128 val] val

Constructors¶
create¶
[Source]


nth: USize val = 0)
: ISize val ?

Parameters¶

s: String box
offset: ISize val = call
nth: USize val = 0

Returns¶

ISize val ?

contains¶
[Source]
Returns true if contains s as a substring, false otherwise.
fun box contains(
s: String box,
offset: ISize val = 0,


where T is the type of the objects in the collection. You don't need to worry about this unless you're writing your own iterators. To use existing collections, such as those provided in the standard library, you can just use `for` and it will all work. If you do write your own iterators, note that we use structural typing, so your iterator doesn't need to declare that it provides any particular type.

You can think of the above example as being equivalent to:

```pony
let iterator = ["Bob"; "Fred"; "Sarah"].values()
while iterator.has_next() do
let name = iterator.next()?
env.out.print(name)
end
```

Note that the variable __name__ is declared _let_, so you cannot assign to the control variable within the loop.

__Can I use break and continue with for loops?__ Yes, `for` loops can have `else` expressions attached and can use `break` and `continue` just as for `while`.


fun ref next()
: val->A ?

Returns¶

val->A ?


```

Again there's something new here. After the name `SetIs` comes the name `A` in square brackets. That's because `SetIs` is a __generic type__. That is, you can give a `SetIs` another type as a parameter, to make specific kinds of set. If you've used Java or C#, this will be pretty familiar. If you've used C++, the equivalent concept is templates, but they work quite differently.

And again the use of `type` just provides a more convenient way to refer to the type we're aliasing:

```pony
HashSet[A, HashIs[A!]]
```

That's another __generic type__. It means a `SetIs` is really a kind of `HashSet`. Another concept has snuck in, which is `!` types. This is a type that is the __alias__ of another type. That's tricky stuff that you only need when writing complex generic types, so we'll leave it for later.

One more example, again from the standard library, is the `Map` type that gets used a lot. It's actually a type alias. Here's the real definition of `Map`:

```pony
type Map[K: (Hashable box & Comparable[K] box), V] is HashMap[K, V, HashEq[K]]
```

Unlike our previous example, the first type parameter, `K`, has a type associated with it. This is a __constraint__, which means when you parameterise a `Map`, the type you pass for `K` must be a subtype of the constraint.


fun box ipproto_pvp()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_rccmon¶
[Source]


_read_buf = recover Array[U8] .> undefined(read_buffer_size) end
_read_buffer_size = read_buffer_size
_yield_after_reading = yield_after_reading
_yield_after_writing = yield_after_writing
_notify = consume notify
let asio_flags =
ifdef not windows then
AsioEvent.read_write_oneshot()
else
AsioEvent.read_write()
end
(let host', let service') = _notify.proxy_via(host, service)
_connect_count =
@pony_os_connect_tcp4(this, host'.cstring(), service'.cstring(),
from.cstring(), asio_flags)
_notify_connecting()

new ip6(
auth: TCPConnectAuth,
notify: TCPConnectionNotify iso,


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


fun box ne(
that: AlignRight val)
: Bool val

Parameters¶

that: AlignRight val

Returns¶

Bool val


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


fun rds_cmsg_masked_atomic_fadd():I32 => @pony_os_sockopt_option(I32(442))
fun rds_cmsg_rdma_args():I32 => @pony_os_sockopt_option(I32(443))
fun rds_cmsg_rdma_dest():I32 => @pony_os_sockopt_option(I32(444))
fun rds_cmsg_rdma_map():I32 => @pony_os_sockopt_option(I32(445))
fun rds_cmsg_rdma_status():I32 => @pony_os_sockopt_option(I32(446))
fun rds_cong_monitor():I32 => @pony_os_sockopt_option(I32(447))
fun rds_cong_monitor_size():I32 => @pony_os_sockopt_option(I32(448))
fun rds_free_mr():I32 => @pony_os_sockopt_option(I32(449))
fun rds_get_mr():I32 => @pony_os_sockopt_option(I32(450))
fun rds_get_mr_for_dest():I32 => @pony_os_sockopt_option(I32(451))
fun rds_ib_abi_version():I32 => @pony_os_sockopt_option(I32(452))
fun rds_ib_gid_len():I32 => @pony_os_sockopt_option(I32(453))
fun rds_info_connections():I32 => @pony_os_sockopt_option(I32(454))
fun rds_info_connection_flag_connected():I32 => @pony_os_sockopt_option(I32(455))
fun rds_info_connection_flag_connecting():I32 => @pony_os_sockopt_option(I32(456))
fun rds_info_connection_flag_sending():I32 => @pony_os_sockopt_option(I32(457))
fun rds_info_connection_stats():I32 => @pony_os_sockopt_option(I32(458))
fun rds_info_counters():I32 => @pony_os_sockopt_option(I32(459))
fun rds_info_first():I32 => @pony_os_sockopt_option(I32(460))
fun rds_info_ib_connections():I32 => @pony_os_sockopt_option(I32(461))


"""
shrink `t` using the generator this one filters upon
and call the filter predicate on the shrunken values
"""
(let s, let shrunken: Iterator[T^]) = _gen.shrink(consume t)
(consume s, _filter_shrunken(shrunken))

fun _filter_shrunken(shrunken: Iterator[T^]): Iterator[T^] =>
Iter[T^](shrunken)
.filter_map[T^]({
(t: T): (T^| None) =>
match predicate(consume t)
| (let matching: T, true) => consume matching
end
})
end)

fun map[U](fn: {(T): U^} box)
: Generator[U]
=>


new ref repeat_value(
value: A)
: Iter[A] ref^

Parameters¶

value: A

Returns¶

Iter[A] ref^

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

Returns¶


input = input'
out = out'
err = err'
args = args'
vars = vars'
exitcode = exitcode'

fun tag _count_strings(data: Pointer[Pointer[U8]] val): USize =>
if data.is_null() then
return 0
end

var i: USize = 0

while
let entry = data._apply(i)
not entry.is_null()
do
i = i + 1
end


fun bool(): Bool =>
"""
Returns the option value as a Bool, defaulting to false.
"""
try _value as Bool else false end

fun string(): String =>
"""
Returns the option value as a String, defaulting to empty.
"""
try _value as String else "" end

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

fun u64(): U64 =>
"""


fun infinite(): Bool =>
"""
Check whether this number is +/-infinity
"""
// True if exponent is all 1s and mantissa is 0
((bits() and 0x7F800000) == 0x7F800000) and  // exp
((bits() and 0x007FFFFF) == 0)  // mantissa

fun nan(): Bool =>
"""
Check whether this number is NaN.
"""
// True if exponent is all 1s and mantissa is non-0
((bits() and 0x7F800000) == 0x7F800000) and  // exp
((bits() and 0x007FFFFF) != 0)  // mantissa

fun ldexp(x: F32, exponent: I32): F32 =>
@ldexpf(x, exponent)

fun frexp(): (F32, U32) =>


String val

split_list¶
[Source]
Separate a list of paths into an array of cleaned paths.
fun box split_list(
path: String val)
: Array[String val] iso^

Parameters¶

path: String val

Returns¶

Array[String val] iso^

random¶


Parameters¶

that: ASCIIAll val

Returns¶

Bool val

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

Parameters¶

that: ASCIIAll val


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


fun box ipproto_ahip()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_argus¶
[Source]


fun box eq(
y: I16 val)
: Bool val

Parameters¶

y: I16 val

Returns¶

Bool val

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

Parameters¶


I64 val | I128 val | ILong val |
ISize val | U8 val | U16 val |
U32 val | U64 val | U128 val |
ULong val | USize val | F32 val |
F64 val) & Real[B] val)](
a: B)
: Real[A] val^

Parameters¶

a: B

Returns¶

Real[A] val^

min_value¶
[Source]
new val min_value()


# Symbol Lookup Cheat Sheet

Pony, like just about any other programming language, has plenty of odd symbols that make up its syntax. If you don't remember what one means, it can be hard to search for them. Below you'll find a table with various Pony symbols and what you should search the tutorial for in order to learn more about the symbol.

| Symbol | Search Keywords       |
| ------ | --------------------- |
| `!`    | Alias                 |
| `->`   | Arrow type, viewpoint |
| `.>`   | Chaining              |
| `^`    | Ephemeral             |
| `@`    | FFI                   |
| `&`    | Intersection          |
| `=>`   | Match arrow           |
| `~`    | Partial application   |
| `?`    | Partial function      |
| `'`    | Prime                 |
| `<:`   | Subtype               |

Here is a more elaborate explanation of Pony's use of special characters: (a line with (2) or (3) means an alternate usage of the symbol of the previous  line)


U32 val

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

Parameters¶

y: U32 val

Returns¶

U32 val

rotr¶
[Source]


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


be dispose() =>
"""
Stop listening.
"""
if not _closed then
_close()
end

fun local_address(): NetAddress =>
"""
Return the bound IP address.
"""
_ip

be _event_notify(event: AsioEventID, flags: U32, arg: U32) =>
"""
When we are readable, we accept new connections until none remain.
"""
if event isnt _event then


else
compile_error "unsupported platform"
end

_FileDes.set_rights(_fd, path)?

new iso _relative(path': FilePath, fd': I32) =>
"""
Internal constructor. Capsicum rights are already set by inheritence.
"""
path = path'
_fd = fd'

fun entries(): Array[String] iso^ ? =>
"""
The entries will include everything in the directory, but it is not
recursive. The path for the entry will be relative to the directory, so it
will contain no directory separators. The entries will not include "." or
"..".
"""


fun box rose_invalid_facility()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

rose_max_digis¶
[Source]


option, if possible, and run with the `--ponynoyield` option.
"""
// TODO more examples in tutorial

actor PonyBench
let _env: Env
let _output_manager: _OutputManager
embed _bench_q: Array[(Benchmark, Bool)] = Array[(Benchmark, Bool)]
var _running: Bool = false

new create(env: Env, list: BenchmarkList) =>
_env = consume env
ifdef debug then
_env.err.print("***WARNING*** Benchmark was built as DEBUG. Timings may be affected.")
end

_output_manager =
if _env.args.contains("-csv", {(a, b) => a == b })
then _CSVOutput(_env)
else _TerminalOutput(_env)


Net package¶
The Net package provides support for creating UDP and TCP clients and
servers, reading and writing network data, and establishing UDP and
TCP connections.
Public Types¶

primitive DNS
primitive DNSAuth
class NetAddress
primitive NetAuth
class NoProxy
primitive OSSockOpt
interface Proxy


fun values(): Iterator[val->A]^ =>
"""
Returns an empty iterator over the elements of the empty list.
"""
object ref is Iterator[val->A]
fun has_next(): Bool => false
fun ref next(): val->A! ? => error
end

fun is_empty(): Bool =>
"""
Returns a Bool indicating if the list is empty.
"""
true

fun is_non_empty(): Bool =>
"""
Returns a Bool indicating if the list is non-empty.
"""
false


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


env.out.print("Result: " + r.string())

fun reduce(l: List[U32], acc: U32, f: {(U32, U32): U32} val): U32 =>
try
let acc' = f(acc, l.shift()?)
reduce(l, acc', f)
else
acc
end
```

The `reduce` method in this example requires the lambda type for the `f` parameter to require a reference capability of `val`. The lambda object passed in as an argument does not need to declare an explicit reference capability because `val` is the default for a lambda that does not capture anything.

As mentioned previously the lambda desugars to an object literal with an `apply` method. The reference capability for the `apply` method defaults to `box` like any other method. In a lambda that captures references, this needs to be `ref` if the function needs to modify any of the captured variables or call `ref` methods on them. The reference capability for the method (versus the reference capability for the object which was described above) is defined by putting the capability before the parenthesized argument list.

```pony
use "collections"

actor Main
new create(env:Env) =>


"""
The number of items in the map.
"""
_size

fun space(): USize =>
"""
The available space in the map. Resize will happen when
size / space >= 0.75.
"""
_array.space()

fun apply(key: box->K!): this->V ? =>
"""
Gets a value from the map. Raises an error if no such item exists.
"""
(let i, let found) = _search(key)

if found then
_array(i)? as (_, this->V)


that: (Exited val | Signaled val)

Returns¶

Bool val


[Source]
fun ref i16()
: I16 val

Returns¶

I16 val

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

Returns¶

I32 val

i64¶


U64 val

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

Returns¶

String iso^

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

Parameters¶


Set a value in the map. Returns the new value, allowing reuse.
"""
let value' = value
try
(let i, let found) = _search(key)
let key' = key
_array(i)? = (consume key, consume value)

if not found then
_size = _size + 1

if (_size * 4) > (_array.size() * 3) then
_resize(_array.size() * 2)
end
end

value'
else
// This is unreachable, since index will never be out-of-bounds.
value'


: U8 val

Returns¶

U8 val

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

Returns¶

U16 val

u32¶
[Source]
fun ref u32()


fun box ip_recvpktinfo()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_recvrssbucketid¶
[Source]


fun box i16()
: I16 val

Returns¶

I16 val

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

Returns¶

I32 val

i64¶
[Source]


Stringable box

Implements¶

Stringable box

Constructors¶
create¶
[Source]
new val create(
num_samples': USize val = 100,
seed': U64 val = call,
max_shrink_rounds': USize val = 10,
max_generator_retries': USize val = 5,
timeout': U64 val = 60000000000,
async': Bool val = false)
: PropertyParams val^

Parameters¶


ULong val | USize val | F32 val |
F64 val))](
len: USize val)
: None val

Parameters¶

len: USize val

Returns¶

None val

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


Returns¶

Promise[(A , B)] tag

join¶
[Source]
Create a promise that is fulfilled when the receiver and all promises in
the given iterator are fulfilled. If the receiver or any promise in the
sequence is rejected then the new promise is also rejected.
Join p1 and p2 with an existing promise, p3.
use "promises"

actor Main
new create(env: Env) =>

let p1 = Promise[String val]
let p2 = Promise[String val]
let p3 = Promise[String val]


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


fun box ipv6_multicast_if()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_nexthop¶
[Source]


be reject()

Public Functions¶
next[B: Any #share]¶
[Source]
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.
If there is no reject function, of if the reject function raises an error,
then the next promise in the chain will be rejected.
fun tag next[B: Any #share](
fulfill: Fulfill[A, B] iso,
rejected: Reject[B] iso = qualify)


that: InputSerialisedAuth val

Returns¶

Bool val

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

Parameters¶

that: InputSerialisedAuth val

Returns¶

Bool val


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

Parameters¶

y: A

Returns¶

A

sub¶
[Source]
fun box sub(


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


: None val

Returns¶

None val

format¶
[Source]
Format the time as for strftime.
Will return an empty string if the format string is "%p" or "%P".
fun box format(
fmt: String val)
: String val ?

Parameters¶

fmt: String val

Returns¶


bufsize: U32 val

Returns¶

U32 val

set_so_sndbuf¶
[Source]
Wrapper for the FFI call setsockopt(fd, SOL_SOCKET, SO_SNDBUF, ...)
fun ref set_so_sndbuf(
bufsize: U32 val)
: U32 val

Parameters¶

bufsize: U32 val

Returns¶


gen1: Generator[T1] val,
gen2: Generator[T2] val,
gen3: Generator[T3] val,
h: TestHelper)
: ForAll3[T1, T2, T3]
=>
ForAll3[T1, T2, T3](gen1, gen2, gen3, h)

fun for_all4[T1, T2, T3, T4](
gen1: Generator[T1] val,
gen2: Generator[T2] val,
gen3: Generator[T3] val,
gen4: Generator[T4] val,
h: TestHelper)
: ForAll4[T1, T2, T3, T4]
=>
ForAll4[T1, T2, T3, T4](gen1, gen2, gen3, gen4, h)


ListNodes[A: A, N: ListNode[A] #read]¶
[Source]
Iterate over the nodes in a List.
class ref ListNodes[A: A, N: ListNode[A] #read] is
Iterator[N] ref

Implements¶

Iterator[N] ref

Constructors¶
create¶


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

Parameters¶

that: Assert val

Returns¶

Bool val

ne¶
[Source]
fun box ne(


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


repr: String val
rounds: USize val = 0
err: Bool val = false

Returns¶

None val


[Source]
Clear all of the any-user flags.
fun ref group()
: None val

Returns¶

None val

private¶
[Source]
Clear all of the group and any-user flags.
fun ref private()
: None val

Returns¶

None val


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

Parameters¶

that: Base64 val

Returns¶

Bool val

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


Public Functions¶
encode_pem¶
[Source]
Encode for PEM (RFC 1421).
fun box encode_pem(
data: ReadSeq[U8 val] box)
: String iso^

Parameters¶

data: ReadSeq[U8 val] box

Returns¶

String iso^

encode_mime¶


# Line 3

```pony
env.out.print("Hello, world!")
```

This is your program! What the heck is it doing?

In Pony, a dot is either a field access or a method call, much like other languages. If the name after the dot has parentheses after it, it's a method call. Otherwise, it's a field access.

So here, we start with a reference to `env`. We then look up the field `out` on our object `env`. As it happens, that field represents `stdout`, i.e. usually it means printing to your console. Then, we call the `print` method on `env.out`. The stuff inside the parentheses are the arguments to the function. In this case, we are passing a __string literal__, i.e. the stuff in double quotes. The `env.out.print` method will implicitly add a `\n` after the string literal, so make sure to not add an extra `\n` if you only wants to output one single line.

In Pony, string literals can be in double quotes, `"`, in which case they follow C/C++ style escaping (using stuff like \n), or they can be triple-quoted, `"""` like in Python, in which case they are considered raw data.

In Pony, `print` only support String type. So make sure to convert variables to String type through `.string()` method.

__What's an `Env`, anyway?__ It's the "environment" your program was invoked with. That means it has command line arguments, environment variables, `stdin`, `stdout`, and `stderr`. Pony has no global variables, so these things are explicitly passed to your program.


Bool val

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

Parameters¶

y: ULong val

Returns¶

Bool val

lt¶
[Source]


else
(let errno: U32, let value: U32) = _OSSocket.get_so_error(fd)
(errno == 0) and (value == 0)
end

fun ref _apply_backpressure() =>
if not _throttled then
_throttled = true
_notify.throttled(this)
end
ifdef not windows then
_writeable = false

// this is safe because asio thread isn't currently subscribed
// for a write event so will not be writing to the readable flag
@pony_asio_event_set_writeable(_event, false)
@pony_asio_event_resubscribe_write(_event)
end

fun ref _release_backpressure() =>


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

Returns¶

USize val

peek¶
[Source]
Return the highest priority item in the heap. For max-heaps, the greatest
item will be returned. For min-heaps, the smallest item will be returned.
fun box peek()
: this->A ?


Public Functions¶
apply¶
[Source]
fun box apply()
: String val

Returns¶

String val

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

Parameters¶


I16 val

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

Parameters¶

y: A

Returns¶


[Source]
Maximum positive value representable.
new val max_value()
: F32 val^

Returns¶

F32 val^

min_normalised¶
[Source]
Minimum positive value representable at full precision (ie a normalised
number).
new val min_normalised()
: F32 val^

Returns¶

F32 val^


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


Complete the Property execution successfully.
fun ref complete()
: None val

Returns¶

None val

fail¶
[Source]
Complete the Property execution
while signalling failure to the PropertyResultNotify.
fun ref fail(
repr: String val,
rounds: USize val = 0,
err: Bool val = false)
: None val

Parameters¶


y: U8 val

Returns¶

U8 val

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

Returns¶

U8 val

eq¶
[Source]


Long tests allow for delayed completion. Any test can call long_test() on its
TestHelper to indicate that it needs to keep running. When the test is finally
complete it calls complete() on its TestHelper.
The complete() function takes a Bool parameter to specify whether the test was
a success. If any asserts fail then the test will be considered a failure
regardless of the value of this parameter. However, complete() must still be
called.
Since failing tests may hang, a timeout must be specified for each long test.
When the test function exits a timer is started with the specified timeout. If
this timer fires before complete() is called the test is marked as a failure
and the timeout is reported.
On a timeout the timed_out() function is called on the unit test object. This
should perform whatever test specific tidy up is required to allow the program
to exit. There is no need to call complete() if a timeout occurs, although it
is not an error to do so.
Note that the timeout is only relevant when a test hangs and would otherwise
prevent the test program from completing. Setting a very long timeout on tests
that should not be able to hang is perfectly acceptable and will not make the
test take any longer if successful.
Timeouts should not be used as the standard method of detecting if a test has


i8¶
fun box i8()
: I8 val

Returns¶

I8 val

i16¶
fun box i16()
: I16 val

Returns¶

I16 val


# Divide by Zero

What's 1 divided by 0? How about 10 divided by 0? What is the result you get in your favorite programming language?

In math, divide by zero is undefined. There is no answer to that question as the expression 1/0 has no meaning. In many programming languages, the answer is a runtime exception that the user has to handle. In Pony, things are a bit different.


U32 val

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

Parameters¶

y: U32 val

Returns¶

(U32 val , U32 val)

rem_unsafe¶
[Source]


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


new val create() =>
_root = _MapSubNodes[K, V, H]
_size = 0

new val _create(r: _MapSubNodes[K, V, H], s: USize) =>
_root = r
_size = s

fun val apply(k: K): val->V ? =>
"""
Attempt to get the value corresponding to k.
"""
_root(0, H.hash(k).u32(), k)? as V

fun val size(): USize =>
"""
Return the amount of key-value pairs in the Map.
"""
_size


fun sctp_cookie_echoed():I32 => @pony_os_sockopt_option(I32(582))
fun sctp_cookie_wait():I32 => @pony_os_sockopt_option(I32(583))
fun sctp_cwnd_logging_enable():I32 => @pony_os_sockopt_option(I32(584))
fun sctp_cwnd_monitor_enable():I32 => @pony_os_sockopt_option(I32(585))
fun sctp_cwr_in_same_window():I32 => @pony_os_sockopt_option(I32(586))
fun sctp_cwr_reduce_override():I32 => @pony_os_sockopt_option(I32(587))
fun sctp_data():I32 => @pony_os_sockopt_option(I32(588))
fun sctp_data_first_frag():I32 => @pony_os_sockopt_option(I32(589))
fun sctp_data_frag_mask():I32 => @pony_os_sockopt_option(I32(590))
fun sctp_data_last_frag():I32 => @pony_os_sockopt_option(I32(591))
fun sctp_data_middle_frag():I32 => @pony_os_sockopt_option(I32(592))
fun sctp_data_not_frag():I32 => @pony_os_sockopt_option(I32(593))
fun sctp_data_sack_immediately():I32 => @pony_os_sockopt_option(I32(594))
fun sctp_data_unordered():I32 => @pony_os_sockopt_option(I32(595))
fun sctp_default_prinfo():I32 => @pony_os_sockopt_option(I32(596))
fun sctp_default_send_param():I32 => @pony_os_sockopt_option(I32(597))
fun sctp_default_sndinfo():I32 => @pony_os_sockopt_option(I32(598))
fun sctp_delayed_sack():I32 => @pony_os_sockopt_option(I32(599))
fun sctp_del_vrf_id():I32 => @pony_os_sockopt_option(I32(600))
fun sctp_disable_fragments():I32 => @pony_os_sockopt_option(I32(601))


Returns¶

Bool val

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

Parameters¶

that: MaxHeapPriority[A] val

Returns¶

Bool val


932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951


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


fun box tcpi_opt_syn_data()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcpi_opt_toe¶
[Source]


fun box fstat()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

fstatfs¶
[Source]


value: val->A,
offset: USize val = 0,
nth: USize val = 0,
predicate: {(A, A): Bool}[A] val = lambda)
: USize val ?

Parameters¶

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

Returns¶

USize val ?

contains¶
[Source]


y: ULong val

Returns¶

ULong val

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

Parameters¶

y: ULong val

Returns¶


fun ipv6_2292hoplimit():I32 => @pony_os_sockopt_option(I32(102))
fun ipv6_2292hopopts():I32 => @pony_os_sockopt_option(I32(103))
fun ipv6_2292pktinfo():I32 => @pony_os_sockopt_option(I32(104))
fun ipv6_2292pktoptions():I32 => @pony_os_sockopt_option(I32(105))
fun ipv6_2292rthdr():I32 => @pony_os_sockopt_option(I32(106))
fun ipv6_addrform():I32 => @pony_os_sockopt_option(I32(107))
fun ipv6_addr_preferences():I32 => @pony_os_sockopt_option(I32(108))
fun ipv6_add_membership():I32 => @pony_os_sockopt_option(I32(109))
fun ipv6_authhdr():I32 => @pony_os_sockopt_option(I32(110))
fun ipv6_autoflowlabel():I32 => @pony_os_sockopt_option(I32(111))
fun ipv6_checksum():I32 => @pony_os_sockopt_option(I32(112))
fun ipv6_dontfrag():I32 => @pony_os_sockopt_option(I32(113))
fun ipv6_drop_membership():I32 => @pony_os_sockopt_option(I32(114))
fun ipv6_dstopts():I32 => @pony_os_sockopt_option(I32(115))
fun ipv6_flowinfo():I32 => @pony_os_sockopt_option(I32(116))
fun ipv6_flowinfo_flowlabel():I32 => @pony_os_sockopt_option(I32(117))
fun ipv6_flowinfo_priority():I32 => @pony_os_sockopt_option(I32(118))
fun ipv6_flowinfo_send():I32 => @pony_os_sockopt_option(I32(119))
fun ipv6_flowlabel_mgr():I32 => @pony_os_sockopt_option(I32(120))
fun ipv6_fl_a_get():I32 => @pony_os_sockopt_option(I32(121))


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

Parameters¶

that: FilePermissionDenied val

Returns¶

Bool val

ne¶
[Source]


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


# Example Program

The following is a complete program with multiple trivial benchmarks followed
by their output.

```pony
use "time"
use "pony_bench"

actor Main is BenchmarkList
new create(env: Env) =>
PonyBench(env, this)

fun tag benchmarks(bench: PonyBench) =>
bench(_Nothing)
bench(_Fib(5))
bench(_Fib(10))
bench(_Fib(20))
bench(_Timer(10_000))


: U64 val

Returns¶

U64 val

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

Returns¶

Bool val

u8¶
[Source]
fun ref u8()


fun box icmp_exc_ttl()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

icmp_frag_needed¶
[Source]


Bool val


Bool val

next¶
[Source]
fun ref next()
: U32 val ?

Returns¶

U32 val ?


fun box acl_check()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

acl_get¶
[Source]


divrem¶
fun box divrem(
y: F64 val)
: (F64 val , F64 val)

Parameters¶

y: F64 val

Returns¶

(F64 val , F64 val)

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


Package

PonyCheck is a library for property based testing
with tight integration into PonyTest.
Property Based Testing¶
In traditional unit testing, the developer specifies one or more input
examples manually for the class or system under test and asserts on certain
output conditions. The difficulty here is to find enough examples to cover
all branches and cases of the class or system under test.
In property based testing, the developer defines a property, a kind of predicate
for the class or system under test that should hold for all kinds or just a
subset of possible input values. The property based testing engine then
generates a big number of random input values and checks if the property holds


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


fun ref size(
rows: U16 val,
cols: U16 val)
: None val

Parameters¶

rows: U16 val
cols: U16 val

Returns¶

None val

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


that: PipeError val

Returns¶

Bool val

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

Parameters¶

that: PipeError val

Returns¶


let c =
try
shorts.shift()?
else
0  // TODO(cq) Should never error since checked
end
match _option_with_short(c)
| let os: OptionSpec =>
if os._requires_arg() and (shorts.size() > 0) then
// opt needs an arg, so consume the remainder of the shorts for targ
if targ is None then
targ = shorts.clone()
shorts.truncate(0)
else
return SyntaxError(_short_string(c), "ambiguous args for short option")
end
end
let arg = if shorts.size() == 0 then targ else None end
match _OptionParser.parse(os, arg, args)
| let o: Option => options.push(o)


Assert¶
[Source]
This is a debug only assertion. If the test is false, it will print any
supplied error message to stderr and raise an error.
primitive val Assert

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

Returns¶


if caps(FileLink) then
set(Cap.linkat())
set(Cap.symlinkat())
end

if caps(FileLookup) then set(Cap.lookup()) end
if caps(FileMkdir) then set(Cap.mkdirat()) end
if caps(FileRead) then set(Cap.read()) end
if caps(FileRemove) then set(Cap.unlinkat()) end
if caps(FileRename) then set(Cap.renameat()) end
if caps(FileSeek) then set(Cap.seek()) end

if caps(FileStat) then
set(Cap.fstat())
set(Cap.fstatfs())
set(Cap.fcntl())
end

if caps(FileSync) then set(Cap.fsync()) end


"""
"\x1B[44m"

fun magenta_bg(): String =>
"""
Magenta background.
"""
"\x1B[45m"

fun cyan_bg(): String =>
"""
Cyan background.
"""
"\x1B[46m"

fun grey_bg(): String =>
"""
Grey background.
"""
"\x1B[100m"


fun box ipproto_udplite()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_visa¶
[Source]


that: box->A

Returns¶

Bool val

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

Parameters¶

that: box->A

Returns¶


end
end

if outer_iterator.has_next() then
try
inner_iterator = outer_iterator.next()?
return has_next()
end
end

false

fun ref next(): A ? =>
if inner_iterator isnt None then
let iter = inner_iterator as Iterator[A]

if iter.has_next() then
return iter.next()?
end
end


Bool val

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

Parameters¶

y: I64 val

Returns¶

Bool val

lt¶
[Source]


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


new val create(
value: A)
: Real[A] val^

Parameters¶

value: A

Returns¶

Real[A] val^

from[B: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val) & Real[B] val)]¶
[Source]
new val from[B: ((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 |


HashSet[A: Any #share, H: HashFunction[A] val]¶
[Source]
A set, built on top of persistent Map. This is implemented as map of an
alias of a type to itself.
class val HashSet[A: Any #share, H: HashFunction[A] val] is
Comparable[HashSet[A, H] box] ref

Implements¶

Comparable[HashSet[A, H] box] ref

Constructors¶


Parameters¶

offset: ISize val = 0
base: U8 val = 0

Returns¶

(A , USize val) ?

f32¶
[Source]
Convert this string starting at the given offset
to a 32-bit floating point number (F32).
This method errors if this string cannot be parsed to a float,
if the result would over- or underflow,
the offset exceeds the size of this string or
there are leftover characters in the string after conversion.
Examples:
"1.5".f32()? == F32(1.5)


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


let message: (String val | None val)¶
[Source]

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

Returns¶

String iso^


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

Returns¶

U32 val

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

Parameters¶


class TermHandler is SignalNotify
let _custodian: Custodian

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

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

actor tag Custodian

Constructors¶
create¶
[Source]
new tag create()
: Custodian tag^

Returns¶


Bool val

expect_action¶
[Source]
Expect some action of the given name to complete
for the property to hold.
If all expected actions are completed successfully,
the property is considered successful.
If 1 action fails, the property is considered failing.
Call complete_action(name) or fail_action(name)
to mark some action as completed.
Example:
actor AsyncActor

let _ph: PropertyHelper

new create(ph: PropertyHelper) =>
_ph = ph


Bool val

printv¶
[Source]
Print an iterable collection of ByteSeqs.
fun ref printv(
data: ByteSeqIter box)
: Bool val

Parameters¶

data: ByteSeqIter box

Returns¶

Bool val


N

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

Parameters¶

n: N

Returns¶

N

int_unbiased[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]¶


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

Parameters¶

c: AsyncBenchContinue val

Returns¶

None val ?

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


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


from: USize val = 0,
to: USize val = call)
: None val

Parameters¶

from: USize val = 0
to: USize val = call

Returns¶

None val

trim¶
[Source]
Return a shared portion of this string, covering from until to.
Both the original and the new string are immutable, as they share memory.
The operation does not allocate a new string pointer nor copy elements.
fun val trim(


Example¶
Iter[I64]([1; 2].values())
.zip[I64]([3; 4].values())

(1, 3) (2, 4)
fun ref zip[B: B](
i2: Iterator[B] ref)
: Iter[(A , B)] ref^

Parameters¶

i2: Iterator[B] ref

Returns¶

Iter[(A , B)] ref^

zip2[B: B, C: C]¶
[Source]


fun box ip_flowtype()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_fw3¶
[Source]


None val

write_final¶
[Source]
Write as much as possible to the socket. Set _writeable to false if not
everything was written. On an error, close the connection. This is for data
that has already been transformed by the notifier. Data will be silently
discarded if the connection has not yet been established though.
fun ref write_final(
data: (String val | Array[U8 val] val))
: None val

Parameters¶

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

Returns¶

None val


452use "debug"
use "collections"

class val _Shrink is Equatable[_Round]
"""
An execution of a property during the shrinking process.
"""
let _round: USize

new val create(round': USize) =>
_round = round'

fun round(): USize => _round

fun inc(): _Round =>
_Shrink.create(this._round + 1)

fun eq(other: box->_Round): Bool =>
match other
| let s: _Shrink => s._round == this._round


592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611


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


# `PONYPATH`

When searching for Pony packages, `ponyc` checks both the installation directory (where the standard libraries reside) and any directories listed in the optional environment variable `PONYPATH`.


Note that the byte length of the generated string can be up to 4 times
the size in code points.
fun box unicode_bmp(
min: USize val = 0,
max: USize val = 100)
: Generator[String val] box

Parameters¶

min: USize val = 0
max: USize val = 100

Returns¶

Generator[String val] box

eq¶
[Source]
fun box eq(


host_eq¶
[Source]
fun box host_eq(
that: NetAddress box)
: Bool val

Parameters¶

that: NetAddress box

Returns¶

Bool val

length¶
[Source]
For platforms (OSX/FreeBSD) with length field as part of


ILong val

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

Parameters¶

y: ILong val

Returns¶

(ILong val , ILong val)

rem¶


# How to create objects with different capabilities

When you write a constructor, by default, that constructor will either create a new object with `ref` or `tag` as the capability. In the case of actors, the constructor will always create a `tag`. For classes, it defaults to `ref` but you can create with other capabilities. Let's take a look at an example:

```pony
class Foo
let x: U32

new val create(x': U32) =>
x = x'
```

Now when you call `Foo.create(1)`, you'll get a `Foo val` instead of `Foo ref`.
But what if you want to create both `val` and `ref` `Foo`s? You could do something like this:

```pony
class Foo
let x: U32

new val create_val(x': U32) =>


[Source]
fun box eq(
that: (Less val | Equal val | Greater val))
: Bool val

Parameters¶

that: (Less val | Equal val | Greater val)

Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: (Less val | Equal val | Greater val))
: Bool val


1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331


Constructors¶
from_u64¶
[Source]
Use seed x to seed a SplitMix64 and use this to
initialize the 128 bits of state.
new ref from_u64(
x: U64 val = 5489)
: XorOshiro128StarStar ref^

Parameters¶

x: U64 val = 5489

Returns¶

XorOshiro128StarStar ref^

create¶


actor Main
new create(env: Env) =>
let wb = Writer
let messages = [[(F32(3597.82), "Anderson"); (F32(-7979.3), "Graham")]
[(F32(3.14159), "Hopper"); (F32(-83.83), "Jones")]]
for items in messages.values() do
wb.i32_be((items.size() / 2).i32())
for (f, s) in items.values() do
wb.f32_be(f)
wb.i32_be(s.size().i32())
wb.write(s.array())
end
let wb_msg = Writer
wb_msg.i32_be(wb.size().i32())
wb_msg.writev(wb.done())
env.out.writev(wb_msg.done())
end
```
"""
var _chunks: Array[ByteSeq] iso = recover Array[ByteSeq] end


not ((b >= 'A') and (b <= 'Z')) and
not ((b >= 'a') and (b <= 'z')) then
error
end
end
nm

fun ref add_command(cmd: CommandSpec box) ? =>
"""
Adds an additional child command to this parent command.
"""
if is_leaf() then error end
_commands.update(cmd.name(), cmd)

fun ref add_help(hname: String = "help", descr': String = "") ? =>
"""
Adds a standard help option and, optionally command, to a root command.
"""
_help_name = hname
_help_info = descr'


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


(I8 val , I8 val) ?

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

Parameters¶

y: I8 val

Returns¶

I8 val ?

mod_partial¶
[Source]


Implements¶

Proxy ref

Constructors¶
create¶
[Source]
new iso create()
: NoProxy iso^

Returns¶

NoProxy iso^

Public Functions¶
apply¶
[Source]


U16 val ?

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

Parameters¶

y: U16 val

Returns¶

U16 val ?

div_partial¶
[Source]


 Format package

The Format package provides support for formatting strings. It can be
used to set things like width, padding and alignment, as well as
controlling the way numbers are displayed (decimal, octal,
hexadecimal).


that: OSSockOpt val

Returns¶

Bool val


Iteration using `While` is more flexible as it allows to continue iterating if a call to `next()` errors.
The `For`-loop does not allow this.


`after_iteration` methods respectively that run before/after each iteration.
"""
fun name(): String
fun config(): BenchConfig => BenchConfig
fun overhead(): MicroBenchmark^ => OverheadBenchmark
fun ref before() ? => None
fun ref before_iteration() ? => None
fun ref apply() ?
fun ref after() ? => None
fun ref after_iteration() ? => None

trait iso AsyncMicroBenchmark
"""
Asynchronous benchmarks must provide this trait. The `apply` method defines a
single iteration in a sample. Each phase of the sample completes when the
given `AsyncBenchContinue` has its `complete` method invoked. Setup and
Teardown are defined by the `before` and `after` methods respectively. The
`before` method runs before a sample of benchmarks and `after` runs after
the all iterations in the sample have completed. If your benchmark requires
setup and/or teardown to occur beween each iteration of the benchmark, then


fun box subc(
y: U128 val)
: (U128 val , Bool val)

Parameters¶

y: U128 val

Returns¶

(U128 val , Bool val)

mulc¶
[Source]
fun box mulc(
y: U128 val)
: (U128 val , Bool val)

Parameters¶


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

Returns¶

String iso^

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

Parameters¶

y: ILong val

Returns¶


Returns¶

Bool val

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

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

Parameters¶

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


Timer¶
[Source]
The Timer class represents a timer that fires after an expiration
time, and then fires at an interval. When a Timer fires, it calls
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:
use "time"

actor Main
new create(env: Env) =>


new val create() =>
_map = HashMap[A, A, H]

new val _create(map': HashMap[A, A, H]) =>
_map = map'

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

fun apply(value: val->A): val->A ? =>
"""
Return the value if it is in the set, otherwise raise an error.
"""
_map(value)?

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


# Primitive literals

When an anonymous type has no fields and no behaviours (like, for example, an object literal declared as a lambda literal), the compiler generates it as an anonymous primitive, unless a non-`val` reference capability is explicitly given. This means no memory allocation is needed to generate an instance of that type.

In other words, in Pony, a lambda that doesn't close over anything has no memory allocation overhead. Nice.

A primitive literal is always returned as a `val`.


# Control Structures

To do real work in a program you have to be able to make decisions, iterate through collections of items and perform actions repeatedly. For this, you need control structures. Pony has control structures that will be familiar to programmers who have used most languages, such as `if`, `while` and `for`, but in Pony, they work slightly differently.


fun box scm_hci_raw_direction()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

scm_timestamping¶
[Source]


Bool val


var z: U64 = _x
z = (z xor (z >> 30)) * U64(0xbf58476d1ce4e5b9)
z = (z xor (z >> 27)) * U64(0x94d049bb133111eb)
z xor (z >> 31)


492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511


fun tag _init(typ': _ValueType, default': (_Value | None))
: (_ValueType, _Value, Bool)
=>
match default'
| None => (typ', false, true)
| let d: _Value => (typ', d, false)
end

new val bool(
name': String,
descr': String = "",
default': (Bool | None) = None)
=>
"""
Creates an Arg with a Bool typed value that can be used like
`<cmd> true`
to yield an arg value like
`cmd.arg("opt").bool() == true`.
"""


Swap foreground and background colour.
fun box reverse(
state: Bool val = true)
: String val

Parameters¶

state: Bool val = true

Returns¶

String val

black¶
[Source]
Black text.
fun box black()
: String val


class iso _I8AddTest is UnitTest
fun name(): String => "_I8AddTest"
fun label(): String => "simple"
fun apply(h: TestHelper) =>
h.assert_eq[I8](1, 1)

Setting up and tearing down a test environment¶
Set Up¶
Any kind of fixture or environment necessary for executing a UnitTest
can be set up either in the tests constructor or in a function called set_up().
set_up() is called before the test is executed. It is partial,
if it errors, the test is not executed but reported as failing during set up.
The test's TestHelper is handed to set_up()
in order to log messages or access the tests Env via TestHelper.env.
Tear Down¶
Each unit test object may define a tear_down() function. This is called after
the test has finished to allow tearing down of any complex environment that had
to be set up for the test.
The tear_down() function is called for each test regardless of whether it


## Considerations


I32 val

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

Parameters¶

y: I32 val

Returns¶

I32 val

op_or¶
[Source]


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

Parameters¶

y: USize val

Returns¶

USize val ?

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

Parameters¶


len: USize val = 0)
: String ref^

Parameters¶

len: USize val = 0

Returns¶

String ref^

from_array¶
[Source]
Create a string from an array, reusing the underlying data pointer.
new val from_array(
data: Array[U8 val] val)
: String val^

Parameters¶


fun chown(uid: U32, gid: U32): Bool =>
"""
Set the owner and group for a path. Does nothing on Windows.
"""
ifdef windows then
false
else
if caps(FileChown) then
0 == @chown(path.cstring(), uid, gid)
else
false
end
end

fun touch(): Bool =>
"""
Set the last access and modification times of a path to now.
"""
set_time(Time.now(), Time.now())


fun box sctp_log_rwnd_enable()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_log_try_advance¶
[Source]


iov.len = data.size()
@writev(1, iov, 1) // Will print "Hello from Pony!"
```

As you saw, a `IOVec` instance in Pony is equivalent to `struct iovec*`. In some cases, like the above example, it can be cumbersome to define a `struct` type in Pony if you only want to use it in a single place. You can also use a pointer to a tuple type as a shorthand for a struct: let's rework the above example:

```pony
use @writev[USize](fd: U32, iov: Pointer[(Pointer[U8] tag, USize)] tag, iovcnt: I32)

let data = "Hello from Pony!"
var iov = (data.cpointer(), data.size())
@writev(1, addressof iov, 1) // Will print "Hello from Pony!"
```

In the example above, the type `Pointer[(Pointer[U8] tag, USize)] tag` is equivalent to the `IOVec` struct type we defined earlier. That is, _a struct type is equivalent to a pointer to a tuple type with the fields of the struct as elements, in the same order as the original struct type defined them_.

**Can I pass struct types by value, instead of passing a pointer?** Not at the moment. This is a known limitation of the current FFI system, but it is something the Pony team is interested in fixing.


fun ref next()
: (K , V) ?

Returns¶

(K , V) ?


Parameters¶

gen1': Generator[T1] val
gen2': Generator[T2] val
gen3': Generator[T3] val
h: TestHelper val

Returns¶

ForAll3[T1, T2, T3] ref^

Public Functions¶
apply¶
[Source]
fun ref apply(
prop: {(T1, T2, T3, PropertyHelper) ?}[T1, T2, T3] val)
: None val ?


None val


recover MyTCPConnectionNotify(env.out) end, "", "8989")

Note: when writing to the connection data will be silently discarded if the
connection has not yet been established.
Backpressure support¶
Write¶
The TCP protocol has built-in backpressure support. This is generally
experienced as the outgoing write buffer becoming full and being unable
to write all requested data to the socket. In TCPConnection, this is
hidden from the programmer. When this occurs, TCPConnection will buffer
the extra data until such time as it is able to be sent. Left unchecked,
this could result in uncontrolled queuing. To address this,
TCPConnectionNotify implements two methods throttled and unthrottled
that are called when backpressure is applied and released.
Upon receiving a throttled notification, your application has two choices
on how to handle it. One is to inform the Pony runtime that it can no
longer make progress and that runtime backpressure should be applied to
any actors sending this one messages. For example, you might construct your
application like:
// Here we have a TCPConnectionNotify that upon construction


default': (String val | None val) = reference

Returns¶

OptionSpec val^

i64¶
[Source]
Creates an Option with an I64 typed value that can be used like
--count=42 -C=42
to yield an option value like
cmd.option("count").i64() == I64(42).
new val i64(
name': String val,
descr': String val = "",
short': (U8 val | None val) = reference,
default': (I64 val | None val) = reference)
: OptionSpec val^


Parameters¶

auth: AmbientAuth val

Returns¶

DeserialiseAuth val^

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

Parameters¶

that: DeserialiseAuth val


: I64 val

Returns¶

I64 val

millis¶
[Source]
Monotonic unadjusted milliseconds.
fun box millis()
: U64 val

Returns¶

U64 val

micros¶
[Source]


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


else
@"llvm.ctlz.i64"(this.u64(), false).usize()
end

fun ctz(): USize =>
ifdef ilp32 then
@"llvm.cttz.i32"(this.u32(), false).usize()
else
@"llvm.cttz.i64"(this.u64(), false).usize()
end

fun clz_unsafe(): USize =>
"""
Unsafe operation.
If this is 0, the result is undefined.
"""
ifdef ilp32 then
@"llvm.ctlz.i32"(this.u32(), true).usize()
else
@"llvm.ctlz.i64"(this.u64(), true).usize()


end
end

fun ref _dispose() =>
"""
Dispose of the AsioEventID.
"""
if not _event.is_null() then
@pony_asio_event_unsubscribe(_event)
_event = AsioEvent.none()
_notify.dispose()
end


652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671


@__cap_rights_clear(addressof _r0, cap, U64(0))
end

fun limit(fd: I32): Bool =>
"""
Limits the fd to the encoded rights.
"""
ifdef freebsd or "capsicum" then
@cap_rights_limit(fd, addressof _r0) == 0
else
true
end

fun ref merge(that: CapRights0) =>
"""
Merge the rights in that into this.
"""
ifdef freebsd or "capsicum" then
@cap_rights_merge(addressof _r0, addressof that._r0)
end


U8 val

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

Returns¶

U16 val

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

Returns¶


var in_list = false

match _list
| let list': List[A] =>
in_list = that._list isnt None
that.remove()

match _prev
| let  prev': ListNode[A] =>
prev'._next = that
else
list'._set_head(that)
end

that._list = list'
that._prev = _prev
that._next = this
_prev = that
list'._increment()
end


: I16 val

Returns¶

I16 val

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

Returns¶

I32 val

i64¶
[Source]
fun ref i64()


fun frequency[T](
weighted_generators: ReadSeq[WeightedGenerator[T]])
: Generator[T]
=>
"""
Choose a value of one of the given Generators,
while controlling the distribution with the associated weights.

The weights are of type `USize` and control how likely a value is chosen.
The likelihood of a value `v` to be chosen
is `weight_v` / `weights_sum`.
If all `weighted_generators` have equal size the distribution
will be uniform.

Example of a generator to output odd `U8` values
twice as likely as even ones:

```pony
Generators.frequency[U8]([
(1, Generators.u8().filter({(u) => (u, (u % 2) == 0 }))


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


collect[optional B: Seq[A!] ref]¶
[Source]
Push each value from the iterator into the collection coll.
Example¶
Iter[I64]([1; 2; 3].values())
.collect(Array[I64](3))

[1, 2, 3]
fun ref collect[optional B: Seq[A!] ref](
coll: B)
: B^

Parameters¶

coll: B

Returns¶

B^