Module: PerfectLib
class Bytes
A Bytes object represents an array of UInt8 and provides various utilities for importing and exporting values into and out of that array.
The object maintains a position marker which is used to denote the position from which new export operations proceed.
An export will advance the position by the appropriate amount.
var position = 0
The position from which new export operations begin.
var data: [UInt8]
The underlying UInt8 array
var availableExportBytes: Int { return self.data.count - self.position }
Indicates the number of bytes which may be successfully exported
func init()
Create an empty Bytes object
func init(existingBytes: [UInt8])
Initialize with existing bytes
func import8Bits(from frm: UInt8) -> Bytes
Imports one UInt8 value appending it to the end of the array
- returns: The Bytes object
func import16Bits(from frm: UInt16) -> Bytes
Imports one UInt16 value appending it to the end of the array
- returns: The Bytes object
func import32Bits(from frm: UInt32) -> Bytes
Imports one UInt32 value appending it to the end of the array
- returns: The Bytes object
func import64Bits(from frm: UInt64) -> Bytes
Imports one UInt64 value appending it to the end of the array
- returns: The Bytes object
func importBytes(from frm: [UInt8]) -> Bytes
Imports an array of UInt8 values appending them to the end of the array
- returns: The Bytes object
func importBytes(from frm: Bytes) -> Bytes
Imports the array values of the given Bytes appending them to the end of the array
- returns: The Bytes object
func importBytes(from frm: ArraySlice<UInt8>) -> Bytes
Imports an `ArraySlice` of UInt8 values appending them to the end of the array
- returns: The Bytes object
func export8Bits() -> UInt8
Exports one UInt8 from the current position. Advances the position marker by 1 byte.
- returns: The UInt8 value
func export16Bits() -> UInt16
Exports one UInt16 from the current position. Advances the position marker by 2 bytes.
- returns: The UInt16 value
func export32Bits() -> UInt32
Exports one UInt32 from the current position. Advances the position marker by 4 bytes.
- returns: The UInt32 value
func export64Bits() -> UInt64
Exports one UInt64 from the current position. Advances the position marker by 8 bytes.
- returns: The UInt64 value
func exportBytes(count cnt: Int) -> [UInt8]
Exports the indicated number of bytes
struct Dir
This class represents a directory on the file system.
It can be used for creating & inspecting directories and enumerating directory contents.
typealias typealias PermissionMode = File.PermissionMode
A typealias for directory permission modes.
func init(_ path: String)
Create a new Dir object with the given path
var exists: Bool
Returns true if the directory exists
func setAsWorkingDir() throws
Set this Dir as the process' working directory.
static var workingDir: Dir
Return the process' current working directory.
func create(perms: PermissionMode = [.rwxUser, .rxGroup, .rxOther]) throws
Creates the directory using the provided permissions. All directories along the path will be created if need be.
- parameter perms: The permissions for use for the new directory and preceeding directories which need to be created. Defaults to RWX-GUO
- throws: `PerfectError.FileError`
func delete() throws
Deletes the directory. The directory must be empty in order to be successfuly deleted.
- throws: `PerfectError.FileError`
var name: String
Returns the name of the directory.
var parentDir: Dir?
Returns a Dir object representing the current Dir's parent. Returns nil if there is no parent.
var path: String
Returns the path to the current directory.
var perms: PermissionMode
Returns the UNIX style permissions for the directory.
func forEachEntry(closure: (String) throws -> ()) throws
Enumerates the contents of the directory passing the name of each contained element to the provided callback.
- parameter closure: The callback which will receive each entry's name
- throws: `PerfectError.FileError`
class File
Provides access to a file on the local file system
var fd = -1
The underlying file system descriptor.
var exists: Bool
Checks that the file exists on the file system
- returns: True if the file exists or false otherwise
var isOpen: Bool
Returns true if the file has been opened
var realPath: String
Returns the file path. If the file is a symbolic link, the link will be resolved.
var modificationTime: Int
Returns the modification date for the file in the standard UNIX format of seconds since 1970/01/01 00:00:00 GMT
- returns: The date as Int
func init(_ path: String, fd: Int32 = -1)
Create a file object given a path and open mode
- parameter path: Path to the file which will be accessed
- parameter fd: The file descriptor, if any, for an already opened file
func close()
Closes the file if it had been opened
func abandon()
Resets the internal file descriptor, leaving the file opened if it had been.
extension File
enum OpenMode
The open mode for the file.
case read
Opens the file for read-only access.
case write
Opens the file for write-only access, creating the file if it did not exist.
case readWrite
Opens the file for read-write access, creating the file if it did not exist.
case append
Opens the file for read-write access, creating the file if it did not exist and moving the file marker to the end.
case truncate
Opens the file for read-write access, creating the file if it did not exist and setting the file's size to zero.
func open(_ mode: OpenMode = .read, permissions: PermissionMode = .rwUserGroup) throws
Opens the file using the given mode.
- throws: `PerfectError.FileError`
extension File
var marker: Int
The current file read/write position.
extension File
func delete()
Closes and deletes the file
func moveTo(path: String, overWrite: Bool = false) throws -> File
Moves the file to the new location, optionally overwriting any existing file
- parameter path: The path to move the file to
- parameter overWrite: Indicates that any existing file at the destination path should first be deleted
- returns: Returns a new file object representing the new location
- throws: `PerfectError.FileError`
func copyTo(path pth: String, overWrite: Bool = false) throws -> File
Copies the file to the new location, optionally overwriting any existing file
- parameter path: The path to copy the file to
- parameter overWrite: Indicates that any existing file at the destination path should first be deleted
- returns: Returns a new file object representing the new location
- throws: `PerfectError.FileError`
extension File
var size: Int
Returns the size of the file in bytes
var isDir: Bool
Returns true if the file is actually a directory
var perms: PermissionMode
Returns the UNIX style permissions for the file
extension File
func readSomeBytes(count: Int) throws -> [UInt8]
Reads up to the indicated number of bytes from the file
- parameter count: The maximum number of bytes to read
- returns: The bytes read as an array of UInt8. May have a count of zero.
- throws: `PerfectError.FileError`
func readString() throws -> String
Reads the entire file as a string
extension File
func write(string: String) throws -> Int
Writes the string to the file using UTF-8 encoding
- parameter s: The string to write
- returns: Returns the number of bytes which were written
- throws: `PerfectError.FileError`
func write(bytes: [UInt8], dataPosition: Int = 0, length: Int = Int.max) throws -> Int
Write the indicated bytes to the file
- parameter bytes: The array of UInt8 to write.
- parameter dataPosition: The offset within `bytes` at which to begin writing.
- parameter length: The number of bytes to write.
- throws: `PerfectError.FileError`
extension File
func lock(byteCount: Int) throws
Attempts to place an advisory lock starting from the current position marker up to the indicated byte count. This function will block the current thread until the lock can be performed.
- parameter byteCount: The number of bytes to lock
- throws: `PerfectError.FileError`
func unlock(byteCount: Int) throws
Unlocks the number of bytes starting from the current position marker up to the indicated byte count.
- parameter byteCount: The number of bytes to unlock
- throws: `PerfectError.FileError`
func tryLock(byteCount: Int) throws
Attempts to place an advisory lock starting from the current position marker up to the indicated byte count. This function will throw an exception if the file is already locked, but will not block the current thread.
- parameter byteCount: The number of bytes to lock
- throws: `PerfectError.FileError`
func testLock(byteCount: Int) throws -> Bool
Tests if the indicated bytes are locked
- parameter byteCount: The number of bytes to test
- returns: True if the file is locked
- throws: `PerfectError.FileError`
class TemporaryFile: File
A temporary, randomly named file.
func convenience init(withPrefix: String)
Create a temporary file, usually in the system's /tmp/ directory
- parameter withPrefix: The prefix for the temporary file's name. Random characters will be appended to the file's eventual name.
global var fileStdin: File
This file can be used to write to standard in
global var fileStdout: File
This file can be used to write to standard out
global var fileStderr: File
This file can be used to write to standard error
class JSONDecoding
This non-instantiable object serves as an access point to a registry for JSONConvertibleObjects
A JSONConvertibleObject is a custom class or struct which can be converted to and from JSON.
typealias typealias JSONConvertibleObjectCreator = () -> JSONConvertibleObject
Function which returns a new instance of a custom object which will have its members set based on the JSON data.
static var objectIdentifierKey = "_jsonobjid"
The key used in JSON data to indicate the type of custom object which was converted.
static func public func createJSONConvertibleObject(values:[String:Any]) -> JSONConvertibleObject?
Instantiate a custom object based on the JSON data.
The system will use the `JSONDecoding.objectIdentifierKey` key to locate the custom object creator.
static func public func createJSONConvertibleObject(name: String, values:[String:Any]) -> JSONConvertibleObject?
Instantiate a custom object based on the JSON data.
The system will use the `name` parameter to locate the custom object creator.
protocol JSONConvertible
Protocol for an object which can be converted into JSON text.
func jsonEncodedString() throws -> String
Returns the JSON encoded String for any JSONConvertible type.
enum JSONConversionError: Error
An error occurring during JSON conversion.
case notConvertible(Any?)
The object did not suppport JSON conversion.
case invalidKey(Any)
A provided key was not a String.
case syntaxError
The JSON text contained a syntax error.
struct JSONConvertibleNull: JSONConvertible
This is a stand-in for a JSON null.
May be produced when decoding.
func jsonEncodedString() throws -> String
This is a stand-in for a JSON null.
May be produced when decoding.
extension String
func jsonDecode() throws -> JSONConvertible
Decode the object represented by the JSON text.
enum PerfectError : Error
Some but not all of the exception types which may be thrown by the system
case networkError(Int32, String)
A network related error code and message.
case fileError(Int32, String)
A file system related error code and message.
case systemError(Int32, String)
A OS level error code and message.
case apiError(String)
An API exception error message.
struct PerfectServer
Provides access to various system level features for the process.
A static instance of this class is created at startup and all access to this object go through the `PerfectServer.staticPerfectServer` static property.
static func func switchTo(userName unam: String) throws
Switch the current process to run with the permissions of the indicated user
class SysProcess
This class permits an external process to be launched given a set of command line arguments and environment variables.
The standard in, out and err file streams are made available. The process can be terminated or permitted to be run to completion.
var stdin: File?
The standard in file stream.
var stdout: File?
The standard out file stream.
var stderr: File?
The standard err file stream.
var pid = pid_t(-1)
The process identifier.
func init(_ cmd: String, args: [String]?, env: [(String,String)]?) throws
Initialize the object and launch the process.
- parameter cmd: The path to the process which will be launched.
- parameter args: An optional array of String arguments which will be given to the process.
- parameter env: An optional array of environment variable name and value pairs.
- throws: `PerfectError.SystemError`
func isOpen() -> Bool
Returns true if the process was opened and was running at some point.
Note that the process may not be currently running. Use `wait(false)` to check if the process is currently running.
func close()
Terminate the process and clean up.
func detach()
Detach from the process such that it will not be manually terminated when this object is deinitialized.
func wait(hang: Bool = true) throws -> Int32
Determine if the process has completed running and retrieve its result code.
func kill(signal: Int32 = SIGTERM) throws -> Int32
Terminate the process and return its result code.
struct GenerateFromPointer<T> : IteratorProtocol
This class permits an UnsafeMutablePointer to be used as a GeneratorType
func init(from: UnsafeMutablePointer<T>, count: Int)
Initialize given an UnsafeMutablePointer and the number of elements pointed to.
func mutating public func next() -> Element?
Return the next element or nil if the sequence has been exhausted.
struct UTF8Encoding
Utility wrapper permitting a UTF-8 character generator to encode a String. Also permits a String to be converted into a UTF-8 byte array.
extension String
var stringByEncodingHTML: String
Returns the String with all special HTML characters encoded.
var stringByEncodingURL: String
Returns the String with all special URL characters encoded.
var stringByDecodingURL: String?
Decode the % encoded characters in a URL and return result
var decodeHex: [UInt8]?
Decode a hex string into resulting byte array
extension String
func parseAuthentication() -> [String:String]
Parse an HTTP Digest authentication header returning a Dictionary containing each part.
func getNow() -> Double
Returns the current time according to ICU
ICU dates are the number of milliseconds since the reference date of Thu, 01-Jan-1970 00:00:00 GMT
func icuDateToSeconds(_ icuDate: Double) -> Int
Converts the milliseconds based ICU date to seconds since the epoch
func secondsToICUDate(_ seconds: Int) -> Double
Converts the seconds since the epoch into the milliseconds based ICU date
func formatDate(_ date: Double, format: String, timezone inTimezone: String? = nil, locale inLocale: String? = nil) throws -> String
Format a date value according to the indicated format string and return a date string.
- parameter date: The date value
- parameter format: The format by which the date will be formatted. Use a valid strftime style format string.
- parameter timezone: The optional timezone in which the date is expected to be based. Default is the local timezone.
- parameter locale: The optional locale which will be used when parsing the date. Default is the current global locale.
- returns: The resulting date string
- throws: `PerfectError.systemError`
extension UnicodeScalar
func isWhiteSpace() -> Bool
Returns true if the UnicodeScalar is a white space character
func isDigit() -> Bool
Returns true if the UnicodeScalar is a digit character
func isAlphaNum() -> Bool
Returns true if the UnicodeScalar is an alpha-numeric character
func isHexDigit() -> Bool
Returns true if the UnicodeScalar is a hexadecimal character