Thursday, 19 May 2016

Haskell: File Buffering operations

Buffer is a temporary storage area usually kept in RAM, used to improve the performance of applications while doing IO operations.

Why buffering is required?
It is because the process of reading from disk, writing data to disk is a time consuming process. So instead of reading character by character from disk, System reads some characters assume 1024 characters at a time and keep them in memory. Once application done with these 1024 characters, system clears the buffer and fetch next 1024 characters from disk and keep it in buffer. Same in the case of writing also, instead of writing character-by-character, system writes some characters to buffer, once buffer filled, it flushes the information in buffer to disk.

Haskell supports three kinds of buffering.
a.   Line Buffering
b.   Block buffering
c.    No buffering

Line Buffering
For the output, the buffer is flushed to disk whenever it sees the new line character (or) the buffer is full. For input, If the buffer is empty, it gets characters from disk, until it sees a new line character (or) the buffer is full. No characters are available until the newline character is available or the buffer is full. For most implementations, terminals will normally be line-buffered.

Block buffering
For output, the entire buffer is written to disk whenever it overflows. For input, whenever the buffer is empty, the next block of data is read into the buffer.

NoBuffering
No buffer at all. Output is written to disk, whenever it sees, input is read and returned immediately.

Following value constructors represent the types of buffering.

Constructor
Description
NoBuffering
Buffering is disabled.
LineBuffering
Enable line buffering
BlockBuffering (Maybe Int)
Enable block buffering, The size of the buffer is n items if the argument is Just n and is otherwise implementation-dependent.
        
For example,
Following program reads some input from user and convert it to upper case.


BufferUtil.hs
import System.IO
import Data.Char

convertToUpper = map toUpper

main = do
        putStrLn "Enter some information"
        inforamtion <- getContents
        putStrLn (convertToUpper inforamtion)

$ ghc BufferUtil.hs
[1 of 1] Compiling Main             ( BufferUtil.hs, BufferUtil.o )
Linking BufferUtil ...
$ ./BufferUtil
Enter some information
Hello ptr
HELLO PTR
How are you
HOW ARE YOU

getContents function returns all user input as a single string, since it is lazy, it return as soon as it sees new line character (Because LineBuffering is the default buffering mode for terminals).


Try changing the buffering mode to BlockBuffering and see the output. It will not convert every new line to upper case, it converts whenever the buffer is full.
$ ghc BufferUtil.hs
[1 of 1] Compiling Main             ( BufferUtil.hs, BufferUtil.o )
Linking BufferUtil ...
$
$ ./BufferUtil
Enter some information
Hello PTR 
How are you
Buddha gave 84,000 instructions on how to train the mind to be happy and free from problems; teachings that some see as just happiness quotes, but to Buddhists worldwide, Buddha’s teachings are taken as pure spiritual instructions which reveal the supreme path to inner peace and happiness.
In a special Buddhist lineage, known as Kadampa Buddhism, Buddha explained the profound practice of training the mind through which we take on the sufferings of others using our love and compassion.

Here is a short explanation of the context of these teachings and some of the happiness quotes that came from this profound practice.
Every living being has the same basic wish – to be happy and avoid suffering. Even newborn babies, animals and insects have this wish. It has been our main wish since beginningless time and it is with us all the time, even in our sleep. We spend our whole life working hard to fulfill this wish.
Since this world evolved, humans beings have spent much time and energy improving external conditions in their search for happiness and a solution to their many problems. What has been the result? Instead of their wishes being fulfilled, human suffering has continued to increase, while the experience of happiness and peace is decreasing. This clearly shows that we need to find a true method for gaining pure happiness and freedom from misery.

All our problems and all our unhappiness are created by our uncontrolled mind and our non-virtuous actions. By engaging in the practice of dharma, we can learn to pacify and control our mind, abandon non-virtuous actions and their root cause, and thereby attain permanent peace, the true cessation of all our suffering.
The supreme dharma of training the mind (Tibetan: Lojong) is an unsurpassed method for controlling our mind, and reveals the principle path to enlightenment.

Within the teachings on training the mind Geshe Chekawa gave a very special instruction: “To remember this train in every activity by words”

These two lines from the root text advise us to memorize certain words to recite at appropriate times so as to remind us of our essential practice of exchanging self with others, and especially our practice of taking and giving. (A free guided audio meditation on this profound practice to counter selfishness and self-cherishing can be found below). There are many quotations from the scripture to choose from.
HELLO PTR
HOW ARE YOU
BUDDHA GAVE 84,000 INSTRUCTIONS ON HOW TO TRAIN THE MIND TO BE HAPPY AND FREE FROM PROBLEMS; TEACHINGS THAT SOME SEE AS JUST HAPPINESS QUOTES, BUT TO BUDDHISTS WORLDWIDE, BUDDHA’S TEACHINGS ARE TAKEN AS PURE SPIRITUAL INSTRUCTIONS WHICH REVEAL THE SUPREME PATH TO INNER PEACE AND HAPPINESS.
IN A SPECIAL BUDDHIST LINEAGE, KNOWN AS KADAMPA BUDDHISM, BUDDHA EXPLAINED THE PROFOUND PRACTICE OF TRAINING THE MIND THROUGH WHICH WE TAKE ON THE SUFFERINGS OF OTHERS USING OUR LOVE AND COMPASSION.

HERE IS A SHORT EXPLANATION OF THE CONTEXT OF THESE TEACHINGS AND SOME OF THE HAPPINESS QUOTES THAT CAME FROM THIS PROFOUND PRACTICE.
EVERY LIVING BEING HAS THE SAME BASIC WISH – TO BE HAPPY AND AVOID SUFFERING. EVEN NEWBORN BABIES, ANIMALS AND INSECTS HAVE THIS WISH. IT HAS BEEN OUR MAIN WISH SINCE BEGINNINGLESS TIME AND IT IS WITH US ALL THE TIME, EVEN IN OUR SLEEP. WE SPEND OUR WHOLE LIFE WORKING HARD TO FULFILL THIS WISH.
SINCE THIS WORLD EVOLVED, HUMANS BEINGS HAVE SPENT MUCH TIME AND ENERGY IMPROVING EXTERNAL CONDITIONS IN THEIR SEARCH FOR HAPPINESS AND A SOLUTION TO THEIR MANY PROBLEMS. WHAT HAS BEEN THE RESULT? INSTEAD OF THEIR WISHES BEING FULFILLED, HUMAN SUFFERING HAS CONTINUED TO INCREASE, WHILE THE EXPERIENCE OF HAPPINESS AND PEACE IS DECREASING. THIS CLEARLY SHOWS THAT WE NEED TO FIND A TRUE METHOD FOR GAINING PURE HAPPINESS AND FREEDOM FROM MISERY.

ALL OUR PROBLEMS AND ALL OUR UNHAPPINESS ARE CREATED BY OUR UNCONTROLLED MIND AND OUR NON-VIRTUOUS ACTIONS. BY ENGAGING IN THE PRACTICE OF DHARMA, WE CAN LEARN TO PACIFY AND CONTROL OUR MIND, ABANDON NON-VIRTUOUS ACTIONS AND THEIR ROOT CAUSE, AND THEREBY ATTAIN PERMANENT PEACE, THE TRUE CESSATION OF ALL OUR SUFFERING.
THE SUPREME DHARMA OF TRAINING THE MIND (TIBETAN: LOJONG) IS AN UNSURPASSED METHOD FOR CONTROLLING OUR MIND, AND REVEALS THE PRINCIPLE PATH TO ENLIGHTENMENT.

WITHIN THE TEACHINGS ON TRAINING THE MIND GESHE CHEKAWA GAVE A VERY SPECIAL INSTRUCTION: “TO REMEMBER THIS TRAIN IN EVERY ACTIVITY BY WORDS”

THESE TWO LINES FROM THE ROOT TEXT A


Set and get the buffering mode
Following functions are used to set and get the buffering mode.

hSetBuffering : Set the buffering mode
Prelude System.IO> :t hSetBuffering
hSetBuffering :: Handle -> BufferMode -> IO ()
Observe the type signature, it takes Handle, BufferMode and set the mode of buffering for handle hdl on subsequent reads and writes.

hSetBuffering stdout (BlockBuffering (Just 1))
Above statement sets the buffering mode to BlockBuffering for stdout.

You may get isPermissionError, if the handle is already in use and the implementation does not allow the buffering mode to be changed.

hGetBuffering : Get the buffering mode for given handle

Prelude System.IO> :t hGetBuffering
hGetBuffering :: Handle -> IO BufferMode

hGetBuffering  takes a handle and return the current buffering mode for handle.

hFlush: Flush data immediately
Prelude System.IO> :t hFlush
hFlush :: Handle -> IO ()

If you call hFlush on any handle, it immediately flush the data in the buffer to operating system. You may get following errors while working with hFlush.

Error
Description
isFullError
Devicei s full
isPermissionError
You will get this error, if a system resource limit would be exceeded

        



Previous                                                 Next                                                 Home

No comments:

Post a Comment