DataReelDataReelC++ Transition Guide

Examples › General Examples

general_print_security

C++17 or laterC++ standard library onlyPortable C++ (tested on Linux)

Legacy: examples_general/print_security/testprog.cpp · Modern: examples_modern/general/print_security/modern.cpp

Modern equivalent of the 6.3.1 print driver checks. The legacy bugs were C string copies that lost their terminator while a long line was cut, filtered or wrapped, and a color table read out of range. With std::string_view a cut or a wrap is a view with a length (no terminator to lose), the output escapes PostScript and HTML special characters into a std::string that grows as needed, and the color table is a std::array read with a checked index.

  ps_cut      Cutting a long line to a maximum length.
  ps_escape   PostScript string escapes for ( ) and backslash.
  ps_wrap     Wrapping a long line at spaces, no part over the width.
  html_escape HTML escapes for & < > and quotes.
  html_color  A color index out of range gives the default color.

Returns 0 if every check passes.

Legacy calls in this program

LegacyModern C++StandardNotes
new / deleteautomatic objects, containers, std::unique_ptr / std::make_uniqueC++11 / C++14Ownership is in the type, and release() shows a hand-over.
strcpy(), strncpy(), memmove() into char arraysstd::string; std::array<char, N> + string_view::copy()C++11 / C++17
DiskFileBstd::fstream (read, write, seekg/seekp, tellg)C++98
clock(), SysTime, GetSystemTime()std::chrono::steady_clock (elapsed), system_clock (calendar)C++11clock() is CPU time, not elapsed time.

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_general/print_security/testprog.cpp 129 lines
#include "gxdlcode.h"

#include <stdio.h>
#include <string.h>
#include <string>
#include <sstream>
#include <fstream>
#include <iterator>
#include "pscript.h"
#include "htmldrv.h"

#if defined (__USE_POSTSCRIPT_PRINTING__) && defined (__USE_HTM_PRINTING__)

static int failures = 0;

static void check(int ok, const char *what)
{
  printf("%s %s\n", ok ? "PASS" : "FAIL", what);
  fflush(stdout);
  if(!ok) failures++;
}

static int count_char(const std::string &s, char c)
// Count c inside the PostScript strings "(...)" only, not in the
// operator and font names around them
{
  int n = 0, in = 0;
  for(size_t i = 0; i < s.size(); i++) {
    if(!in && s[i] == '(') in = 1;
    else if(in && s[i] == '\\') i++;
    else if(in && s[i] == ')') in = 0;
    else if(in && s[i] == c) n++;
  }
  return n;
}

int main()
{
  PostScriptDrv ps;
  ps.DocumentSetup();
  int cols = ps.Columns();
  check(cols > 10 && cols < 1000, "ps: DocumentSetup() column count");

  // ps_cut: a heap line of exactly cols+50 'a' characters
  {
    std::string line(cols + 50, 'a');
    char *in = new char[line.size() + 1];
    memcpy(in, line.c_str(), line.size() + 1);
    std::ostringstream out;
    int rv = ps.ProcessText(in, out, 1, 0);
    check(rv == 1 && count_char(out.str(), 'a') == cols,
	  "ps_cut: a long line is cut to the column count");
    delete[] in;
  }

  // ps_filter: the nroff filter on a long line ending in a repeated pair
  {
    std::string line(cols + 3, 'b');
    line += "xyxyx";
    char *in = new char[line.size() + 1];
    memcpy(in, line.c_str(), line.size() + 1);
    std::ostringstream out;
    ps.ProcessText(in, out, 1, 1);
    check(1, "ps_filter: nroff filter at the end of a long line (ASan)");
    delete[] in;
  }

  // ps_wrap: ConvertTextFile() wraps a long line
  {
    const char *fn = "print_sec.txt";
    FILE *fp = fopen(fn, "wb");
    std::string line(cols * 2 + 5, 'c');
    fputs(line.c_str(), fp); fputs("\n", fp);
    fclose(fp);
    DiskFileB f;
    int ok = f.df_Open(fn, DiskFileB::df_READONLY) == DiskFileB::df_NO_ERROR;
    std::ostringstream out;
    int rv = ok ? ps.ConvertTextFile(f, out, 1, 0) : 0;
    f.df_Close();
    remove(fn);
    int expect = (int)line.size();
    if(expect > MAX_LINE - 1) expect = MAX_LINE - 1; // df_GetLine() limit
    check(rv == 1 && count_char(out.str(), 'c') == expect,
	  "ps_wrap: a wrapped line prints each character once");
  }

  // ps_maxlen: PrintLine() with a length limit
  {
    const char *fn = "print_sec.ps";
    std::ofstream os(fn);
    char in[64];
    memset(in, 'd', 63); in[63] = 0;
    int rv = ps.PrintLine(in, 10, os);
    os.close();
    std::ifstream is(fn);
    std::string all((std::istreambuf_iterator<char>(is)),
		    std::istreambuf_iterator<char>());
    is.close();
    remove(fn);
    check(rv == 1 && count_char(all, 'd') == 10, "ps_maxlen: PrintLine() cuts to max_len");
  }

  // html_color
  {
    std::ostringstream out;
    HyperText ht(out);
    ht.StartBody((htmCOLORS)99);
    ht.GenTable(1, 4, 75, 1, (htmCOLORS)-5);
    ht.GetSystemTime(0);
    check(out.str().find("BGCOLOR=\"#000000\"") != std::string::npos &&
	  out.str().find("BORDERCOLOR=\"#000000\"") != std::string::npos,
	  "html_color: colors out of range use the first color");
  }

  if(failures) printf("%d check(s) FAILED\n", failures);
  else printf("All checks passed\n");
  return failures ? 1 : 0;
}
#else
int main()
{
  printf("SKIP: the library was built without the print drivers\n");
  return 0;
}
#endif
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++17)

examples_modern/general/print_security/modern.cpp 94 lines
#include <array>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>

static int failures = 0;
static void check(bool ok, const char *what)
{
  std::cout << (ok ? "PASS: " : "FAIL: ") << what << "\n";
  if(!ok) failures++;
}

std::string_view cut(std::string_view line, std::size_t max_len)
{
  return line.substr(0, max_len);
}

std::string ps_escape(std::string_view s)
{
  std::string r;
  for(char c : s) {
    if(c == '(' || c == ')' || c == '\\') r += '\\';
    r += c;
  }
  return "(" + r + ")";
}

std::vector<std::string_view> wrap(std::string_view line, std::size_t width)
{
  std::vector<std::string_view> parts;
  while(line.size() > width) {
    auto space = line.rfind(' ', width);
    std::size_t len = (space == std::string_view::npos || space == 0) ? width : space;
    parts.push_back(line.substr(0, len));
    line.remove_prefix(len);
    if(!line.empty() && line[0] == ' ') line.remove_prefix(1);
  }
  parts.push_back(line);
  return parts;
}

std::string html_escape(std::string_view s)
{
  std::string r;
  for(char c : s) {
    switch(c) {
      case '&': r += "&amp;"; break;
      case '<': r += "&lt;"; break;
      case '>': r += "&gt;"; break;
      case '"': r += "&quot;"; break;
      case '\'': r += "&#39;"; break;
      default: r += c;
    }
  }
  return r;
}

constexpr std::array<std::string_view, 4> colors = {"#000000", "#ff0000",
                                                    "#00ff00", "#0000ff"};
std::string_view color(int index)
{
  if(index < 0 || std::size_t(index) >= colors.size()) return colors[0];
  return colors[std::size_t(index)];
}

int main()
{
  std::string long_line(5000, 'x');
  check(cut(long_line, 80).size() == 80, "ps_cut: cut to 80 characters");
  check(cut("short", 80) == "short", "ps_cut: short line unchanged");

  check(ps_escape("a(b)c\\d") == "(a\\(b\\)c\\\\d)", "ps_escape: ( ) and \\");

  std::string words;
  for(int i = 0; i < 500; i++) words += "word ";
  bool ok = true;
  std::size_t total = 0;
  for(auto part : wrap(words, 72)) { ok = ok && part.size() <= 72; total += part.size(); }
  check(ok, "ps_wrap: no part longer than the width");
  check(wrap(std::string(300, 'y'), 72).size() == 5, "ps_wrap: a line with no spaces");

  check(html_escape("<a href=\"x\">&</a>") ==
        "&lt;a href=&quot;x&quot;&gt;&amp;&lt;/a&gt;", "html_escape");
  check(color(2) == "#00ff00" && color(4) == "#000000" && color(-1) == "#000000",
        "html_color: out of range index");

  std::cout << (failures ? "FAILED" : "All checks passed") << "\n";
  return failures ? 1 : 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=17
cmake --build build-modern --target general_print_security
./build-modern/general_print_security
# or without CMake:
g++ -std=c++17 -pthread -o general_print_security examples_modern/general/print_security/modern.cpp

Output of the modern program

From run_modern_tests.sh on RHEL 10, GCC 14, C++20.

PASS: ps_cut: cut to 80 characters
PASS: ps_cut: short line unchanged
PASS: ps_escape: ( ) and \
PASS: ps_wrap: no part longer than the width
PASS: ps_wrap: a line with no spaces
PASS: html_escape
PASS: html_color: out of range index
All checks passed