[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3. Bigloo Common Library

3.1 Introduction  
3.2 regex  internationalized basic and extended regular expression matching
3.3 The GNU DBM interface  
3.4 MzScheme compatibility module  MzScheme compatibility procedures
3.5 Dynamic linking library  Dynamic link support
3.6 SRFI-1 List Library  
3.7 SRFI-13 String Library  
3.8 Miscellaneous stuff  assorted stuff
3.11 cgen - bigloo preprocessor  bigloo preprocessor
3.9 iconv - charset conversion procedures  charset conversion procedures
3.10 Time-related procedures  times and dates
3.12 Advanced afile utility  advanced afile utility
3.13 Command-line applications support  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.1 Introduction

The bigloo-common library is a set of miscellaneous types and procedures. Some other bigloo-lib's libraries rely on it. This library includes:

At the moment, the stuff was selected based only on my own practical needs in course of working on some Web-related projects. By this reason, the library is not (and probably never will be) completed.

Also, though a few Bigloo procedures are re-implemented in this library, in no case this library replaces the Bigloo runtime library.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2 regex

This section describes the regex module, which provides an interface to C runtime regex functions.

The regex module is optional, i.e. you can disable its compilation by using --without-regexp flag for configure. Also note that configure script can detect that regexps are broken on your system and disable this feature.

To help you detect whether you have regexps while in interpreter, the 'regexp symbol is defined through the register-eval-srfi! construct, so you may test it with cond-expand. For example, the common library test script conditionally includes the regexp-test call:

 
(cond-expand (regexp (regexp-test))
	     (else (print "regexps are disabled by configure")))


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.1 Regexp Matching

The procedures described here, are intended for end-user applications. They are compatible to those provided by MzScheme.

procedure: regexp rexp-or-string #!optional flags::regcomp-flags => regexp

If a regex object was passed as the rexp-or-string argument, just return it.

If a string was passed as the rexp-or-string argument, allocates a new regexp object and compiles rexp-or-string into regular expression object with regcomp, passing the optional flags arguments along. Signals an error if something went wrong during the compilation.

It is an error if the rexp-or-string was neither regexp nor string.

Simple regexp example:

 
(regexp "q") => #<foreign:REGEXP:21490>
(regexp "(") error--> "( ) or \( \) imbalance -- ("

Simple vs. case insensitive match example:

 
(define rexp(regexp "qwerty"))
(regexp-match rexp "QWERTY")
=> #f

(define rexp(regexp "qwerty" 'icase))
(regexp-match rexp "QWERTY")
=> (QWERTY)

Basic vs. Extended regexp match example:

 
(define rexp(regexp "a|b" 'basic))
(regexp-match rexp "a|b")
=> ("a|b")

(define rexp(regexp "a|b")) ;; 'extended flag set by default
(regexp-match rexp "a|b")
=> ("a")

Using of nosub flag example:

 
(define rexp(regexp "qwerty" 'nosub))
(regexp-match rexp "qwerty")
=> ()

procedure: regexp-match rexp-or-string str::bstring #!optional offset::int eflags::regexec-flags => #f or pair

Return #f if string str does not match pattern. Otherwise return the list object. Unless the nosub flag was given, the list has at least one element, the whole match substring found. The rest elements are partial sub-matches. The pattern argument must be either regexp or scheme string. In later case pattern is compiled into temporary regexp object, which is automatically released.

Example:

 
(regexp-match "q" "asdf")
=> #f
(regexp-match "q" "qwerty")
=> (q)
(regexp-match "([a-z]+)([0-9]+)" "qwerty1234")
=> (qwerty1234 qwerty 1234)

The optional argument offset allows to skip first offset characters from the beginning of matched string, for example:

 
(regexp-match "[a-z]+" "qwerty")  ;; offset=0
=> (qwerty)
(regexp-match "[a-z]+" "qwerty" 2)
=> (erty)

The optional eflag arguments may be any of the following symbols :

notbol
The match-beginning-of-line operator always fails to match (but see the compilation flag newline above). This flag may be used when different portions of a string are passed to regexp-match and the beginning of the string should not be interpreted as the beginning of the line.

noteol
The match-end-of-line operator always fails to match (but see the compilation flag newline above)

 
(define rexp(regexp "^qwerty"))
(regexp-match rexp "qwerty")  ;; BOL matches as usual
=> ("qwerty")

(regexp-match-positions rexp "qwerty" 0 'notbol)
=> #f                  ;; BOL match suppressed

procedure: regexp-match-positions pattern rexp-or-string str::bstring #!optional offset::int => #f or pair

Same as regexp-match, but returns the matched substrings position inside the source string instead of substrings itself, for example:

 
(regexp-match-positions "q" "asdf")
=> #f
(regexp-match-positions "q" "qwerty")
=> ((0 . 1))
(regexp-match-positions "([a-z]+)([0-9]+)" "qwerty1234")
=> ((0 . 10) (0 . 6) (6 . 10))

regexp-match-positions does not imply copying of strings, thus it is extremely useful when applyed to long strings.

procedure: regexp-replace* pattern src::bstring insert::bstring => bstring

Return copy of src string where all occurrences of pattern are replaces by insert string.

 
(regexp-replace* "[a-z]" "1a2b3c" " Letter ")
=> "1 Letter 2 Letter 3 Letter "

Note: no context replacements are currently implemented. For example:

 
(regexp-replace* "[a-z]" "1a2b3c" " Letter &")
=> "Letter &2 Letter &3 Letter &"

but not "1 Letter a2 Letter b3 Letter c", as one may expect.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.2 C runtime API

Procedures described here are direct interfaces to corresponding C runtime calls. You woudn't want to use them in end-user applications.

procedure: regcomp preg::regexp rexp-or-string #!optional flags::regcomp-flags => regcomp-error

Compile pattern string into previously allocated preg regexp structure. Once compiled, the regexp object may be reused multiple time.

The optional flags arguments may be any of the following symbols in any sequence (see regcomp manual page) :

basic
Use POSIX Basic Regular Expression syntax when interpreting regex. If not set, POSIX Extended Regular Expression syntax is used. See manual page regex(7) for details.

icase
Do not differentiate case. Subsequent regexec searches using this pattern buffer will be case insensitive (2).

nosub
Support for substring addressing of matches is not required. The list resulted from successful match will be always empty. Use it if you only want to know whether the match was found.

newline
Match-any-character operators don't match a newline.

A non-matching list ([^...]) not containing a newline does not match a newline.

Match-beginning-of-line operator (^) matches the empty string immediately after a newline, regardless of whether the flags argument of regexp-match or regexp-match, contains notbol.

Match-end-of-line operator ($) matches the empty string immediately before a newline, regardless of whether the flags argument of regexp-match or regexp-match contains noteol.

procedure: regerror errorid::regcomp-error rexp::regexp => bstring

Given the error code, returned by regcomp or regexec, return the error description.

 
(regerror 'erange (regexp " "))
=> "invalid endpoint in range"

procedure: regfree rexp::regexp => #unspecified

Free the memory allocated to the rexp by the regcomp.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.3 The GNU DBM interface

As stated in GNU dbm documentation:

GNU dbm (gdbm)is a library of database functions that use extendible hashing and works similar to the standard UNIX dbm functions. These routines are provided to a programmer needing to create and manipulate a hashed database.

The basic use of gdbm is to store key/data pairs in a data file. Each key must be unique and each key is paired with only one data item. The keys can not be directly accessed in sorted order.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.3.1 Opening and closing the database

procedure: gdbm-open filename::string #!optional flags::pair-nil #!key block-size::int mode::int onerror::procedure => gdbm-file

The procedure gdbm-open opens or creates gdbm database file filename.

The parameters are:

filename
The name of the file to open.

#!optional flag::pair-nil
If flags includes the reader symbol only, the user wants to just read the database and any call to gdbm-store or gdbm-delete will fail. Many readers can access the database at the same time. If flags includes the writer symbol, the user wants both read and write access to the database and requires exclusive access. If flags includes the wrcreat, the user wants both read and write access to the database and if the database does not exist, create a new one. If flags includes the newdb, the user want a new database created, regardless of whether one existed, and wants read and write access to the new database. The following may also be added to the flags: the sync symbol, which causes all database operations to be synchronized to the disk, and the nolock symbol, which prevents the library from performing any locking on the database file.

#!key block-size
It is used during initialization to determine the size of various constructs. It is the size of a single transfer from disk to memory. This parameter is ignored if the file has been previously initialized. The minimum size is 512. If the value is omitted or less than 512, the file system blocksize is used, otherwise the value of block-size is used.

#!key mode
File mode (see chmod(2) and open(2) man pages) if the file is created).

#!key onerror
A procedure for gdbm to call if it detects a fatal error. The only parameter of this function is a string.

This feature is is not implemented yet.

The return value is the object needed by all other functions to access that gdbm file.

For example:
 
(let((conn(gdbm-open "test.db")))
  ...
  (gdbm-close conn))

procedure: gdbm-close gdbm::gdbm-file

The procedure gdbm-close closes the gdbm file and frees all memory associated with it. It also updates the reader/writer count on the file.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.3.2 Storing and fetching data

procedure: gdbm-store gdbm::gdbm-file key::bstring value::bstring #!optional replace?

The procedure gdbm-store inserts or replaces records in the database.

The key argument is the key data in a form of Bigloo string object. The value argument holds the data to be associated with the key.

If the replace? argument is not given, then if any data was already associated with the key, no action is performed, and the procedure returns #t.

If the replace? argument evaluates to scheme true value, the old data associated with the key, if any, is always replaced by the new one.

For example:
 
;; Create a new GDBM storage file named `test.db'
(define gdbm (gdbm-open "test.db" '(wrcreat)))

;; store the key "key" associated with the "value" string. The false
;; return value means no data was previously associated with the word
;; "key"
(gdbm-store gdbm "key" "value")
=> #f

;; Try to store a new value for same key, no replacement is
;; allowed. The true return value means no action was taken since data
;; is already associated with this key
(gdbm-store gdbm "key" "newvalue")
=> #t

;; This assures no replacement occured
(gdbm-fetch gdbm "key")
=> "value"

;; Replace the value in a database. Note the optional `replace?'
;; argument is now #t
(gdbm-store gdbm "key" "newvalue" #t)

;; Check the replacement was successfull
(gdbm-fetch gdbm "key")
=> "newvalue"
=>

procedure: gdbm-delete gdbm::gdbm-file key::bstring => bool

Delete the record associated with the key if any. Return #f if the record wasn't found, #t otherwise.

For example:
 
(gdbm-store gdbm "newkey" "newvalue")

(gdbm-delete gdbm "newkey")
=> #f

(gdbm-delete gdbm "newkey")
=> #t

procedure: gdbm-fetch gdbm::gdbm-file key::bstring

Look up the data associated with the key. Return the data string found or #f if the key wasn't found in a database.

procedure: gdbm-exists gdbm::gdbm-file key::bstring

Unlike the gdbm-fetch procedure, this procedure does not retrieve any data, and simply returns true of false, depending on whether the key exists, or not.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.3.3 Enumerating database entries

procedure: gdbm-firstkey gdbm::gdbm-file
procedure: gdbm-nextkey gdbm::gdbm-file key::bstring

Enumerate database records.

Example: print all database records.

 
(let loop ((key(gdbm-firstkey gdbm)))
  (when key
	(print key " -> "(gdbm-fetch gdbm key))
	(loop (gdbm-nextkey gdbm key))))


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.3.4 Miscellanea

procedure: gdbm-reorganize gdbm::gdbm-file

Try to shrink the database after multiple deletions were done. See GDBM documentation for details.

procedure: gdbm-sync gdbm::gdbm-file

The procedure gdbm-sync assures all data flushed to the disk. Instead you may use the sync flag when opening the database with gdbm-open.

procedure: gdbm-setopt gdbm::gdbm-file option::gdbm-setopt-flags value
conn option value

The procedure gdbm-setopt sets certain options on an already open database. The valid options are:

cachesize
Set the size of the internal bucket cache. This option may only be set once on each gdbm descriptor, and is set automatically to 100 upon the first access to the database.

fastmode
Set fast mode to either on or off. This allows fast mode to be toggled on an already open and active database.

syncmode
Turn on or off file system synchronization operations.

centfree
Set central free block pool to either on or off. The default is off, which is how previous versions of Gdbm handled free blocks. If set, this option causes all subsequent free blocks to be placed in the global pool, allowing (in theory) more file space to be reused more quickly.

coalesceblks
Set free block merging to either on or off. The default is off, which is how previous versions of Gdbm handled free blocks. If set, this option causes adjacent free blocks to be merged. This can become a CPU expensive process with time, though, especially if used in conjunction with centfree.

Example: force a database to use a cache of 10, after opening it with gdbm-open.

 
(gdbm-setopt gdbm 'cachesize 10)

procedure: gdbm-fdesc gdbm::gdbm-file => int

The procedure gdbm-fdesc returns the file descriptor of the database.

procedure: gdbm-version => string

The procedure gdbm-version returns the underlying GDBM library version description.

For example:
 
(gdbm-version)
=> This is GDBM version 1.8.0, as of May 19, 1999.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.4 MzScheme compatibility module

This section describes the mzcompat module, which provides a few procedures to facilitate reuse of code written for MzScheme.

The mzcompat module is optional, its compilation is disabled by default. To enable it, call configure with --with-compat switch.

To detect whether you have mzcompat module enabled when in interpreter, test 'mzscheme-compat symbol with cond-expand. For example:

 
(cond-expand (mzscheme-compat (mzscheme-test))
	     (else (print "MzScheme compatibility is disabled by configure")))

macro: case-lambda patterns

The analog of match-lambda construct. Differs from match-lambda in that the execution flow only depends on number of arguments, but not on their types.

Example:
 
(define print-args
  (case-lambda
   (()
    (print "no args was given"))
   ((a)
    (print "only one argument was given: " a))
   (args
    (print (length args) " arguments were given"))))

(print-args)
-| no args was given
(print-args 'one)
-| only one argument was given: ONE
(print-args 'one 'two 'three)
-| 3 arguments were given

inline procedure: load-relative-extension fname::bstring

Means nothing in bigloo-lib.

procedure: make-parameter value #!optional filter => procedure

Creates a closure, which being called without arguments returns the value value, being called with one argument arg, sets the variable value to arg. If filter procedure is provided, the new value is passed to that procedure, and the value returned by filter is stored in value variable.

Example:

 
(define my-value (make-parameter 0))
=> #<procedure:400edad0.-1>
(my-value)
=> 0
(my-value 1)
(my-value)
=> 1

The following procedure always converts its argument to string before remembering it:

 
(define my-string-value
  (make-parameter
   ""
   (lambda(o)
     (cond((string? o)
	   o)
	  ((number? o)
	   (number->string o))
	  (else(error "my-string-value" "invalid argument"o))))))

(my-string-value 1)
(pp(my-string-value))
-| #"1"

In MzScheme parameters have their own types and are scoped to execution threads. Since Bigloo does not provide multi-threading, bigloo-lib parameters eare implemented as ordinary scheme procedures.

inline procedure: directory-exists? path::bstring => #unspecified

Aliases Bigloo directory? procedure

procedure: make-directory path::bstring #!optional mask::int

Create the new directory path with access mask mask. The default value of mask is #o0777.

procedure: current-directory #!optional newdir

Get or set the application process current directory.

 
(current-directory)
=> /usr/local/bin

(current-directory "/home/wowa")
=> #unspecified

(current-directory)
=> /home/wowa

procedure: build-path dir::bstring chunks => #unspecified

Construct a directory name from chunks. Each chunk may be the path by itself, i.e. include the slash character. Chunk should not start with slash character, i.e. all sub-paths must be relative.

Example:

 
(build-path "/a/b/c" "d/e/f" "y")
=> "/a/b/c/d/e/f/y"

(build-path "/a/b/c" "/d/e/f" "y")
error--> absolute paths should not be appended: /d/e/f


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.5 Dynamic linking library

This section describes the dl module, which provides an interface to libdl.so system library.

With the use of this module, you can load shared objects dynamically and retrieve values of the symbols registered in that objects.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.5.1 Types

foreign: dl

An open shared object handle as returned by dlopen

foreign: dlsym

A symbol object as returned by dlsym.

enum: dlopen-flags

A set of possible values for the mode argument of dlopen procedure.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.5.2 Procedures

procedure: dlopen #!optional (path "") #!rest dlopen-flags => dl

The procedure dlopen loads a dynamic library from the file path and returns an opaque "handle" for the dynamic library. The dlopen-flags argument is a list of flags. Each flag must be one of the following scheme symbols: lazy, now or global. See the dlopen man page for the meaning of these arguments.

procedure: dlsym handle::dl name::string => dlsym

TBD


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.6 SRFI-1 List Library

TBD


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.7 SRFI-13 String Library

Bigloo-lib provides a limited support for string-lib, the SRFI-13 string library. The limitations are as follows:

The rest of this chapter is based mostly on original SRFI document, copyrighted by Olin Shivers.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.7.1 Procedure specifications

In the following procedure specifications:

Passing values to procedures with these parameters that do not satisfy these types is an error.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.7.2 Predicates

procedure: string-null? s::bstring => bool

Is s the empty string?

 
(string-null? "")
=> #t

procedure: string-every pred::procedure s::string #!optional start end

Checks to see if predicate pred is true of every character in S, proceeding from left (index start) to right (index end).

If STRING-EVERY returns true, the returned true value is the one produced by the final application of pred to S[end]. If STRING-EVERY is applied to an empty sequence of characters, it simply returns #t.

procedure: string-any pred::procedure s::string #!optional start end

Checks to see if predicate pred is true of any character in S, proceeding from left (index start) to right (index end).

If string-any returns true, the returned true value is the one produced by the application of pred.

 
(string-every values "qwerty")
=>


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.7.3 Constructors

procedure: string-tabulate proc::procedure len::int => bstring
proc is an integer->char procedure. Construct a string of size len by applying proc to each index to produce the corresponding string element. The order in which proc is applied to the indices is not specified.

Example:
 
(string-tabulate (lambda(i)(integer->char(+fx i 32))) 20)
=> " !\"#$%&'()*+,-./0123"


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.7.4 List & string conversion

procedure: string->list s::bstring #!optional start end => pair-nil

string->list returns a newly allocated list of the characters that make up the given string. list->string returns a newly allocated string formed from the characters in the list char-list, which must be a list of characters. string->list and list->string are inverses so far as equal? is concerned.

string->list is extended from the R5RS definition to take optional start/end arguments.

 
(string->list "asdf")
=> (#\a #\s #\d #\f)

procedure: reverse-list->string char-list::pair-nil => bstring

An efficient implementation of (compose string->list reverse):

 
(reverse-list->string '(#\a #\B #\c))
=> "cBa"

This is a common idiom in the epilog of string-processing loops that accumulate an answer in a reverse-order list. (See also reverse-string-concatenate for the "chunked" variant.)

procedure: string-join string-list::pair-nil #!optional delimiter grammar => bstring

This procedure is a simple unparser - it pastes strings together using the delimiter string.

The grammar argument is a symbol that determines how the delimiter is used, and defaults to 'infix.

The delimiter is the string used to delimit elements; it defaults to a single space " ".

Example:

 
(join-strings '("foo" "bar" "baz") ":")         => "foo:bar:baz"
(join-strings '("foo" "bar" "baz") ":" 'suffix) => "foo:bar:baz:"

;; Infix grammar is ambiguous wrt empty list vs. empty string,
(join-strings '()   ":") => ""
(join-strings '("") ":") => ""

;; but suffix & prefix grammars are not.
(join-strings '()   ":" 'suffix) => ""
(join-strings '("") ":" 'suffix) => ":"


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.7.5 Selection

procedure: string-copy s::bstring #!optional start end => bstring

string-copy is extended from its R5RS definition by the addition of its optional start/end parameters. In contrast to SUBSTRING/SHARED, it is guaranteed to produce a freshly-allocated string.

Use string-copy when you want to indicate explicitly in your code that you wish to allocate new storage; use SUBSTRING/SHARED when you don't care if you get a fresh copy or share storage with the original string.

Example:
 
(string-copy "Beta substitution") => "Beta substitution"
(string-copy "Beta substitution" 1 10) 
=> "eta subst"
(string-copy "Beta substitution" 5) => "substitution"

procedure: substring/shared s::bstring #!optional start end => bstring

substring/shared returns a string whose contents are the characters of s beginning with index start (inclusive) and ending with index end (exclusive). It differs from the R5RS substring in two ways:

Example:
 
(let((s "Beta substitution"))
  (eq?(substring/shared s 0)s))
=> #t

procedure: string-copy! target::bstring tstart s #!optional start end => bstring

Copy the sequence of characters from index range (start,end) in string s to string target, beginning at index tstart. The characters are copied left-to-right or right-to-left as needed -- the copy is guaranteed to work, even if target and s are the same string.

It is an error if the copy operation runs off the end of the target string, e.g.

 
(string-copy! (string-copy "Microsoft") 0
"Regional Microsoft Operating Companies") error-->

Note: though the result of string-copy! is defined as unspecified by SRFI document, the implementation always returns the target argument.

Example:
 
(string-copy! "qwerty" 2 "asdf")
=> "qwasdf"

procedure: string-take s::bstring nchars::int => bstring

string-take returns the first ncharsof s;

If this procedure produces the entire string, it may return either s or a copy of s; in some implementations, proper substrings may share memory with s.

Example:
 
(string-take "Pete Szilagyi" 6) => "Pete S"

It is an error to take more characters than are in the string:
 
(string-take "foo" 37) error-->

inline procedure: string-drop s::bstring nchars::int => bstring

string-drop returns all but the first ncharsof s.

If this procedure produces the entire string, it may return either s or a copy of s; in some implementations, proper substrings may share memory with s.

Example:
 
(string-drop "Pete Szilagyi" 6) => "zilagyi"

It is an error to drop more characters than are in the string:
 
(string-drop "foo" 37) error-->

procedure: string-take-right s::bstring nchars::int => bstring

string-take-right returns the last ncharsof s.

If this procedure produces the entire string, it may return either s or a copy of s; in some implementations, proper substrings may share memory with s.

Example:
 
(string-take-right "Beta rules" 5) => "rules"
It is an error to take more characters than are in the string:
 
(string-take-right "foo" 37) error-->

procedure: string-drop-right s::bstring nchars::int => bstring

string-drop-right returns all but the last ncharsof s.

If this procedure produces the entire string, it may return either s or a copy of s; in some implementations, proper substrings may share memory with s.

Example:
 
(string-drop-right "Beta rules" 5) => "Beta "
It is an error to drop more characters than are in the string:
 
(string-drop-right "foo" 37) error-->

procedure: string-pad s::bstring len::int #!optional char start end => bstring

Build a string of length len comprised of s padded on the left by as many occurrences of the character char as needed. If s has more than len chars, it is truncated on the left to length len. char defaults to #\space.

If len <= end - start, the returned value is allowed to share storage with s, or be exactly s (if len = end - start).

Example:
 
(string-pad     "325" 5) => "  325"
(string-pad   "71325" 5) => "71325"
(string-pad "8871325" 5) => "71325"

procedure: string-pad-right s::bstring len::int #!optional char start end => bstring

Build a string of length len comprised of s padded on the right by as many occurrences of the character char as needed. If s has more than len chars, it is truncated on the right to length len. char defaults to #\space.

If len <= end - start, the returned value is allowed to share storage with s, or be exactly s (if len = end - start).

Example:
 
(string-pad-right     "325" 5) => "325  "
(string-pad-right   "71325" 5) => "71325"
(string-pad-right "8871325" 5) => "88713"

procedure: string-trim s::bstring #!optional char/char-set/pred start end => bstring

The string-trim, string-trim-right, string-trim-both procedures trim s by skipping over all characters on the left / on the right / on both sides that satisfy the second parameter char/char-set/pred:

char/char/set-pred defaults to the character set char-set:whitespace defined in SRFI-14.

If no trimming occurs, these functions return s.

Example:
 
(string-trim #"  The outlook wasn't brilliant,  \n\r")
=> #"The outlook wasn't brilliant,  \n\r"

procedure: string-trim-right s::bstring #!optional char/char-set/pred start end => bstring

See description of string-trim.

Example:
 
(string-trim-right #"  The outlook wasn't brilliant,  \n\r")
=> #"  The outlook wasn't brilliant,"

procedure: string-trim-both s::bstring #!optional char/char-set/pred start end => bstring

See description of string-trim.

Example:
 
(string-trim-both #"  The outlook wasn't brilliant,  \n\r")
=> #"The outlook wasn't brilliant,"


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.7.6 Modification

procedure: string-fill! s::bstring char::char #!optional start end

Stores char in every element of s and returns (in this implementation only) the s string.

string-fill! is extended from the R5RS definition to take optional start/end arguments.

Example:
 
(let((s "12345678"))
  (string-fill! s #\space 2 4)
  s)
=> "12  5678"


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.7.7 Comparison

These procedures are the lexicographic extensions to strings of the corresponding orderings on characters. For example, STRING< is the lexicographic ordering on strings induced by the ordering CHAR<? on characters. If two strings differ in length but are the same up to the length of the shorter string, the shorter string is considered to be lexicographically less than the longer string.

The optional start/end indices restrict the comparison to the indicated substrings of s1 and s2.

string-ci=, string-ci<>, string-ci<, string-ci>, string-ci<= and string-ci>= procedures are case-insensitive variants of string=, string<>, string<, string>, string<= and string>= correspondingly.

Comparison is simply done on individual code-points of the string. True text collation is not handled by this SRFI.

Case-insensitive comparison is done by case-folding characters with the operation (char-downcase (char-upcase c))

procedure: string= s1::bstring s2::bstring #!optional start1 end1 start2 end2 => bool

Test strings for equality. See notes at the beginning of this section.

procedure: string<> s1::bstring s2::bstring #!optional start1 end1 start2 end2 => bool

Test strings for inequality. See notes at the beginning of this section.

procedure: string< s1::bstring s2::bstring #!optional start1 end1 start2 end2 => bool

Test if s1 string is less than s2 string. See notes at the beginning of this section.

procedure: string> s1::bstring s2::bstring #!optional start1 end1 start2 end2 => bool

Test if s1 string is greater than s2 string. See notes at the beginning of this section.

procedure: string<= s1::bstring s2::bstring #!optional start1 end1 start2 end2 => bool

Test if s1 string is less than or equal to s2 string. See notes at the beginning of this section.

procedure: string>= s1::bstring s2::bstring #!optional start1 end1 start2 end2 => bool

Test if s1 string is greater than or equal to s2 string. See notes at the beginning of this section.

procedure: string-ci= s1::bstring s2::bstring #!optional start1 end1 start2 end2 => bool

Test strings for equality case-insensitive. See notes at the beginning of this section.

procedure: string-ci<> s1::bstring s2::bstring #!optional start1 end1 start2 end2 => bool

Test strings for inequality case-insensitive. See notes at the beginning of this section.

procedure: string-ci< s1::bstring s2::bstring #!optional start1 end1 start2 end2 => bool

Test if s1 string is less than s2 string case-insensitive. See notes at the beginning of this section.

procedure: string-ci> s1::bstring s2::bstring #!optional start1 end1 start2 end2 => bool

Test if s1 string is greater than s2 string case-insensitive. See notes at the beginning of this section.

procedure: string-ci<= s1::bstring s2::bstring #!optional start1 end1 start2 end2 => bool

Test if s1 string is less than or equal to s2 string case-insensitive. See notes at the beginning of this section.

procedure: string-ci>= s1::bstring s2::bstring #!optional start1 end1 start2 end2 => bool

Test if s1 string is greater than or equal to s2 string case-insensitive. See notes at the beginning of this section.

procedure: string-hash s::bstring #!optional bound start end => int

Compute a hash value for the string s. bound is either #f or a non-negative exact integer. If an integer, it gives the target range of the hash function -- the returned value will be in the range [0,bound].

If bound is either #f or not given, the implementation may use an implementation-specific default value, which might be chosen, for instance, to map all strings into the range of integers that can be efficiently represented.

The optional start/end indices restrict the hash operation to the indicated substring of s.

Invariants: (<= 0 (string-hash s b) (- b 1))

 
(string=    s1 s2)  =>  (= (string-hash s1 b)    (string-hash s2 b))

procedure: string-hash-ci s::bstring #!optional bound start end => int

string-hash-ci is the case-insensitive variant of string-hash.

Invariants: (<= 0 (string-hash-ci s b) (- b 1))

 
(string-ci= s1 s2)  =>  (= (string-hash-ci s1 b) (string-hash-ci s2 b))


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.7.8 Prefixes & suffixes

procedure: string-prefix-length s1::bstring s2::bstring #!optional start1 end1 start2 end2 => int

Return the length of the longest common prefix of the two strings. This is equivalent to the "mismatch index" for the strings (modulo the starti index offsets).

The optional start/end indices restrict the comparison to the indicated substrings of s1 and s2.

Example:
 
(string-prefix-length "qwertyasdf" "qwertypoiuy")
=> 6

procedure: string-suffix-length s1::bstring s2::bstring #!optional start1 end1 start2 end2 => int

Return the length of the longest common suffix of the two strings. This is equivalent to the "mismatch index" for the strings (modulo the starti index offsets).

The optional start/end indices restrict the comparison to the indicated substrings of s1 and s2.

Example:
 
(string-prefix-length "asdfqwerty" "poiuqwerty")
=> 6

procedure: string-prefix-length-ci s1::bstring s2::bstring #!optional start1 end1 start2 end2 => int

Case-insensitive variant of string-prefix-length.

procedure: string-suffix-length-ci s1::bstring s2::bstring #!optional start1 end1 start2 end2 => int

Case-insensitive variant of string-suffix-length.

procedure: string-prefix? s1::bstring s2::bstring #!optional start1 end1 start2 end2 => int

Is s1 a prefix of s2?

Example:
 
(string-prefix? "qwerty" "qwertyasdf"
=> #t

procedure: string-suffix? s1::bstring s2::bstring #!optional start1 end1 start2 end2 => int

Is s1 a suffix of s2?

Example:
 
(string-prefix? "qwerty" "asdfqwerty"
=> #t

procedure: string-prefix-ci? s1::bstring s2::bstring #!optional start1 end1 start2 end2 => int

Case-insensitive variant of string-prefix?.

procedure: string-suffix-ci? s1::bstring s2::bstring #!optional start1 end1 start2 end2 => int

Case-insensitive variant of string-suffix?.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.7.9 Searching

procedure: string-index s::bstring char/char-set/pred #!optional start end => int or #f

string-index searches through the string from the left, returning the index of the first occurrence of a character which

If no match is found, the functions return #f.

The start and end parameters specify the beginning and end indices of the search; the search includes the start index, but not the end index. The first index considered is end-1.

procedure: string-index-right s::bstring char/char-set/pred #!optional start end => int or #f

string-index-right searches through the string from the right, returning the index of the first occurrence of a character which

If no match is found, the functions return #f.

The start and end parameters specify the beginning and end indices of the search; the search includes the start index, but not the end index. The first index considered is start.

procedure: string-skip s::bstring char/char-set/pred #!optional start end => int or #f

The string-skip functions is similar to string-index, but uses the complement of the criteria: is searches for the first char that *doesn't* satisfy the test. E.g., to skip over initial whitespace, say

 
(cond ((string-skip s char-set:whitespace) =>
  (lambda (i)
    ;; (string-ref s i) is not whitespace.
    ...)))

procedure: string-skip-right s::bstring char/char-set/pred #!optional start end => int or #f

The string-skip-right functions is similar to string-index-right, but uses the complement of the criteria: is searches for the first char that *doesn't* satisfy the test.

procedure: string-count s char/char-set/pred #!optional start end

TBD

procedure: string-contains s1::bstring s2::bstring #!optional start1 end1 start2 end2

TBD

procedure: string-contains-ci s1 s2 #!optional start1 end1 start2 end2

TBD

procedure: string-titlecase s #!optional start end

TBD

procedure: string-titlecase! s #!optional start end

TBD

procedure: string-upcase s #!optional start end => bstring

TBD

procedure: string-upcase! s #!optional start end

TBD

procedure: string-downcase s #!optional start end => bstring

TBD

procedure: string-downcase! s #!optional start end

TBD

procedure: string-reverse s #!optional start end => bstring

TBD

procedure: string-reverse! s #!optional start end

TBD

procedure: string-concatenate string-list::pair-nil => bstring

TBD

procedure: string-concatenate/shared string-list::pair-nil => bstring

TBD

procedure: string-append/shared string-list => bstring

TBD

procedure: reverse-string-concatenate string-list #!optional final-string end => bstring

TBD

procedure: reverse-string-concatenate/shared string-list #!optional final-string end => bstring

TBD

procedure: string-map proc s #!optional start end => bstring

TBD

procedure: string-map! proc s #!optional start end

TBD

procedure: string-fold kons knil s #!optional start end

TBD

procedure: string-fold-right kons knil s #!optional start end

TBD

procedure: string-unfold p f g seed #!optional base make-final => bstring

TBD

procedure: string-unfold-right p f g seed #!optional base make-final => bstring

TBD

procedure: string-for-each proc s #!optional start end

TBD

procedure: xsubstring s from #!optional to start end => bstring

TBD

procedure: string-xcopy! target tstart s sfrom #!optional sto start end

TBD

procedure: string-replace s1 s2 #!optional start1 end1 start2 end2 => bstring

TBD

procedure: string-tokenize s #!optional token-set start end => pair-nil

TBD

procedure: string-filter s char/char-set/pred #!optional start end => bstring

TBD

procedure: string-delete s char/char-set/pred #!optional start end => bstring

TBD

procedure: string-parse-start+end proc s args

TBD

procedure: string-parse-final-start+end proc s args

TBD

procedure: check-substring-spec proc s start end

TBD

procedure: substring-spec-ok? s start end => bool

TBD

procedure: make-kmp-restart-vector c= s #!optional start end => vector

TBD

procedure: kmp-step pat rv c= c i

TBD

procedure: string-search-kmp pat rv c= i s #!optional start end => int

TBD


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.8 Miscellaneous stuff

procedure: environ => pair-nil

Obtain the current environment as a list of name/value pairs. For example:

 
(pp(environ))
-| ((#"_" . #"/usr/local/bin/bigloo-common")
 (#"CONFIG_SITE" . #"/home/wowa/.autoconf")
 (#"HOME" . #"/home/wowa")
 (#"TERM" . #"emacs")
 (#"OSTYPE" . #"solaris2.7")
...

Probably you'll need this procedure for debugging only. Use getenv and setenv Bigloo procedures instead.

procedure: setenv name::string value::string

The setenv procedure makes the value of the environment variable name equal to value by altering an existing variable or creating a new one.

procedure: unsetenv name::string

The unsetenv procedure function deletes the variable name from the environment.

procedure: errno #!optional new-value => int

Return the value of libc errno variable. If the new-value parameter is present, set the value of errno to new-value.

 
(errno) => 0
;; try an illegal operation
(open "nonexistentfile")
-| *** ERROR:bigloo:open:
file opening error -- nonexistentfile

;; read error code and reset errno
(errno 0) => 2

procedure: mmap length #!key fd prot flags offset
=> bstring

The mmap procedure asks to map length bytes starting at offset offset from the file (or other object) specified by fd into memory.

length::int
The number of bytes to map. Since the mmap result is returned in form of Bigloo bstring, the length really passed to libc mmap() includes the bstring object overhead too.

#!key fd
Descriptor of file to map. Since the result always includes the overhead of bstring object, this mmap implementation is practical useless if you want to map anything but dummy devices such a /dev/zero.

If fd argument is omitted, the /dev/zero device is used to get a file descriptor.

#!key prot
List of protection flag symbols. The valid values are:

exec
Pages may be executed.
read
Pages may be read.
write
Pages may be written.
none
Pages may not be accessed.

#!key flags
List of mmap options. The valid values are fixed, shared and private. The values denywrite, executable and anonymous are also valid but have no effect on systems other than Linux. See the mmap manual pages for details.

#!key offset
Byte offset from beginning of file to be mapped.

This procedure may be useful if you want to temporary allocate the huge amount of memory which should be released and returned to operating system. Besides, the memory allocated with mmap is not accessed until you really use it, so the allocation is very fast.

In the following example we will illustrate this feature. First we measure how much memory the application process consumes, using the ps command:

 
bash$ ps u 17012
USER       PID %CPU %MEM   VSZ  RSS TTY      STAT START   TIME COM
wowa     17012  2.1  5.7  7108 2236 ttyp4    S    20:32   0:00 /us

Then we mmap 16M of memory:

 
(define mem (mmap #x1000000))

As we may expect the process virtual memory increases now by 16M:
 
USER       PID %CPU %MEM   VSZ  RSS TTY      STAT START   TIME COM
wowa     17012  0.1  5.8 23496 2260 ttyp4    S    20:32   0:00 /us

Now we do the unmap:

 
(munmap mem)

And measure the process memory again:

 
USER       PID %CPU %MEM   VSZ  RSS TTY      STAT START   TIME COM
wowa     17012  0.0  5.7  7108 2252 ttyp4    S    20:32   0:00 /us

procedure: munmap mem::bstring

Release memory mapped by mmap.

procedure: stat what => stat

Return information about the specified file. The argument what should be either the name of the file or open file descriptor.

The result is of type stat, for which the following read accessor procedures are defined:

stat-mode
file protection mode flag list. See below.
stat-uid
User ID of the file's owner
stat-gid
Group ID of the file's group
stat-size
File size in bytes
stat-atime::double
Time of last access
stat-mtime::double
Time of last data modification
stat-ctime::double
Time of last file status change

The meaning of abovementioned stat-mode flag list is as follows:

fsock => file is a socket
flnk => file is a symbolic link
freg => file is a regular file
fblk => file is a block device
fdir => file is a directory
fchr => file is a character device
fifo => file is a fifo
suid => file has the UID bit set
sgid => file has the GID bit set
svtx => file has the sticky bit set
rusr => file owner has read permission
wusr => file owner has write permission
xusr => file owner has execute permission
rgrp => file group has read permission
wgrp => file group has write permission
xgrp => file group has execute permission
roth => file others have read permission
woth => file others have write permisson
xoth => file others have execute permission

 
(let((st(stat "/etc/passwd"))
     (pt(lambda(seconds)(strftime(localtime seconds)))))
  (print "User ID:         " (stat-uid st))
  (print "Group ID:        " (stat-gid st))
  (print "Size:            " (stat-size st))
  (print "Flags:           " (stat-mode st))
  (print "Accessed:        " (pt(stat-atime st)))
  (print "Data modified:   " (pt(stat-mtime st)))
  (print "Status modified: " (pt(stat-ctime st))))
-| User ID:         0
-| Group ID:        0
-| Size:            2110
-| Flags:           (roth rgrp wusr rusr freg)
-| Accessed:        10/01/01 18:54:05
-| Data modified:   09/21/01 17:21:52
-| Status modified: 09/21/01 17:21:52

procedure: isatty fd::int => bool

Test for a terminal device. Argument what should be open file descriptor. Example:

 
(isatty(open "/dev/tty"))
=> #t
(isatty(open "/etc/passwd"))
=> #f

procedure: open file-name::string . oflag => int

Open file name file-name, return the integer file descriptor.

The optional oflag arguments may be any of the following symbols: rdonly, wronly, rdwr, append, nonblock, creat, trunc, excl or noctty. See open(2) manual page for the meaning of the flag values.

Example:

 
(let*((fd(open "/etc/passwd"))
      (bytes(fdread fd 100)))
  (close fd)
  bytes)
-| root:XXXXXXXXX:0:0:root:/root:/bin/bash
-| bin:*:1:1:bin:/bin:
-| daemon:*:2:2:daemon:/sbin:
-| adm:*:3:4

procedure: close fd::int => int

Close a file descriptor, so that it no longer refers to any file and may be reused.

procedure: fdread fd::int arg => bstring

Read using the open file descriptor fd by calling libc read() function.

If argument arg is a string, it used to receive the bytes read, and the length of that string used as byte count. Otherwise is should be an integer number of bytes to read, and a fresh buffer will be allocated for each operation call.

procedure: fdwrite fd::int str::bstring => int

Try to write the str to specified file descriptor. Return the number of bytes really wrote.

procedure: getppid => int

getppid returns the process ID of the parent of the current process.

procedure: getpid => int

getpid returns the process ID of the current process. (This is often used by routines that generate unique temporary file names.)

procedure: getlogin => bstring or #f

The getlogin procedure returns a pointer to the login name as found in /var/adm/utmp. It may be used in conjunction when the same user ID is shared by several login names. See getlogin(3c) manual page for details.

If getlogin is called within a process that is not attached to a terminal, it returns #f. In later case use the cuserid procedure instead.

As example of how the getlogin works, we first run the utility from non-terminal xemacs window, and then from the rlogin shell:

 
bigloo-common
1:=> (getlogin)
=> #f
1:=> 
bash-2.03$ rlogin localhost
Password: 
Last login: Thu May  4 15:19:55 from localhost
bash-2.03$ bigloo-common
bigloo-common
1:=> (getlogin)
(getlogin)
=> wowa
1:=> 
bash-2.03$ 

procedure: getpwnam what::symbol #!optional name => #unspecified

The getpwnam procedure is used to obtain password entries. The what arguments controls which entry will be returned by the procedure. The valid values of what are:

name
user's login name (string)
uid
user's uid (integer)
gid
user's gid (integer)
gecos
typically user's full name (string)
dir
user's home dir (string)
shell
user's login shell (string)

The optional name argument may be integer user ID or string user name of the user in question. If omitted, the name of current user as returned by cuserid is used.

 
(getpwnam 'shell)
=> "/usr/bin/bash"
(getpwnam 'dir "adm")
=> "/var/adm"

procedure: cuserid => bstring
The cuserid procedure generates a character-string representation of the login name under which the owner of the current process is logged in.

 
(cuserid)
=> wowa

procedure: strxfrm src::bstring => bstring

The strxfrm procedure transforms the src string into a form such that the result of memcmp on two strings that have been transformed with strxfrm is the same as the result of locale-sensitive string-comparing procedures (string=?, string<? etc.) on the two strings before their transformation. (See setlocale).

 
(setlocale 'all "ru_RU.KOI8-R")
(pp(strxfrm "qwerty"))
-| #"\304\210\304\232\303\244"
(setlocale 'all "C")
(pp(strxfrm "qwerty"))
-| #"qwerty"

procedure: crypt passwd::bstring salt::bstring => bstring
crypt(3) is the password encryption function. It is based on the Data Encryption Standard algorithm with variations intended (among other things) to discourage use of hardware implementations of a key search.

passwd is a user's typed password.

salt is a two-character string chosen from the set [a-zA-Z0-9./]. This string is used to perturb the algorithm in one of 4096 different ways.

See the man pages for crypt(3).

 
(crypt "my-secret-password" "joe")
 => "jonhWNi0AD56g"

procedure: md5 data::bstring #!optional start end => bstring

Calculate digest using md5 algorithm. Return 16-byte long byte string. Optional start and end parameters may be used to work with substrings. For example:

 
(pp (md5 "qwerty"))
-| #"\330W\216\337\204X\316\006\373\305\273v\245\214\\\244"

md5 digest may include any characters, it is usually converted to printed form with string->hex, for example:

 
(string->hex (md5 "qwerty"))
=> "d8578edf8458ce06fbc5bb76a58c5ca4"

procedure: char->hex c::uchar => bstring

char->hex prints character c to hexadecimal string, for example:

 
(char->hex #\newline)
=> "0a"

procedure: string->hex str::bstring => bstring

string->hex prints string str using char->hex conversion, for example:

 
(string->hex "Hello")
=> "48656c6c6f"

procedure: string-grammar-apply s::bstring next-token::procedure => bstring

s string to parse. next-token procedure of one argument which must be a scheme input port.

The procedure string-grammar-apply translates strings. It creates an input port, and applies next-token to this port. The string output port is also created, and the result returned by next-token is printed to it using scheme display procedure. The operation repeats until the input is exausted.

The contents of an output port is returned.

For example an http-url-decode procedure in http library, which decodes URL uses this procedure:

 
(define (http-url-decode str)
  (string-grammar-apply
   str
   (lambda(port)
     (read/rp
      (regular-grammar
       ()
       ((: (in "%^") xdigit xdigit)
	(integer->char(string->number(the-substring 1 3)16)))
       (#\+ #\space))
      port))))

(http-url-decode "%61%62+%63%64") => "ab cd"

procedure: string*->string-list sp::string* => pair-nil
procedure: string-list->string* sl::pair-nil => string*

sp a pointer to a C array of C zero-terminated strings. The array must be terminated by NULL value.

The convenience procedures string*->string-list and string-list->string* converts an array of C strings to and from scheme list object correspondingly. Such arrays are very common in C APIs.

For example, the C-runtime environ global variable may be accessed in this way:

 
(pragma "extern char** environ")
(pp(string*->string-list(pragma::string* "environ")))
-|
("PWD=/home/wowa/"
 "HOSTNAME=duron"
 "LD_LIBRARY_PATH=/usr/X11R6/lib:/usr/local/lib"
 "HOSTDISPLAY=localhost:0.0"
 ...
)

procedure: apropos rexp::regexp-or-string

The procedure apropos returns the list of all Bigloo globals visible to eval procedure which match the given regular expression.

Examples:

Print all globals having "string->" in a name:

 
(pp(apropos "string->"))
-|
(string->keyword
  string->elong
  string->obj
  ieee-string->double
  ucs2-string->utf8-string
  string->hex
  string->integer
  string->symbol
  ieee-string->real
  string->0..2^x-1
  ieee-string->float
  string->0..255
  utf8-string->ucs2-string
  string->list
  string->number
  string->llong
  string->real
  ucs2-string->list
  string->symbol-ci)

Print all globals wich a name ending with "list":

 
(pp(apropos "list$"))
-|
(symbol-plist
  process-list
  directory->list
  list
  vector->list
  string*->string-list
  make-list
  circular-list
  unix-path->list
  path->list
  hashtable-key-list
  string->list
  hashtable->list
  ucs2-string->list
  flatten-list
  history-list)


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.9 iconv - charset conversion procedures

This section describes the interface to iconv - a set of libc functions for character set conversion. See iconv(3) manual page for details.

The iconv module is optional, i.e. you can disable its compilation by using --without-iconv flag for configure. Or the configure may detect that your libc does not have iconv functions and automatically disable this feature.

To let you detect whether character conversion is supported by the library from inside the interpreted code, the 'iconv symbol is defined through the register-eval-srfi! mechanism, so you can check it with cond-expand.

foreign type: iconv

The structure holding the information about the source and target character sets and current state of conversion.

procedure: iconv-open tocode::string fromcode::string writer::procedure => iconv

The iconv-open procedure returns a conversion descriptor that describes a conversion from the codeset specified by the fromcode argument to the codeset specified by the tocode argument. For state-dependent encodings, the conversion descriptor will be in a codeset-dependent initial shift state, ready for immediate use with the iconv procedure.

The writer should be a one-argument procedure which handles partial conversion result strings during subsequent calls to the iconv-write.

In the folowing example the iconv objects is created which will display the converted strings to the current-output-port.

 
(iconv-open "KOI8-R" "UTF-8" display)
=> #<foreign:ICONV:21410>

procedure: iconv-write cd::iconv src::bstring

The iconv-write procedure converts the sequence of characters from the code set specified in parameter fromcode of iconv-open, in the array specified by src, into a sequence of corresponding characters in the code set specified in parameter tocode of iconv-open, in the return string. The code sets are those specified in the cd argument.

The result of conversion is passed to the procedure specified in parameter writer of iconv-open.

procedure: make-iconv-encoder from::bstring to::bstring => #unspecified

Returns the procedure of the form (lambda (#!optional s #!key from to onerror)). This procedure, being called with arguments returns the string s converted to the target encoding. The keyed arguments from and to may be used to make the translation on the substring of s.

You should close the iconv object used to perform the translation by calling this procedure with no parameters.

Examples:

Translate my name in Russian from KOI8-R (one of Cyrillic most widely used Russian code sets) to UTF-8:

 
(define koi8->utf8(make-iconv-encoder "KOI8-R" "UTF-8"))
(koi8->utf8 "χΟΧΑ")
=> "\320\222\320\276\320\262\320\260"

;; Now skip one character
(koi8->utf8 "χΟΧΑ" from: 1)
=> "\320\276\320\262\320\260"

;; Close the iconv structure
(koi8->utf8)

procedure: iconv-close cd::iconv => int

Release the cd object and all related resources.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.10 Time-related procedures

This section describes types and procedures, dealing with time. They let you measure calendar and UNIX process time, print time using locale settings, and also do some arithmetics with times and dates.

foreign: tm

A wrapper for C library struct tm structure, broken-down time representation.

The following read accessors are defined:

tm-sec
The number of seconds after the minute, normally in the range 0 to 59, but can be up to 61 to allow for leap seconds.

tm-min
The number of minutes after the hour, in the range 0 to 59.

tm-hour
The number of hours past midnight, in the range 0 to 23.

tm-mday
The day of the month, in the range 1 to 31.

tm-mon
The number of months since January, in the range 0 to 11.

tm-year
The number of years since 1900.

See also strftime procedure description to print these objects in human-readable form.

procedure: make-tm => tm

Allocate an uninitialized object of type tm. This procedure is used internally by other time-manipulation procedures. Perhaps, you do not want to call it explicitly.

procedure: gmtime seconds::double #!optional tm::tm => tm

Interface for C runtime gmtime call. Take number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC), and convert it to broken-down time representation, expressed in Coordinated Universal Time (UTC).

 
(strftime(gmtime(current-seconds)))
=> 04/16/00 17:56:54

procedure: localtime seconds::double #!optional tm::tm => tm

Same as gmtime, but the result is expressed relative to the user's specified time zone.

The procedure also sets the values returned by tzname and timezone and daylight.

procedure: timezone => int

Return number of seconds west of UTC. For example, here in Moscow:

 
(timezone)
=> -10800
(/ (timezone) 3600)
=> -3

procedure: tzname => 2 scheme values

Return names of time zone as two scheme values. See tzset manual pages for details. The values are also set by localtime. For example:

 
(define(tzprint)
  (multiple-value-bind
   (name name1)
   (tzname)
   (print name ", " name1)))

(tzprint)
(localtime 0.0) ;; this call for side effects only
(tzprint)
=> GMT, GMT
MSK, MSD

procedure: daylight => bool

A flag that indicates whether daylight saving time is in effect at the time described. Return positive value if daylight saving time is in effect, zero if it is not, and negative value if the information is not available.

procedure: strftime tm::tm #!optional format::bstring => bstring

The strftime procedure formats the broken-down time tm according to the format specification. If format argument is omitted, the "%x %X" string is used to format output. See strftime manual pages for details.

Examples:

 
(define now(localtime(current-seconds)))
=> #<foreign:TM:806dbd0>

(strftime now)
"04/16/00 23:38:14"

(strftime now "%Y%m%d%H%M%S")
"20000416233814"

procedure: current-seconds => double

Number of seconds as returned by gettimeofday C runtime call. The name of procedure chosen to be compatible with analogous procedure in MzScheme.

Example:

 
(current-seconds)
=> 955914618.43757

procedure: current-milliseconds => double

Defined as:

 
(define(current-milliseconds::double)
  (* (current-seconds) 1000.0))

procedure: ctime seconds::double => bstring

Interface for ctime_r C runtime procedure. Return 26-character string with fixed-format time representation, for example:

 
(ctime (current-seconds)) => "Mon Apr 17 12:28:54 2000"

procedure: mktime year month day #!optional hour minute second => tm

Constructor for objects of tm type. The arguments are:

year::int
The year, including the century number
month::int
Month in an year number from 1 to 12
day::int
Day in a month number
hour::int
Hour in day number from 0 to 23. Default is 0.
minute::int
Minute in a hour number from 0 to 59. Default is 0.
second::int
Second in a minute number. Default is 0.

Example:
 
(strftime(mktime 1960 12 27))
=> "12/27/60 00:00:00"

procedure: read-date fmt::bstring port::input-port => tm

Read date/time from port port using the specification fmt. The format of the specification is a subset that of strftime specification (only %S, %M, %H, %I, %d, %m, %Y, %p and %% escape sequences are supported).

Examples:

 
(strftime
  (read-date "%Y%m%d%H%M%S"
             (open-input-string "20000416233814")))
=> "04/16/00 23:38:14"
(strftime
  (read-date
    "%d.%m.%Y %H:%M:%S"
    (open-input-string "26.05.2002 14:16:01")))
=> "05/26/02 14:16:01"

procedure: times #!optional which? => long

The times procedure measures various time-accounting information. Depending on value of argument which? of symbol type it returns the following values:

utime
User time
stime
System time
cutime
User time of children
cstime
System time of children

If argument which? is absent, the times procedure returns five scheme values: the number of clock ticks that have elapsed since the system has been up, and all the values just described, i.e. utime, stime, cutime and cstime.

All the values are measured in system clock ticks. The length of one tick is system-dependent. Number of clocks per second may be obtained by calling clocks-per-second procedure.

Examples:

Here number of system clock ticks from the system start-up is measured:

 
(times)
=> 1720216

The same value but now in seconds:

 
(/(times)(clocks-per-second))
=> 17340.09

The following example is a complete utility that measures the external process times.

The initial times are measured and stored in local variables total, cutime and cstime, external process is spawned using bigloo run-process procedure See Info file `bigloo', node `Process support'. After the spawned process is finished, the statistics is printed to standard error port in form similar that of Unix time utility.

 
#!/usr/local/bin/bigloo-common

(multiple-value-bind
 (total utime stime cutime cstime)
 (times)
 (apply run-process
	(append (cddr(command-line))
		'(wait: #t)))
 (multiple-value-bind
  (ntotal nutime nstime ncutime ncstime)
  (times)
  (let((ticks(clocks-per-second))
       (user-ticks(- ncutime cutime))
       (system-ticks(- ncstime cstime))
       (elapsed-ticks(- ntotal total)))
    (fprintf
     (current-error-port)
     "~auser ~asystem ~aelapsed ~a%CPU~%"
     (/ user-ticks ticks)
     (/ system-ticks ticks)
     (/ elapsed-ticks ticks)
     (inexact->exact
      (*(/(+ user-ticks system-ticks) elapsed-ticks)100))))))

The utility usage example (provided the ./time is the script location):

 
bash$ ./time gzip -c /vmlinuz > /dev/null
1.17user 0.03system 1.2elapsed 100%CPU

procedure: tm->utctime time::tm => bstring

Print time argument in UTC time format.

 
(tm->utctime(localtime(current-seconds)))
=> 20000531123949Z

procedure: utctime->tm utc::bstring => tm
utc
 
(strftime(utctime->tm "20000531123949Z"))
=> 05/31/00 12:39:49


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.11 cgen - bigloo preprocessor

This section describes cgen -- the utility for creating bigloo interfaces to C libraries.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index]