summaryrefslogtreecommitdiffstats
path: root/doc/src/examples/tetrix.qdoc
blob: a4340dc4eb0b6f3c2634cd4a8ab302121a2d7556 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

/*! 
    \example widgets/tetrix
    \title Tetrix Example

    The Tetrix example is a Qt version of the classic Tetrix game.

    \image tetrix-example.png

    The object of the game is to stack pieces dropped from the top of the
    playing area so that they fill entire rows at the bottom of the playing area.

    When a row is filled, all the blocks on that row are removed, the player earns
    a number of points, and the pieces above are moved down to occupy that row.
    If more than one row is filled, the blocks on each row are removed, and the
    player earns extra points.

    The \gui{Left} cursor key moves the current piece one space to the left, the
    \gui{Right} cursor key moves it one space to the right, the \gui{Up} cursor
    key rotates the piece counter-clockwise by 90 degrees, and the \gui{Down}
    cursor key rotates the piece clockwise by 90 degrees.

    To avoid waiting for a piece to fall to the bottom of the board, press \gui{D}
    to immediately move the piece down by one row, or press the \gui{Space} key to
    drop it as close to the bottom of the board as possible.

    This example shows how a simple game can be created using only three classes:

    \list
    \o The \c TetrixWindow class is used to display the player's score, number of
       lives, and information about the next piece to appear.
    \o The \c TetrixBoard class contains the game logic, handles keyboard input, and
       displays the pieces on the playing area.
    \o The \c TetrixPiece class contains information about each piece.
    \endlist

    In this approach, the \c TetrixBoard class is the most complex class, since it
    handles the game logic and rendering. One benefit of this is that the
    \c TetrixWindow and \c TetrixPiece classes are very simple and contain only a
    minimum of code.

    \section1 TetrixWindow Class Definition

    The \c TetrixWindow class is used to display the game information and contains
    the playing area:

    \snippet examples/widgets/tetrix/tetrixwindow.h 0

    We use private member variables for the board, various display widgets, and
    buttons to allow the user to start a new game, pause the current game, and quit.

    Although the window inherits QWidget, the constructor does not provide an
    argument to allow a parent widget to be specified. This is because the window
    will always be used as a top-level widget.

    \section1 TetrixWindow Class Implementation

    The constructor sets up the user interface elements for the game:

    \snippet examples/widgets/tetrix/tetrixwindow.cpp 0

    We begin by constructing a \c TetrixBoard instance for the playing area and a
    label that shows the next piece to be dropped into the playing area; the label
    is initially empty.

    Three QLCDNumber objects are used to display the score, number of lives, and
    lines removed. These initially show default values, and will be filled in
    when a game begins:

    \snippet examples/widgets/tetrix/tetrixwindow.cpp 1

    Three buttons with shortcuts are constructed so that the user can start a
    new game, pause the current game, and quit the application:

    \snippet examples/widgets/tetrix/tetrixwindow.cpp 2
    \snippet examples/widgets/tetrix/tetrixwindow.cpp 3

    These buttons are configured so that they never receive the keyboard focus;
    we want the keyboard focus to remain with the \c TetrixBoard instance so that
    it receives all the keyboard events. Nonetheless, the buttons will still respond
    to \key{Alt} key shortcuts.

    We connect \l{QAbstractButton::}{clicked()} signals from the \gui{Start}
    and \gui{Pause} buttons to the board, and from the \gui{Quit} button to the
    application's \l{QApplication::}{quit()} slot.

    \snippet examples/widgets/tetrix/tetrixwindow.cpp 4
    \snippet examples/widgets/tetrix/tetrixwindow.cpp 5

    Signals from the board are also connected to the LCD widgets for the purpose of
    updating the score, number of lives, and lines removed from the playing area.

    We place the label, LCD widgets, and the board into a QGridLayout
    along with some labels that we create with the \c createLabel() convenience
    function:

    \snippet examples/widgets/tetrix/tetrixwindow.cpp 6

    Finally, we set the grid layout on the widget, give the window a title, and
    resize it to an appropriate size.

    The \c createLabel() convenience function simply creates a new label on the
    heap, gives it an appropriate alignment, and returns it to the caller:

    \snippet examples/widgets/tetrix/tetrixwindow.cpp 7

    Since each label will be used in the widget's layout, it will become a child
    of the \c TetrixWindow widget and, as a result, it will be deleted when the
    window is deleted.

    \section1 TetrixPiece Class Definition

    The \c TetrixPiece class holds information about a piece in the game's
    playing area, including its shape, position, and the range of positions it can
    occupy on the board:

    \snippet examples/widgets/tetrix/tetrixpiece.h 0

    Each shape contains four blocks, and these are defined by the \c coords private
    member variable. Additionally, each piece has a high-level description that is
    stored internally in the \c pieceShape variable.

    The constructor is written inline in the definition, and simply ensures that
    each piece is initially created with no shape. The \c shape() function simply
    returns the contents of the \c pieceShape variable, and the \c x() and \c y()
    functions return the x and y-coordinates of any given block in the shape.

    \section1 TetrixPiece Class Implementation

    The \c setRandomShape() function is used to select a random shape for a piece:

    \snippet examples/widgets/tetrix/tetrixpiece.cpp 0

    For convenience, it simply chooses a random shape from the \c TetrixShape enum
    and calls the \c setShape() function to perform the task of positioning the
    blocks.

    The \c setShape() function uses a look-up table of pieces to associate each
    shape with an array of block positions:

    \snippet examples/widgets/tetrix/tetrixpiece.cpp 1
    \snippet examples/widgets/tetrix/tetrixpiece.cpp 2

    These positions are read from the table into the piece's own array of positions,
    and the piece's internal shape information is updated to use the new shape.

    The \c x() and \c y() functions are implemented inline in the class definition,
    returning positions defined on a grid that extends horizontally and vertically
    with coordinates from -2 to 2. Although the predefined coordinates for each
    piece only vary horizontally from -1 to 1 and vertically from -1 to 2, each
    piece can be rotated by 90, 180, and 270 degrees.

    The \c minX() and \c maxX() functions return the minimum and maximum horizontal
    coordinates occupied by the blocks that make up the piece:

    \snippet examples/widgets/tetrix/tetrixpiece.cpp 3
    \snippet examples/widgets/tetrix/tetrixpiece.cpp 4

    Similarly, the \c minY() and \c maxY() functions return the minimum and maximum
    vertical coordinates occupied by the blocks:

    \snippet examples/widgets/tetrix/tetrixpiece.cpp 5
    \snippet examples/widgets/tetrix/tetrixpiece.cpp 6

    The \c rotatedLeft() function returns a new piece with the same shape as an
    existing piece, but rotated counter-clockwise by 90 degrees:

    \snippet examples/widgets/tetrix/tetrixpiece.cpp 7

    Similarly, the \c rotatedRight() function returns a new piece with the same
    shape as an existing piece, but rotated clockwise by 90 degrees:

    \snippet examples/widgets/tetrix/tetrixpiece.cpp 9

    These last two functions enable each piece to create rotated copies of itself.

    \section1 TetrixBoard Class Definition

    The \c TetrixBoard class inherits from QFrame and contains the game logic and display features:

    \snippet examples/widgets/tetrix/tetrixboard.h 0

    Apart from the \c setNextPieceLabel() function and the \c start() and \c pause()
    public slots, we only provide public functions to reimplement QWidget::sizeHint()
    and QWidget::minimumSizeHint(). The signals are used to communicate changes to
    the player's information to the \c TetrixWindow instance.

    The rest of the functionality is provided by reimplementations of protected event
    handlers and private functions:

    \snippet examples/widgets/tetrix/tetrixboard.h 1

    The board is composed of a fixed-size array whose elements correspond to
    spaces for individual blocks. Each element in the array contains a \c TetrixShape
    value corresponding to the type of shape that occupies that element.

    Each shape on the board will occupy four elements in the array, and these will
    all contain the enum value that corresponds to the type of the shape.

    We use a QBasicTimer to control the rate at which pieces fall toward the bottom
    of the playing area. This allows us to provide an implementation of
    \l{QObject::}{timerEvent()} that we can use to update the widget.

    \section1 TetrixBoard Class Implementation

    In the constructor, we customize the frame style of the widget, ensure that
    keyboard input will be received by the widget by using Qt::StrongFocus for the
    focus policy, and initialize the game state:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 0

    The first (next) piece is also set up with a random shape.

    The \c setNextPieceLabel() function is used to pass in an externally-constructed
    label to the board, so that it can be shown alongside the playing area:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 1

    We provide a reasonable size hint and minimum size hint for the board, based on
    the size of the space for each block in the playing area:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 2
    \snippet examples/widgets/tetrix/tetrixboard.cpp 3

    By using a minimum size hint, we indicate to the layout in the parent widget
    that the board should not shrink below a minimum size.

    A new game is started when the \c start() slot is called. This resets the
    game's state, the player's score and level, and the contents of the board:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 4

    We also emit signals to inform other components of these changes before creating
    a new piece that is ready to be dropped into the playing area. We start the
    timer that determines how often the piece drops down one row on the board.

    The \c pause() slot is used to temporarily stop the current game by stopping the
    internal timer:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 5
    \snippet examples/widgets/tetrix/tetrixboard.cpp 6

    We perform checks to ensure that the game can only be paused if it is already
    running and not already paused.

    The \c paintEvent() function is straightforward to implement. We begin by
    calling the base class's implementation of \l{QWidget::}{paintEvent()} before
    constructing a QPainter for use on the board:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 7

    Since the board is a subclass of QFrame, we obtain a QRect that covers the area
    \e inside the frame decoration before drawing our own content.

    If the game is paused, we want to hide the existing state of the board and
    show some text. We achieve this by painting text onto the widget and returning
    early from the function. The rest of the painting is performed after this point.

    The position of the top of the board is found by subtracting the total height
    of each space on the board from the bottom of the frame's internal rectangle.
    For each space on the board that is occupied by a piece, we call the
    \c drawSquare() function to draw a block at that position.

    \snippet examples/widgets/tetrix/tetrixboard.cpp 8
    \snippet examples/widgets/tetrix/tetrixboard.cpp 9

    Spaces that are not occupied by blocks are left blank.

    Unlike the existing pieces on the board, the current piece is drawn
    block-by-block at its current position:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 10
    \snippet examples/widgets/tetrix/tetrixboard.cpp 11
    \snippet examples/widgets/tetrix/tetrixboard.cpp 12

    The \c keyPressEvent() handler is called whenever the player presses a key while
    the \c TetrixBoard widget has the keyboard focus.

    \snippet examples/widgets/tetrix/tetrixboard.cpp 13

    If there is no current game, the game is running but paused, or if there is no
    current shape to control, we simply pass on the event to the base class.

    We check whether the event is about any of the keys that the player uses to
    control the current piece and, if so, we call the relevant function to handle
    the input:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 14

    In the case where the player presses a key that we are not interested in, we
    again pass on the event to the base class's implementation of
    \l{QWidget::}{keyPressEvent()}.

    The \c timerEvent() handler is called every time the class's QBasicTimer
    instance times out. We need to check that the event we receive corresponds to
    our timer. If it does, we can update the board:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 15
    \snippet examples/widgets/tetrix/tetrixboard.cpp 16
    \snippet examples/widgets/tetrix/tetrixboard.cpp 17

    If a row (or line) has just been filled, we create a new piece and reset the
    timer; otherwise we move the current piece down by one row. We let the base
    class handle other timer events that we receive.

    The \c clearBoard() function simply fills the board with the
    \c TetrixShape::NoShape value:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 18

    The \c dropDown() function moves the current piece down as far as possible on
    the board, either until it is touching the bottom of the playing area or it is
    stacked on top of another piece:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 19
    \snippet examples/widgets/tetrix/tetrixboard.cpp 20

    The number of rows the piece has dropped is recorded and passed to the
    \c pieceDropped() function so that the player's score can be updated.

    The \c oneLineDown() function is used to move the current piece down by one row
    (line), either when the user presses the \gui{D} key or when the piece is
    scheduled to move:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 21

    If the piece cannot drop down by one line, we call the \c pieceDropped() function
    with zero as the argument to indicate that it cannot fall any further, and that
    the player should receive no extra points for the fall.

    The \c pieceDropped() function itself is responsible for awarding points to the
    player for positioning the current piece, checking for full rows on the board
    and, if no lines have been removed, creating a new piece to replace the current
    one:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 22
    \snippet examples/widgets/tetrix/tetrixboard.cpp 23

    We call \c removeFullLines() each time a piece has been dropped. This scans
    the board from bottom to top, looking for blank spaces on each row.

    \snippet examples/widgets/tetrix/tetrixboard.cpp 24
    \snippet examples/widgets/tetrix/tetrixboard.cpp 25
    \snippet examples/widgets/tetrix/tetrixboard.cpp 26
    \snippet examples/widgets/tetrix/tetrixboard.cpp 27

    If a row contains no blank spaces, the rows above it are copied down by one row
    to compress the stack of pieces, the top row on the board is cleared, and the
    number of full lines found is incremented.

    \snippet examples/widgets/tetrix/tetrixboard.cpp 28
    \snippet examples/widgets/tetrix/tetrixboard.cpp 29

    If some lines have been removed, the player's score and the total number of lines
    removed are updated. The \c linesRemoved() and \c scoreChanged() signals are
    emitted to send these new values to other widgets in the window.

    Additionally, we set the timer to elapse after half a second, set the
    \c isWaitingAfterLine flag to indicate that lines have been removed, unset
    the piece's shape to ensure that it is not drawn, and update the widget.
    The next time that the \c timerEvent() handler is called, a new piece will be
    created and the game will continue.

    The \c newPiece() function places the next available piece at the top of the
    board, and creates a new piece with a random shape:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 30
    \snippet examples/widgets/tetrix/tetrixboard.cpp 31

    We place a new piece in the middle of the board at the top. The game is over if
    the piece can't move, so we unset its shape to prevent it from being drawn, stop
    the timer, and unset the \c isStarted flag.

    The \c showNextPiece() function updates the label that shows the next piece to
    be dropped:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 32
    \snippet examples/widgets/tetrix/tetrixboard.cpp 33

    We draw the piece's component blocks onto a pixmap that is then set on the label.

    The \c tryMove() function is used to determine whether a piece can be positioned
    at the specified coordinates:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 34

    We examine the spaces on the board that the piece needs to occupy and, if they
    are already occupied by other pieces, we return \c false to indicate that the
    move has failed.

    \snippet examples/widgets/tetrix/tetrixboard.cpp 35

    If the piece could be placed on the board at the desired location, we update the
    current piece and its position, update the widget, and return \c true to indicate
    success.

    The \c drawSquare() function draws the blocks (normally squares) that make up
    each piece using different colors for pieces with different shapes:

    \snippet examples/widgets/tetrix/tetrixboard.cpp 36

    We obtain the color to use from a look-up table that relates each shape to an
    RGB value, and use the painter provided to draw the block at the specified
    coordinates.
*/
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Copyright by The HDF Group.                                               *
 * Copyright by the Board of Trustees of the University of Illinois.         *
 * All rights reserved.                                                      *
 *                                                                           *
 * This file is part of HDF5.  The full HDF5 copyright notice, including     *
 * terms governing use, modification, and redistribution, is contained in    *
 * the files COPYING and Copyright.html.  COPYING can be found at the root   *
 * of the source code distribution tree; Copyright.html can be found at the  *
 * root level of an installed copy of the electronic HDF5 document set and   *
 * is linked from the top-level documents page.  It can also be found at     *
 * http://hdfgroup.org/HDF5/doc/Copyright.html.  If you do not have          *
 * access to either file, you may request a copy from help@hdfgroup.org.     *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#define H5A_PACKAGE             /*prevent warning from including H5Apkg   */
#define H5O_PACKAGE		/*suppress error about including H5Opkg	  */
#define H5S_PACKAGE	        /*suppress error about including H5Spkg	  */


#include "H5private.h"		/* Generic Functions			*/
#include "H5Apkg.h"		/* Attributes				*/
#include "H5Dprivate.h"		/* Datasets				*/
#include "H5Eprivate.h"		/* Error handling		  	*/
#include "H5Iprivate.h"		/* IDs			  		*/
#include "H5MMprivate.h"	/* Memory management			*/
#include "H5Opkg.h"             /* Object headers			*/
#include "H5Spkg.h"		/* Dataspaces				*/
#include "H5SMprivate.h"	/* Shared Object Header Messages	*/

/* PRIVATE PROTOTYPES */
static herr_t H5O_attr_encode(H5F_t *f, uint8_t *p, const void *mesg);
static void *H5O_attr_decode(H5F_t *f, hid_t dxpl_id, unsigned mesg_flags,
    unsigned *ioflags, const uint8_t *p);
static void *H5O_attr_copy(const void *_mesg, void *_dest);
static size_t H5O_attr_size(const H5F_t *f, const void *_mesg);
static herr_t H5O_attr_free(void *mesg);
static herr_t H5O_attr_pre_copy_file(H5F_t *file_src, const void *mesg_src,
    hbool_t *deleted, const H5O_copy_t *cpy_info, void *udata);
static void *H5O_attr_copy_file(H5F_t *file_src, const H5O_msg_class_t *mesg_type,
    void *native_src, H5F_t *file_dst, hbool_t *recompute_size,
    H5O_copy_t *cpy_info, void *udata, hid_t dxpl_id);
static herr_t H5O_attr_post_copy_file(const H5O_loc_t *src_oloc,
    const void *mesg_src, H5O_loc_t *dst_oloc, void *mesg_dst, hid_t dxpl_id,
    H5O_copy_t *cpy_info);
static herr_t H5O_attr_get_crt_index(const void *_mesg, H5O_msg_crt_idx_t *crt_idx);
static herr_t H5O_attr_set_crt_index(void *_mesg, H5O_msg_crt_idx_t crt_idx);
static herr_t H5O_attr_debug(H5F_t *f, hid_t dxpl_id, const void *_mesg,
			      FILE * stream, int indent, int fwidth);

/* Set up & include shared message "interface" info */
#define H5O_SHARED_TYPE			H5O_MSG_ATTR
#define H5O_SHARED_DECODE		H5O_attr_shared_decode
#define H5O_SHARED_DECODE_REAL		H5O_attr_decode
#define H5O_SHARED_ENCODE		H5O_attr_shared_encode
#define H5O_SHARED_ENCODE_REAL		H5O_attr_encode
#define H5O_SHARED_SIZE			H5O_attr_shared_size
#define H5O_SHARED_SIZE_REAL		H5O_attr_size
#define H5O_SHARED_DELETE		H5O_attr_shared_delete
#define H5O_SHARED_DELETE_REAL		H5O_attr_delete
#define H5O_SHARED_LINK			H5O_attr_shared_link
#define H5O_SHARED_LINK_REAL		H5O_attr_link
#define H5O_SHARED_COPY_FILE		H5O_attr_shared_copy_file
#define H5O_SHARED_COPY_FILE_REAL	H5O_attr_copy_file
#define H5O_SHARED_POST_COPY_FILE	H5O_attr_shared_post_copy_file
#define H5O_SHARED_POST_COPY_FILE_REAL	H5O_attr_post_copy_file
#define H5O_SHARED_DEBUG		H5O_attr_shared_debug
#define H5O_SHARED_DEBUG_REAL		H5O_attr_debug
#include "H5Oshared.h"			/* Shared Object Header Message Callbacks */

/* This message derives from H5O message class */
const H5O_msg_class_t H5O_MSG_ATTR[1] = {{
    H5O_ATTR_ID,		/* message id number            */
    "attribute",		/* message name for debugging   */
    sizeof(H5A_t),		/* native message size          */
    H5O_SHARE_IS_SHARABLE,	/* messages are sharable?       */
    H5O_attr_shared_decode,	/* decode message               */
    H5O_attr_shared_encode,	/* encode message               */
    H5O_attr_copy,		/* copy the native value        */
    H5O_attr_shared_size,	/* size of raw message          */
    H5O_attr_reset,	        /* reset method                 */
    H5O_attr_free,	        /* free method			*/
    H5O_attr_shared_delete,	/* file delete method		*/
    H5O_attr_shared_link,	/* link method			*/
    NULL,			/*set share method		*/
    NULL,		    	/*can share method		*/
    H5O_attr_pre_copy_file,	/* pre copy native value to file */
    H5O_attr_shared_copy_file,	/* copy native value to file    */
    H5O_attr_shared_post_copy_file,	/* post copy native value to file    */
    H5O_attr_get_crt_index,	/* get creation index		*/
    H5O_attr_set_crt_index,	/* set creation index		*/
    H5O_attr_shared_debug	/* debug the message            */
}};

/* Flags for attribute flag encoding */
#define H5O_ATTR_FLAG_TYPE_SHARED       0x01
#define H5O_ATTR_FLAG_SPACE_SHARED      0x02
#define H5O_ATTR_FLAG_ALL               0x03

/* Declare external the free list for H5S_t's */
H5FL_EXTERN(H5S_t);

/* Declare external the free list for H5S_extent_t's */
H5FL_EXTERN(H5S_extent_t);


/*--------------------------------------------------------------------------
 NAME
    H5O_attr_decode
 PURPOSE
    Decode a attribute message and return a pointer to a memory struct
        with the decoded information
 USAGE
    void *H5O_attr_decode(f, dxpl_id, mesg_flags, p)
        H5F_t *f;               IN: pointer to the HDF5 file struct
        hid_t dxpl_id;          IN: DXPL for any I/O
        unsigned mesg_flags;    IN: Message flags to influence decoding
        const uint8_t *p;       IN: the raw information buffer
 RETURNS
    Pointer to the new message in native order on success, NULL on failure
 DESCRIPTION
        This function decodes the "raw" disk form of a attribute message
    into a struct in memory native format.  The struct is allocated within this
    function using malloc() and is returned to the caller.
--------------------------------------------------------------------------*/
static void *
H5O_attr_decode(H5F_t *f, hid_t dxpl_id, unsigned UNUSED mesg_flags,
    unsigned *ioflags, const uint8_t *p)
{
    H5A_t		*attr = NULL;
    H5S_extent_t	*extent;	/*extent dimensionality information  */
    size_t		name_len;   	/*attribute name length */
    unsigned            flags = 0;      /* Attribute flags */
    H5A_t		*ret_value;     /* Return value */

    FUNC_ENTER_NOAPI_NOINIT(H5O_attr_decode)

    /* check args */
    HDassert(f);
    HDassert(p);

    if(NULL == (attr = H5FL_CALLOC(H5A_t)))
	HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL, "memory allocation failed")

    if(NULL == (attr->shared = H5FL_CALLOC(H5A_shared_t)))
        HGOTO_ERROR(H5E_FILE, H5E_NOSPACE, NULL, "can't allocate shared attr structure")

    /* Version number */
    attr->shared->version = *p++;
    if(attr->shared->version < H5O_ATTR_VERSION_1 || attr->shared->version > H5O_ATTR_VERSION_LATEST)
	HGOTO_ERROR(H5E_ATTR, H5E_CANTLOAD, NULL, "bad version number for attribute message")

    /* Get the flags byte if we have a later version of the attribute */
    if(attr->shared->version >= H5O_ATTR_VERSION_2) {
        flags = *p++;

        /* Check for unknown flag */
        if(flags & (unsigned)~H5O_ATTR_FLAG_ALL)
            HGOTO_ERROR(H5E_ATTR, H5E_CANTLOAD, NULL, "unknown flag for attribute message")
    } /* end if */
    else
        p++;    /* Byte is unused when version<2 */

    /*
     * Decode the sizes of the parts of the attribute.  The sizes stored in
     * the file are exact but the parts are aligned on 8-byte boundaries.
     */
    UINT16DECODE(p, name_len); /*including null*/
    UINT16DECODE(p, attr->shared->dt_size);
    UINT16DECODE(p, attr->shared->ds_size);

    /*
     * Decode the character encoding for the name for versions 3 or later,
     * as well as some reserved bytes.
     */
    if(attr->shared->version >= H5O_ATTR_VERSION_3)
        attr->shared->encoding = *p++;

    /* Decode and store the name */
    if(NULL == (attr->shared->name = H5MM_strdup((const char *)p)))
	HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL, "memory allocation failed")
    if(attr->shared->version < H5O_ATTR_VERSION_2)
        p += H5O_ALIGN_OLD(name_len);    /* advance the memory pointer */
    else
        p += name_len;    /* advance the memory pointer */

    /* Decode the attribute's datatype */
    if(NULL == (attr->shared->dt = (H5T_t *)(H5O_MSG_DTYPE->decode)(f, dxpl_id, ((flags & H5O_ATTR_FLAG_TYPE_SHARED) ? H5O_MSG_FLAG_SHARED : 0), ioflags, p)))
        HGOTO_ERROR(H5E_ATTR, H5E_CANTDECODE, NULL, "can't decode attribute datatype")
    if(attr->shared->version < H5O_ATTR_VERSION_2)
        p += H5O_ALIGN_OLD(attr->shared->dt_size);
    else
        p += attr->shared->dt_size;

    /* decode the attribute dataspace.  It can be shared in versions >= 3
     * What's actually shared, though, is only the extent.
     */
    if(NULL == (attr->shared->ds = H5FL_CALLOC(H5S_t)))
	HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL, "memory allocation failed")

    /* Decode attribute's dataspace extent */
    if((extent = (H5S_extent_t *)(H5O_MSG_SDSPACE->decode)(f, dxpl_id, ((flags & H5O_ATTR_FLAG_SPACE_SHARED) ? H5O_MSG_FLAG_SHARED : 0), ioflags, p)) == NULL)
        HGOTO_ERROR(H5E_ATTR, H5E_CANTDECODE, NULL, "can't decode attribute dataspace")

    /* Copy the extent information to the dataspace */
    HDmemcpy(&(attr->shared->ds->extent), extent, sizeof(H5S_extent_t));

    /* Release temporary extent information */
    (void)H5FL_FREE(H5S_extent_t, extent);

    /* Default to entire dataspace being selected */
    if(H5S_select_all(attr->shared->ds, FALSE) < 0)
        HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSET, NULL, "unable to set all selection")

    if(attr->shared->version < H5O_ATTR_VERSION_2)
        p += H5O_ALIGN_OLD(attr->shared->ds_size);
    else
        p += attr->shared->ds_size;

    /* Compute the size of the data */
    H5_ASSIGN_OVERFLOW(attr->shared->data_size, H5S_GET_EXTENT_NPOINTS(attr->shared->ds) * H5T_get_size(attr->shared->dt), hsize_t, size_t);

    /* Go get the data */
    if(attr->shared->data_size) {
        if(NULL == (attr->shared->data = H5FL_BLK_MALLOC(attr_buf, attr->shared->data_size)))
            HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL, "memory allocation failed")
        HDmemcpy(attr->shared->data, p, attr->shared->data_size);
    } /* end if */

    /* Indicate that the fill values aren't to be written out */
    attr->shared->initialized = 1;

    /* Increment the reference count for this object header message in cache(compact
       storage) or for the object from dense storage. */
    attr->shared->nrefs++;

    /* Set return value */
    ret_value = attr;

done:
    FUNC_LEAVE_NOAPI(ret_value)
} /* end H5O_attr_decode() */


/*--------------------------------------------------------------------------
 NAME
    H5O_attr_encode
 PURPOSE
    Encode a simple attribute message
 USAGE
    herr_t H5O_attr_encode(f, p, mesg)
        H5F_t *f;         IN: pointer to the HDF5 file struct
        const uint8 *p;         IN: the raw information buffer
        const void *mesg;       IN: Pointer to the simple datatype struct
 RETURNS
    Non-negative on success/Negative on failure
 DESCRIPTION
        This function encodes the native memory form of the attribute
    message in the "raw" disk form.
--------------------------------------------------------------------------*/
static herr_t
H5O_attr_encode(H5F_t *f, uint8_t *p, const void *mesg)
{
    const H5A_t *attr = (const H5A_t *) mesg;
    size_t      name_len;   /* Attribute name length */
    htri_t      is_type_shared;    /* Flag to indicate that a shared datatype is used for this attribute */
    htri_t      is_space_shared;   /* Flag to indicate that a shared dataspace is used for this attribute */
    unsigned    flags = 0;      /* Attribute flags */
    herr_t      ret_value = SUCCEED;      /* Return value */

    FUNC_ENTER_NOAPI_NOINIT(H5O_attr_encode)

    /* check args */
    HDassert(f);
    HDassert(p);
    HDassert(attr);

    /* Check whether datatype and dataspace are shared */
    if((is_type_shared = H5O_msg_is_shared(H5O_DTYPE_ID, attr->shared->dt)) < 0)
        HGOTO_ERROR(H5E_OHDR, H5E_BADMESG, FAIL, "can't determine if datatype is shared")

    if((is_space_shared = H5O_msg_is_shared(H5O_SDSPACE_ID, attr->shared->ds)) < 0)
        HGOTO_ERROR(H5E_OHDR, H5E_BADMESG, FAIL, "can't determine if dataspace is shared")

    /* Encode Version */
    *p++ = attr->shared->version;

    /* Set attribute flags if version >1 */
    if(attr->shared->version >= H5O_ATTR_VERSION_2) {
        flags = (is_type_shared ? H5O_ATTR_FLAG_TYPE_SHARED : 0 );
        flags |= (is_space_shared ? H5O_ATTR_FLAG_SPACE_SHARED : 0);
        *p++ = flags;    /* Set flags for attribute */
    } /* end if */
    else
        *p++ = 0; /* Reserved, for version <2 */

    /*
     * Encode the lengths of the various parts of the attribute message. The
     * encoded lengths are exact but we pad each part except the data to be a
     * multiple of eight bytes (in the first version).
     */
    name_len = HDstrlen(attr->shared->name) + 1;
    UINT16ENCODE(p, name_len);
    UINT16ENCODE(p, attr->shared->dt_size);
    UINT16ENCODE(p, attr->shared->ds_size);

    /* The character encoding for the attribute's name, in later versions */
    if(attr->shared->version >= H5O_ATTR_VERSION_3)
        *p++ = attr->shared->encoding;

    /* Write the name including null terminator */
    HDmemcpy(p, attr->shared->name, name_len);
    if(attr->shared->version < H5O_ATTR_VERSION_2) {
        /* Pad to the correct number of bytes */
        HDmemset(p + name_len, 0, H5O_ALIGN_OLD(name_len) - name_len);
        p += H5O_ALIGN_OLD(name_len);
    } /* end if */
    else
        p += name_len;

    /* encode the attribute datatype */
    if((H5O_MSG_DTYPE->encode)(f, FALSE, p, attr->shared->dt) < 0)
        HGOTO_ERROR(H5E_ATTR, H5E_CANTENCODE, FAIL, "can't encode attribute datatype")

    if(attr->shared->version < H5O_ATTR_VERSION_2) {
        HDmemset(p + attr->shared->dt_size, 0, H5O_ALIGN_OLD(attr->shared->dt_size) - attr->shared->dt_size);
        p += H5O_ALIGN_OLD(attr->shared->dt_size);
    } /* end if */
    else
        p += attr->shared->dt_size;

    /* encode the attribute dataspace */
    if((H5O_MSG_SDSPACE->encode)(f, FALSE, p, &(attr->shared->ds->extent)) < 0)
        HGOTO_ERROR(H5E_ATTR, H5E_CANTENCODE, FAIL, "can't encode attribute dataspace")

    if(attr->shared->version < H5O_ATTR_VERSION_2) {
        HDmemset(p + attr->shared->ds_size, 0, H5O_ALIGN_OLD(attr->shared->ds_size) - attr->shared->ds_size);
        p += H5O_ALIGN_OLD(attr->shared->ds_size);
    } /* end if */
    else
        p += attr->shared->ds_size;

    /* Store attribute data.  If there's no data, store 0 as fill value. */
    if(attr->shared->data)
        HDmemcpy(p, attr->shared->data, attr->shared->data_size);
    else
        HDmemset(p, 0, attr->shared->data_size);

done:
    FUNC_LEAVE_NOAPI(ret_value);
} /* end H5O_attr_encode() */


/*--------------------------------------------------------------------------
 NAME
    H5O_attr_copy
 PURPOSE
    Copies a message from MESG to DEST, allocating DEST if necessary.
 USAGE
    void *H5O_attr_copy(mesg, dest)
        const void *mesg;       IN: Pointer to the source attribute struct
        const void *dest;       IN: Pointer to the destination attribute struct
 RETURNS
    Pointer to DEST on success, NULL on failure
 DESCRIPTION
        This function copies a native (memory) attribute message,
    allocating the destination structure if necessary.
--------------------------------------------------------------------------*/
static void *
H5O_attr_copy(const void *_src, void *_dst)
{
    void *ret_value;            /* Return value */

    FUNC_ENTER_NOAPI_NOINIT(H5O_attr_copy)

    /* check args */
    HDassert(_src);

    /* copy */
    if(NULL == (ret_value = (H5A_t *)H5A_copy((H5A_t *)_dst, (const H5A_t *)_src)))
        HGOTO_ERROR(H5E_ATTR, H5E_CANTINIT, NULL, "can't copy attribute")

done:
    FUNC_LEAVE_NOAPI(ret_value)
} /* end H5O_attr_copy() */


/*--------------------------------------------------------------------------
 NAME
    H5O_attr_size
 PURPOSE
    Return the raw message size in bytes
 USAGE
    size_t H5O_attr_size(f, mesg)
        H5F_t *f;         IN: pointer to the HDF5 file struct
        const void *mesg;     IN: Pointer to the source attribute struct
 RETURNS
    Size of message on success, 0 on failure
 DESCRIPTION
        This function returns the size of the raw attribute message on
    success.  (Not counting the message type or size fields, only the data
    portion of the message).  It doesn't take into account alignment.
--------------------------------------------------------------------------*/
static size_t
H5O_attr_size(const H5F_t UNUSED *f, const void *_mesg)
{
    const H5A_t         *attr = (const H5A_t *)_mesg;
    size_t		name_len;
    size_t		ret_value = 0;

    FUNC_ENTER_NOAPI_NOINIT_NOFUNC(H5O_attr_size)

    HDassert(attr);

    /* Common size information */
    ret_value = 1 +				/*version               */
                1 +				/*reserved/flags	*/
                2 +				/*name size inc. null	*/
                2 +				/*type size		*/
                2; 				/*space size		*/

    /* Length of attribute name */
    name_len = HDstrlen(attr->shared->name) + 1;

    /* Version-specific size information */
    if(attr->shared->version == H5O_ATTR_VERSION_1)
        ret_value += H5O_ALIGN_OLD(name_len) +	/*attribute name	*/
                    H5O_ALIGN_OLD(attr->shared->dt_size) +	/*datatype		*/
                    H5O_ALIGN_OLD(attr->shared->ds_size) +	/*dataspace		*/
                    attr->shared->data_size;		/*the data itself	*/
    else if(attr->shared->version == H5O_ATTR_VERSION_2)
        ret_value += name_len	+		/*attribute name	*/
                    attr->shared->dt_size +		/*datatype		*/
                    attr->shared->ds_size +		/*dataspace		*/
                    attr->shared->data_size;		/*the data itself	*/
    else if(attr->shared->version == H5O_ATTR_VERSION_3)
        ret_value += 1 +                        /*character encoding    */
                    name_len	+		/*attribute name	*/
                    attr->shared->dt_size +		/*datatype		*/
                    attr->shared->ds_size +		/*dataspace		*/
                    attr->shared->data_size;		/*the data itself	*/
    else
        HDassert(0 && "Bad attribute version");

    FUNC_LEAVE_NOAPI(ret_value)
} /* end H5O_attr_size() */


/*-------------------------------------------------------------------------
 * Function:    H5O_attr_reset
 *
 * Purpose:     Frees resources within a attribute message, but doesn't free
 *              the message itself.
 *
 * Return:      Non-negative on success/Negative on failure
 *
 * Programmer:  Robb Matzke
 *              Tuesday, December  9, 1997
 *
 * Modification:Raymond Lu
 *              25 June 2008
 *              Made this function empty.  The freeing action is actually
 *              done in H5O_attr_free (see H5O_msg_free_real).  But this
 *              empty reset function needs to be here.  Otherwise, the
 *              caller function H5O_msg_reset_real will zero-set the whole
 *              message.
 *-------------------------------------------------------------------------
 */
herr_t
H5O_attr_reset(void UNUSED *_mesg)
{
    FUNC_ENTER_NOAPI_NOINIT_NOFUNC(H5O_attr_reset)

    FUNC_LEAVE_NOAPI(SUCCEED)
} /* end H5O_attr_reset() */


/*-------------------------------------------------------------------------
 * Function:	H5O_attr_free
 *
 * Purpose:	Free's the message
 *
 * Return:	Non-negative on success/Negative on failure
 *
 * Programmer:	Quincey Koziol
 *              Thursday, November 18, 2004
 *
 * Modification:Raymond Lu
 *              4 June 2008
 *              Let this function call H5A_close in turn.
 *
 *-------------------------------------------------------------------------
 */
static herr_t
H5O_attr_free(void *mesg)
{
    H5A_t *attr = (H5A_t *)mesg;
    herr_t ret_value = SUCCEED;   /* Return value */

    FUNC_ENTER_NOAPI_NOINIT(H5O_attr_free)

    HDassert(mesg);

    if(H5A_close(attr) < 0)
        HGOTO_ERROR(H5E_ATTR, H5E_CANTCLOSEOBJ, FAIL, "unable to close attribute object")

done:
    FUNC_LEAVE_NOAPI(ret_value)
} /* end H5O_attr_free() */


/*-------------------------------------------------------------------------
 * Function:    H5O_attr_delete
 *
 * Purpose:     Free file space referenced by message
 *
 * Return:      Non-negative on success/Negative on failure
 *
 * Programmer:  Quincey Koziol
 *              Friday, September 26, 2003
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5O_attr_delete(H5F_t *f, hid_t dxpl_id, H5O_t *oh, void *_mesg)
{
    H5A_t *attr = (H5A_t *) _mesg;
    herr_t ret_value = SUCCEED;   /* Return value */

    FUNC_ENTER_NOAPI_NOINIT(H5O_attr_delete)

    /* check args */
    HDassert(f);
    HDassert(attr);

    /* Decrement reference count on datatype in file */
    if((H5O_MSG_DTYPE->del)(f, dxpl_id, oh, attr->shared->dt) < 0)
        HGOTO_ERROR(H5E_ATTR, H5E_LINKCOUNT, FAIL, "unable to adjust datatype link count")

    /* Decrement reference count on dataspace in file */
    if((H5O_MSG_SDSPACE->del)(f, dxpl_id, oh, attr->shared->ds) < 0)
        HGOTO_ERROR(H5E_ATTR, H5E_LINKCOUNT, FAIL, "unable to adjust dataspace link count")

done:
    FUNC_LEAVE_NOAPI(ret_value)
} /* end H5O_attr_delete() */


/*-------------------------------------------------------------------------
 * Function:    H5O_attr_link
 *
 * Purpose:     Increment reference count on any objects referenced by
 *              message
 *
 * Return:      Non-negative on success/Negative on failure
 *
 * Programmer:  Quincey Koziol
 *              Friday, September 26, 2003
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5O_attr_link(H5F_t *f, hid_t dxpl_id, H5O_t *oh, void *_mesg)
{
    H5A_t *attr = (H5A_t *) _mesg;
    herr_t ret_value = SUCCEED;   /* Return value */

    FUNC_ENTER_NOAPI_NOINIT(H5O_attr_link)

    /* check args */
    HDassert(f);
    HDassert(attr);

    /* Re-share attribute's datatype and dataspace to increment their
     * reference count if they're shared.
     * Otherwise they may be deleted when the attribute
     * message is deleted.
     */
    /* Increment reference count on datatype & dataspace in file */
    if((H5O_MSG_DTYPE->link)(f, dxpl_id, oh, attr->shared->dt) < 0)
        HGOTO_ERROR(H5E_ATTR, H5E_LINKCOUNT, FAIL, "unable to adjust datatype link count")
    if((H5O_MSG_SDSPACE->link)(f, dxpl_id, oh, attr->shared->ds) < 0)
        HGOTO_ERROR(H5E_ATTR, H5E_LINKCOUNT, FAIL, "unable to adjust dataspace link count")

done:
    FUNC_LEAVE_NOAPI(ret_value)
} /* end H5O_attr_link() */


/*-------------------------------------------------------------------------
 * Function:    H5O_attr_pre_copy_file
 *
 * Purpose:     Perform any necessary actions before copying message between
 *              files for attribute messages.
 *
 * Return:      Success:        Non-negative
 *
 *              Failure:        Negative
 *
 * Programmer:  Quincey Koziol
 *              Monday, June 26, 2006
 *
 *-------------------------------------------------------------------------
 */
static herr_t
H5O_attr_pre_copy_file(H5F_t UNUSED *file_src, const void UNUSED *native_src,
    hbool_t *deleted, const H5O_copy_t *cpy_info, void UNUSED *udata)
{
    FUNC_ENTER_NOAPI_NOINIT_NOFUNC(H5O_attr_pre_copy_file)

    /* check args */
    HDassert(deleted);
    HDassert(cpy_info);

    /* If we are not copying attributes into the destination file, indicate
     *  that this message should be deleted.
     */
    if(cpy_info->copy_without_attr)
        *deleted = TRUE;

    FUNC_LEAVE_NOAPI(SUCCEED)
} /* end H5O_attr_pre_copy_file() */


/*-------------------------------------------------------------------------
 * Function:    H5O_attr_copy_file
 *
 * Purpose:     Copies a message from _MESG to _DEST in file
 *
 * Return:      Success:        Ptr to _DEST
 *
 *              Failure:        NULL
 *
 * Programmer:  Quincey Koziol
 *              November 1, 2005
 *
 *-------------------------------------------------------------------------
 */
static void *
H5O_attr_copy_file(H5F_t UNUSED *file_src, const H5O_msg_class_t UNUSED *mesg_type,
    void *native_src, H5F_t *file_dst, hbool_t *recompute_size,
    H5O_copy_t *cpy_info, void UNUSED *udata, hid_t dxpl_id)
{
    H5A_t        *attr_src = (H5A_t *)native_src;
    H5A_t        *attr_dst = NULL;

    /* for dataype conversion */
    hid_t       tid_src = -1;           /* Datatype ID for source datatype */
    hid_t       tid_dst = -1;           /* Datatype ID for destination datatype */
    hid_t       tid_mem = -1;           /* Datatype ID for memory datatype */
    void       *buf = NULL;             /* Buffer for copying data */
    void       *reclaim_buf = NULL;     /* Buffer for reclaiming data */
    hid_t       buf_sid = -1;           /* ID for buffer dataspace */

    void        *ret_value;             /* Return value */

    FUNC_ENTER_NOAPI_NOINIT(H5O_attr_copy_file)

    /* check args */
    HDassert(attr_src);
    HDassert(file_dst);
    HDassert(cpy_info);
    HDassert(!cpy_info->copy_without_attr);

    /* Allocate space for the destination message */
    if(NULL == (attr_dst = H5FL_CALLOC(H5A_t)))
        HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL, "memory allocation failed")

    /* Copy the top level of the attribute */
    *attr_dst = *attr_src;

    if(NULL == (attr_dst->shared = H5FL_CALLOC(H5A_shared_t)))
        HGOTO_ERROR(H5E_FILE, H5E_NOSPACE, NULL, "can't allocate shared attr structure")

    /* Don't have an opened group location for copy */
    H5O_loc_reset(&(attr_dst->shared->oloc));
    H5G_name_reset(&(attr_dst->path));
    attr_dst->obj_opened = FALSE;

    /* Reference count for the header message in the cache */
    attr_dst->shared->nrefs = 1;

    /* Copy attribute's name */
    attr_dst->shared->name = H5MM_strdup(attr_src->shared->name);
    HDassert(attr_dst->shared->name);

    /* Copy attribute's datatype */
    /* (Start destination datatype as transient, even if source is named) */
    if(NULL == (attr_dst->shared->dt = H5T_copy(attr_src->shared->dt, H5T_COPY_ALL)))
        HGOTO_ERROR(H5E_OHDR, H5E_CANTCOPY, NULL, "cannot copy datatype")

    /* Set the location of the destination datatype */
    if(H5T_set_loc(attr_dst->shared->dt, file_dst, H5T_LOC_DISK) < 0)
        HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, NULL, "cannot mark datatype on disk")

    /* Check for named datatype being copied */
    if(H5T_committed(attr_src->shared->dt)) {
        H5O_loc_t         *src_oloc;           /* Pointer to source datatype's object location */
        H5O_loc_t         *dst_oloc;           /* Pointer to dest. datatype's object location */

        /* Get group entries for source & destination */
        src_oloc = H5T_oloc(attr_src->shared->dt);
        HDassert(src_oloc);
        dst_oloc = H5T_oloc(attr_dst->shared->dt);
        HDassert(dst_oloc);

        /* Reset object location for new object */
        H5O_loc_reset(dst_oloc);
        dst_oloc->file = file_dst;

        /* Copy the shared object from source to destination */
        if(H5O_copy_header_map(src_oloc, dst_oloc, dxpl_id, cpy_info, FALSE) < 0)
            HGOTO_ERROR(H5E_OHDR, H5E_CANTCOPY, NULL, "unable to copy object")

        /* Update shared message info from named datatype info */
        H5T_update_shared(attr_dst->shared->dt);
    } /* end if */
    else {
        /* If the datatype is not named, it may have been shared in the
         * source file's heap.  Un-share it for now. We'll try to shared
         * it in the destination file below.
         */
        if(H5O_msg_reset_share(H5O_DTYPE_ID, attr_dst->shared->dt) < 0)
            HGOTO_ERROR(H5E_OHDR, H5E_CANTINIT, NULL, "unable to reset datatype sharing")
    } /* end else */

    /* Copy the dataspace for the attribute */
    attr_dst->shared->ds = H5S_copy(attr_src->shared->ds, FALSE, FALSE);
    HDassert(attr_dst->shared->ds);

    /* Reset the dataspace's sharing in the source file before trying to share
     * it in the destination.
     */
    if(H5O_msg_reset_share(H5O_SDSPACE_ID, attr_dst->shared->ds) < 0)
        HGOTO_ERROR(H5E_OHDR, H5E_CANTINIT, NULL, "unable to reset dataspace sharing")


    /* Try to share both the datatype and dataset.  This does nothing if the
     * datatype is committed or sharing is disabled.
     */
    if(H5SM_try_share(file_dst, dxpl_id, NULL, H5O_DTYPE_ID, attr_dst->shared->dt, NULL) < 0)
	HGOTO_ERROR(H5E_OHDR, H5E_WRITEERROR, NULL, "can't share attribute datatype")
    if(H5SM_try_share(file_dst, dxpl_id, NULL, H5O_SDSPACE_ID, attr_dst->shared->ds, NULL) < 0)
	HGOTO_ERROR(H5E_OHDR, H5E_WRITEERROR, NULL, "can't share attribute dataspace")

    /* Compute the sizes of the datatype and dataspace. This is their raw
     * size unless they're shared.
     */
    attr_dst->shared->dt_size = H5O_msg_raw_size(file_dst, H5O_DTYPE_ID, FALSE, attr_dst->shared->dt);
    HDassert(attr_dst->shared->dt_size > 0);
    attr_dst->shared->ds_size = H5O_msg_raw_size(file_dst, H5O_SDSPACE_ID, FALSE, attr_dst->shared->ds);
    HDassert(attr_dst->shared->ds_size > 0);

    /* Check whether to recompute the size of the attribute */
    /* (happens when the datatype or dataspace changes sharing status) */
    if(attr_dst->shared->dt_size != attr_src->shared->dt_size || attr_dst->shared->ds_size != attr_src->shared->ds_size)
        *recompute_size = TRUE;

    /* Compute the size of the data */
    H5_ASSIGN_OVERFLOW(attr_dst->shared->data_size, H5S_GET_EXTENT_NPOINTS(attr_dst->shared->ds) * H5T_get_size(attr_dst->shared->dt), hsize_t, size_t);

    /* Copy (& convert) the data, if necessary */
    if(attr_src->shared->data) {
        if(NULL == (attr_dst->shared->data = H5FL_BLK_MALLOC(attr_buf, attr_dst->shared->data_size)))
            HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL, "memory allocation failed")

        /* Check if we need to convert data */
        if(H5T_detect_class(attr_src->shared->dt, H5T_VLEN) > 0) {
            H5T_path_t  *tpath_src_mem, *tpath_mem_dst;   /* Datatype conversion paths */
            H5T_t *dt_mem;              /* Memory datatype */
            size_t src_dt_size;         /* Source datatype size */
            size_t tmp_dt_size;         /* Temp. datatype size */
            size_t max_dt_size;         /* Max atatype size */
            H5S_t *buf_space;           /* Dataspace describing buffer */
            hsize_t buf_dim;            /* Dimension for buffer */
            size_t nelmts;              /* Number of elements in buffer */
            size_t buf_size;            /* Size of copy buffer */

            /* Create datatype ID for src datatype */
            if((tid_src = H5I_register(H5I_DATATYPE, attr_src->shared->dt, FALSE)) < 0)
                HGOTO_ERROR(H5E_DATATYPE, H5E_CANTREGISTER, NULL, "unable to register source file datatype")

            /* create a memory copy of the variable-length datatype */
            if(NULL == (dt_mem = H5T_copy(attr_src->shared->dt, H5T_COPY_TRANSIENT)))
                HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, NULL, "unable to copy")
            if((tid_mem = H5I_register(H5I_DATATYPE, dt_mem, FALSE)) < 0)
                HGOTO_ERROR(H5E_DATATYPE, H5E_CANTREGISTER, NULL, "unable to register memory datatype")

            /* create variable-length datatype at the destinaton file */
            if((tid_dst = H5I_register(H5I_DATATYPE, attr_dst->shared->dt, FALSE)) < 0)
                HGOTO_ERROR(H5E_DATATYPE, H5E_CANTREGISTER, NULL, "unable to register destination file datatype")

            /* Set up the conversion functions */
            if(NULL == (tpath_src_mem = H5T_path_find(attr_src->shared->dt, dt_mem, NULL, NULL, dxpl_id, FALSE)))
                HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, NULL, "unable to convert between src and mem datatypes")
            if(NULL == (tpath_mem_dst = H5T_path_find(dt_mem, attr_dst->shared->dt, NULL, NULL, dxpl_id, FALSE)))
                HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, NULL, "unable to convert between mem and dst datatypes")

            /* Determine largest datatype size */
            if(0 == (src_dt_size = H5T_get_size(attr_src->shared->dt)))
                HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, NULL, "unable to determine datatype size")
            if(0 == (tmp_dt_size = H5T_get_size(dt_mem)))
                HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, NULL, "unable to determine datatype size")
            max_dt_size = MAX(src_dt_size, tmp_dt_size);
            if(0 == (tmp_dt_size = H5T_get_size(attr_dst->shared->dt)))
                HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, NULL, "unable to determine datatype size")
            max_dt_size = MAX(max_dt_size, tmp_dt_size);

            /* Set number of whole elements that fit in buffer */
            if(0 == (nelmts = attr_src->shared->data_size / src_dt_size))
                HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, NULL, "element size too large")

            /* Set up number of bytes to copy, and initial buffer size */
            buf_size = nelmts * max_dt_size;

            /* Create dataspace for number of elements in buffer */
            buf_dim = nelmts;

            /* Create the space and set the initial extent */
            if(NULL == (buf_space = H5S_create_simple((unsigned)1, &buf_dim, NULL)))
                HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCREATE, NULL, "can't create simple dataspace")

            /* Atomize */
            if((buf_sid = H5I_register(H5I_DATASPACE, buf_space, FALSE)) < 0) {
                H5S_close(buf_space);
                HGOTO_ERROR(H5E_ATOM, H5E_CANTREGISTER, NULL, "unable to register dataspace ID")
            } /* end if */

            /* Allocate memory for recclaim buf */
            if(NULL == (reclaim_buf = H5FL_BLK_MALLOC(attr_buf, buf_size)))
                HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL, "memory allocation NULLed for raw data chunk")

            /* Allocate memory for copying the chunk */
            if(NULL == (buf = H5FL_BLK_MALLOC(attr_buf, buf_size)))
                HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL, "memory allocation NULLed for raw data chunk")

            HDmemcpy(buf, attr_src->shared->data, attr_src->shared->data_size);

            /* Convert from source file to memory */
            if(H5T_convert(tpath_src_mem, tid_src, tid_mem, nelmts, (size_t)0, (size_t)0, buf, NULL, dxpl_id) < 0)
                HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, NULL, "datatype conversion NULLed")

            HDmemcpy(reclaim_buf, buf, buf_size);

            /* Convert from memory to destination file */
            if(H5T_convert(tpath_mem_dst, tid_mem, tid_dst, nelmts, (size_t)0, (size_t)0, buf, NULL, dxpl_id) < 0)
                HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, NULL, "datatype conversion NULLed")

            HDmemcpy(attr_dst->shared->data, buf, attr_dst->shared->data_size);

            if(H5D_vlen_reclaim(tid_mem, buf_space, H5P_DATASET_XFER_DEFAULT, reclaim_buf) < 0)
                HGOTO_ERROR(H5E_DATASET, H5E_BADITER, NULL, "unable to reclaim variable-length data")
        }  /* end if */
        else {
            HDassert(attr_dst->shared->data_size == attr_src->shared->data_size);
            HDmemcpy(attr_dst->shared->data, attr_src->shared->data, attr_src->shared->data_size);
        } /* end else */
    } /* end if(attr_src->shared->data) */

    /* Recompute the version to encode the destination attribute */
    if(H5A_set_version(file_dst, attr_dst) < 0)
        HGOTO_ERROR(H5E_ATTR, H5E_CANTSET, NULL, "unable to update attribute version")

    /* Indicate that the fill values aren't to be written out */
    attr_dst->shared->initialized = TRUE;

    /* Set return value */
    ret_value = attr_dst;

done:
    if(buf_sid > 0)
        if(H5I_dec_ref(buf_sid, FALSE) < 0)
            HDONE_ERROR(H5E_ATTR, H5E_CANTFREE, NULL, "Can't decrement temporary dataspace ID")
    if(tid_src > 0)
        /* Don't decrement ID, we want to keep underlying datatype */
        if(H5I_remove(tid_src) == NULL)
            HDONE_ERROR(H5E_ATTR, H5E_CANTFREE, NULL, "Can't decrement temporary datatype ID")
    if(tid_dst > 0)
        /* Don't decrement ID, we want to keep underlying datatype */
        if(H5I_remove(tid_dst) == NULL)
            HDONE_ERROR(H5E_ATTR, H5E_CANTFREE, NULL, "Can't decrement temporary datatype ID")
    if(tid_mem > 0)
        /* Decrement the memory datatype ID, it's transient */
        if(H5I_dec_ref(tid_mem, FALSE) < 0)
            HDONE_ERROR(H5E_ATTR, H5E_CANTFREE, NULL, "Can't decrement temporary datatype ID")
    if(buf)
        buf = H5FL_BLK_FREE(attr_buf, buf);
    if(reclaim_buf)
        reclaim_buf = H5FL_BLK_FREE(attr_buf, reclaim_buf);

    /* Release destination attribute information on failure */
    if(!ret_value && attr_dst && H5A_close(attr_dst) < 0)
        HDONE_ERROR(H5E_ATTR, H5E_CANTFREE, NULL, "can't close attribute")

    FUNC_LEAVE_NOAPI(ret_value)
} /* H5O_attr_copy_file() */


/*-------------------------------------------------------------------------
 * Function:    H5O_attr_post_copy_file
 *
 * Purpose:     Finish copying a message from between files.
 *              We have to copy the values of a reference attribute in the
 *              post copy because H5O_post_copy_file() fails at the case that
 *              an object may have a reference attribute that points to the
 *              object itself.
 *
 * Return:      Non-negative on success/Negative on failure
 *
 * Programmer:  Peter Cao
 *              March 6, 2005
 *
 *-------------------------------------------------------------------------
 */
static herr_t
H5O_attr_post_copy_file(const H5O_loc_t *src_oloc, const void *mesg_src,
    H5O_loc_t *dst_oloc, void *mesg_dst, hid_t dxpl_id, H5O_copy_t *cpy_info)
{
    const H5A_t  *attr_src = (const H5A_t *)mesg_src;
    H5A_t  *attr_dst = (H5A_t *)mesg_dst;
    H5F_t  *file_src = src_oloc->file;
    H5F_t  *file_dst = dst_oloc->file;
    herr_t ret_value = SUCCEED;   /* Return value */


    FUNC_ENTER_NOAPI_NOINIT(H5O_attr_post_copy_file)

    /* check args */
    HDassert(attr_src);
    HDassert(file_src);
    HDassert(attr_dst);
    HDassert(file_dst);

    /* Only need to fix reference attribute with real data being copied to
     *  another file.
     */
    if((NULL != attr_src->shared->data) &&
            (H5T_get_class(attr_src->shared->dt, FALSE) == H5T_REFERENCE) &&
            (file_src != file_dst)) {

        /* copy object pointed by reference. The current implementation does not
         *  deal with nested reference such as reference in a compound structure
         */

        /* Check for expanding references */
        if(cpy_info->expand_ref) {
            size_t ref_count;

            /* Determine # of reference elements to copy */
            ref_count = attr_dst->shared->data_size / H5T_get_size(attr_dst->shared->dt);

            /* Copy objects referenced in source buffer to destination file and set destination elements */
            if(H5O_copy_expand_ref(file_src, attr_src->shared->data, dxpl_id,
                    file_dst, attr_dst->shared->data, ref_count, H5T_get_ref_type(attr_src->shared->dt), cpy_info) < 0)
                HGOTO_ERROR(H5E_ATTR, H5E_CANTCOPY, FAIL, "unable to copy reference attribute")
        } /* end if */
        else
            /* Reset value to zero */
            HDmemset(attr_dst->shared->data, 0, attr_dst->shared->data_size);
    } /* end if */

done:
    FUNC_LEAVE_NOAPI(ret_value)
} /* H5O_attr_post_copy_file() */


/*-------------------------------------------------------------------------
 * Function:	H5O_attr_get_crt_index
 *
 * Purpose:	Get creation index from the message
 *
 * Return:      Success:        Non-negative
 *              Failure:        Negative
 *
 * Programmer:	Quincey Koziol
 *              Thursday, January 18, 2007
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5O_attr_get_crt_index(const void *_mesg, H5O_msg_crt_idx_t *crt_idx /*out*/)
{
    const H5A_t  *attr = (const H5A_t *)_mesg;

    FUNC_ENTER_NOAPI_NOINIT_NOFUNC(H5O_attr_get_crt_index)

    HDassert(attr);
    HDassert(crt_idx);

    /* Get the attribute's creation index */
    *crt_idx = attr->shared->crt_idx;

    FUNC_LEAVE_NOAPI(SUCCEED)
} /* end H5O_attr_get_crt_index() */


/*-------------------------------------------------------------------------
 * Function:	H5O_attr_set_crt_index
 *
 * Purpose:	Set creation index from the message
 *
 * Return:      Success:        Non-negative
 *              Failure:        Negative
 *
 * Programmer:	Quincey Koziol
 *              Thursday, January 18, 2007
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5O_attr_set_crt_index(void *_mesg, H5O_msg_crt_idx_t crt_idx)
{
    H5A_t  *attr = (H5A_t *)_mesg;

    FUNC_ENTER_NOAPI_NOINIT_NOFUNC(H5O_attr_set_crt_index)

    HDassert(attr);

    /* Set the creation index */
    attr->shared->crt_idx = crt_idx;

    FUNC_LEAVE_NOAPI(SUCCEED)
} /* end H5O_attr_set_crt_index() */


/*--------------------------------------------------------------------------
 NAME
    H5O_attr_debug
 PURPOSE
    Prints debugging information for an attribute message
 USAGE
    void *H5O_attr_debug(f, mesg, stream, indent, fwidth)
        H5F_t *f;               IN: pointer to the HDF5 file struct
        const void *mesg;       IN: Pointer to the source attribute struct
        FILE *stream;           IN: Pointer to the stream for output data
        int indent;            IN: Amount to indent information by
        int fwidth;            IN: Field width (?)
 RETURNS
    Non-negative on success/Negative on failure
 DESCRIPTION
        This function prints debugging output to the stream passed as a
    parameter.
--------------------------------------------------------------------------*/
static herr_t
H5O_attr_debug(H5F_t *f, hid_t dxpl_id, const void *_mesg, FILE * stream, int indent,
	       int fwidth)
{
    const H5A_t *mesg = (const H5A_t *)_mesg;
    const char		*s;             /* Temporary string pointer */
    char		buf[256];       /* Temporary string buffer */
    herr_t ret_value = SUCCEED;         /* Return value */

    FUNC_ENTER_NOAPI_NOINIT(H5O_attr_debug)

    /* check args */
    HDassert(f);
    HDassert(stream);
    HDassert(indent >= 0);
    HDassert(fwidth >= 0);

    fprintf(stream, "%*s%-*s \"%s\"\n", indent, "", fwidth,
	    "Name:",
	    mesg->shared->name);
    switch(mesg->shared->encoding) {
        case H5T_CSET_ASCII:
            s = "ASCII";
            break;
        case H5T_CSET_UTF8:
            s = "UTF-8";
            break;
        default:
            sprintf(buf, "H5T_CSET_RESERVED_%d", (int)(mesg->shared->encoding));
            s = buf;
            break;
    } /* end switch */
    fprintf(stream, "%*s%-*s %s\n", indent, "", fwidth,
            "Character Set of Name:",
            s);
    HDfprintf(stream, "%*s%-*s %t\n", indent, "", fwidth,
	    "Initialized:",
	    mesg->shared->initialized);
    HDfprintf(stream, "%*s%-*s %t\n", indent, "", fwidth,
	    "Object opened:",
	    mesg->obj_opened);
    HDfprintf(stream, "%*s%-*s %a\n", indent, "", fwidth,
	    "Object:",
	    mesg->shared->oloc.addr);

    /* Check for attribute creation order index on the attribute */
    if(mesg->shared->crt_idx != H5O_MAX_CRT_ORDER_IDX)
        HDfprintf(stream, "%*s%-*s %u\n", indent, "", fwidth,
                "Creation Index:",
                (unsigned)mesg->shared->crt_idx);

    fprintf(stream, "%*sDatatype...\n", indent, "");
    fprintf(stream, "%*s%-*s %lu\n", indent+3, "", MAX(0,fwidth-3),
	    "Encoded Size:",
	    (unsigned long)(mesg->shared->dt_size));
    if((H5O_MSG_DTYPE->debug)(f, dxpl_id, mesg->shared->dt, stream, indent + 3, MAX(0, fwidth - 3)) < 0)
        HGOTO_ERROR(H5E_OHDR, H5E_WRITEERROR, FAIL, "unable to display datatype message info")

    fprintf(stream, "%*sDataspace...\n", indent, "");
    fprintf(stream, "%*s%-*s %lu\n", indent+3, "", MAX(0, fwidth - 3),
	    "Encoded Size:",
	    (unsigned long)(mesg->shared->ds_size));
    if(H5S_debug(f, dxpl_id, mesg->shared->ds, stream, indent+3, MAX(0, fwidth - 3)) < 0)
        HGOTO_ERROR(H5E_OHDR, H5E_WRITEERROR, FAIL, "unable to display dataspace message info")

done:
    FUNC_LEAVE_NOAPI(ret_value)
} /* end H5O_attr_debug() */