From a918b0109a5bf49bc2a85c46959f305e9ee0f0f6 Mon Sep 17 00:00:00 2001 From: Alexandre Erwin Ittner Date: Sun, 8 Jun 2008 16:31:47 +0000 Subject: [PATCH] Adding sample Unicode I/O library git-svn-id: file:///var/svn/lua-iconv/trunk@58 9538949d-8f27-0410-946f-ce01ef448559 --- uniopen.lua | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 uniopen.lua diff --git a/uniopen.lua b/uniopen.lua new file mode 100644 index 0000000..f8c7710 --- /dev/null +++ b/uniopen.lua @@ -0,0 +1,37 @@ + +-- Simple (and incomplete) Unicode I/O layer. + +module("uniopen", package.seeall) + +require "iconv" + +local mt = { __index = _M } + +function open(fname, mode, fromcharset, tocharset) + assert(mode == "r" or mode == "rb", "Only read modes are supported yet") + tocharset = tocharset or "utf8" + local cd = assert(iconv.new(fromcharset, tocharset), "Bad charset") + local fp = io.open(fname, mode) + if not fp then + return nil + end + local o = { fp = fp, cd = cd } + setmetatable(o, mt) + return o; +end + +function read(fp, mod) + assert(fp and fp.fp and fp.cd, "Bad file descriptor") + local ret = fp.fp:read(mod) + if ret then + return fp.cd:iconv(ret) -- returns: string, error code + else + return nil + end +end + +function close(fp) + assert(fp and fp.fp, "Bad file descriptor") + fp.fp:close() +end +