2015年11月29日日曜日

Sample code like GetOpt for C#

Sample code like GetOpt for C#

---- GetOpt.cs ----

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetOptForConsole
{
    using GetOptDic = System.Collections.Generic.Dictionary<String, Object>;
    using GetOptList = System.Collections.Specialized.StringCollection;

    /// <summary>
    /// Analyze argument class.
    /// </summary>
    /// <example>
    /// src1 /MAT dir1\dir2\mat.txt src2 /material dir2\dir3\mat.txt /omi abc /dmy def src3 src4
    /// /MAT and /material : set to the same variable.
    /// </example>
    /// <code>
    /// string materialFile;
    /// var opt = new GetOpt();
    /// opt.Add("/MAT", c => materialFile = c);
    /// opt.Add("/material", c => materialFile = c);
    /// opt.Add("/omi", "");
    /// opt.Run(args);
    /// string omi = opt["/omi"];
    /// string mat = opt["/MAT"];    // throw ArgumentException
    ///
    /// string [] newArgs = opt.Args.ToString();
    /// --- OR ---
    /// foreach(string a in opt.Args) {
    ///     ...
    /// }
    /// --- OR ---
    /// if (opt.Args.Count >= 1) source1 = opt.Args[0];
    /// if (opt.Args.Count >= 2) source2 = opt.Args[1];
    /// </code>
    class GetOpt
    {
        /// <summary>
        /// Store option arguments.
        /// </summary>
        private GetOptDic mOptions = new GetOptDic();
        /// <summary>
        /// Store non option arguments.
        /// </summary>
        private GetOptList mArgs = new GetOptList();

        public GetOpt() { }
        public GetOpt(GetOpt iOriginal) { this.mOptions.Concat(iOriginal.mOptions); }

        /// <summary>
        /// Regist option argument (if action).
        /// </summary>
        /// <param name="iKey">Option name. (ex: /MAT)</param>
        /// <param name="iValue">Action. (ex: (Action \lt string \gt )(c => { materialPath = c; }) )</param>
        public void Add(string iKey, Action<string> iValue) { this.mOptions.Add(iKey, iValue); }
        /// <summary>
        /// Regist option argument (if string).
        /// </summary>
        /// <param name="iKey">Option name. (ex: /MAT)</param>
        /// <param name="iValue">Initial value. default is <seealso cref="String.Empty"/> 。</param>
        public void Add(string iKey, string iValue = "") { this.mOptions.Add(iKey, iValue); }
        /// <summary>
        /// Get option value. (if string)
        /// </summary>
        /// <param name="iKey">Option name. (ex: /MAT)</param>
        /// <returns>Option value. </returns>
        /// <exception cref="ArgumentException">Illigal argument. the value is action. </exception>
        public string this[string iKey]
        {
            get
            {
                object val = this.mOptions[iKey];
                if (val is string)
                {
                    // unboxing.
                    return (string)val;
                }
                else
                {
                    throw new ArgumentException(message: "Illigal argument. the value is action.", paramName: "iKey");
                }
            }
        }
        /// <summary>
        /// Get the collection of non option value.
        /// </summary>
        public System.Collections.Specialized.StringCollection Args
        {
            get
            {
                return mArgs;
            }
        }
        /// <summary>
        /// Analyze argument.
        /// </summary>
        /// <param name="args">Arguments. </param>
        public void Run(string[] args)
        {
            string curOption = "";
            foreach (string curArg in args)
            {
                if (curOption != "")
                {
                    if (this.mOptions[curOption] is string)
                    {
                        this.mOptions[curOption] = curArg;
                    }
                    else if (this.mOptions[curOption] is Action<string>)
                    {
                        var action = (Action<string>)this.mOptions[curOption];
                        action(curArg);
                    }
                    curOption = "";
                }
                else if (this.mOptions.ContainsKey(curArg))
                {
                    curOption = curArg;
                }
                else
                {
                    mArgs.Add(curArg);
                }

            }
        }
    }

    class SampleOfGetOpt
    {
        public static void SampleMain()
        {
            var originalArgs = new string[] { @"src1", @"/MAT", @"dir1\dir2\mat.txt", @"src2", @"/material", @"dir2\dir3\mat.txt", @"/omi", @"abc", @"/dmy", @"def", @"src3", @"src4" };

            string materialFile = "";
            var opt = new GetOpt();
            opt.Add("/MAT", c => materialFile = c);
            opt.Add("/material", c => materialFile = c);
            opt.Add("/omi", "");
            opt.Add("/dmy", "");
            opt.Run(originalArgs);

            Console.WriteLine("materialFile=[" + materialFile + "]");

            string omi = opt["/omi"];
            Console.WriteLine("/omi=[" + omi + "]");

            string dmy = opt["/dmy"];
            Console.WriteLine("/dmy=[" + dmy + "]");

            string mat = "";
            try
            {
                mat = opt["/MAT"];    // throw ArgumentException
                Console.WriteLine("/MAT=[" + mat + "]");
            }
            catch (Exception e)
            {
                Console.WriteLine("/MAT=[[" + e.ToString() + "]]");
            }

            foreach (string a in opt.Args)
            {
                Console.WriteLine("opt.Args=[" + a + "]");
            }
        }
    }
}



2013年3月15日金曜日

dynamic link library sample code


/* dynamic link library sample code */
/* It's copy free. */

#include <dlfcn.h> /* dlopen, etc */

typedef void (*func1_t) (int a);
typedef void (*func2_t) (int b);
typedef struct tag_funclist_t {
    func1_t  func1;
    func2_t  func2;
}   funclist_t;

#define DLL_FILE_NAME "libXXXX.so"

long load( void ** opp_handle, func_t * p_funclist )
{
    long ret = 0;
    void * p_handle = NULL;
    const char * p_error = NULL;
    const char * p_symbol = NULL;
    void * p_func = NULL;

    if ( ! opp_handle && ! p_funclist ) {
        ret = 1;
    }

    if ( ! ret ) {
        dlerror();
        p_handle = dlopen( DLL_FILE_NAME, RTLD_NOW );
        p_error = dlerror();  /* thread unsafe */
        if ( ! p_handle ) {
            ret = 1;
            fprintf( stderr, "[load] Could not found " DLL_FILE_NAME " [%s]\n", p_error );
        }
    }

    if ( ! ret && ! p_handle ) {
        if ( ! ret ) {
            p_symbol = "func1";
            p_func = p_funclist->func1 = (func1_t)dlsym( p_handle, p_symbol );
            p_error = dlerror();  /* thread unsafe */
            if ( ! p_func ) ret = 1;
        }
        if ( ! ret ) {
            p_symbol = "func2";
            p_func = p_funclist->func2 = (func2_t)dlsym( p_handle, p_symbol );
            p_error = dlerror();  /* thread unsafe */
            if ( ! p_func ) ret = 1;
        }
        if ( ret ) {
            fprintf( stderr, "[load] Could not found the symbol (%s) in " DLL_FILE_NAME ": %s\n", p_symbol, p_error );
        }
    }

    if ( opp_handle ) {
        *opp_handle = p_handle;
    }
    return ret;

}

long unload( void * p_handle )
{
    return dlcolose( p_handle );
}

int main ( int argc, char **argv )
{
    int ret = 0;
    void * p_handle = NULL;
    funclist_t funclist;
    funclist_t * p_funclist = &funclist;

    if ( ! ret ) {
        ret = load( p_handle, p_funclist );
    }
    if ( ! ret && ! p_funclist ) {
        int x;
        p_funclist->func1(x);
        p_funclist->func2(x);
    }
    if ( ! ret ) {
        ret = unload( p_handle );
    }
    return ret;
}

2013年3月7日木曜日

base64 source code "bin to ascii"


/*----------------------------------------------------------------
 * base64_bin_to_ascii.c
 *
 * This source code is double license under:
 *   The MIT License (X11 License)
 *   Apache License, Version 2.0
 *
 * Copyright (c) 2013-2013 elf17 chobitprogram.blogspot.com All Rights Reserved.
 ----------------------------------------------------------------*/
/*----------------------------------------------------------------
 * The MIT License (MIT)
 * Copyright (c) 2013-2013 elf17 chobitprogram.blogspot.com
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom
 * the Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
 * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
 * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 ----------------------------------------------------------------*/
/*----------------------------------------------------------------
 * Copyright elf17 chobitprogram.blogspot.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ----------------------------------------------------------------*/

/**
 * convert 3 bytes binary to 4 bytes ascii + NULL terminator by base64.
 * @return status
 * @retval -1 : error charactor is found.
 * @retval  0 : success.
 * @retval  1 : detect end of data.
 * @see l64a()
 */
int b64a(const unsigned char * src, int len, unsigned char * dst)
{
    int ret = 0;                        /* return code */
    static const unsigned char b64str[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    unsigned char s[4] = {0};           /* src 8 bits + NULL terminator */
    unsigned char d[5] = {0};           /* dst 6 bits + NULL terminator */
    unsigned char f[4] = {1,1,1,1};     /* dst flag. true if src not exist. */
    int i = 0;                          /* loop counter */
    if ( len == 0 ) {
        dst[0] = 0;                     /* NULL terminator */
        ret = 1;                        /* detect end of data */
    } else {
        if ( len >= 1 ) {       s[0] = src[0]; f[0] = 0;       f[1] = 0;       }
        if ( len >= 2 ) {       s[1] = src[1]; f[1] = 0;       f[2] = 0;       }
        if ( len >= 3 ) {       s[2] = src[2]; f[2] = 0;       f[3] = 0;       }
        d[0] = (( s[0] & 0xfc ) >> 2);
        d[1] = (( s[0] & 0x03 ) << 4) | (( s[1] & 0xf0 ) >> 4 );
        d[2] = (( s[1] & 0x0f ) << 2) | (( s[2] & 0xc0 ) >> 6 );
        d[3] = (( s[2] & 0x3f )     );
        for ( i = 0 ; i < 4 ; i++ ) {
            if ( f[i] != 0 ) {          /* src not exist */
                dst[i] = '=';           /* NULL terminator */
                ret = 1;                /* detect end of data */
                /* no break ... output is always (4+1) bytes. */
            } else if ( d[i] >= 64 ) {  /* error data */
                dst[i] = 0;             /* NULL terminator */
                ret = -1;               /* error data */
                break;
            } else {
                dst[i] = b64str[d[i]];  /* convert to base64 string */
            }
        }
    }
    dst[4] = 0;                         /* NULL terminator */
    return ret;
}

/**
 * convert binary to ascii by base64.
 * @return status
 * @retval -1 : error charactor is found.
 * @retval  0 : success.
 * @see l64a(), b64a()
 */
int base64_bin_to_ascii(const unsigned char * src, int len, unsigned char * dst)
{
    int ret = 0;                        /* return code */
    const unsigned char * s = src;
    unsigned char * d = dst;
    int i = 0;                          /* loop counter */
    for ( i = 0 ; i < len ;  i += 3, s += 3, d += 4 ) {
        ret = b64a( s, (len - i), d );
        if ( ret != 0 ) {
            break;
        }
    }
    /* if error */
    if ( ret < 0 ) {
        dst[0] = 0;
    } else if ( ret > 0 ) {
        ret = 0;
    }
    return ret;
}