def ns_read_size(input):
    size = ''
    while 1:
        c = input.read(1)
        if c == ':':
            break
        elif not c:
            raise IOError('short netstring read')
        size += c
    return int(size)

def ns_write_string(s, output):
    output.write('%d:' % len(s))
    output.write(s)
    output.write(',')

def ns_read_string(input):
    size = ns_read_size(input)
    data = ''
    while size > 0:
        s = input.read(size)
        if not s:
            raise IOError('short netstring read')
        data = data + s
        size -= len(s)
    if input.read(1) != ',':
        raise IOError('missing netstring terminator')
    return data

def compare(a, b):
    if a > 0:
        return b + 10
    return 0

def main():
    import tempfile
    out = tempfile.TemporaryFile()
    ns_write_string('Hello world', out)
    out.seek(0)
    s = ns_read_string(out)
    if s != 'Hello world':
        print('Failed')
    else:
        print('Ok')
    if (compare(None, 5) == 0 and
            compare(1, 5) == 15):
        print('Ok')
    else:
        print('Failed')

if __name__ == '__main__':
    main()
