summaryrefslogtreecommitdiff
path: root/ecos/packages/language/cxx/ustl/current/src/cmemlink.cpp
blob: 10b63ba36dd016841d9ab37b7591c8d42ea1f4ab (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
// This file is part of the uSTL library, an STL implementation.
//
// Copyright (c) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.

#include "cmemlink.h"
#ifdef CYGCLS_USTL_FSTREAMS
#include "ofstream.h"
#else
#include "sostream.h"
#endif
#include "strmsize.h"
#include "ualgo.h"
#include "config.h"

namespace ustl {

/// \brief Attaches the object to pointer \p p of size \p n.
///
/// If \p p is NULL and \p n is non-zero, bad_alloc is thrown and current
/// state remains unchanged.
///
void cmemlink::link (const void* p, size_type n)
{
    if (!p && n)
	USTL_THROW(bad_alloc (n));
    unlink();
    relink (p, n);
}

void cmemlink::unlink (void) throw()
{
    m_Data = NULL; m_Size = 0;
}

/// Writes the object to stream \p os
void cmemlink::write (ostream& os) const
{
    const written_size_type sz (size());
    assert (sz == size() && "No support for writing memblocks larger than 4G");
    os << sz;
    os.write (cdata(), sz);
    os.align (stream_align_of (sz));
}

/// Writes the object to stream \p os
void cmemlink::text_write (ostringstream& os) const
{
    os.write (begin(), readable_size());
}

/// Returns the number of bytes required to write this object to a stream.
cmemlink::size_type cmemlink::stream_size (void) const
{
    const written_size_type sz (size());
    return (Align (stream_size_of (sz) + sz, stream_align_of(sz)));
}

#ifdef CYGCLS_USTL_FSTREAMS
/// Writes the data to file \p "filename".
void cmemlink::write_file (const char* filename, int mode) const
{
    fstream f;
    f.exceptions (fstream::allbadbits);
    f.open (filename, fstream::out | fstream::trunc, mode);
    f.write (cdata(), readable_size());
    f.close();
}
#endif

/// Compares to memory block pointed by l. Size is compared first.
bool cmemlink::operator== (const cmemlink& l) const
{
    return (l.m_Size == m_Size &&
	    (l.m_Data == m_Data || 0 == memcmp (l.m_Data, m_Data, m_Size)));
}

} // namespace ustl