home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1995 July / macformat-026.iso / mac / Shareware City / Developers / NString 1.0 beta / Sources / NString_Assignment.cxx < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-11  |  1.7 KB  |  76 lines  |  [TEXT/KAHL]

  1.  
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. #include "NString.h"
  6. #include "NString_Misc.h"
  7.  
  8. //_________________________________________________________________________________
  9.  
  10. NString& NString::operator= (const char *s)
  11. {
  12.     const char *fname = "operator= (const char *)";
  13.     unsigned long int new_length;
  14.     
  15.     if (s == NULL)
  16.         s = "";
  17.         
  18.     new_length = strlen(s);
  19.  
  20.     if (sb->refs > 1)                                            // there's another variable looking at this string body
  21.     {
  22.         if (! GetNewSB(new_length))
  23.             OUT_OF_MEM(fname);
  24.     }
  25.     else
  26.     {
  27.         if (! ReallocStrBuf(new_length))
  28.             OUT_OF_MEM(fname);
  29.         sb->len = new_length;
  30.     }
  31.         
  32.     strcpy(sb->str, s);
  33.     return (*this);
  34. }
  35.  
  36. //_________________________________________________________________________________
  37.  
  38. NString& NString::operator= (const char c)
  39. {
  40.     const char *fname = "operator= (const char)";    // the method's name (for error handling purposes)
  41.     
  42.     if (c == '\0')
  43.         USAGE_ERR(fname, "Attempted assignment of NUL character to NString");
  44.  
  45.     if (sb->refs > 1)                                            // there's another variable looking at this string body
  46.     {
  47.         if (! GetNewSB(1))
  48.             OUT_OF_MEM(fname);
  49.     }
  50.     else                                                                // this string body isn't being used by anyone else (sb->refs == 1)
  51.     {
  52.         if (! ReallocStrBuf(1))
  53.             OUT_OF_MEM(fname);
  54.         sb->len = 1;
  55.     }
  56.         
  57.     sb->str[0] = c;                                                // define the string contents
  58.     sb->str[1] = '\0';
  59.     
  60.     return (*this);
  61. }
  62.  
  63. //_________________________________________________________________________________
  64.  
  65. NString& NString::operator= (const NString& s)
  66. {
  67.     s.sb->refs++;                                                // protect against "st = st"
  68.     if ((--(sb->refs)) == 0)                                // the old string body isn't being used any more
  69.     {
  70.         free(sb->str);
  71.         delete sb;
  72.     }
  73.     sb = s.sb;                                                        // set this variable to look at the same string body as "s"
  74.     return (*this);
  75. }
  76.