# -*- coding: utf-8 -*-
# Elisa - Home multimedia server
# Copyright (C) 2006-2008 Fluendo Embedded S.L. (www.fluendo.com).
# All rights reserved.
#
# This file is available under one of two license agreements.
#
# This file is licensed under the GPL version 3.
# See "LICENSE.GPL" in the root of this distribution including a special
# exception to use Elisa with Fluendo's plugins.
#
# The GPL part of Elisa is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Elisa" in the root directory of this distribution package
# for details on that license.

"""
Utility functions for sorting
"""

__maintainer__ = 'Florian Boucault <florian@fluendo.com>'


import re

"""
As proved here http://blog.pobblelabs.org/2007/12/11/exception-handling-slow/
try-except is to time consuming, a Much faster way it the check for the digit
directly:
"""

NUMS = re.compile('([0-9]+)')

def _natural_key(s):
    # strip the spaces
    s = s.strip()
    return [ part.isdigit() and int(part) or part.lower() for part in NUMS.split(s) ]

def natural_sort(l):
    """
    Case insensitive human compliant sort.

    @param l: list that needs to be sorted
    @type l:  list of unicode
    """
    l.sort(key=_natural_key)

