Build system improvements
[ustl.git] / cmemlink.cc
blobd13992ea56402b5076653de9f2612ef20acf5935
1 // This file is part of the ustl library, an STL implementation.
2 //
3 // Copyright (C) 2005 by Mike Sharov <msharov@users.sourceforge.net>
4 // This file is free software, distributed under the MIT License.
5 //
6 // cmemlink.cc
7 //
8 // See cmemlink.h for documentation.
9 //
11 #include "cmemlink.h"
12 #include "ofstream.h"
13 #include "strmsize.h"
14 #include "ualgo.h"
16 namespace ustl {
18 /// \brief Attaches the object to pointer \p p of size \p n.
19 ///
20 /// If \p p is NULL and \p n is non-zero, bad_alloc is thrown and current
21 /// state remains unchanged.
22 ///
23 void cmemlink::link (const void* p, size_type n)
25 if (!p && n)
26 throw bad_alloc (n);
27 unlink();
28 relink (p, n);
31 /// Writes the object to stream \p os
32 void cmemlink::write (ostream& os) const
34 const written_size_type sz (size());
35 assert (sz == size() && "No support for writing memblocks larger than 4G");
36 os << sz;
37 os.write (cdata(), sz);
38 os.align (alignof (sz));
41 /// Writes the object to stream \p os
42 void cmemlink::text_write (ostringstream& os) const
44 os.write (begin(), readable_size());
47 /// Returns the number of bytes required to write this object to a stream.
48 cmemlink::size_type cmemlink::stream_size (void) const
50 const written_size_type sz (size());
51 return (Align (stream_size_of (sz) + sz, alignof(sz)));
54 /// Writes the data to file \p "filename".
55 void cmemlink::write_file (const char* filename, int mode) const
57 fstream f;
58 f.exceptions (fstream::allbadbits);
59 f.open (filename, fstream::out | fstream::trunc, mode);
60 f.write (cdata(), readable_size());
61 f.close();
64 /// swaps the contents with \p l
65 void cmemlink::swap (cmemlink& l)
67 #if CPU_HAS_MMX && SIZE_OF_POINTER == 4
68 asm (
69 "movq %0, %%mm0\n\t"
70 "movq %2, %%mm1\n\t"
71 "movq %%mm0, %2\n\t"
72 "movq %%mm1, %0"
73 : "=m"(m_Data), "=m"(m_Size), "=m"(l.m_Data), "=m"(l.m_Size)
75 : "mm0", "mm1", "st", "st(1)");
76 simd::reset_mmx();
77 #elif CPU_HAS_SSE && SIZE_OF_POINTER == 8
78 asm (
79 "movups %0, %%xmm0\n\t"
80 "movups %2, %%xmm1\n\t"
81 "movups %%xmm0, %2\n\t"
82 "movups %%xmm1, %0"
83 : "=m"(m_Data), "=m"(m_Size), "=m"(l.m_Data), "=m"(l.m_Size)
85 : "xmm0", "xmm1");
86 #else
87 ::ustl::swap (m_Data, l.m_Data);
88 ::ustl::swap (m_Size, l.m_Size);
89 #endif
92 /// Compares to memory block pointed by l. Size is compared first.
93 bool cmemlink::operator== (const cmemlink& l) const
95 return (l.m_Size == m_Size &&
96 (l.m_Data == m_Data || 0 == memcmp (l.m_Data, m_Data, m_Size)));
99 } // namespace ustl