Перейти к содержимому
Топаз6.0 · До релиза
Загрузка →

Поиск в документации

Спецификация 6.0

Выберите результат стрелками и нажмите Enter, чтобы открыть его.

Введите имя API, номер диагностики, правило или тему проекта.

    Библиотека · std.bytes

    Bytes.get

    Reads an optional byte at an index.

    get(index: int) -> Option<int>
    Модуль
    std.bytes →
    Получатель
    Bytes
    Минимальное число аргументов
    1
    Максимальное число аргументов
    1

    Declaration and parameters

    Ссылка

    Доступность

    Включено по умолчанию · Не определено

    Import std.bytes in language mode 5.21.

    The current compiler selects std/bytes.tpz for this language mode. Availability in other released editions and inclusion in each installed distribution are Pending.

    Получатель

    Bytes

    Ограничения параметров

    A Bytes value is an immutable ordered sequence of octets. Each octet is an int from 0 through 255.

    Bytes.empty returns the empty sequence. Bytes.fromArray accepts an Array<int> and returns an independent snapshot in Ok.

    Bytes.fromArray returns Err with a string identifying the first element outside 0 through 255. It does not wrap, clamp, or return a partial sequence.

    Bytes.toArray returns a new Array<int> in byte order. Mutating that array or the original input array does not change an existing Bytes value.

    Bytes.concat returns the receiver bytes followed by the argument bytes. Either input may be empty and both inputs retain their contents.

    Bytes.get uses a zero-based byte index. It returns Some(byte) within the sequence and None() for every negative or past-end index.

    Bytes.length is the number of bytes and is read as a property. Compare it with zero to test emptiness.

    Receivers and supplied arguments evaluate once from left to right before the operation begins. These operations perform no I/O or text normalization.

    A correctly typed lookup or concatenation has no data-dependent Result failure. Allocation exhaustion is an operational failure and is not a decoded data error.

    Результат

    The declared result type is Option<int>.

    Эффекты

    Ошибки

    Result and effects

    Ссылка

    Read a zero-based byte index as Some(byte). Negative and past-end indices return None().

    Resolved contracts

    Ссылка

    Related entries

    Ссылка

    std.bytes →

    Construct and inspect immutable byte sequences

    Ссылка
    Правилоtopaz.stdlib.contract.bytes-values.rule

    Construct and inspect immutable byte sequences

    A Bytes value is an immutable ordered sequence of octets. Each octet is an int from 0 through 255.

    Bytes.empty returns the empty sequence. Bytes.fromArray accepts an Array<int> and returns an independent snapshot in Ok.

    Bytes.fromArray returns Err with a string identifying the first element outside 0 through 255. It does not wrap, clamp, or return a partial sequence.

    Bytes.toArray returns a new Array<int> in byte order. Mutating that array or the original input array does not change an existing Bytes value.

    Bytes.concat returns the receiver bytes followed by the argument bytes. Either input may be empty and both inputs retain their contents.

    Bytes.get uses a zero-based byte index. It returns Some(byte) within the sequence and None() for every negative or past-end index.

    Bytes.length is the number of bytes and is read as a property. Compare it with zero to test emptiness.

    Receivers and supplied arguments evaluate once from left to right before the operation begins. These operations perform no I/O or text normalization.

    A correctly typed lookup or concatenation has no data-dependent Result failure. Allocation exhaustion is an operational failure and is not a decoded data error.

    Причина

    Exact octets keep binary payloads independent of text encoding. Snapshot conversion prevents later array edits from silently changing a payload.

    Preserve empty values and byte order

    Ссылка
    main.tpzPreserve empty values and byte orderОткрыть песочницу →
    1. import std.bytes { Bytes }
    2. import std.io
    3. import std.test
    4. let empty = test.assertOk(Bytes.fromArray([]))
    5. let value = test.assertOk(Bytes.fromArray([0, 128, 255]))
    6. io.writeLine(Bytes.empty().toHex())
    7. io.writeLine(empty.concat(value).toHex())
    8. io.writeLine(value.concat(test.assertOk(Bytes.fromArray([1]))).toHex())
    Ожидаемый выводКод завершения 0
    
    0080ff
    0080ff01
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 0080ff
    2. 0080ff01

    Reject out-of-range array elements

    Ссылка
    main.tpzReject out-of-range array elementsОткрыть песочницу →
    1. import std.bytes { Bytes }
    2. import std.io
    3. for values in ([[0, -1, 255], [0, 256, 255]]) {
    4. match (Bytes.fromArray(values)) {
    5. case Err(_) => io.writeLine("invalid byte")
    6. case Ok(_) => io.writeLine("accepted")
    7. }
    8. }
    Ожидаемый выводКод завершения 0
    invalid byte
    invalid byte
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. invalid byte
    2. invalid byte

    Read optional bytes at both boundaries

    Ссылка
    main.tpzRead optional bytes at both boundariesОткрыть песочницу →
    1. import std.bytes { Bytes }
    2. import std.io
    3. import std.test
    4. let value = test.assertOk(Bytes.fromArray([0, 128, 255]))
    5. for index in ([-1, 0, 2, 3]) {
    6. match (value.get(index)) {
    7. case Some(byte) => io.writeLine("{byte}")
    8. case None() => io.writeLine("absent")
    9. }
    10. }
    Ожидаемый выводКод завершения 0
    absent
    0
    255
    absent
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. absent
    2. 0
    3. 255
    4. absent

    Keep array edits independent from bytes

    Ссылка
    main.tpzKeep array edits independent from bytesОткрыть песочницу →
    1. import std.bytes { Bytes }
    2. import std.io
    3. import std.test
    4. let mut input = [0, 255]
    5. let value = test.assertOk(Bytes.fromArray(input))
    6. let mut output = value.toArray()
    7. input[0] = 7
    8. output[1] = 8
    9. io.writeLine(value.toHex())
    10. io.writeLine("{input[0]},{output[1]}")
    Ожидаемый выводКод завершения 0
    00ff
    7,8
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 00ff
    2. 7,8

    Evaluate the receiver before its argument

    Ссылка
    main.tpzEvaluate the receiver before its argumentОткрыть песочницу →
    1. import std.bytes { Bytes }
    2. import std.io
    3. function receiver() -> Bytes {
    4. io.writeLine("receiver")
    5. return "a".encodeUtf8()
    6. }
    7. function argument() -> Bytes {
    8. io.writeLine("argument")
    9. return "b".encodeUtf8()
    10. }
    11. io.writeLine(receiver().concat(argument()).toHex())
    Ожидаемый выводКод завершения 0
    receiver
    argument
    6162
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. receiver
    2. argument
    3. 6162

    Меню

    Загрузка →